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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eb165c0eb929b542178daea7057c258718d1ba6a | testfixtures/snippet.py | testfixtures/snippet.py | # -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
return SnippetVersion(
snippet=snippet,
created_at=created_at,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
| # -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
version = SnippetVersion(
snippet=snippet,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
if created_at is not None:
version.created_at = created_at
return version
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
| Set creation date via field, not via constructor | Set creation date via field, not via constructor
| Python | bsd-3-clause | m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps | # -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
return SnippetVersion(
snippet=snippet,
created_at=created_at,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
Set creation date via field, not via constructor | # -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
version = SnippetVersion(
snippet=snippet,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
if created_at is not None:
version.created_at = created_at
return version
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
| <commit_before># -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
return SnippetVersion(
snippet=snippet,
created_at=created_at,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
<commit_msg>Set creation date via field, not via constructor<commit_after> | # -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
version = SnippetVersion(
snippet=snippet,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
if created_at is not None:
version.created_at = created_at
return version
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
| # -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
return SnippetVersion(
snippet=snippet,
created_at=created_at,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
Set creation date via field, not via constructor# -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
version = SnippetVersion(
snippet=snippet,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
if created_at is not None:
version.created_at = created_at
return version
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
| <commit_before># -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
return SnippetVersion(
snippet=snippet,
created_at=created_at,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
<commit_msg>Set creation date via field, not via constructor<commit_after># -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
version = SnippetVersion(
snippet=snippet,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
if created_at is not None:
version.created_at = created_at
return version
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
|
88b984a084385574bb420a0b81627914229f08e9 | nova/policies/quota_class_sets.py | nova/policies/quota_class_sets.py | # Copyright 2016 Cloudbase Solutions Srl
# 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.
from oslo_policy import policy
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
policy.RuleDefault(
name=POLICY_ROOT % 'show',
check_str='is_admin:True or quota_class:%(quota_class)s'),
policy.RuleDefault(
name=POLICY_ROOT % 'update',
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return quota_class_sets_policies
| # Copyright 2016 Cloudbase Solutions Srl
# 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.
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
base.create_rule_default(
POLICY_ROOT % 'show',
'is_admin:True or quota_class:%(quota_class)s',
"List quotas for specific quota classs",
[
{
'method': 'GET',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
base.create_rule_default(
POLICY_ROOT % 'update',
base.RULE_ADMIN_API,
'Update quotas for specific quota class',
[
{
'method': 'PUT',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
]
def list_rules():
return quota_class_sets_policies
| Add policy description for os-quota-classes | Add policy description for os-quota-classes
This commit adds policy doc for os-quota-classes policies.
Partial implement blueprint policy-docs
Change-Id: Ic7568b77ebfaa012e4310c3c1beac68587bd19f6
| Python | apache-2.0 | rahulunair/nova,klmitch/nova,klmitch/nova,mikalstill/nova,vmturbo/nova,jianghuaw/nova,Juniper/nova,Juniper/nova,gooddata/openstack-nova,klmitch/nova,phenoxim/nova,openstack/nova,gooddata/openstack-nova,mikalstill/nova,mahak/nova,vmturbo/nova,openstack/nova,vmturbo/nova,rajalokan/nova,jianghuaw/nova,vmturbo/nova,rahulunair/nova,rajalokan/nova,Juniper/nova,Juniper/nova,mahak/nova,rajalokan/nova,phenoxim/nova,jianghuaw/nova,openstack/nova,gooddata/openstack-nova,klmitch/nova,mahak/nova,rahulunair/nova,gooddata/openstack-nova,jianghuaw/nova,rajalokan/nova,mikalstill/nova | # Copyright 2016 Cloudbase Solutions Srl
# 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.
from oslo_policy import policy
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
policy.RuleDefault(
name=POLICY_ROOT % 'show',
check_str='is_admin:True or quota_class:%(quota_class)s'),
policy.RuleDefault(
name=POLICY_ROOT % 'update',
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return quota_class_sets_policies
Add policy description for os-quota-classes
This commit adds policy doc for os-quota-classes policies.
Partial implement blueprint policy-docs
Change-Id: Ic7568b77ebfaa012e4310c3c1beac68587bd19f6 | # Copyright 2016 Cloudbase Solutions Srl
# 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.
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
base.create_rule_default(
POLICY_ROOT % 'show',
'is_admin:True or quota_class:%(quota_class)s',
"List quotas for specific quota classs",
[
{
'method': 'GET',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
base.create_rule_default(
POLICY_ROOT % 'update',
base.RULE_ADMIN_API,
'Update quotas for specific quota class',
[
{
'method': 'PUT',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
]
def list_rules():
return quota_class_sets_policies
| <commit_before># Copyright 2016 Cloudbase Solutions Srl
# 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.
from oslo_policy import policy
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
policy.RuleDefault(
name=POLICY_ROOT % 'show',
check_str='is_admin:True or quota_class:%(quota_class)s'),
policy.RuleDefault(
name=POLICY_ROOT % 'update',
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return quota_class_sets_policies
<commit_msg>Add policy description for os-quota-classes
This commit adds policy doc for os-quota-classes policies.
Partial implement blueprint policy-docs
Change-Id: Ic7568b77ebfaa012e4310c3c1beac68587bd19f6<commit_after> | # Copyright 2016 Cloudbase Solutions Srl
# 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.
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
base.create_rule_default(
POLICY_ROOT % 'show',
'is_admin:True or quota_class:%(quota_class)s',
"List quotas for specific quota classs",
[
{
'method': 'GET',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
base.create_rule_default(
POLICY_ROOT % 'update',
base.RULE_ADMIN_API,
'Update quotas for specific quota class',
[
{
'method': 'PUT',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
]
def list_rules():
return quota_class_sets_policies
| # Copyright 2016 Cloudbase Solutions Srl
# 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.
from oslo_policy import policy
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
policy.RuleDefault(
name=POLICY_ROOT % 'show',
check_str='is_admin:True or quota_class:%(quota_class)s'),
policy.RuleDefault(
name=POLICY_ROOT % 'update',
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return quota_class_sets_policies
Add policy description for os-quota-classes
This commit adds policy doc for os-quota-classes policies.
Partial implement blueprint policy-docs
Change-Id: Ic7568b77ebfaa012e4310c3c1beac68587bd19f6# Copyright 2016 Cloudbase Solutions Srl
# 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.
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
base.create_rule_default(
POLICY_ROOT % 'show',
'is_admin:True or quota_class:%(quota_class)s',
"List quotas for specific quota classs",
[
{
'method': 'GET',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
base.create_rule_default(
POLICY_ROOT % 'update',
base.RULE_ADMIN_API,
'Update quotas for specific quota class',
[
{
'method': 'PUT',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
]
def list_rules():
return quota_class_sets_policies
| <commit_before># Copyright 2016 Cloudbase Solutions Srl
# 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.
from oslo_policy import policy
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
policy.RuleDefault(
name=POLICY_ROOT % 'show',
check_str='is_admin:True or quota_class:%(quota_class)s'),
policy.RuleDefault(
name=POLICY_ROOT % 'update',
check_str=base.RULE_ADMIN_API),
]
def list_rules():
return quota_class_sets_policies
<commit_msg>Add policy description for os-quota-classes
This commit adds policy doc for os-quota-classes policies.
Partial implement blueprint policy-docs
Change-Id: Ic7568b77ebfaa012e4310c3c1beac68587bd19f6<commit_after># Copyright 2016 Cloudbase Solutions Srl
# 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.
from nova.policies import base
POLICY_ROOT = 'os_compute_api:os-quota-class-sets:%s'
quota_class_sets_policies = [
base.create_rule_default(
POLICY_ROOT % 'show',
'is_admin:True or quota_class:%(quota_class)s',
"List quotas for specific quota classs",
[
{
'method': 'GET',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
base.create_rule_default(
POLICY_ROOT % 'update',
base.RULE_ADMIN_API,
'Update quotas for specific quota class',
[
{
'method': 'PUT',
'path': '/os-quota-class-sets/{quota_class}'
}
]),
]
def list_rules():
return quota_class_sets_policies
|
c370fdfc405d1ff3dd31d9f6a589b0b795c28c55 | examples/06-list-activated-methods.py | examples/06-list-activated-methods.py | # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.desciption} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
| # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.description} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
| Fix typo in methods example. | Fix typo in methods example.
| Python | bsd-2-clause | mollie/mollie-api-python | # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.desciption} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
Fix typo in methods example. | # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.description} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
| <commit_before># Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.desciption} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
<commit_msg>Fix typo in methods example.<commit_after> | # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.description} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
| # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.desciption} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
Fix typo in methods example.# Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.description} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
| <commit_before># Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.desciption} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
<commit_msg>Fix typo in methods example.<commit_after># Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.description} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
|
1249c93696f9baa0eefefa373edcc8189802cce5 | script/blender_2cloud.py | script/blender_2cloud.py | import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
| import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.ply': lambda file: bpy.ops.import_mesh.ply(filepath=file),
'.stl': lambda file: bpy.ops.import_mesh.stl(filepath=file),
'.3ds': lambda file: bpy.ops.import_scene.autodesk_3ds(filepath=file, axis_forward='Y', axis_up='Z'),
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
| Add ply, stl and 3ds support to blendel_2cloud.py. | Add ply, stl and 3ds support to blendel_2cloud.py.
| Python | bsd-2-clause | jrl-umi3218/sch-creator,jrl-umi3218/sch-creator,jrl-umi3218/sch-creator | import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
Add ply, stl and 3ds support to blendel_2cloud.py. | import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.ply': lambda file: bpy.ops.import_mesh.ply(filepath=file),
'.stl': lambda file: bpy.ops.import_mesh.stl(filepath=file),
'.3ds': lambda file: bpy.ops.import_scene.autodesk_3ds(filepath=file, axis_forward='Y', axis_up='Z'),
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
| <commit_before>import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
<commit_msg>Add ply, stl and 3ds support to blendel_2cloud.py.<commit_after> | import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.ply': lambda file: bpy.ops.import_mesh.ply(filepath=file),
'.stl': lambda file: bpy.ops.import_mesh.stl(filepath=file),
'.3ds': lambda file: bpy.ops.import_scene.autodesk_3ds(filepath=file, axis_forward='Y', axis_up='Z'),
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
| import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
Add ply, stl and 3ds support to blendel_2cloud.py.import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.ply': lambda file: bpy.ops.import_mesh.ply(filepath=file),
'.stl': lambda file: bpy.ops.import_mesh.stl(filepath=file),
'.3ds': lambda file: bpy.ops.import_scene.autodesk_3ds(filepath=file, axis_forward='Y', axis_up='Z'),
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
| <commit_before>import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
<commit_msg>Add ply, stl and 3ds support to blendel_2cloud.py.<commit_after>import os
import sys
import bpy
# file loader per extension
loader_factory = {
'.ply': lambda file: bpy.ops.import_mesh.ply(filepath=file),
'.stl': lambda file: bpy.ops.import_mesh.stl(filepath=file),
'.3ds': lambda file: bpy.ops.import_scene.autodesk_3ds(filepath=file, axis_forward='Y', axis_up='Z'),
'.obj': lambda file: bpy.ops.import_scene.obj(filepath=file, axis_forward='Y', axis_up='Z'),
'.wrl': lambda file: bpy.ops.import_scene.x3d(filepath=file, axis_forward='Y', axis_up='Z')
}
def convert(input_filename, output_filename):
"convert a file to a qc file."
ext = os.path.splitext(input_filename)[1]
try:
loader = loader_factory[ext]
except KeyError:
raise RuntimeError('%s is not supported' % ext)
loader(input_filename)
bpy.ops.export_scene.qc(filepath=output_filename)
def main():
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
fbx_in = argv[0]
fbx_out = argv[1]
convert(fbx_in, fbx_out)
if __name__ == '__main__':
main()
|
a64d6f6de26302e5b8764e248c5df0a529a86343 | fireplace/cards/league/collectible.py | fireplace/cards/league/collectible.py | from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
| from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
##
# Secrets
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
| Move Sacred Trial to secret section | Move Sacred Trial to secret section
| Python | agpl-3.0 | amw2104/fireplace,jleclanche/fireplace,amw2104/fireplace,NightKev/fireplace,smallnamespace/fireplace,Ragowit/fireplace,Ragowit/fireplace,beheh/fireplace,smallnamespace/fireplace | from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
Move Sacred Trial to secret section | from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
##
# Secrets
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
| <commit_before>from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
<commit_msg>Move Sacred Trial to secret section<commit_after> | from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
##
# Secrets
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
| from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
Move Sacred Trial to secret sectionfrom ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
##
# Secrets
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
| <commit_before>from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
<commit_msg>Move Sacred Trial to secret section<commit_after>from ..utils import *
##
# Minions
# Obsidian Destroyer
class LOE_009:
events = OWN_TURN_END.on(Summon(CONTROLLER, "LOE_009t"))
##
# Spells
# Forgotten Torch
class LOE_002:
play = Hit(TARGET, 3), Shuffle(CONTROLLER, "LOE_002t")
class LOE_002t:
play = Hit(TARGET, 6)
# Raven Idol
class LOE_115:
choose = ("LOE_115a", "LOE_115b")
##
# Secrets
# Sacred Trial
class LOE_027:
events = Play(OPPONENT, MINION | HERO).after(
(Count(ENEMY_MINIONS) >= 4) &
(Reveal(SELF), Destroy(Play.CARD))
)
|
6a293fef25b5760d8b783ad0db1d00a3d5cf4e7f | packs/puppet/actions/lib/python_actions.py | packs/puppet/actions/lib/python_actions.py | from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self):
super(PupperBasePythonAction, self).__init__()
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
| from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self, config):
super(PuppetBasePythonAction, self).__init__(config=config)
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
| Update affected Puppet action constructor to take in "config" argument. | Update affected Puppet action constructor to take in "config" argument.
| Python | apache-2.0 | Aamir-raza-1/st2contrib,digideskio/st2contrib,dennybaa/st2contrib,armab/st2contrib,lmEshoo/st2contrib,armab/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,jtopjian/st2contrib,digideskio/st2contrib,pidah/st2contrib,tonybaloney/st2contrib,pinterb/st2contrib,StackStorm/st2contrib,lakshmi-kannan/st2contrib,Aamir-raza-1/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pinterb/st2contrib,pearsontechnology/st2contrib,pearsontechnology/st2contrib,psychopenguin/st2contrib,jtopjian/st2contrib,dennybaa/st2contrib,pidah/st2contrib,armab/st2contrib,lmEshoo/st2contrib,pidah/st2contrib,meirwah/st2contrib,StackStorm/st2contrib,lakshmi-kannan/st2contrib,meirwah/st2contrib,psychopenguin/st2contrib | from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self):
super(PupperBasePythonAction, self).__init__()
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
Update affected Puppet action constructor to take in "config" argument. | from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self, config):
super(PuppetBasePythonAction, self).__init__(config=config)
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
| <commit_before>from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self):
super(PupperBasePythonAction, self).__init__()
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
<commit_msg>Update affected Puppet action constructor to take in "config" argument.<commit_after> | from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self, config):
super(PuppetBasePythonAction, self).__init__(config=config)
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
| from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self):
super(PupperBasePythonAction, self).__init__()
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
Update affected Puppet action constructor to take in "config" argument.from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self, config):
super(PuppetBasePythonAction, self).__init__(config=config)
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
| <commit_before>from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self):
super(PupperBasePythonAction, self).__init__()
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
<commit_msg>Update affected Puppet action constructor to take in "config" argument.<commit_after>from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self, config):
super(PuppetBasePythonAction, self).__init__(config=config)
self.client = self._get_client()
def _get_client(self):
master_config = self.config['master']
auth_config = self.config['auth']
client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'],
master_port=master_config['port'],
client_cert_path=auth_config['client_cert_path'],
client_cert_key_path=auth_config['client_cert_key_path'],
ca_cert_path=auth_config['ca_cert_path'])
return client
|
6023fa1fdec83c0a4568529982a69ae64801ad5f | src/cli/_actions/_pool.py | src/cli/_actions/_pool.py | """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(_, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(_, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
return (rc, message)
| """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(result, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
if rc == 0:
print("New pool with object path: %s" % result)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(result, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
if rc == 0:
print("Deleted pool with object path: %s" % result)
return (rc, message)
| Add some extra output for create and destroy. | Add some extra output for create and destroy.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
| Python | apache-2.0 | stratis-storage/stratis-cli,stratis-storage/stratis-cli | """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(_, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(_, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
return (rc, message)
Add some extra output for create and destroy.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com> | """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(result, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
if rc == 0:
print("New pool with object path: %s" % result)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(result, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
if rc == 0:
print("Deleted pool with object path: %s" % result)
return (rc, message)
| <commit_before>"""
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(_, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(_, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
return (rc, message)
<commit_msg>Add some extra output for create and destroy.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com><commit_after> | """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(result, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
if rc == 0:
print("New pool with object path: %s" % result)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(result, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
if rc == 0:
print("Deleted pool with object path: %s" % result)
return (rc, message)
| """
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(_, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(_, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
return (rc, message)
Add some extra output for create and destroy.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>"""
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(result, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
if rc == 0:
print("New pool with object path: %s" % result)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(result, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
if rc == 0:
print("Deleted pool with object path: %s" % result)
return (rc, message)
| <commit_before>"""
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(_, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(_, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
return (rc, message)
<commit_msg>Add some extra output for create and destroy.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com><commit_after>"""
Miscellaneous pool-level actions.
"""
from __future__ import print_function
from .._errors import StratisCliValueUnimplementedError
def create_pool(dbus_thing, namespace):
"""
Create a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
if namespace.redundancy != 'none':
raise StratisCliValueUnimplementedError(
namespace.redundancy,
"namespace.redundancy"
)
(result, rc, message) = dbus_thing.CreatePool(
namespace.name,
namespace.device,
len(namespace.device)
)
if rc == 0:
print("New pool with object path: %s" % result)
return (rc, message)
def list_pools(dbus_thing, namespace):
"""
List all stratis pools.
:param Interface dbus_thing: the interface to the stratis manager
"""
# pylint: disable=unused-argument
(result, rc, message) = dbus_thing.ListPools()
if rc != 0:
return (rc, message)
for item in result:
print(item)
return (rc, message)
def destroy_pool(dbus_thing, namespace):
"""
Destroy a stratis pool.
"""
if namespace.force:
raise StratisCliValueUnimplementedError(
namespace.force,
"namespace.force"
)
(result, rc, message) = dbus_thing.DestroyPool(
namespace.name
)
if rc == 0:
print("Deleted pool with object path: %s" % result)
return (rc, message)
|
ee9b869f2bb43e00da7c208cc2cfc9641d631b1a | examples/canvas/repeat_texture.py | examples/canvas/repeat_texture.py | '''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.properties import ObjectProperty
from kivy.lang import Builder
kv = '''
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
Label:
text: '{} (try to resize the window)'.format(root.size)
'''
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
| '''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder
kv = '''
<LabelOnBackground>:
canvas.before:
Color:
rgb: self.background
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
LabelOnBackground:
text: '{} (try to resize the window)'.format(root.size)
color: (0.4, 1, 1, 1)
background: (.3, .3, .3)
pos_hint: {'center_x': .5, 'center_y': .5 }
size_hint: None, None
height: 30
width: 250
'''
class LabelOnBackground(Label):
background = ListProperty((0.2, 0.2, 0.2))
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
| Add background color to size message. | Add background color to size message.
Added a colored background to the label because it kept getting lost in
the white ‘K’ field. Also changed the label color to cyan for
readability.
| Python | mit | jkankiewicz/kivy,bob-the-hamster/kivy,KeyWeeUsr/kivy,LogicalDash/kivy,ernstp/kivy,yoelk/kivy,jegger/kivy,LogicalDash/kivy,darkopevec/kivy,akshayaurora/kivy,gonzafirewall/kivy,rafalo1333/kivy,thezawad/kivy,bhargav2408/kivy,aron-bordin/kivy,Cheaterman/kivy,andnovar/kivy,MiyamotoAkira/kivy,youprofit/kivy,VinGarcia/kivy,el-ethan/kivy,xpndlabs/kivy,viralpandey/kivy,manashmndl/kivy,Farkal/kivy,el-ethan/kivy,xpndlabs/kivy,jkankiewicz/kivy,arcticshores/kivy,jffernandez/kivy,bionoid/kivy,matham/kivy,denys-duchier/kivy,xiaoyanit/kivy,MiyamotoAkira/kivy,adamkh/kivy,bliz937/kivy,xiaoyanit/kivy,jehutting/kivy,jffernandez/kivy,angryrancor/kivy,ernstp/kivy,MiyamotoAkira/kivy,Farkal/kivy,kivy/kivy,bhargav2408/kivy,Shyam10/kivy,adamkh/kivy,bob-the-hamster/kivy,jffernandez/kivy,rnixx/kivy,habibmasuro/kivy,aron-bordin/kivy,gonzafirewall/kivy,cbenhagen/kivy,arcticshores/kivy,dirkjot/kivy,gonzafirewall/kivy,habibmasuro/kivy,Ramalus/kivy,Shyam10/kivy,janssen/kivy,xpndlabs/kivy,denys-duchier/kivy,MiyamotoAkira/kivy,ernstp/kivy,bionoid/kivy,inclement/kivy,CuriousLearner/kivy,vitorio/kivy,jegger/kivy,manthansharma/kivy,janssen/kivy,jehutting/kivy,yoelk/kivy,inclement/kivy,vipulroxx/kivy,arlowhite/kivy,inclement/kivy,matham/kivy,Cheaterman/kivy,yoelk/kivy,cbenhagen/kivy,darkopevec/kivy,bionoid/kivy,Shyam10/kivy,jffernandez/kivy,darkopevec/kivy,adamkh/kivy,cbenhagen/kivy,angryrancor/kivy,matham/kivy,rafalo1333/kivy,jegger/kivy,autosportlabs/kivy,xiaoyanit/kivy,yoelk/kivy,dirkjot/kivy,thezawad/kivy,ernstp/kivy,CuriousLearner/kivy,habibmasuro/kivy,akshayaurora/kivy,Cheaterman/kivy,vipulroxx/kivy,bionoid/kivy,Cheaterman/kivy,jegger/kivy,autosportlabs/kivy,mSenyor/kivy,kived/kivy,Shyam10/kivy,dirkjot/kivy,vipulroxx/kivy,viralpandey/kivy,andnovar/kivy,andnovar/kivy,bliz937/kivy,manashmndl/kivy,Ramalus/kivy,kived/kivy,manashmndl/kivy,arcticshores/kivy,manthansharma/kivy,youprofit/kivy,el-ethan/kivy,akshayaurora/kivy,autosportlabs/kivy,tony/kivy,jkankiewicz/kivy,arcticshores/kivy,janssen/kivy,Farkal/kivy,angryrancor/kivy,VinGarcia/kivy,kivy/kivy,janssen/kivy,bliz937/kivy,tony/kivy,denys-duchier/kivy,mSenyor/kivy,CuriousLearner/kivy,manthansharma/kivy,vitorio/kivy,arlowhite/kivy,kivy/kivy,vipulroxx/kivy,denys-duchier/kivy,edubrunaldi/kivy,bob-the-hamster/kivy,dirkjot/kivy,viralpandey/kivy,adamkh/kivy,edubrunaldi/kivy,LogicalDash/kivy,manthansharma/kivy,darkopevec/kivy,jehutting/kivy,rnixx/kivy,aron-bordin/kivy,VinGarcia/kivy,KeyWeeUsr/kivy,rnixx/kivy,rafalo1333/kivy,matham/kivy,tony/kivy,Farkal/kivy,iamutkarshtiwari/kivy,angryrancor/kivy,iamutkarshtiwari/kivy,vitorio/kivy,thezawad/kivy,iamutkarshtiwari/kivy,aron-bordin/kivy,Ramalus/kivy,youprofit/kivy,arlowhite/kivy,KeyWeeUsr/kivy,jkankiewicz/kivy,KeyWeeUsr/kivy,mSenyor/kivy,LogicalDash/kivy,bob-the-hamster/kivy,gonzafirewall/kivy,bhargav2408/kivy,kived/kivy,edubrunaldi/kivy | '''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.properties import ObjectProperty
from kivy.lang import Builder
kv = '''
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
Label:
text: '{} (try to resize the window)'.format(root.size)
'''
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
Add background color to size message.
Added a colored background to the label because it kept getting lost in
the white ‘K’ field. Also changed the label color to cyan for
readability. | '''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder
kv = '''
<LabelOnBackground>:
canvas.before:
Color:
rgb: self.background
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
LabelOnBackground:
text: '{} (try to resize the window)'.format(root.size)
color: (0.4, 1, 1, 1)
background: (.3, .3, .3)
pos_hint: {'center_x': .5, 'center_y': .5 }
size_hint: None, None
height: 30
width: 250
'''
class LabelOnBackground(Label):
background = ListProperty((0.2, 0.2, 0.2))
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
| <commit_before>'''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.properties import ObjectProperty
from kivy.lang import Builder
kv = '''
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
Label:
text: '{} (try to resize the window)'.format(root.size)
'''
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
<commit_msg>Add background color to size message.
Added a colored background to the label because it kept getting lost in
the white ‘K’ field. Also changed the label color to cyan for
readability.<commit_after> | '''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder
kv = '''
<LabelOnBackground>:
canvas.before:
Color:
rgb: self.background
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
LabelOnBackground:
text: '{} (try to resize the window)'.format(root.size)
color: (0.4, 1, 1, 1)
background: (.3, .3, .3)
pos_hint: {'center_x': .5, 'center_y': .5 }
size_hint: None, None
height: 30
width: 250
'''
class LabelOnBackground(Label):
background = ListProperty((0.2, 0.2, 0.2))
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
| '''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.properties import ObjectProperty
from kivy.lang import Builder
kv = '''
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
Label:
text: '{} (try to resize the window)'.format(root.size)
'''
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
Add background color to size message.
Added a colored background to the label because it kept getting lost in
the white ‘K’ field. Also changed the label color to cyan for
readability.'''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder
kv = '''
<LabelOnBackground>:
canvas.before:
Color:
rgb: self.background
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
LabelOnBackground:
text: '{} (try to resize the window)'.format(root.size)
color: (0.4, 1, 1, 1)
background: (.3, .3, .3)
pos_hint: {'center_x': .5, 'center_y': .5 }
size_hint: None, None
height: 30
width: 250
'''
class LabelOnBackground(Label):
background = ListProperty((0.2, 0.2, 0.2))
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
| <commit_before>'''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.properties import ObjectProperty
from kivy.lang import Builder
kv = '''
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
Label:
text: '{} (try to resize the window)'.format(root.size)
'''
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
<commit_msg>Add background color to size message.
Added a colored background to the label because it kept getting lost in
the white ‘K’ field. Also changed the label color to cyan for
readability.<commit_after>'''
Demonstrate repeating textures
==============================
This was a test to fix an issue with repeating texture and window reloading.
'''
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder
kv = '''
<LabelOnBackground>:
canvas.before:
Color:
rgb: self.background
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
texture: app.texture
LabelOnBackground:
text: '{} (try to resize the window)'.format(root.size)
color: (0.4, 1, 1, 1)
background: (.3, .3, .3)
pos_hint: {'center_x': .5, 'center_y': .5 }
size_hint: None, None
height: 30
width: 250
'''
class LabelOnBackground(Label):
background = ListProperty((0.2, 0.2, 0.2))
class RepeatTexture(App):
texture = ObjectProperty()
def build(self):
self.texture = Image(source='mtexture1.png').texture
self.texture.wrap = 'repeat'
self.texture.uvsize = (8, 8)
return Builder.load_string(kv)
RepeatTexture().run()
|
bfc7a13439114313897526ea461f404539cc3fe5 | tests/test_publisher.py | tests/test_publisher.py | import gc
import sys
import warnings
import weakref
from lektor.publisher import Command
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
| import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
| Test that local rsync publishing works (with and w/o delete option) | Test that local rsync publishing works (with and w/o delete option)
This excercises #946
| Python | bsd-3-clause | lektor/lektor,lektor/lektor,lektor/lektor,lektor/lektor | import gc
import sys
import warnings
import weakref
from lektor.publisher import Command
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
Test that local rsync publishing works (with and w/o delete option)
This excercises #946 | import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
| <commit_before>import gc
import sys
import warnings
import weakref
from lektor.publisher import Command
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
<commit_msg>Test that local rsync publishing works (with and w/o delete option)
This excercises #946<commit_after> | import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
| import gc
import sys
import warnings
import weakref
from lektor.publisher import Command
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
Test that local rsync publishing works (with and w/o delete option)
This excercises #946import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
| <commit_before>import gc
import sys
import warnings
import weakref
from lektor.publisher import Command
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
<commit_msg>Test that local rsync publishing works (with and w/o delete option)
This excercises #946<commit_after>import gc
import os
import sys
import warnings
import weakref
import pytest
from lektor.publisher import Command
from lektor.publisher import publish
def test_Command_triggers_no_warnings():
# This excercises the issue where publishing via rsync resulted
# in ResourceWarnings about unclosed streams.
with warnings.catch_warnings():
warnings.simplefilter("error")
# This is essentially how RsyncPublisher runs rsync.
with Command([sys.executable, "-c", "print()"]) as client:
for _ in client:
pass
# The ResourceWarnings regarding unclosed files we are checking for
# are issued during finalization. Without this extra effort,
# finalization wouldn't happen until after the test completes.
client_is_alive = weakref.ref(client)
del client
if client_is_alive():
gc.collect()
if client_is_alive():
warnings.warn(
"Unable to trigger garbage collection of Command instance, "
"so unable to check for warnings issued during finalization."
)
@pytest.mark.parametrize("delete", ["yes", "no"])
def test_RsyncPublisher_integration(env, tmp_path, delete):
# Integration test of local rsync deployment
# Ensures that RsyncPublisher can successfully invoke rsync
files = {"file.txt": "content\n"}
output = tmp_path / "output"
output.mkdir()
for path, content in files.items():
output.joinpath(path).write_text(content)
target_path = tmp_path / "target"
target_path.mkdir()
target = f"rsync://{target_path.resolve()}?delete={delete}"
event_iter = publish(env, target, output)
for line in event_iter:
print(line)
target_files = {
os.fspath(_.relative_to(target_path)): _.read_text()
for _ in target_path.iterdir()
}
assert target_files == files
|
88e165ffb0ec856fcce4af57292bdb45dd6eecfc | thumbor/app.py | thumbor/app.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
# TODO Old handler to upload images
if context.config.UPLOAD_ENABLED:
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
if context.config.UPLOAD_ENABLED:
# TODO Old handler to upload images
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
| Disable REST Upload by default | Disable REST Upload by default
| Python | mit | marcelometal/thumbor,Jimdo/thumbor,2947721120/thumbor,BetterCollective/thumbor,scorphus/thumbor,adeboisanger/thumbor,adeboisanger/thumbor,wking/thumbor,gselva/thumbor,davduran/thumbor,gi11es/thumbor,gselva/thumbor,camargoanderso/thumbor,camargoanderso/thumbor,abaldwin1/thumbor,wking/thumbor,gselva/thumbor,2947721120/thumbor,jiangzhonghui/thumbor,raphaelfruneaux/thumbor,jdunaravich/thumbor,scorphus/thumbor,Bladrak/thumbor,davduran/thumbor,voxmedia/thumbor,fanhero/thumbor,kkopachev/thumbor,2947721120/thumbor,marcelometal/thumbor,food52/thumbor,Jimdo/thumbor,kkopachev/thumbor,marcelometal/thumbor,aaxx/thumbor,felipemorais/thumbor,figarocms/thumbor,BetterCollective/thumbor,lfalcao/thumbor,okor/thumbor,jdunaravich/thumbor,kkopachev/thumbor,grevutiu-gabriel/thumbor,MaTriXy/thumbor,felipemorais/thumbor,scorphus/thumbor,scorphus/thumbor,MaTriXy/thumbor,fanhero/thumbor,suwaji/thumbor,jiangzhonghui/thumbor,fanhero/thumbor,davduran/thumbor,thumbor/thumbor,raphaelfruneaux/thumbor,felipemorais/thumbor,MaTriXy/thumbor,Bladrak/thumbor,gselva/thumbor,figarocms/thumbor,felipemorais/thumbor,dhardy92/thumbor,grevutiu-gabriel/thumbor,MaTriXy/thumbor,jdunaravich/thumbor,2947721120/thumbor,lfalcao/thumbor,aaxx/thumbor,abaldwin1/thumbor,figarocms/thumbor,food52/thumbor,thumbor/thumbor,kkopachev/thumbor,suwaji/thumbor,wking/thumbor,suwaji/thumbor,jiangzhonghui/thumbor,Jimdo/thumbor,dhardy92/thumbor,food52/thumbor,abaldwin1/thumbor,suwaji/thumbor,wking/thumbor,figarocms/thumbor,lfalcao/thumbor,BetterCollective/thumbor,voxmedia/thumbor,thumbor/thumbor,aaxx/thumbor,okor/thumbor,gi11es/thumbor,aaxx/thumbor,davduran/thumbor,grevutiu-gabriel/thumbor,okor/thumbor,dhardy92/thumbor,raphaelfruneaux/thumbor,voxmedia/thumbor,Jimdo/thumbor,jiangzhonghui/thumbor,camargoanderso/thumbor,camargoanderso/thumbor,jdunaravich/thumbor,thumbor/thumbor,adeboisanger/thumbor,grevutiu-gabriel/thumbor,fanhero/thumbor,gi11es/thumbor,raphaelfruneaux/thumbor,lfalcao/thumbor,abaldwin1/thumbor,adeboisanger/thumbor,food52/thumbor | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
# TODO Old handler to upload images
if context.config.UPLOAD_ENABLED:
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
Disable REST Upload by default | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
if context.config.UPLOAD_ENABLED:
# TODO Old handler to upload images
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
# TODO Old handler to upload images
if context.config.UPLOAD_ENABLED:
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
<commit_msg>Disable REST Upload by default<commit_after> | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
if context.config.UPLOAD_ENABLED:
# TODO Old handler to upload images
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
# TODO Old handler to upload images
if context.config.UPLOAD_ENABLED:
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
Disable REST Upload by default#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
if context.config.UPLOAD_ENABLED:
# TODO Old handler to upload images
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
# TODO Old handler to upload images
if context.config.UPLOAD_ENABLED:
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
<commit_msg>Disable REST Upload by default<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
if context.config.UPLOAD_ENABLED:
# TODO Old handler to upload images
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
|
37bb334a1c59920d92649b0cedddf62863bf6da8 | scipy/weave/tests/test_inline_tools.py | scipy/weave/tests/test_inline_tools.py | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
try:
a = 1
result = inline_tools.inline(code,['a'])
assert(1) # should've thrown a ValueError
except ValueError:
pass
from distutils.errors import DistutilsError, CompileError
try:
a = 'string'
result = inline_tools.inline(code,['a'])
assert(1) # should've gotten an error
except:
# ?CompileError is the error reported, but catching it doesn't work
pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
| from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
| Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite. | Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.
| Python | bsd-3-clause | kalvdans/scipy,chatcannon/scipy,trankmichael/scipy,ilayn/scipy,jsilter/scipy,tylerjereddy/scipy,mikebenfield/scipy,minhlongdo/scipy,trankmichael/scipy,WillieMaddox/scipy,piyush0609/scipy,surhudm/scipy,Dapid/scipy,chatcannon/scipy,grlee77/scipy,vanpact/scipy,Kamp9/scipy,Srisai85/scipy,ilayn/scipy,dch312/scipy,chatcannon/scipy,kleskjr/scipy,gef756/scipy,ndchorley/scipy,Shaswat27/scipy,woodscn/scipy,jjhelmus/scipy,cpaulik/scipy,anielsen001/scipy,mortada/scipy,njwilson23/scipy,lukauskas/scipy,anntzer/scipy,zerothi/scipy,aman-iitj/scipy,ChanderG/scipy,befelix/scipy,vhaasteren/scipy,arokem/scipy,pizzathief/scipy,trankmichael/scipy,sriki18/scipy,maniteja123/scipy,ChanderG/scipy,pyramania/scipy,sargas/scipy,e-q/scipy,rgommers/scipy,jakevdp/scipy,Dapid/scipy,maciejkula/scipy,gdooper/scipy,Newman101/scipy,ChanderG/scipy,larsmans/scipy,giorgiop/scipy,petebachant/scipy,WillieMaddox/scipy,jonycgn/scipy,WarrenWeckesser/scipy,fernand/scipy,kalvdans/scipy,Eric89GXL/scipy,perimosocordiae/scipy,pizzathief/scipy,sonnyhu/scipy,jonycgn/scipy,apbard/scipy,aeklant/scipy,sonnyhu/scipy,mhogg/scipy,niknow/scipy,anielsen001/scipy,matthew-brett/scipy,endolith/scipy,andim/scipy,ortylp/scipy,vberaudi/scipy,futurulus/scipy,jsilter/scipy,mortada/scipy,sauliusl/scipy,vberaudi/scipy,jjhelmus/scipy,felipebetancur/scipy,pnedunuri/scipy,Kamp9/scipy,ales-erjavec/scipy,zxsted/scipy,sriki18/scipy,vberaudi/scipy,FRidh/scipy,sargas/scipy,pnedunuri/scipy,mgaitan/scipy,haudren/scipy,hainm/scipy,tylerjereddy/scipy,nonhermitian/scipy,pbrod/scipy,gertingold/scipy,teoliphant/scipy,vhaasteren/scipy,kleskjr/scipy,woodscn/scipy,jor-/scipy,newemailjdm/scipy,grlee77/scipy,hainm/scipy,chatcannon/scipy,gdooper/scipy,sonnyhu/scipy,dominicelse/scipy,fernand/scipy,mhogg/scipy,nonhermitian/scipy,sonnyhu/scipy,rgommers/scipy,FRidh/scipy,piyush0609/scipy,cpaulik/scipy,cpaulik/scipy,arokem/scipy,gef756/scipy,bkendzior/scipy,vanpact/scipy,njwilson23/scipy,ogrisel/scipy,raoulbq/scipy,vanpact/scipy,mortonjt/scipy,mgaitan/scipy,jjhelmus/scipy,ilayn/scipy,pyramania/scipy,matthew-brett/scipy,surhudm/scipy,hainm/scipy,FRidh/scipy,jonycgn/scipy,endolith/scipy,behzadnouri/scipy,richardotis/scipy,e-q/scipy,gdooper/scipy,jseabold/scipy,pizzathief/scipy,WillieMaddox/scipy,aarchiba/scipy,dch312/scipy,futurulus/scipy,lukauskas/scipy,pyramania/scipy,aeklant/scipy,giorgiop/scipy,felipebetancur/scipy,gef756/scipy,pnedunuri/scipy,jamestwebber/scipy,mortonjt/scipy,witcxc/scipy,Eric89GXL/scipy,mtrbean/scipy,andyfaff/scipy,argriffing/scipy,fernand/scipy,fredrikw/scipy,haudren/scipy,surhudm/scipy,Shaswat27/scipy,kleskjr/scipy,person142/scipy,jor-/scipy,aeklant/scipy,perimosocordiae/scipy,newemailjdm/scipy,juliantaylor/scipy,Shaswat27/scipy,maniteja123/scipy,surhudm/scipy,mingwpy/scipy,zxsted/scipy,jamestwebber/scipy,perimosocordiae/scipy,ilayn/scipy,argriffing/scipy,zxsted/scipy,anielsen001/scipy,fredrikw/scipy,felipebetancur/scipy,Kamp9/scipy,gdooper/scipy,petebachant/scipy,chatcannon/scipy,Dapid/scipy,behzadnouri/scipy,witcxc/scipy,teoliphant/scipy,vigna/scipy,FRidh/scipy,scipy/scipy,josephcslater/scipy,zerothi/scipy,efiring/scipy,raoulbq/scipy,rmcgibbo/scipy,mtrbean/scipy,nonhermitian/scipy,chatcannon/scipy,anntzer/scipy,cpaulik/scipy,kleskjr/scipy,pnedunuri/scipy,mhogg/scipy,juliantaylor/scipy,woodscn/scipy,befelix/scipy,jakevdp/scipy,zaxliu/scipy,maciejkula/scipy,scipy/scipy,petebachant/scipy,scipy/scipy,giorgiop/scipy,larsmans/scipy,nvoron23/scipy,Shaswat27/scipy,mtrbean/scipy,Newman101/scipy,lhilt/scipy,Gillu13/scipy,endolith/scipy,felipebetancur/scipy,efiring/scipy,raoulbq/scipy,aarchiba/scipy,ogrisel/scipy,trankmichael/scipy,niknow/scipy,richardotis/scipy,mortonjt/scipy,jonycgn/scipy,matthewalbani/scipy,Gillu13/scipy,WillieMaddox/scipy,nvoron23/scipy,zerothi/scipy,dominicelse/scipy,perimosocordiae/scipy,aman-iitj/scipy,kleskjr/scipy,vanpact/scipy,jor-/scipy,person142/scipy,befelix/scipy,Gillu13/scipy,vigna/scipy,aman-iitj/scipy,jjhelmus/scipy,pschella/scipy,argriffing/scipy,anielsen001/scipy,sauliusl/scipy,tylerjereddy/scipy,vanpact/scipy,aarchiba/scipy,Stefan-Endres/scipy,zxsted/scipy,Eric89GXL/scipy,pbrod/scipy,ogrisel/scipy,jsilter/scipy,scipy/scipy,vanpact/scipy,Newman101/scipy,sargas/scipy,rmcgibbo/scipy,vberaudi/scipy,jamestwebber/scipy,ndchorley/scipy,lukauskas/scipy,pnedunuri/scipy,larsmans/scipy,Kamp9/scipy,mtrbean/scipy,grlee77/scipy,andim/scipy,newemailjdm/scipy,gdooper/scipy,andim/scipy,FRidh/scipy,josephcslater/scipy,newemailjdm/scipy,Kamp9/scipy,haudren/scipy,anielsen001/scipy,jseabold/scipy,richardotis/scipy,arokem/scipy,gfyoung/scipy,anielsen001/scipy,vhaasteren/scipy,vhaasteren/scipy,dominicelse/scipy,ChanderG/scipy,nmayorov/scipy,tylerjereddy/scipy,matthew-brett/scipy,jseabold/scipy,mingwpy/scipy,apbard/scipy,Stefan-Endres/scipy,person142/scipy,Kamp9/scipy,jonycgn/scipy,arokem/scipy,mdhaber/scipy,witcxc/scipy,jsilter/scipy,hainm/scipy,hainm/scipy,mgaitan/scipy,pyramania/scipy,sonnyhu/scipy,WarrenWeckesser/scipy,perimosocordiae/scipy,ogrisel/scipy,mikebenfield/scipy,ndchorley/scipy,maniteja123/scipy,pbrod/scipy,mortonjt/scipy,andyfaff/scipy,Gillu13/scipy,matthewalbani/scipy,rmcgibbo/scipy,ChanderG/scipy,mgaitan/scipy,argriffing/scipy,zerothi/scipy,mdhaber/scipy,Stefan-Endres/scipy,richardotis/scipy,cpaulik/scipy,fredrikw/scipy,piyush0609/scipy,fredrikw/scipy,Gillu13/scipy,trankmichael/scipy,niknow/scipy,andyfaff/scipy,WillieMaddox/scipy,lukauskas/scipy,nvoron23/scipy,sriki18/scipy,minhlongdo/scipy,aeklant/scipy,e-q/scipy,rmcgibbo/scipy,pschella/scipy,ales-erjavec/scipy,lhilt/scipy,mdhaber/scipy,mingwpy/scipy,witcxc/scipy,niknow/scipy,piyush0609/scipy,anntzer/scipy,mortonjt/scipy,kalvdans/scipy,jor-/scipy,sauliusl/scipy,aman-iitj/scipy,jjhelmus/scipy,ortylp/scipy,behzadnouri/scipy,surhudm/scipy,njwilson23/scipy,mdhaber/scipy,lhilt/scipy,teoliphant/scipy,gertingold/scipy,gfyoung/scipy,pizzathief/scipy,josephcslater/scipy,dominicelse/scipy,anntzer/scipy,giorgiop/scipy,andim/scipy,andyfaff/scipy,mortada/scipy,e-q/scipy,vhaasteren/scipy,aarchiba/scipy,teoliphant/scipy,Eric89GXL/scipy,maniteja123/scipy,dch312/scipy,newemailjdm/scipy,efiring/scipy,gef756/scipy,lukauskas/scipy,zaxliu/scipy,Shaswat27/scipy,zaxliu/scipy,Dapid/scipy,surhudm/scipy,minhlongdo/scipy,ales-erjavec/scipy,sonnyhu/scipy,endolith/scipy,mtrbean/scipy,rmcgibbo/scipy,lukauskas/scipy,dominicelse/scipy,behzadnouri/scipy,Shaswat27/scipy,richardotis/scipy,endolith/scipy,Srisai85/scipy,argriffing/scipy,rgommers/scipy,ogrisel/scipy,woodscn/scipy,behzadnouri/scipy,mingwpy/scipy,aman-iitj/scipy,mhogg/scipy,jsilter/scipy,mingwpy/scipy,jonycgn/scipy,Eric89GXL/scipy,mortada/scipy,dch312/scipy,giorgiop/scipy,sriki18/scipy,Srisai85/scipy,jseabold/scipy,sargas/scipy,nmayorov/scipy,Srisai85/scipy,mikebenfield/scipy,efiring/scipy,apbard/scipy,zaxliu/scipy,pizzathief/scipy,grlee77/scipy,pbrod/scipy,minhlongdo/scipy,matthewalbani/scipy,Eric89GXL/scipy,woodscn/scipy,jakevdp/scipy,gef756/scipy,hainm/scipy,WillieMaddox/scipy,teoliphant/scipy,juliantaylor/scipy,newemailjdm/scipy,behzadnouri/scipy,vberaudi/scipy,jakevdp/scipy,kalvdans/scipy,vigna/scipy,andyfaff/scipy,njwilson23/scipy,ortylp/scipy,argriffing/scipy,futurulus/scipy,WarrenWeckesser/scipy,maciejkula/scipy,mortada/scipy,richardotis/scipy,efiring/scipy,nvoron23/scipy,jakevdp/scipy,maciejkula/scipy,vigna/scipy,zaxliu/scipy,juliantaylor/scipy,maniteja123/scipy,ilayn/scipy,aeklant/scipy,befelix/scipy,nvoron23/scipy,Stefan-Endres/scipy,ortylp/scipy,mdhaber/scipy,njwilson23/scipy,Newman101/scipy,josephcslater/scipy,minhlongdo/scipy,sriki18/scipy,FRidh/scipy,Stefan-Endres/scipy,jor-/scipy,pnedunuri/scipy,WarrenWeckesser/scipy,kleskjr/scipy,befelix/scipy,sargas/scipy,sriki18/scipy,zerothi/scipy,gfyoung/scipy,tylerjereddy/scipy,gef756/scipy,Srisai85/scipy,mortada/scipy,ilayn/scipy,pschella/scipy,nmayorov/scipy,felipebetancur/scipy,nmayorov/scipy,mhogg/scipy,gertingold/scipy,matthewalbani/scipy,bkendzior/scipy,larsmans/scipy,arokem/scipy,jseabold/scipy,person142/scipy,bkendzior/scipy,futurulus/scipy,matthewalbani/scipy,anntzer/scipy,rgommers/scipy,mingwpy/scipy,Gillu13/scipy,larsmans/scipy,nonhermitian/scipy,vhaasteren/scipy,aman-iitj/scipy,larsmans/scipy,vberaudi/scipy,andim/scipy,Newman101/scipy,njwilson23/scipy,Srisai85/scipy,cpaulik/scipy,aarchiba/scipy,jseabold/scipy,haudren/scipy,WarrenWeckesser/scipy,kalvdans/scipy,ndchorley/scipy,zaxliu/scipy,gfyoung/scipy,fernand/scipy,mikebenfield/scipy,woodscn/scipy,maniteja123/scipy,person142/scipy,raoulbq/scipy,niknow/scipy,mgaitan/scipy,maciejkula/scipy,matthew-brett/scipy,Dapid/scipy,ndchorley/scipy,ales-erjavec/scipy,zerothi/scipy,endolith/scipy,fredrikw/scipy,vigna/scipy,zxsted/scipy,futurulus/scipy,gertingold/scipy,jamestwebber/scipy,anntzer/scipy,matthew-brett/scipy,perimosocordiae/scipy,efiring/scipy,andyfaff/scipy,pschella/scipy,pschella/scipy,sauliusl/scipy,fredrikw/scipy,gfyoung/scipy,petebachant/scipy,mikebenfield/scipy,rgommers/scipy,fernand/scipy,scipy/scipy,bkendzior/scipy,nonhermitian/scipy,fernand/scipy,zxsted/scipy,mgaitan/scipy,petebachant/scipy,mhogg/scipy,grlee77/scipy,mortonjt/scipy,futurulus/scipy,nvoron23/scipy,sauliusl/scipy,WarrenWeckesser/scipy,pyramania/scipy,bkendzior/scipy,lhilt/scipy,haudren/scipy,apbard/scipy,ales-erjavec/scipy,pbrod/scipy,ortylp/scipy,ChanderG/scipy,andim/scipy,Dapid/scipy,juliantaylor/scipy,apbard/scipy,ales-erjavec/scipy,lhilt/scipy,ndchorley/scipy,raoulbq/scipy,haudren/scipy,nmayorov/scipy,piyush0609/scipy,sauliusl/scipy,mdhaber/scipy,minhlongdo/scipy,piyush0609/scipy,Stefan-Endres/scipy,jamestwebber/scipy,witcxc/scipy,dch312/scipy,gertingold/scipy,raoulbq/scipy,felipebetancur/scipy,niknow/scipy,e-q/scipy,pbrod/scipy,josephcslater/scipy,ortylp/scipy,rmcgibbo/scipy,petebachant/scipy,scipy/scipy,trankmichael/scipy,Newman101/scipy,mtrbean/scipy,giorgiop/scipy | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
try:
a = 1
result = inline_tools.inline(code,['a'])
assert(1) # should've thrown a ValueError
except ValueError:
pass
from distutils.errors import DistutilsError, CompileError
try:
a = 'string'
result = inline_tools.inline(code,['a'])
assert(1) # should've gotten an error
except:
# ?CompileError is the error reported, but catching it doesn't work
pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite. | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
| <commit_before>from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
try:
a = 1
result = inline_tools.inline(code,['a'])
assert(1) # should've thrown a ValueError
except ValueError:
pass
from distutils.errors import DistutilsError, CompileError
try:
a = 'string'
result = inline_tools.inline(code,['a'])
assert(1) # should've gotten an error
except:
# ?CompileError is the error reported, but catching it doesn't work
pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
<commit_msg>Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.<commit_after> | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
| from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
try:
a = 1
result = inline_tools.inline(code,['a'])
assert(1) # should've thrown a ValueError
except ValueError:
pass
from distutils.errors import DistutilsError, CompileError
try:
a = 'string'
result = inline_tools.inline(code,['a'])
assert(1) # should've gotten an error
except:
# ?CompileError is the error reported, but catching it doesn't work
pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
| <commit_before>from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
try:
a = 1
result = inline_tools.inline(code,['a'])
assert(1) # should've thrown a ValueError
except ValueError:
pass
from distutils.errors import DistutilsError, CompileError
try:
a = 'string'
result = inline_tools.inline(code,['a'])
assert(1) # should've gotten an error
except:
# ?CompileError is the error reported, but catching it doesn't work
pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
<commit_msg>Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.<commit_after>from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
10ea9d7e542807e064e36b5f9ce8bccd32990fb4 | app.py | app.py | import requests
from flask import Flask, render_template
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
@app.route("/<source>")
def index(source="bbc"):
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run() | import requests
from flask import Flask, render_template, request
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
def index():
query = request.args.get("source")
if query is None or query.lower() not in sources.keys():
source = "bbc"
else:
source = query.lower()
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run() | Use GET request arguments to determine the news source. | Use GET request arguments to determine the news source.
| Python | mit | alchermd/headlines,alchermd/headlines | import requests
from flask import Flask, render_template
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
@app.route("/<source>")
def index(source="bbc"):
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run()Use GET request arguments to determine the news source. | import requests
from flask import Flask, render_template, request
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
def index():
query = request.args.get("source")
if query is None or query.lower() not in sources.keys():
source = "bbc"
else:
source = query.lower()
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run() | <commit_before>import requests
from flask import Flask, render_template
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
@app.route("/<source>")
def index(source="bbc"):
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run()<commit_msg>Use GET request arguments to determine the news source.<commit_after> | import requests
from flask import Flask, render_template, request
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
def index():
query = request.args.get("source")
if query is None or query.lower() not in sources.keys():
source = "bbc"
else:
source = query.lower()
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run() | import requests
from flask import Flask, render_template
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
@app.route("/<source>")
def index(source="bbc"):
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run()Use GET request arguments to determine the news source.import requests
from flask import Flask, render_template, request
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
def index():
query = request.args.get("source")
if query is None or query.lower() not in sources.keys():
source = "bbc"
else:
source = query.lower()
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run() | <commit_before>import requests
from flask import Flask, render_template
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
@app.route("/<source>")
def index(source="bbc"):
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run()<commit_msg>Use GET request arguments to determine the news source.<commit_after>import requests
from flask import Flask, render_template, request
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("appconfig.py")
sources = {
"bbc": "bbc-news",
"cnn": "cnn",
"hackernews": "hacker-news"
}
def create_link(source):
if source in sources.keys():
return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}"
@app.route("/")
def index():
query = request.args.get("source")
if query is None or query.lower() not in sources.keys():
source = "bbc"
else:
source = query.lower()
r = requests.get(create_link(source))
return render_template("index.html", articles=r.json().get("articles"), source=source)
if __name__ == "__main__":
app.run() |
1ca86b0d7ca23adcc6a5cb925b00d8c8925ed8cc | app.py | app.py | import sys
import asyncio
import telepot
from telepot.delegate import per_chat_id
from telepot.async.delegate import create_open
"""
$ python3.4 countera.py <token>
Count number of messages. Start over if silent for 10 seconds.
"""
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(MessageCounter, self).__init__(seed_tuple, timeout)
self._count = 0
@asyncio.coroutine
def on_message(self, msg):
self._count += 1
yield from self.sender.sendMessage(self._count)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.async.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageCounter, timeout=10)),
])
loop = asyncio.get_event_loop()
loop.create_task(bot.messageLoop())
print('Listening ...')
loop.run_forever() | """
import sys
import time
import random
import datetime
"""
import telepot
from telepot.delegate import per_chat_id, create_open
class VeryCruel(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(VeryCruel, self).__init__(seed_tuple,timeout)
def reply_to_serjant(self,m):
self.sender.sendMessage('Сообщение получено от %s c id %s' % (m.from_, m.from_.id))
def on_message(self, msg):
content_type, chat_type, chat_id = telepot.glance2(msg)
m = telepot.namedtuple(msg, 'Message')
if chat_id < 0:
# public chat
self.reply_to_serjant(m)
else:
# private conversation
if content_type == 'text':
if 'хуй' in m.text:
self.sender.sendMessage('НЕ МАТЕРИСЬ, ПИДАРАС!', reply_to_message_id=m.message_id)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(VeryCruel, timeout=15)),
])
bot.notifyOnMessage(run_forever=True)
| Rewrite bot to answer private or public messages | Rewrite bot to answer private or public messages
| Python | mit | vasua/verycruelbot | import sys
import asyncio
import telepot
from telepot.delegate import per_chat_id
from telepot.async.delegate import create_open
"""
$ python3.4 countera.py <token>
Count number of messages. Start over if silent for 10 seconds.
"""
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(MessageCounter, self).__init__(seed_tuple, timeout)
self._count = 0
@asyncio.coroutine
def on_message(self, msg):
self._count += 1
yield from self.sender.sendMessage(self._count)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.async.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageCounter, timeout=10)),
])
loop = asyncio.get_event_loop()
loop.create_task(bot.messageLoop())
print('Listening ...')
loop.run_forever()Rewrite bot to answer private or public messages | """
import sys
import time
import random
import datetime
"""
import telepot
from telepot.delegate import per_chat_id, create_open
class VeryCruel(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(VeryCruel, self).__init__(seed_tuple,timeout)
def reply_to_serjant(self,m):
self.sender.sendMessage('Сообщение получено от %s c id %s' % (m.from_, m.from_.id))
def on_message(self, msg):
content_type, chat_type, chat_id = telepot.glance2(msg)
m = telepot.namedtuple(msg, 'Message')
if chat_id < 0:
# public chat
self.reply_to_serjant(m)
else:
# private conversation
if content_type == 'text':
if 'хуй' in m.text:
self.sender.sendMessage('НЕ МАТЕРИСЬ, ПИДАРАС!', reply_to_message_id=m.message_id)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(VeryCruel, timeout=15)),
])
bot.notifyOnMessage(run_forever=True)
| <commit_before>import sys
import asyncio
import telepot
from telepot.delegate import per_chat_id
from telepot.async.delegate import create_open
"""
$ python3.4 countera.py <token>
Count number of messages. Start over if silent for 10 seconds.
"""
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(MessageCounter, self).__init__(seed_tuple, timeout)
self._count = 0
@asyncio.coroutine
def on_message(self, msg):
self._count += 1
yield from self.sender.sendMessage(self._count)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.async.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageCounter, timeout=10)),
])
loop = asyncio.get_event_loop()
loop.create_task(bot.messageLoop())
print('Listening ...')
loop.run_forever()<commit_msg>Rewrite bot to answer private or public messages<commit_after> | """
import sys
import time
import random
import datetime
"""
import telepot
from telepot.delegate import per_chat_id, create_open
class VeryCruel(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(VeryCruel, self).__init__(seed_tuple,timeout)
def reply_to_serjant(self,m):
self.sender.sendMessage('Сообщение получено от %s c id %s' % (m.from_, m.from_.id))
def on_message(self, msg):
content_type, chat_type, chat_id = telepot.glance2(msg)
m = telepot.namedtuple(msg, 'Message')
if chat_id < 0:
# public chat
self.reply_to_serjant(m)
else:
# private conversation
if content_type == 'text':
if 'хуй' in m.text:
self.sender.sendMessage('НЕ МАТЕРИСЬ, ПИДАРАС!', reply_to_message_id=m.message_id)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(VeryCruel, timeout=15)),
])
bot.notifyOnMessage(run_forever=True)
| import sys
import asyncio
import telepot
from telepot.delegate import per_chat_id
from telepot.async.delegate import create_open
"""
$ python3.4 countera.py <token>
Count number of messages. Start over if silent for 10 seconds.
"""
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(MessageCounter, self).__init__(seed_tuple, timeout)
self._count = 0
@asyncio.coroutine
def on_message(self, msg):
self._count += 1
yield from self.sender.sendMessage(self._count)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.async.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageCounter, timeout=10)),
])
loop = asyncio.get_event_loop()
loop.create_task(bot.messageLoop())
print('Listening ...')
loop.run_forever()Rewrite bot to answer private or public messages"""
import sys
import time
import random
import datetime
"""
import telepot
from telepot.delegate import per_chat_id, create_open
class VeryCruel(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(VeryCruel, self).__init__(seed_tuple,timeout)
def reply_to_serjant(self,m):
self.sender.sendMessage('Сообщение получено от %s c id %s' % (m.from_, m.from_.id))
def on_message(self, msg):
content_type, chat_type, chat_id = telepot.glance2(msg)
m = telepot.namedtuple(msg, 'Message')
if chat_id < 0:
# public chat
self.reply_to_serjant(m)
else:
# private conversation
if content_type == 'text':
if 'хуй' in m.text:
self.sender.sendMessage('НЕ МАТЕРИСЬ, ПИДАРАС!', reply_to_message_id=m.message_id)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(VeryCruel, timeout=15)),
])
bot.notifyOnMessage(run_forever=True)
| <commit_before>import sys
import asyncio
import telepot
from telepot.delegate import per_chat_id
from telepot.async.delegate import create_open
"""
$ python3.4 countera.py <token>
Count number of messages. Start over if silent for 10 seconds.
"""
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(MessageCounter, self).__init__(seed_tuple, timeout)
self._count = 0
@asyncio.coroutine
def on_message(self, msg):
self._count += 1
yield from self.sender.sendMessage(self._count)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.async.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageCounter, timeout=10)),
])
loop = asyncio.get_event_loop()
loop.create_task(bot.messageLoop())
print('Listening ...')
loop.run_forever()<commit_msg>Rewrite bot to answer private or public messages<commit_after>"""
import sys
import time
import random
import datetime
"""
import telepot
from telepot.delegate import per_chat_id, create_open
class VeryCruel(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(VeryCruel, self).__init__(seed_tuple,timeout)
def reply_to_serjant(self,m):
self.sender.sendMessage('Сообщение получено от %s c id %s' % (m.from_, m.from_.id))
def on_message(self, msg):
content_type, chat_type, chat_id = telepot.glance2(msg)
m = telepot.namedtuple(msg, 'Message')
if chat_id < 0:
# public chat
self.reply_to_serjant(m)
else:
# private conversation
if content_type == 'text':
if 'хуй' in m.text:
self.sender.sendMessage('НЕ МАТЕРИСЬ, ПИДАРАС!', reply_to_message_id=m.message_id)
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(VeryCruel, timeout=15)),
])
bot.notifyOnMessage(run_forever=True)
|
0de818d8ff2aa77fc172199226aea3abffa7f3b1 | bot.py | bot.py | from discord.ext.commands import Bot
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if hasattr(exception, 'original'):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
| from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if isinstance(exception, CommandInvokeError):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
| Change hasattr check to isinstance check because it's faster. | Change hasattr check to isinstance check because it's faster.
| Python | mit | BeatButton/beattie,BeatButton/beattie-bot | from discord.ext.commands import Bot
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if hasattr(exception, 'original'):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
Change hasattr check to isinstance check because it's faster. | from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if isinstance(exception, CommandInvokeError):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
| <commit_before>from discord.ext.commands import Bot
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if hasattr(exception, 'original'):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
<commit_msg>Change hasattr check to isinstance check because it's faster.<commit_after> | from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if isinstance(exception, CommandInvokeError):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
| from discord.ext.commands import Bot
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if hasattr(exception, 'original'):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
Change hasattr check to isinstance check because it's faster.from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if isinstance(exception, CommandInvokeError):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
| <commit_before>from discord.ext.commands import Bot
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if hasattr(exception, 'original'):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
<commit_msg>Change hasattr check to isinstance check because it's faster.<commit_after>from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, exception, ctx):
if isinstance(exception, MissingRequiredArgument):
await ctx.send('Missing required arguments.')
elif not isinstance(exception, CommandNotFound):
await ctx.send('Generic error handler triggered. '
'This should never happen.')
if isinstance(exception, CommandInvokeError):
exception = exception.original
raise exception
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
msg = message.content.split(None, 1)
msg[0] = msg[0].lower()
message.content = ' '.join(msg)
await self.process_commands(message)
async def on_command_error(self, exception, ctx):
if ctx.command is None or not hasattr(ctx.command, 'on_error'):
await self.handle_error(exception, ctx)
|
60fc1add06ffb54aff2b0bf1c28d0cb476d35aae | polling_stations/settings/local.example.py | polling_stations/settings/local.example.py | DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
| DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| Send email to console as local default | Send email to console as local default
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
Send email to console as local default | DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| <commit_before>DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
<commit_msg>Send email to console as local default<commit_after> | DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
Send email to console as local defaultDATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| <commit_before>DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
<commit_msg>Send email to console as local default<commit_after>DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "polling_stations",
"USER": "postgres",
"PASSWORD": "",
"HOST": "", # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
"PORT": "", # Set to empty string for default.
}
}
EVERY_ELECTION = {"CHECK": False, "HAS_ELECTION": True}
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
9f83315c1be0268836a3a10fade9ba832d614e79 | regserver/regulations/tests/views_sidebar_tests.py | regserver/regulations/tests/views_sidebar_tests.py | import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['doc1', '1111-1']},
{'reference': ['doc2', '1111-1']},
],
'1111-1-a': [{'reference': ['doc1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
| import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['1992-1', '1111-1']},
{'reference': ['1992-2', '1111-1']},
],
'1111-1-a': [{'reference': ['1992-1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
self.assertTrue('1992-2' in response.content)
self.assertTrue('1111-1' in response.content)
self.assertTrue('1992-1' in response.content)
self.assertTrue('1111-1-a' in response.content)
| Use a 'valid' doc number | Use a 'valid' doc number
| Python | cc0-1.0 | tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,grapesmoker/regulations-site,grapesmoker/regulations-site,jeremiak/regulations-site,eregs/regulations-site,ascott1/regulations-site,18F/regulations-site,grapesmoker/regulations-site,18F/regulations-site,eregs/regulations-site,eregs/regulations-site,ascott1/regulations-site,EricSchles/regulations-site,adderall/regulations-site,EricSchles/regulations-site,jeremiak/regulations-site,EricSchles/regulations-site,tadhg-ohiggins/regulations-site,adderall/regulations-site,willbarton/regulations-site,tadhg-ohiggins/regulations-site,ascott1/regulations-site,adderall/regulations-site,ascott1/regulations-site,willbarton/regulations-site,18F/regulations-site,18F/regulations-site,grapesmoker/regulations-site,willbarton/regulations-site,willbarton/regulations-site,jeremiak/regulations-site,eregs/regulations-site,jeremiak/regulations-site,adderall/regulations-site,EricSchles/regulations-site | import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['doc1', '1111-1']},
{'reference': ['doc2', '1111-1']},
],
'1111-1-a': [{'reference': ['doc1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
Use a 'valid' doc number | import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['1992-1', '1111-1']},
{'reference': ['1992-2', '1111-1']},
],
'1111-1-a': [{'reference': ['1992-1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
self.assertTrue('1992-2' in response.content)
self.assertTrue('1111-1' in response.content)
self.assertTrue('1992-1' in response.content)
self.assertTrue('1111-1-a' in response.content)
| <commit_before>import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['doc1', '1111-1']},
{'reference': ['doc2', '1111-1']},
],
'1111-1-a': [{'reference': ['doc1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
<commit_msg>Use a 'valid' doc number<commit_after> | import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['1992-1', '1111-1']},
{'reference': ['1992-2', '1111-1']},
],
'1111-1-a': [{'reference': ['1992-1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
self.assertTrue('1992-2' in response.content)
self.assertTrue('1111-1' in response.content)
self.assertTrue('1992-1' in response.content)
self.assertTrue('1111-1-a' in response.content)
| import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['doc1', '1111-1']},
{'reference': ['doc2', '1111-1']},
],
'1111-1-a': [{'reference': ['doc1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
Use a 'valid' doc numberimport re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['1992-1', '1111-1']},
{'reference': ['1992-2', '1111-1']},
],
'1111-1-a': [{'reference': ['1992-1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
self.assertTrue('1992-2' in response.content)
self.assertTrue('1111-1' in response.content)
self.assertTrue('1992-1' in response.content)
self.assertTrue('1111-1-a' in response.content)
| <commit_before>import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['doc1', '1111-1']},
{'reference': ['doc2', '1111-1']},
],
'1111-1-a': [{'reference': ['doc1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
<commit_msg>Use a 'valid' doc number<commit_after>import re
from unittest import TestCase
from mock import patch
from django.test.client import Client
class ViewsSideBarViewTest(TestCase):
"""Integration tests for the sidebar"""
@patch('regulations.views.sidebar.api_reader')
def test_get(self, api_reader):
api_reader.Client.return_value.layer.return_value = {
'1111-1': [
{'reference': ['1992-1', '1111-1']},
{'reference': ['1992-2', '1111-1']},
],
'1111-1-a': [{'reference': ['1992-1', '1111-1-a']}]
}
response = Client().get('/partial/sidebar/1111-1/verver')
self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content)))
self.assertTrue('1111.1(a)' in response.content)
self.assertTrue('1992-2' in response.content)
self.assertTrue('1111-1' in response.content)
self.assertTrue('1992-1' in response.content)
self.assertTrue('1111-1-a' in response.content)
|
22a024856b6fa602ee9d6fd7fb6031dde359cc9c | pytablewriter/writer/text/_csv.py | pytablewriter/writer/text/_csv.py | from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| Modify initialization to be more properly for CsvTableWriter class | Modify initialization to be more properly for CsvTableWriter class
| Python | mit | thombashi/pytablewriter | from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
Modify initialization to be more properly for CsvTableWriter class | from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| <commit_before>from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
<commit_msg>Modify initialization to be more properly for CsvTableWriter class<commit_after> | from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
Modify initialization to be more properly for CsvTableWriter classfrom typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| <commit_before>from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
<commit_msg>Modify initialization to be more properly for CsvTableWriter class<commit_after>from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
|
9543d080bf39503a47879b74960f0999e8e94172 | linked_list.py | linked_list.py | #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
# def search
l = LinkedList()
# l.insert('Nick')
# l.insert('Constantine')
# l.insert('Maria')
# l.insert('Bob')
print(l.size())
| #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
def search(self, value):
z = 1
a = self._head.next
while z:
if a.val == value:
z = 0
return a
elif not a.next:
z = 0
return None
else:
a = a.next
l = LinkedList()
l.insert('Nick')
l.insert('Constantine')
l.insert('Maria')
l.insert('Bob')
print(l.size())
print(l.search("Constantine"))
| Add working search function v1 | Nick: Add working search function v1
| Python | mit | constanthatz/data-structures | #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
# def search
l = LinkedList()
# l.insert('Nick')
# l.insert('Constantine')
# l.insert('Maria')
# l.insert('Bob')
print(l.size())
Nick: Add working search function v1 | #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
def search(self, value):
z = 1
a = self._head.next
while z:
if a.val == value:
z = 0
return a
elif not a.next:
z = 0
return None
else:
a = a.next
l = LinkedList()
l.insert('Nick')
l.insert('Constantine')
l.insert('Maria')
l.insert('Bob')
print(l.size())
print(l.search("Constantine"))
| <commit_before>#!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
# def search
l = LinkedList()
# l.insert('Nick')
# l.insert('Constantine')
# l.insert('Maria')
# l.insert('Bob')
print(l.size())
<commit_msg>Nick: Add working search function v1<commit_after> | #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
def search(self, value):
z = 1
a = self._head.next
while z:
if a.val == value:
z = 0
return a
elif not a.next:
z = 0
return None
else:
a = a.next
l = LinkedList()
l.insert('Nick')
l.insert('Constantine')
l.insert('Maria')
l.insert('Bob')
print(l.size())
print(l.search("Constantine"))
| #!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
# def search
l = LinkedList()
# l.insert('Nick')
# l.insert('Constantine')
# l.insert('Maria')
# l.insert('Bob')
print(l.size())
Nick: Add working search function v1#!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
def search(self, value):
z = 1
a = self._head.next
while z:
if a.val == value:
z = 0
return a
elif not a.next:
z = 0
return None
else:
a = a.next
l = LinkedList()
l.insert('Nick')
l.insert('Constantine')
l.insert('Maria')
l.insert('Bob')
print(l.size())
print(l.search("Constantine"))
| <commit_before>#!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
# def search
l = LinkedList()
# l.insert('Nick')
# l.insert('Constantine')
# l.insert('Maria')
# l.insert('Bob')
print(l.size())
<commit_msg>Nick: Add working search function v1<commit_after>#!/usr/bin/env python
from __future__ import print_function
class Node(object):
def __init__(self, value):
self._val = value
self._next = None
@property
def next(self):
return self._next
@next.setter
def next(self, value):
self._next = value
@property
def val(self):
return self._val
class LinkedList(object):
def __init__(self):
self._head = None
@property
def head(self):
return self._head
def insert(self, val):
if not self._head:
self._head = Node(val)
self._head.next = None
else:
b = self._head
self._head = Node(val)
self._head.next = b
def pop(self):
self._head = self._head.next
def size(self):
i = 0
if not self._head:
return i
else:
i = 1
if not self._head.next:
return i
else:
i = 2
z = 1
a = self._head.next
while z:
if not a.next:
z = 0
return i
else:
a = a.next
i += 1
def search(self, value):
z = 1
a = self._head.next
while z:
if a.val == value:
z = 0
return a
elif not a.next:
z = 0
return None
else:
a = a.next
l = LinkedList()
l.insert('Nick')
l.insert('Constantine')
l.insert('Maria')
l.insert('Bob')
print(l.size())
print(l.search("Constantine"))
|
de24375a9d23f07eced1a8e7f2cffcf02e34bdf2 | integration_tests/conftest.py | integration_tests/conftest.py | import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--auth-type', 'text',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
| import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
| Remove auth-type option from tests | Remove auth-type option from tests
| Python | apache-2.0 | DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe | import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--auth-type', 'text',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
Remove auth-type option from tests | import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
| <commit_before>import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--auth-type', 'text',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
<commit_msg>Remove auth-type option from tests<commit_after> | import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
| import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--auth-type', 'text',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
Remove auth-type option from testsimport os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
| <commit_before>import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--auth-type', 'text',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
<commit_msg>Remove auth-type option from tests<commit_after>import os
import subprocess
import sys
import time
import pytest
ARGS = [
'--debug',
'--deployment-name', 'integration_test',
'--dbuser', 'zoeuser',
'--dbhost', 'postgres',
'--dbport', '5432',
'--dbname', 'zoe',
'--dbpass', 'zoepass',
'--master-url', 'tcp://localhost:4850',
'--listen-port', '5100',
'--workspace-base-path', '/tmp',
'--workspace-deployment-path', 'integration_test',
'--auth-file', 'zoepass.csv',
'--backend', 'DockerEngine',
'--backend-docker-config-file', 'integration_tests/sample_docker.conf',
'--zapp-shop-path', 'contrib/zapp-shop-sample'
]
@pytest.fixture(scope="session")
def zoe_api_process(request):
"""Fixture that starts the Zoe API process."""
proc = subprocess.Popen(["python", "zoe-api.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(2)
@pytest.fixture(scope="session")
def zoe_master_process(request):
"""Fixture that starts the Zoe Master process."""
os.mkdir('/tmp/integration_test')
proc = subprocess.Popen(["python", "zoe-master.py"] + ARGS, stderr=sys.stderr, stdout=sys.stdout)
request.addfinalizer(proc.terminate)
time.sleep(4)
|
f1afb7700ade910ca79a105ec9fe94448cb57d8d | byceps/blueprints/shop_order_admin/forms.py | byceps/blueprints/shop_order_admin/forms.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired()])
| # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired, Length
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired(), Length(max=200)])
| Validate length of cancelation reason supplied via form | Validate length of cancelation reason supplied via form
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired()])
Validate length of cancelation reason supplied via form | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired, Length
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired(), Length(max=200)])
| <commit_before># -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired()])
<commit_msg>Validate length of cancelation reason supplied via form<commit_after> | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired, Length
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired(), Length(max=200)])
| # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired()])
Validate length of cancelation reason supplied via form# -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired, Length
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired(), Length(max=200)])
| <commit_before># -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired()])
<commit_msg>Validate length of cancelation reason supplied via form<commit_after># -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_order_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import TextAreaField
from wtforms.validators import InputRequired, Length
from ...util.l10n import LocalizedForm
class CancelForm(LocalizedForm):
reason = TextAreaField('Begründung', validators=[InputRequired(), Length(max=200)])
|
73252b6c5600ebd857d8904c01a4b9b04d316da7 | hpcbench/cli/__init__.py | hpcbench/cli/__init__.py | """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
| """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
LOGGING_FORMAT = "%(asctime)-15s:%(levelname)s:%(name)s:%(message)s"
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level, format=LOGGING_FORMAT)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
| Add date in log format | Add date in log format
| Python | mit | tristan0x/hpcbench,tristan0x/hpcbench,tristan0x/hpcbench | """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
Add date in log format | """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
LOGGING_FORMAT = "%(asctime)-15s:%(levelname)s:%(name)s:%(message)s"
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level, format=LOGGING_FORMAT)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
| <commit_before>"""Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
<commit_msg>Add date in log format<commit_after> | """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
LOGGING_FORMAT = "%(asctime)-15s:%(levelname)s:%(name)s:%(message)s"
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level, format=LOGGING_FORMAT)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
| """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
Add date in log format"""Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
LOGGING_FORMAT = "%(asctime)-15s:%(levelname)s:%(name)s:%(message)s"
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level, format=LOGGING_FORMAT)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
| <commit_before>"""Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
<commit_msg>Add date in log format<commit_after>"""Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
LOGGING_FORMAT = "%(asctime)-15s:%(levelname)s:%(name)s:%(message)s"
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
logging.basicConfig(level=level, format=LOGGING_FORMAT)
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments
|
5ff16a552e167eb9405713f6c919a729f27f84ee | busbus/util/__init__.py | busbus/util/__init__.py | from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
print('Lazy.__get__ --> {0}'.format(self.value))
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
| from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
| Remove spurious print statement in busbus.util.Lazy | Remove spurious print statement in busbus.util.Lazy
| Python | mit | spaceboats/busbus | from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
print('Lazy.__get__ --> {0}'.format(self.value))
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
Remove spurious print statement in busbus.util.Lazy | from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
| <commit_before>from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
print('Lazy.__get__ --> {0}'.format(self.value))
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
<commit_msg>Remove spurious print statement in busbus.util.Lazy<commit_after> | from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
| from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
print('Lazy.__get__ --> {0}'.format(self.value))
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
Remove spurious print statement in busbus.util.Lazyfrom abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
| <commit_before>from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
print('Lazy.__get__ --> {0}'.format(self.value))
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
<commit_msg>Remove spurious print statement in busbus.util.Lazy<commit_after>from abc import ABCMeta, abstractmethod
import six
import busbus
@six.add_metaclass(ABCMeta)
class Iterable(object):
def __iter__(self):
return self
@abstractmethod
def __next__(self):
return NotImplemented
# Python 2 compatibility
def next(self):
return self.__next__()
class Lazy(object):
def __init__(self, f, *args):
self.f = f
self.args = args
self.called = False
def __get__(self, instance, owner):
if not self.called:
self.value = self.f(*self.args)
self.called = True
return self.value
def entity_type(obj):
try:
if not isinstance(obj, type):
obj = type(obj)
return next(x for x in obj.mro() if x in busbus.ENTITIES)
except StopIteration:
raise TypeError
def clsname(obj):
return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
|
a40a925c29b04b1b6822566e72db4afa5552479c | pygame/_error.py | pygame/_error.py | """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], int) or
not isinstance(rect[1], int)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
return rect
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
| """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
from numbers import Number
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
# This is as liberal as pygame when used for pygame.surface, but
# more liberal for pygame.display. I don't think the inconsistency
# matters
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], Number) or
not isinstance(rect[1], Number)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
# We'll throw a conversion TypeError here if someone is using a
# complex number, but so does pygame.
return int(rect[0]), int(rect[1])
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
| Support arbitary numeric types for creating pygame surfaces | Support arbitary numeric types for creating pygame surfaces
| Python | lgpl-2.1 | CTPUG/pygame_cffi,CTPUG/pygame_cffi,CTPUG/pygame_cffi | """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], int) or
not isinstance(rect[1], int)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
return rect
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
Support arbitary numeric types for creating pygame surfaces | """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
from numbers import Number
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
# This is as liberal as pygame when used for pygame.surface, but
# more liberal for pygame.display. I don't think the inconsistency
# matters
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], Number) or
not isinstance(rect[1], Number)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
# We'll throw a conversion TypeError here if someone is using a
# complex number, but so does pygame.
return int(rect[0]), int(rect[1])
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
| <commit_before>""" SDL errors.def
"""
from pygame._sdl import sdl, ffi
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], int) or
not isinstance(rect[1], int)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
return rect
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
<commit_msg>Support arbitary numeric types for creating pygame surfaces<commit_after> | """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
from numbers import Number
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
# This is as liberal as pygame when used for pygame.surface, but
# more liberal for pygame.display. I don't think the inconsistency
# matters
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], Number) or
not isinstance(rect[1], Number)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
# We'll throw a conversion TypeError here if someone is using a
# complex number, but so does pygame.
return int(rect[0]), int(rect[1])
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
| """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], int) or
not isinstance(rect[1], int)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
return rect
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
Support arbitary numeric types for creating pygame surfaces""" SDL errors.def
"""
from pygame._sdl import sdl, ffi
from numbers import Number
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
# This is as liberal as pygame when used for pygame.surface, but
# more liberal for pygame.display. I don't think the inconsistency
# matters
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], Number) or
not isinstance(rect[1], Number)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
# We'll throw a conversion TypeError here if someone is using a
# complex number, but so does pygame.
return int(rect[0]), int(rect[1])
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
| <commit_before>""" SDL errors.def
"""
from pygame._sdl import sdl, ffi
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], int) or
not isinstance(rect[1], int)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
return rect
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
<commit_msg>Support arbitary numeric types for creating pygame surfaces<commit_after>""" SDL errors.def
"""
from pygame._sdl import sdl, ffi
from numbers import Number
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
# This is as liberal as pygame when used for pygame.surface, but
# more liberal for pygame.display. I don't think the inconsistency
# matters
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], Number) or
not isinstance(rect[1], Number)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
# We'll throw a conversion TypeError here if someone is using a
# complex number, but so does pygame.
return int(rect[0]), int(rect[1])
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
|
75df2d93a2624f091eac5d1ff076985b0a2fd462 | src/core/migrations/0019_set_default_news_items.py | src/core/migrations/0019_set_default_news_items.py | from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation SET
value = 5 WHERE master_id = {master_id} AND value IS NULL;
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
| from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation
SET value = 5
WHERE master_id = {master_id} AND value IN (NULL, "", " ");
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
| Handle setting values of '' and ' ' | 747: Handle setting values of '' and ' '
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation SET
value = 5 WHERE master_id = {master_id} AND value IS NULL;
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
747: Handle setting values of '' and ' ' | from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation
SET value = 5
WHERE master_id = {master_id} AND value IN (NULL, "", " ");
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
| <commit_before>from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation SET
value = 5 WHERE master_id = {master_id} AND value IS NULL;
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
<commit_msg>747: Handle setting values of '' and ' '<commit_after> | from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation
SET value = 5
WHERE master_id = {master_id} AND value IN (NULL, "", " ");
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
| from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation SET
value = 5 WHERE master_id = {master_id} AND value IS NULL;
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
747: Handle setting values of '' and ' 'from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation
SET value = 5
WHERE master_id = {master_id} AND value IN (NULL, "", " ");
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
| <commit_before>from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation SET
value = 5 WHERE master_id = {master_id} AND value IS NULL;
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
<commit_msg>747: Handle setting values of '' and ' '<commit_after>from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation
SET value = 5
WHERE master_id = {master_id} AND value IN (NULL, "", " ");
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
|
67a60baad538f70decad3cb9d51676068965f240 | lucid/optvis/param/images.py | lucid/optvis/param/images.py | # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, w, h, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
| # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, h, w, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
| Fix image width and height switching | Fix image width and height switching
| Python | apache-2.0 | tensorflow/lucid,tensorflow/lucid,tensorflow/lucid,tensorflow/lucid | # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, w, h, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
Fix image width and height switching | # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, h, w, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
| <commit_before># Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, w, h, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
<commit_msg>Fix image width and height switching<commit_after> | # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, h, w, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
| # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, w, h, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
Fix image width and height switching# Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, h, w, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
| <commit_before># Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, w, h, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
<commit_msg>Fix image width and height switching<commit_after># Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""High-level wrapper for paramaterizing images."""
import tensorflow as tf
from lucid.optvis.param.color import to_valid_rgb
from lucid.optvis.param.spatial import pixel_image, fft_image
def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False):
h = h or w
batch = batch or 1
channels = 4 if alpha else 3
shape = [batch, h, w, channels]
param_f = fft_image if fft else pixel_image
t = param_f(shape, sd=sd)
rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True)
if alpha:
a = tf.nn.sigmoid(t[..., 3:])
return tf.concat([rgb, a], -1)
return rgb
|
9d08d3b463e99eb665844f16ff30e7b83b4b8dfd | client_logging/views.py | client_logging/views.py | from django.views import View
from django import http
from uxhelpers.utils import json_response
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except Exception:
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
| from django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
logger.error('received log event from frontend')
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except (ValueError, KeyError):
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
| Add another missing import and only handle specific exceptions | Add another missing import and only handle specific exceptions
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | from django.views import View
from django import http
from uxhelpers.utils import json_response
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except Exception:
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
Add another missing import and only handle specific exceptions | from django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
logger.error('received log event from frontend')
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except (ValueError, KeyError):
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
| <commit_before>from django.views import View
from django import http
from uxhelpers.utils import json_response
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except Exception:
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
<commit_msg>Add another missing import and only handle specific exceptions<commit_after> | from django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
logger.error('received log event from frontend')
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except (ValueError, KeyError):
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
| from django.views import View
from django import http
from uxhelpers.utils import json_response
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except Exception:
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
Add another missing import and only handle specific exceptionsfrom django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
logger.error('received log event from frontend')
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except (ValueError, KeyError):
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
| <commit_before>from django.views import View
from django import http
from uxhelpers.utils import json_response
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except Exception:
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
<commit_msg>Add another missing import and only handle specific exceptions<commit_after>from django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, request):
logger.error('received log event from frontend')
try:
json_data = json.loads(request.body)
level = json_data['level']
logger.log(LEVELS[level], json_data['message'])
except (ValueError, KeyError):
logger.warning('Malformed client log received')
return json_response(request, {'status': 200})
|
860636fa3d0354b8358b490c28ed92d727207744 | pola/views.py | pola/views.py | from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
context['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
context['most_popular_products'] = (Product.objects.with_query_count()
.order_by('query_count')[:10])
context['most_popular_companies'] = (Company.objects.with_query_count()
.order_by('query_count')[:10])
return context
| from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
c = super(FrontPageView, self).get_context_data(**kwargs)
c['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
c['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
c['most_popular_products'] = (Product.objects
.with_query_count()
.filter(company__isnull=True)
.order_by('query_count')[:10])
c['most_popular_companies'] = (Company.objects
.with_query_count()
.filter(plCapital__isnull=True)
.order_by('query_count')[:10])
return c
| Add extra condition to home page's box | Add extra condition to home page's box
| Python | bsd-3-clause | KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend | from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
context['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
context['most_popular_products'] = (Product.objects.with_query_count()
.order_by('query_count')[:10])
context['most_popular_companies'] = (Company.objects.with_query_count()
.order_by('query_count')[:10])
return context
Add extra condition to home page's box | from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
c = super(FrontPageView, self).get_context_data(**kwargs)
c['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
c['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
c['most_popular_products'] = (Product.objects
.with_query_count()
.filter(company__isnull=True)
.order_by('query_count')[:10])
c['most_popular_companies'] = (Company.objects
.with_query_count()
.filter(plCapital__isnull=True)
.order_by('query_count')[:10])
return c
| <commit_before>from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
context['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
context['most_popular_products'] = (Product.objects.with_query_count()
.order_by('query_count')[:10])
context['most_popular_companies'] = (Company.objects.with_query_count()
.order_by('query_count')[:10])
return context
<commit_msg>Add extra condition to home page's box<commit_after> | from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
c = super(FrontPageView, self).get_context_data(**kwargs)
c['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
c['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
c['most_popular_products'] = (Product.objects
.with_query_count()
.filter(company__isnull=True)
.order_by('query_count')[:10])
c['most_popular_companies'] = (Company.objects
.with_query_count()
.filter(plCapital__isnull=True)
.order_by('query_count')[:10])
return c
| from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
context['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
context['most_popular_products'] = (Product.objects.with_query_count()
.order_by('query_count')[:10])
context['most_popular_companies'] = (Company.objects.with_query_count()
.order_by('query_count')[:10])
return context
Add extra condition to home page's boxfrom django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
c = super(FrontPageView, self).get_context_data(**kwargs)
c['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
c['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
c['most_popular_products'] = (Product.objects
.with_query_count()
.filter(company__isnull=True)
.order_by('query_count')[:10])
c['most_popular_companies'] = (Company.objects
.with_query_count()
.filter(plCapital__isnull=True)
.order_by('query_count')[:10])
return c
| <commit_before>from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
context = super(FrontPageView, self).get_context_data(**kwargs)
context['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
context['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
context['most_popular_products'] = (Product.objects.with_query_count()
.order_by('query_count')[:10])
context['most_popular_companies'] = (Company.objects.with_query_count()
.order_by('query_count')[:10])
return context
<commit_msg>Add extra condition to home page's box<commit_after>from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
from product.models import Product
from company.models import Company
from report.models import Report
class FrontPageView(LoginRequiredMixin, TemplateView):
template_name = 'pages/home-cms.html'
def get_context_data(self, *args, **kwargs):
c = super(FrontPageView, self).get_context_data(**kwargs)
c['oldest_reports'] = (Report.objects.only_open()
.order_by('-created_at')[:10])
c['newest_reports'] = (Report.objects.only_open()
.order_by('created_at')[:10])
c['most_popular_products'] = (Product.objects
.with_query_count()
.filter(company__isnull=True)
.order_by('query_count')[:10])
c['most_popular_companies'] = (Company.objects
.with_query_count()
.filter(plCapital__isnull=True)
.order_by('query_count')[:10])
return c
|
1aec583a52ac9edc95138f5df356da60451dfe2b | enthought/tvtk/view/parametric_function_source_view.py | enthought/tvtk/view/parametric_function_source_view.py | from enthought.traits.ui.api import View, HGroup, Item
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
| from enthought.traits.ui.api import View, HGroup, Item
from enthought.tvtk.tvtk_base import TVTKBaseHandler
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
Item('handler.advanced_view'),
handler = TVTKBaseHandler,
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
| Add handler to the view. | Add handler to the view.
| Python | bsd-3-clause | liulion/mayavi,liulion/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,dmsurti/mayavi,alexandreleroux/mayavi | from enthought.traits.ui.api import View, HGroup, Item
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
Add handler to the view. | from enthought.traits.ui.api import View, HGroup, Item
from enthought.tvtk.tvtk_base import TVTKBaseHandler
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
Item('handler.advanced_view'),
handler = TVTKBaseHandler,
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
| <commit_before>from enthought.traits.ui.api import View, HGroup, Item
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
<commit_msg>Add handler to the view.<commit_after> | from enthought.traits.ui.api import View, HGroup, Item
from enthought.tvtk.tvtk_base import TVTKBaseHandler
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
Item('handler.advanced_view'),
handler = TVTKBaseHandler,
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
| from enthought.traits.ui.api import View, HGroup, Item
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
Add handler to the view.from enthought.traits.ui.api import View, HGroup, Item
from enthought.tvtk.tvtk_base import TVTKBaseHandler
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
Item('handler.advanced_view'),
handler = TVTKBaseHandler,
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
| <commit_before>from enthought.traits.ui.api import View, HGroup, Item
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
<commit_msg>Add handler to the view.<commit_after>from enthought.traits.ui.api import View, HGroup, Item
from enthought.tvtk.tvtk_base import TVTKBaseHandler
view = View((['generate_texture_coordinates'], ['scalar_mode'],
HGroup(Item('u_resolution', label = 'u'),
Item('v_resolution', label = 'v'),
Item('w_resolution', label = 'w'),
label = 'Resolution', show_border = True)),
Item('handler.advanced_view'),
handler = TVTKBaseHandler,
title='Edit ParametricFunctionSource properties', scrollable=True,
buttons=['OK', 'Cancel'])
|
11095d00dd1e4805739ffc376328e4ad2a6893fb | h2o-py/tests/testdir_algos/gbm/pyunit_cv_nfolds_gbm.py | h2o-py/tests/testdir_algos/gbm/pyunit_cv_nfolds_gbm.py | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm() | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
print(prostate_gbm.model_performance(xval=True))
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()
| Add pyunit test for model_performance(xval=True) | PUBDEV-2984: Add pyunit test for model_performance(xval=True)
| Python | apache-2.0 | mathemage/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,spennihana/h2o-3,mathemage/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,spennihana/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,mathemage/h2o-3,h2oai/h2o-3,michalkurka/h2o-3 | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()PUBDEV-2984: Add pyunit test for model_performance(xval=True) | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
print(prostate_gbm.model_performance(xval=True))
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()
| <commit_before>from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()<commit_msg>PUBDEV-2984: Add pyunit test for model_performance(xval=True)<commit_after> | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
print(prostate_gbm.model_performance(xval=True))
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()
| from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()PUBDEV-2984: Add pyunit test for model_performance(xval=True)from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
print(prostate_gbm.model_performance(xval=True))
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()
| <commit_before>from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()<commit_msg>PUBDEV-2984: Add pyunit test for model_performance(xval=True)<commit_after>from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
prostate.summary()
prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli")
prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate)
prostate_gbm.show()
print(prostate_gbm.model_performance(xval=True))
# Can specify both nfolds >= 2 and validation data at once
try:
H2OGradientBoostingEstimator(nfolds=5,
distribution="bernoulli").train(x=list(range(2,9)),
y=1,
training_frame=prostate,
validation_frame=prostate)
assert True
except EnvironmentError:
assert False, "expected an error"
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_nfolds_gbm)
else:
cv_nfolds_gbm()
|
97041c2b874dde32632485f210e3f9885aac95df | commands/get_popular.py | commands/get_popular.py | from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
records.append(APP.Movie.get_data(movie))
output(records)
| from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
data = APP.Movie.get_data(movie)
if not data:
continue
records.append(data)
output(records)
| Stop adding database misses to output array. | Stop adding database misses to output array.
| Python | mit | EmilStenstrom/nephele | from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
records.append(APP.Movie.get_data(movie))
output(records)
Stop adding database misses to output array. | from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
data = APP.Movie.get_data(movie)
if not data:
continue
records.append(data)
output(records)
| <commit_before>from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
records.append(APP.Movie.get_data(movie))
output(records)
<commit_msg>Stop adding database misses to output array.<commit_after> | from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
data = APP.Movie.get_data(movie)
if not data:
continue
records.append(data)
output(records)
| from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
records.append(APP.Movie.get_data(movie))
output(records)
Stop adding database misses to output array.from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
data = APP.Movie.get_data(movie)
if not data:
continue
records.append(data)
output(records)
| <commit_before>from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
records.append(APP.Movie.get_data(movie))
output(records)
<commit_msg>Stop adding database misses to output array.<commit_after>from importlib import import_module
from application import APPLICATION as APP
from utils.movie_util import update_moviedata
def get_popular():
APP.debug("Fetching popular movies...")
provider_module = import_module(APP.setting("POPULARITY_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Fetching from %s" % provider_module.IDENTIFIER)
return provider.get_popular()
def output(movie_data):
provider_module = import_module(APP.setting("OUTPUT_PROVIDER"))
provider = provider_module.Provider()
APP.debug("Outputting data with %s" % provider_module.IDENTIFIER)
provider.output(movie_data)
def main(arguments):
APP.settings["DEBUG"] = arguments["--debug"]
popular = get_popular()
update_moviedata(popular, APP)
records = []
for movie in popular:
data = APP.Movie.get_data(movie)
if not data:
continue
records.append(data)
output(records)
|
4c4c5d7d1854d0810e9bd6f4acd00dcb6ea25a6b | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter, util
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| Remove unnecessary import of util | Remove unnecessary import of util | Python | mit | thebinarypenguin/SublimeLinter-contrib-raml-cop | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter, util
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
Remove unnecessary import of util | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| <commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter, util
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
<commit_msg>Remove unnecessary import of util<commit_after> | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter, util
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
Remove unnecessary import of util#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| <commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter, util
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
<commit_msg>Remove unnecessary import of util<commit_after>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
|
185b93373c6f792619ec9e8225e3d699e6bd41e0 | l10n_br_data_base/__manifest__.py | l10n_br_data_base/__manifest__.py | # -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
| # -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '10.0.0.0.0',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
| Migrate l10n_br_data_base to version 10 | [MIG] Migrate l10n_br_data_base to version 10
| Python | agpl-3.0 | thinkopensolutions/l10n-brazil,thinkopensolutions/l10n-brazil,odoo-brazil/l10n-brazil-wip,odoo-brazil/l10n-brazil-wip | # -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
[MIG] Migrate l10n_br_data_base to version 10 | # -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '10.0.0.0.0',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
| <commit_before># -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
<commit_msg>[MIG] Migrate l10n_br_data_base to version 10<commit_after> | # -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '10.0.0.0.0',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
| # -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
[MIG] Migrate l10n_br_data_base to version 10# -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '10.0.0.0.0',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
| <commit_before># -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
<commit_msg>[MIG] Migrate l10n_br_data_base to version 10<commit_after># -*- coding: utf-8 -*-
# Copyright (C) 2009 - TODAY Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation Data Extension for Base',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '10.0.0.0.0',
'depends': [
'l10n_br_base',
],
'data': [
'data/res.bank.csv',
],
'demo': [],
'category': 'Localisation',
'installable': True,
'auto_install': True,
}
|
c6edb08cdb5ee34accb8a6d74a78f372e2b8addb | tests/chainer_tests/training_tests/test_trainer.py | tests/chainer_tests/training_tests/test_trainer.py | import collections
import os
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
| import collections
import os
import shutil
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
try:
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
finally:
shutil.rmtree(tempdir)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
| Clean up temporary directory after the test | Clean up temporary directory after the test
| Python | mit | chainer/chainer,ronekko/chainer,chainer/chainer,okuta/chainer,jnishi/chainer,jnishi/chainer,pfnet/chainer,ktnyt/chainer,jnishi/chainer,niboshi/chainer,wkentaro/chainer,keisuke-umezawa/chainer,okuta/chainer,wkentaro/chainer,chainer/chainer,ysekky/chainer,wkentaro/chainer,cupy/cupy,chainer/chainer,keisuke-umezawa/chainer,okuta/chainer,niboshi/chainer,okuta/chainer,niboshi/chainer,ktnyt/chainer,keisuke-umezawa/chainer,ktnyt/chainer,hvy/chainer,wkentaro/chainer,kiyukuta/chainer,cupy/cupy,kashif/chainer,cupy/cupy,hvy/chainer,aonotas/chainer,ktnyt/chainer,hvy/chainer,tkerola/chainer,keisuke-umezawa/chainer,cupy/cupy,delta2323/chainer,niboshi/chainer,anaruse/chainer,hvy/chainer,jnishi/chainer,rezoo/chainer | import collections
import os
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
Clean up temporary directory after the test | import collections
import os
import shutil
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
try:
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
finally:
shutil.rmtree(tempdir)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
| <commit_before>import collections
import os
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
<commit_msg>Clean up temporary directory after the test<commit_after> | import collections
import os
import shutil
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
try:
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
finally:
shutil.rmtree(tempdir)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
| import collections
import os
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
Clean up temporary directory after the testimport collections
import os
import shutil
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
try:
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
finally:
shutil.rmtree(tempdir)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
| <commit_before>import collections
import os
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
<commit_msg>Clean up temporary directory after the test<commit_after>import collections
import os
import shutil
import tempfile
import time
import unittest
import mock
from chainer import serializers
from chainer import testing
from chainer import training
class TestTrainerElapsedTime(unittest.TestCase):
def setUp(self):
self.trainer = _get_mocked_trainer()
def test_elapsed_time(self):
with self.assertRaises(RuntimeError):
self.trainer.elapsed_time
self.trainer.run()
self.assertGreater(self.trainer.elapsed_time, 0)
def test_elapsed_time_serialization(self):
self.trainer.run()
serialized_time = self.trainer.elapsed_time
tempdir = tempfile.mkdtemp()
try:
path = os.path.join(tempdir, 'trainer.npz')
serializers.save_npz(path, self.trainer)
trainer = _get_mocked_trainer((20, 'iteration'))
serializers.load_npz(path, trainer)
trainer.run()
self.assertGreater(trainer.elapsed_time, serialized_time)
finally:
shutil.rmtree(tempdir)
def _get_mocked_trainer(stop_trigger=(10, 'iteration')):
updater = mock.Mock()
updater.get_all_optimizers.return_value = {}
updater.iteration = 0
def update():
updater.iteration += 1
updater.update = update
return training.Trainer(updater, stop_trigger)
testing.run_module(__name__, __file__)
|
1639a91f018e29c4572242a94c5faf7281b15a6e | netdisco/discoverables/belkin_wemo.py | netdisco/discoverables/belkin_wemo.py | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device['macAddress'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''))
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| Handle mac address missing in early wemo firmware. | Handle mac address missing in early wemo firmware.
| Python | mit | balloob/netdisco,sfam/netdisco,brburns/netdisco | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device['macAddress'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
Handle mac address missing in early wemo firmware. | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''))
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| <commit_before>""" Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device['macAddress'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
<commit_msg>Handle mac address missing in early wemo firmware.<commit_after> | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''))
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device['macAddress'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
Handle mac address missing in early wemo firmware.""" Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''))
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| <commit_before>""" Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device['macAddress'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
<commit_msg>Handle mac address missing in early wemo firmware.<commit_after>""" Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''))
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
|
3767fc5d1bf21d4321342e7332f569a97b7396b4 | ipython/config_helper_functions.py | ipython/config_helper_functions.py | import os
import IPython.ipapi
ip = IPython.ipapi.get()
# some config helper functions you can use
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
'''Usage: import_some('path','makepath path')'''
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
| """Some config helper functions you can use"""
import os
import IPython.ipapi
ip = IPython.ipapi.get()
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
"""Usage: import_some('path','path')"""
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
| Use triple quotes for docstrings | Use triple quotes for docstrings
git-svn-id: 71e07130022bd36facd9e5e4cff6aac120a9d616@756 f6a8b572-8bf8-43d5-8295-329fc01c5294
| Python | mit | jalanb/jab,jalanb/dotjab,jalanb/dotjab,jalanb/jab | import os
import IPython.ipapi
ip = IPython.ipapi.get()
# some config helper functions you can use
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
'''Usage: import_some('path','makepath path')'''
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
Use triple quotes for docstrings
git-svn-id: 71e07130022bd36facd9e5e4cff6aac120a9d616@756 f6a8b572-8bf8-43d5-8295-329fc01c5294 | """Some config helper functions you can use"""
import os
import IPython.ipapi
ip = IPython.ipapi.get()
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
"""Usage: import_some('path','path')"""
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
| <commit_before>import os
import IPython.ipapi
ip = IPython.ipapi.get()
# some config helper functions you can use
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
'''Usage: import_some('path','makepath path')'''
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
<commit_msg>Use triple quotes for docstrings
git-svn-id: 71e07130022bd36facd9e5e4cff6aac120a9d616@756 f6a8b572-8bf8-43d5-8295-329fc01c5294<commit_after> | """Some config helper functions you can use"""
import os
import IPython.ipapi
ip = IPython.ipapi.get()
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
"""Usage: import_some('path','path')"""
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
| import os
import IPython.ipapi
ip = IPython.ipapi.get()
# some config helper functions you can use
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
'''Usage: import_some('path','makepath path')'''
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
Use triple quotes for docstrings
git-svn-id: 71e07130022bd36facd9e5e4cff6aac120a9d616@756 f6a8b572-8bf8-43d5-8295-329fc01c5294"""Some config helper functions you can use"""
import os
import IPython.ipapi
ip = IPython.ipapi.get()
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
"""Usage: import_some('path','path')"""
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
| <commit_before>import os
import IPython.ipapi
ip = IPython.ipapi.get()
# some config helper functions you can use
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
'''Usage: import_some('path','makepath path')'''
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
<commit_msg>Use triple quotes for docstrings
git-svn-id: 71e07130022bd36facd9e5e4cff6aac120a9d616@756 f6a8b572-8bf8-43d5-8295-329fc01c5294<commit_after>"""Some config helper functions you can use"""
import os
import IPython.ipapi
ip = IPython.ipapi.get()
def import_mod(modules):
""" Usage: import_mod("os sys") """
for m in modules.split():
ip.ex("import %s" % m)
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def import_some(module,things):
"""Usage: import_some('path','path')"""
for thing in things.split():
ip.ex('from %s import %s' % (module,thing))
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
|
5e3c81a34944c5877f0fd5e3824216ac7057f413 | src/waypoints_reader/scripts/yaml_reader.py | src/waypoints_reader/scripts/yaml_reader.py | #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data['name'],
x = waypoint_data['x'],
y = waypoint_data['y'],
importance = waypoint_data['importance'],
radius = waypoint_data['radius'],
drag = waypoint_data['drag'])
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
| #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data.get('name', ""),
x = waypoint_data['x'], # required
y = waypoint_data['y'], # required
radius = waypoint_data['radius'], # required
importance = waypoint_data.get('importance', 0),
drag = waypoint_data.get('drag', 0))
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
| Update read method for dictionaly type | Update read method for dictionaly type
| Python | bsd-3-clause | CIR-KIT/fifth_robot_pkg,CIR-KIT/fifth_robot_pkg,CIR-KIT/fifth_robot_pkg | #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data['name'],
x = waypoint_data['x'],
y = waypoint_data['y'],
importance = waypoint_data['importance'],
radius = waypoint_data['radius'],
drag = waypoint_data['drag'])
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
Update read method for dictionaly type | #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data.get('name', ""),
x = waypoint_data['x'], # required
y = waypoint_data['y'], # required
radius = waypoint_data['radius'], # required
importance = waypoint_data.get('importance', 0),
drag = waypoint_data.get('drag', 0))
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
| <commit_before>#!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data['name'],
x = waypoint_data['x'],
y = waypoint_data['y'],
importance = waypoint_data['importance'],
radius = waypoint_data['radius'],
drag = waypoint_data['drag'])
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
<commit_msg>Update read method for dictionaly type<commit_after> | #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data.get('name', ""),
x = waypoint_data['x'], # required
y = waypoint_data['y'], # required
radius = waypoint_data['radius'], # required
importance = waypoint_data.get('importance', 0),
drag = waypoint_data.get('drag', 0))
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
| #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data['name'],
x = waypoint_data['x'],
y = waypoint_data['y'],
importance = waypoint_data['importance'],
radius = waypoint_data['radius'],
drag = waypoint_data['drag'])
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
Update read method for dictionaly type#!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data.get('name', ""),
x = waypoint_data['x'], # required
y = waypoint_data['y'], # required
radius = waypoint_data['radius'], # required
importance = waypoint_data.get('importance', 0),
drag = waypoint_data.get('drag', 0))
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
| <commit_before>#!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data['name'],
x = waypoint_data['x'],
y = waypoint_data['y'],
importance = waypoint_data['importance'],
radius = waypoint_data['radius'],
drag = waypoint_data['drag'])
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
<commit_msg>Update read method for dictionaly type<commit_after>#!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def pub_data():
pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10)
rospy.init_node('yaml_reader', anonymous=True)
msg = GoalSequence()
for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')):
waypoint = Waypoint(name = waypoint_data.get('name', ""),
x = waypoint_data['x'], # required
y = waypoint_data['y'], # required
radius = waypoint_data['radius'], # required
importance = waypoint_data.get('importance', 0),
drag = waypoint_data.get('drag', 0))
msg.waypoints.append(waypoint)
pub.publish(msg)
if __name__ == '__main__':
try:
pub_data()
except rospy.ROSInterruptException:
pass
|
5e87af4770a05bc187df7efbb5292c876393aef0 | nbgrader/apps/formgradeapp.py | nbgrader/apps/formgradeapp.py | from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template, get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
@catch_config_error
def initialize(self, argv=None):
self.postprocessor_class = 'nbgrader.postprocessors.ServeFormGrader'
super(FormgradeApp, self).initialize(argv)
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
| from IPython.config.loader import Config
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
'serve': (
{'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
"Run the form grading server"
)
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
| Make form grade server be a flag | Make form grade server be a flag
| Python | bsd-3-clause | modulexcite/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,modulexcite/nbgrader,alope107/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,dementrock/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,MatKallada/nbgrader,MatKallada/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jdfreder/nbgrader,jhamrick/nbgrader,dementrock/nbgrader,jdfreder/nbgrader,ellisonbg/nbgrader,alope107/nbgrader | from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template, get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
@catch_config_error
def initialize(self, argv=None):
self.postprocessor_class = 'nbgrader.postprocessors.ServeFormGrader'
super(FormgradeApp, self).initialize(argv)
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
Make form grade server be a flag | from IPython.config.loader import Config
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
'serve': (
{'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
"Run the form grading server"
)
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
| <commit_before>from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template, get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
@catch_config_error
def initialize(self, argv=None):
self.postprocessor_class = 'nbgrader.postprocessors.ServeFormGrader'
super(FormgradeApp, self).initialize(argv)
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
<commit_msg>Make form grade server be a flag<commit_after> | from IPython.config.loader import Config
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
'serve': (
{'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
"Run the form grading server"
)
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
| from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template, get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
@catch_config_error
def initialize(self, argv=None):
self.postprocessor_class = 'nbgrader.postprocessors.ServeFormGrader'
super(FormgradeApp, self).initialize(argv)
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
Make form grade server be a flagfrom IPython.config.loader import Config
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
'serve': (
{'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
"Run the form grading server"
)
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
| <commit_before>from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template, get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
@catch_config_error
def initialize(self, argv=None):
self.postprocessor_class = 'nbgrader.postprocessors.ServeFormGrader'
super(FormgradeApp, self).initialize(argv)
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
<commit_msg>Make form grade server be a flag<commit_after>from IPython.config.loader import Config
from IPython.utils.traitlets import Unicode
from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template_path
aliases = {}
aliases.update(base_aliases)
aliases.update({
'regexp': 'FindStudentID.regexp'
})
flags = {}
flags.update(base_flags)
flags.update({
'serve': (
{'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
"Run the form grading server"
)
})
class FormgradeApp(CustomNbConvertApp):
name = Unicode(u'nbgrader-formgrade')
description = Unicode(u'Grade a notebook using an HTML form')
aliases = aliases
flags = flags
student_id = Unicode(u'', config=True)
def _export_format_default(self):
return 'html'
def build_extra_config(self):
self.extra_config = Config()
self.extra_config.Exporter.preprocessors = [
'nbgrader.preprocessors.FindStudentID'
]
self.extra_config.Exporter.template_file = 'formgrade'
self.extra_config.Exporter.template_path = ['.', get_template_path()]
self.config.merge(self.extra_config)
|
6aa95264e31f7b2eebb34432eace9440de5f0cb2 | s3authbasic/tests/test_views.py | s3authbasic/tests/test_views.py | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertIn(expect, result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
| from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertTrue(expect in result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
| Fix tests python 2.6 support | Fix tests python 2.6 support
| Python | mit | ant30/s3authbasic | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertIn(expect, result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
Fix tests python 2.6 support | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertTrue(expect in result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
| <commit_before>from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertIn(expect, result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
<commit_msg>Fix tests python 2.6 support<commit_after> | from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertTrue(expect in result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
| from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertIn(expect, result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
Fix tests python 2.6 supportfrom s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertTrue(expect in result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
| <commit_before>from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertIn(expect, result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
<commit_msg>Fix tests python 2.6 support<commit_after>from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON
class ViewsTests(BaseAppTest):
def test_validpath(self):
for (path, expect) in (
('/', 'home'),
('/index.html', 'home'),
('/level1', 'level 1'),
('/level1/', 'level 1'),
('/level1/index.html', 'level 1'),
('/level1/other.html', 'other'),
('/level1/level2', 'level 2'),
('/level1/level2/index.html', 'level 2'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=200)
self.assertTrue(expect in result.body)
def test_not_validpath(self):
for path in (
'/other.html',
'/index',
'/level1/index',
'/level3/',
):
self.testapp.get(path, extra_environ=AUTH_ENVIRON,
status=404)
class MimeTypeTests(BaseAppTest):
def test_mimetypes(self):
for (path, mimetype) in (
('/', 'text/html'),
('/index.html', 'text/html'),
('/example.jpeg', 'image/jpeg'),
):
result = self.testapp.get(path, extra_environ=AUTH_ENVIRON)
self.assertEqual(result.content_type, mimetype)
|
79f672d6fb129c90306afb3d8ad7ed599063bc07 | setup.py | setup.py | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Topic :: Utilities",
],
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Utilities",
],
)
| Add classifier for Python 3.7. | Add classifier for Python 3.7.
| Python | mit | zsiciarz/django-pgallery,zsiciarz/django-pgallery | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Topic :: Utilities",
],
)
Add classifier for Python 3.7. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Utilities",
],
)
| <commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Topic :: Utilities",
],
)
<commit_msg>Add classifier for Python 3.7.<commit_after> | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Utilities",
],
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Topic :: Utilities",
],
)
Add classifier for Python 3.7.import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Utilities",
],
)
| <commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Topic :: Utilities",
],
)
<commit_msg>Add classifier for Python 3.7.<commit_after>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="django-pgallery",
version=__import__("pgallery").__version__,
description="Photo gallery app for PostgreSQL and Django.",
long_description=read("README.rst"),
author="Zbigniew Siciarz",
author_email="zbigniew@siciarz.net",
url="https://github.com/zsiciarz/django-pgallery",
download_url="https://pypi.python.org/pypi/django-pgallery",
license="MIT",
install_requires=[
"Django>=2.0,<3.0",
"Pillow",
"psycopg2>=2.5",
"django-markitup>=3.5",
"django-model-utils>=4.0",
],
packages=find_packages(exclude=["tests"]),
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Utilities",
],
)
|
673da77b56cf21b540c9b7afbd483fecd6f43d7a | setup.py | setup.py | import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
]
)
| import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
'notebook',
]
)
| Add 'notebook' as a dependency | Add 'notebook' as a dependency
| Python | bsd-2-clause | allanlwu/allangdrive,allanlwu/allangdrive,yuvipanda/nbresuse,yuvipanda/nbresuse | import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
]
)
Add 'notebook' as a dependency | import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
'notebook',
]
)
| <commit_before>import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
]
)
<commit_msg>Add 'notebook' as a dependency<commit_after> | import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
'notebook',
]
)
| import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
]
)
Add 'notebook' as a dependencyimport setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
'notebook',
]
)
| <commit_before>import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
]
)
<commit_msg>Add 'notebook' as a dependency<commit_after>import setuptools
setuptools.setup(
name="nbresuse",
version='0.1.0',
url="https://github.com/yuvipanda/nbresuse",
author="Yuvi Panda",
description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
packages=setuptools.find_packages(),
install_requires=[
'psutil',
'notebook',
]
)
|
7b61dd4a9d67b81565349114f953c841de447a4c | setup.py | setup.py | from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose==0.11.4',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
| from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
| Update to get newest nose version. | Update to get newest nose version.
| Python | mit | hltbra/specloud | from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose==0.11.4',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
Update to get newest nose version. | from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
| <commit_before>from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose==0.11.4',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
<commit_msg>Update to get newest nose version.<commit_after> | from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
| from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose==0.11.4',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
Update to get newest nose version.from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
| <commit_before>from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose==0.11.4',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
<commit_msg>Update to get newest nose version.<commit_after>from setuptools import setup, find_packages
import os
version = '0.4.3'
here = os.path.abspath(os.path.dirname(__file__))
long_description = open(os.path.join(here, 'README.rst')).read()
setup(name='specloud',
version=version,
description="install nosetests and plugins to ease bdd unit specs",
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Natural Language :: Portuguese (Brazilian)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
keywords='test bdd nosetests spec unit',
author='Hugo Lopes Tavares',
author_email='hltbra@gmail.com',
url='http://github.com/hugobr/specloud',
license='MIT',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'nose',
'figleaf',
'pinocchio==0.2',
],
dependency_links = [
'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2',
],
entry_points="""
[console_scripts]
specloud = specloud:main
""",
)
|
bf9f55d60087624df84c32ec6d1e5cf58045ed25 | setup.py | setup.py | # -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| # -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
long_description_content_type='text/x-rst',
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| Add long description content type | Add long description content type
| Python | bsd-2-clause | migonzalvar/dj-email-url | # -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
Add long description content type | # -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
long_description_content_type='text/x-rst',
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| <commit_before># -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
<commit_msg>Add long description content type<commit_after> | # -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
long_description_content_type='text/x-rst',
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| # -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
Add long description content type# -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
long_description_content_type='text/x-rst',
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| <commit_before># -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
<commit_msg>Add long description content type<commit_after># -*- coding: utf-8 -*-
"""Packaging implementation"""
from os.path import dirname, join
from setuptools import setup
def read_file(filename):
with open(join(dirname(__file__), filename)) as file:
return file.read()
setup(
name='dj-email-url',
version='1.0.4',
url='https://github.com/migonzalvar/dj-email-url',
license='BSD',
author='Miguel Gonzalez',
author_email='migonzalvar@gmail.com',
description='Use an URL to configure email backend settings in your '
'Django Application.',
long_description=read_file('README.rst') + '\n'
+ read_file('CHANGELOG.rst'),
long_description_content_type='text/x-rst',
py_modules=['dj_email_url'],
zip_safe=False,
include_package_data=True,
platforms='any',
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
401efb45b472b27c6e08fe5216040d39ea521b94 | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = '',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = 'A module to read environment variables.',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
| Add a description for the package | Add a description for the package
| Python | apache-2.0 | MarcMeszaros/envitro | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = '',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
Add a description for the package | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = 'A module to read environment variables.',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
| <commit_before># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = '',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
<commit_msg>Add a description for the package<commit_after> | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = 'A module to read environment variables.',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = '',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
Add a description for the package# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = 'A module to read environment variables.',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
| <commit_before># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = '',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
<commit_msg>Add a description for the package<commit_after># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = 'envitro',
version = '0.1.0',
packages = find_packages(),
description = 'A module to read environment variables.',
license = 'Apache 2',
author = 'Marc Meszaros',
author_email = 'me@marcmeszaros.com',
url = 'https://github.com/MarcMeszaros/envitro',
keywords = [
'config', 'environment', '12factor'
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
],
)
|
c955f4c7aa281286cabd2dcb5ca33ac5b21bec2b | setup.py | setup.py | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.3', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
| #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.0', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
| Make minimum cffi versions consistent | Make minimum cffi versions consistent
| Python | mit | anibali/pywebp,anibali/pywebp,anibali/pywebp | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.3', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
Make minimum cffi versions consistent | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.0', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
| <commit_before>#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.3', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
<commit_msg>Make minimum cffi versions consistent<commit_after> | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.0', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
| #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.3', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
Make minimum cffi versions consistent#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.0', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
| <commit_before>#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.3', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
<commit_msg>Make minimum cffi versions consistent<commit_after>#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='webp',
version='0.1.0a17',
url='https://github.com/anibali/pywebp',
packages=find_packages(include=['webp', 'webp.*', 'webp_build']),
package_data={'webp_build': ['*.h', '*.c']},
author='Aiden Nibali',
description='Python bindings for WebP',
license='MIT',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
zip_safe=True,
test_suite='tests',
setup_requires=['cffi>=1.0.0', 'conan>=1.8.0', 'importlib_resources>=1.0.0'],
cffi_modules=['webp_build/builder.py:ffibuilder'],
install_requires=['cffi>=1.0.0', 'Pillow>=4.0.0', 'numpy>=1.0.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'License :: OSI Approved :: MIT License',
]
)
|
f56dedd5ed73291c749a980c7d16f1e0b5a122c5 | setup.py | setup.py | """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.3",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.4",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| Add new version to PyPi | Add new version to PyPi
| Python | bsd-3-clause | codeforamerica/three | """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.3",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
Add new version to PyPi | """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.4",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| <commit_before>"""
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.3",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
<commit_msg>Add new version to PyPi<commit_after> | """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.4",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| """
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.3",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
Add new version to PyPi"""
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.4",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| <commit_before>"""
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.3",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
<commit_msg>Add new version to PyPi<commit_after>"""
Setup and installation for the package.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="three",
version="0.4",
url="http://github.com/codeforamerica/three",
author="Zach Williams",
author_email="hey@zachwill.com",
description="An easy-to-use wrapper for the Open311 API",
packages=[
'three'
],
install_requires=[
'mock',
'simplejson',
'requests',
],
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
|
73a566525d94de0f1c0a35a93592d18d1c71eda5 | setup.py | setup.py | from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Python-Tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
| from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
| Remove python prefix from name | Remove python prefix from name
| Python | apache-2.0 | trygveaa/python-tunigo | from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Python-Tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
Remove python prefix from name | from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
| <commit_before>from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Python-Tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
<commit_msg>Remove python prefix from name<commit_after> | from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
| from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Python-Tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
Remove python prefix from namefrom __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
| <commit_before>from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Python-Tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
<commit_msg>Remove python prefix from name<commit_after>from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='trygveaa@gmail.com',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
|
9f668ed8039b0c2c5702625583f0d5c8b47cf27a | setup.py | setup.py | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances!',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
| Update to new version :) | Update to new version :)
| Python | mit | jleeothon/trufflehog | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances!',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
Update to new version :) | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
| <commit_before>import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances!',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
<commit_msg>Update to new version :)<commit_after> | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
| import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances!',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
Update to new version :)import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
| <commit_before>import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances!',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
<commit_msg>Update to new version :)<commit_after>import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='trufflehog',
version='0.1.1',
packages=['trufflehog'],
include_package_data=True,
license='MIT',
description='Track Django model instances',
long_description=README,
url='https://github.com/jleeothon/trufflehog',
author='Johnny Lee',
author_email='jleeothon@outlook.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=['django'],
tests_require=['django'],
)
|
59196bea40b8d77f01d2d6d57212167870fb504d | setup.py | setup.py | from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| Update Trove classifier to include Python 3.7 | Update Trove classifier to include Python 3.7
| Python | mit | samteezy/snappass-heroku,samteezy/snappass-heroku,pinterest/snappass,samteezy/snappass-heroku,pinterest/snappass,pinterest/snappass | from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
Update Trove classifier to include Python 3.7 | from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| <commit_before>from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
<commit_msg>Update Trove classifier to include Python 3.7<commit_after> | from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
Update Trove classifier to include Python 3.7from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| <commit_before>from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
<commit_msg>Update Trove classifier to include Python 3.7<commit_after>from setuptools import setup
setup(
name='snappass',
version='1.3.0',
description="It's like SnapChat... for Passwords.",
long_description=(open('README.rst').read() + '\n\n' +
open('AUTHORS.rst').read()),
url='http://github.com/Pinterest/snappass/',
install_requires=['Flask', 'redis', 'cryptography'],
license='MIT',
author='Dave Dash',
author_email='dd+github@davedash.com',
packages=['snappass'],
entry_points={
'console_scripts': [
'snappass = snappass.main:main',
],
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
|
24994d0e9c7bf35a12baad371cdbe16b836588c3 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingestor:main',
'print_image = ingester.utils:print_image',
]
},
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingester:main',
'print_image = ingester.utils:print_image',
]
},
)
| Fix typo when renaming ingestor -> ingester | Fix typo when renaming ingestor -> ingester
| Python | bsd-3-clause | omad/datacube-experiments | #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingestor:main',
'print_image = ingester.utils:print_image',
]
},
)
Fix typo when renaming ingestor -> ingester | #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingester:main',
'print_image = ingester.utils:print_image',
]
},
)
| <commit_before>#!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingestor:main',
'print_image = ingester.utils:print_image',
]
},
)
<commit_msg>Fix typo when renaming ingestor -> ingester<commit_after> | #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingester:main',
'print_image = ingester.utils:print_image',
]
},
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingestor:main',
'print_image = ingester.utils:print_image',
]
},
)
Fix typo when renaming ingestor -> ingester#!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingester:main',
'print_image = ingester.utils:print_image',
]
},
)
| <commit_before>#!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingestor:main',
'print_image = ingester.utils:print_image',
]
},
)
<commit_msg>Fix typo when renaming ingestor -> ingester<commit_after>#!/usr/bin/env python
from setuptools import setup
setup(
name='datacube-experiments',
description='Experimental Datacube v2 Ingestor',
version='0.0.1',
packages=['ingester'],
url='http://github.com/omad/datacube-experiments',
install_requires=[
'click',
'eodatasets',
'eotools',
'gdal',
'pathlib',
'pyyaml',
'numpy',
'netCDF4',
],
tests_require=[
'pytest',
],
entry_points={
'console_scripts': [
'datacube_ingest = ingester.datacube_ingester:main',
'print_image = ingester.utils:print_image',
]
},
)
|
2fbf7ea2dd7f163bb86f60e5c607af2fd43e1739 | kicost/currency_converter/download_rates.py | kicost/currency_converter/download_rates.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
| #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import os
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
if os.environ.get('KICOST_CURRENCY_RATES'):
with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f:
content = f.read()
else:
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
| Allow to fake the currency rates. | Allow to fake the currency rates.
- The envidonment variable KICOST_CURRENCY_RATES can be used to fake
the cunrrency rates.
- It must indicate the name of an XML file containing the desired
rates.
- The format is the one used by the European Central Bank.
| Python | mit | xesscorp/KiCost,xesscorp/KiCost,hildogjr/KiCost,hildogjr/KiCost,xesscorp/KiCost,hildogjr/KiCost | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
Allow to fake the currency rates.
- The envidonment variable KICOST_CURRENCY_RATES can be used to fake
the cunrrency rates.
- It must indicate the name of an XML file containing the desired
rates.
- The format is the one used by the European Central Bank. | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import os
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
if os.environ.get('KICOST_CURRENCY_RATES'):
with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f:
content = f.read()
else:
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
| <commit_before>#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
<commit_msg>Allow to fake the currency rates.
- The envidonment variable KICOST_CURRENCY_RATES can be used to fake
the cunrrency rates.
- It must indicate the name of an XML file containing the desired
rates.
- The format is the one used by the European Central Bank.<commit_after> | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import os
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
if os.environ.get('KICOST_CURRENCY_RATES'):
with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f:
content = f.read()
else:
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
| #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
Allow to fake the currency rates.
- The envidonment variable KICOST_CURRENCY_RATES can be used to fake
the cunrrency rates.
- It must indicate the name of an XML file containing the desired
rates.
- The format is the one used by the European Central Bank.#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import os
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
if os.environ.get('KICOST_CURRENCY_RATES'):
with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f:
content = f.read()
else:
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
| <commit_before>#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
<commit_msg>Allow to fake the currency rates.
- The envidonment variable KICOST_CURRENCY_RATES can be used to fake
the cunrrency rates.
- It must indicate the name of an XML file containing the desired
rates.
- The format is the one used by the European Central Bank.<commit_after>#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Salvador E. Tropea
# Copyright (c) 2021 Instituto Nacional de Tecnología Industrial
# License: Apache 2.0
# Project: KiCost
"""
Simple helper to download the exchange rates.
"""
import os
import sys
from bs4 import BeautifulSoup
if sys.version_info[0] < 3:
from urllib2 import urlopen, URLError
else:
from urllib.request import urlopen, URLError
# Author information.
__author__ = 'Salvador Eduardo Tropea'
__webpage__ = 'https://github.com/set-soft/'
__company__ = 'INTI-CMNB - Argentina'
url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
def download_rates():
content = ''
if os.environ.get('KICOST_CURRENCY_RATES'):
with open(os.environ['KICOST_CURRENCY_RATES'], 'rt') as f:
content = f.read()
else:
try:
content = urlopen(url).read().decode('utf8')
except URLError:
pass
soup = BeautifulSoup(content, 'xml')
rates = {'EUR': 1.0}
date = ''
for entry in soup.find_all('Cube'):
currency = entry.get('currency')
if currency is not None:
rates[currency] = float(entry.get('rate'))
elif entry.get('time'):
date = entry.get('time')
return date, rates
|
ff3c3c3842790cc9eb06f1241d6da77f828859c1 | IPython/external/qt.py | IPython/external/qt.py | """ A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Use PyQt by default until PySide is stable.
qt_api = os.environ.get('QT_API', 'pyqt')
if qt_api == 'pyqt':
# For PySide compatibility, use the new string API that automatically
# converts QStrings to unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
else:
from PySide import QtCore, QtGui, QtSvg
| """ A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
| Clean up in Qt API switcher. | Clean up in Qt API switcher.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | """ A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Use PyQt by default until PySide is stable.
qt_api = os.environ.get('QT_API', 'pyqt')
if qt_api == 'pyqt':
# For PySide compatibility, use the new string API that automatically
# converts QStrings to unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
else:
from PySide import QtCore, QtGui, QtSvg
Clean up in Qt API switcher. | """ A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
| <commit_before>""" A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Use PyQt by default until PySide is stable.
qt_api = os.environ.get('QT_API', 'pyqt')
if qt_api == 'pyqt':
# For PySide compatibility, use the new string API that automatically
# converts QStrings to unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
else:
from PySide import QtCore, QtGui, QtSvg
<commit_msg>Clean up in Qt API switcher.<commit_after> | """ A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
| """ A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Use PyQt by default until PySide is stable.
qt_api = os.environ.get('QT_API', 'pyqt')
if qt_api == 'pyqt':
# For PySide compatibility, use the new string API that automatically
# converts QStrings to unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
else:
from PySide import QtCore, QtGui, QtSvg
Clean up in Qt API switcher.""" A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
| <commit_before>""" A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Use PyQt by default until PySide is stable.
qt_api = os.environ.get('QT_API', 'pyqt')
if qt_api == 'pyqt':
# For PySide compatibility, use the new string API that automatically
# converts QStrings to unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
else:
from PySide import QtCore, QtGui, QtSvg
<commit_msg>Clean up in Qt API switcher.<commit_after>""" A Qt API selector that can be used to switch between PyQt and PySide.
"""
import os
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
|
d5ded8c16f91c1171d7435749b050c5c13c3ce1b | echo_client.py | echo_client.py | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
print response_msg
if __name__ == '__main__':
client(sys.argv[1])
| import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
return response_msg
if __name__ == '__main__':
client(sys.argv[1])
| Return response instead of print on client side | Return response instead of print on client side
| Python | mit | jwarren116/network-tools,jwarren116/network-tools | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
print response_msg
if __name__ == '__main__':
client(sys.argv[1])
Return response instead of print on client side | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
return response_msg
if __name__ == '__main__':
client(sys.argv[1])
| <commit_before>import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
print response_msg
if __name__ == '__main__':
client(sys.argv[1])
<commit_msg>Return response instead of print on client side<commit_after> | import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
return response_msg
if __name__ == '__main__':
client(sys.argv[1])
| import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
print response_msg
if __name__ == '__main__':
client(sys.argv[1])
Return response instead of print on client sideimport socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
return response_msg
if __name__ == '__main__':
client(sys.argv[1])
| <commit_before>import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
print response_msg
if __name__ == '__main__':
client(sys.argv[1])
<commit_msg>Return response instead of print on client side<commit_after>import socket
import sys
def client(msg):
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect(('127.0.0.1', 50000))
# sends command line message to server, closes socket to writing
client_socket.sendall(msg)
client_socket.shutdown(socket.SHUT_WR)
buffsize = 32
response_msg = ''
done = False
while not done:
msg_part = client_socket.recv(buffsize)
if len(msg_part) < buffsize:
done = True
client_socket.close()
response_msg += msg_part
return response_msg
if __name__ == '__main__':
client(sys.argv[1])
|
975664ce73283d89b1b3e9422366da87c67860ad | girder/test_girder/test_web_client.py | girder/test_girder/test_web_client.py | import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
| import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
# 'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
| Disable the annotationSpec so that CI will pass until we fix it. | Disable the annotationSpec so that CI will pass until we fix it.
| Python | apache-2.0 | DigitalSlideArchive/large_image,girder/large_image,DigitalSlideArchive/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image | import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
Disable the annotationSpec so that CI will pass until we fix it. | import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
# 'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
| <commit_before>import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
<commit_msg>Disable the annotationSpec so that CI will pass until we fix it.<commit_after> | import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
# 'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
| import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
Disable the annotationSpec so that CI will pass until we fix it.import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
# 'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
| <commit_before>import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
<commit_msg>Disable the annotationSpec so that CI will pass until we fix it.<commit_after>import os
import pytest
from pytest_girder.web_client import runWebClientTest
from .girder_utilities import girderWorker # noqa
@pytest.mark.usefixtures('girderWorker') # noqa
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
# 'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
|
f14329dd4449c352cdf82ff2ffab0bfb9bcff882 | parser.py | parser.py | from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command and params must be non-empty
if len(command) == 0 or len(params) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
| from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command must be non-empty
if len(command) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
| Fix parsing irc messages with empty list of parameters | Fix parsing irc messages with empty list of parameters
| Python | mit | aalien/mib | from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command and params must be non-empty
if len(command) == 0 or len(params) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
Fix parsing irc messages with empty list of parameters | from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command must be non-empty
if len(command) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
| <commit_before>from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command and params must be non-empty
if len(command) == 0 or len(params) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
<commit_msg>Fix parsing irc messages with empty list of parameters<commit_after> | from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command must be non-empty
if len(command) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
| from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command and params must be non-empty
if len(command) == 0 or len(params) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
Fix parsing irc messages with empty list of parametersfrom collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command must be non-empty
if len(command) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
| <commit_before>from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command and params must be non-empty
if len(command) == 0 or len(params) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
<commit_msg>Fix parsing irc messages with empty list of parameters<commit_after>from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command
- params are the parameters for the command,
not including the possible postfix
- postfix is the part of the parameters starting with :, without the :
"""
if not line:
return None
prefix = ''
command = ''
params = ''
postfix = ''
# prefix is present is line starts with ':'
if line[0] == ':':
prefix, line = line.split(' ', 1)
# there might be more than one space between
# the possible prefix and command, so we'll strip them
command, line = line.lstrip().split(' ', 1)
# postfix is present is line has ':'
index = line.find(':')
if index != -1:
params = line[:index]
postfix = line[index:]
else:
params = line
# command must be non-empty
if len(command) == 0:
return None
return IRCMsg(prefix=prefix[1:], cmd=command, params=params,
postfix=postfix[1:])
|
d6a054b4d59081920c68917c659ecd51a4517086 | client.py | client.py | import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
| import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
headers = {"Range": "0-0"}
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
| Add Range header for GET that should be HEAD | Add Range header for GET that should be HEAD
| Python | mit | davidthewatson/postgrest_python_requests_client | import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
Add Range header for GET that should be HEAD | import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
headers = {"Range": "0-0"}
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
| <commit_before>import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
<commit_msg>Add Range header for GET that should be HEAD<commit_after> | import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
headers = {"Range": "0-0"}
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
| import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
Add Range header for GET that should be HEADimport json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
headers = {"Range": "0-0"}
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
| <commit_before>import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
<commit_msg>Add Range header for GET that should be HEAD<commit_after>import json
import requests
import requests_jwt
try:
from config import credentials, urls
except ImportError:
print('Config.py not found. Copy config.in to config.py and edit to suit.')
exit()
PAGE_SIZE = 20
def login(email, password):
r = requests.post(urls.login,
json={"email": email,
"pass": password})
r.raise_for_status()
return r
def construct_jwt_auth(response):
token = json.loads(response.text)['token']
auth = requests_jwt.JWTAuth(token)
return auth
def get_result_size():
headers = {"Range": "0-0"}
r = requests.get(urls.data, auth=auth)
size = int(r.headers['Content-Range'].split('/')[1])
return size
def get_range(beg, end, auth):
end = beg + PAGE_SIZE if beg + PAGE_SIZE < end else end
this_range = '{0}-{1}'.format(beg, end)
headers = {"Range": "{}".format(this_range)}
r = requests.get(urls.data, auth=auth,
headers=headers)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
r = login(credentials.email, credentials.password)
auth = construct_jwt_auth(r)
size = get_result_size()
for i in range(0, size, PAGE_SIZE):
this_range = get_range(i, i+PAGE_SIZE-1, auth)
print(str(this_range) + '\n')
|
d7241f9c22ae6e962a2a7a7b2d9cf2a8eb1044a6 | scripts/stops.py | scripts/stops.py | #!/usr/bin/python
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
| #!/usr/bin/python
# Written by Taylor Denouden March 17, 2014
# Script to convert GTFS stops to geojson
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
| Add author note and description | Add author note and description
| Python | mit | bus-viz/bus-viz,bus-viz/bus-viz,bus-viz/bus-viz | #!/usr/bin/python
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
Add author note and description | #!/usr/bin/python
# Written by Taylor Denouden March 17, 2014
# Script to convert GTFS stops to geojson
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
| <commit_before>#!/usr/bin/python
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
<commit_msg>Add author note and description<commit_after> | #!/usr/bin/python
# Written by Taylor Denouden March 17, 2014
# Script to convert GTFS stops to geojson
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
| #!/usr/bin/python
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
Add author note and description#!/usr/bin/python
# Written by Taylor Denouden March 17, 2014
# Script to convert GTFS stops to geojson
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
| <commit_before>#!/usr/bin/python
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
<commit_msg>Add author note and description<commit_after>#!/usr/bin/python
# Written by Taylor Denouden March 17, 2014
# Script to convert GTFS stops to geojson
import sys
import csv
import json
def main(argv):
if len(argv) < 1:
print "Usage: ./stops.py outFile.js [/path/to/stops.txt]"
csvFile = open(argv[1] if argv[1] else "stops.txt")
features = []
for row in csv.DictReader(csvFile):
feature = {
'type': 'Feature',
'properties': {
'stop_id': row['stop_id'],
'stop_name': row['stop_name'],
'location_type': row['location_type'],
'parent_station': row['parent_station'],
'stop_short_name': row['stop_short_name']
},
'geometry': {
'type': 'Point',
'coordinates': [float(row['stop_lon']), float(row['stop_lat'])]
}
}
features.append(feature)
with open(argv[0], 'w') as outfile:
outfile.write("var bus_stops = " + json.dumps({'type': 'FeatureCollection', 'features': features}))
if __name__ == "__main__":
main(sys.argv[1:])
|
56a08fae0947f1c3057aebc39a898a4dd390da6e | st2common/st2common/constants/scheduler.py | st2common/st2common/constants/scheduler.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = ['SCHEDULER_ENABLED_LOG_LINE', 'SCHEDULER_DISABLED_LOG_LINE']
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = 'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = 'Scheduler is disabled.'
| # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = [
'SCHEDULER_ENABLED_LOG_LINE',
'SCHEDULER_DISABLED_LOG_LINE'
]
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = b'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = b'Scheduler is disabled.'
| Fix st2actions tests so they pass under Python 3. | Fix st2actions tests so they pass under Python 3.
| Python | apache-2.0 | Plexxi/st2,nzlosh/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = ['SCHEDULER_ENABLED_LOG_LINE', 'SCHEDULER_DISABLED_LOG_LINE']
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = 'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = 'Scheduler is disabled.'
Fix st2actions tests so they pass under Python 3. | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = [
'SCHEDULER_ENABLED_LOG_LINE',
'SCHEDULER_DISABLED_LOG_LINE'
]
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = b'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = b'Scheduler is disabled.'
| <commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = ['SCHEDULER_ENABLED_LOG_LINE', 'SCHEDULER_DISABLED_LOG_LINE']
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = 'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = 'Scheduler is disabled.'
<commit_msg>Fix st2actions tests so they pass under Python 3.<commit_after> | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = [
'SCHEDULER_ENABLED_LOG_LINE',
'SCHEDULER_DISABLED_LOG_LINE'
]
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = b'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = b'Scheduler is disabled.'
| # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = ['SCHEDULER_ENABLED_LOG_LINE', 'SCHEDULER_DISABLED_LOG_LINE']
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = 'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = 'Scheduler is disabled.'
Fix st2actions tests so they pass under Python 3.# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = [
'SCHEDULER_ENABLED_LOG_LINE',
'SCHEDULER_DISABLED_LOG_LINE'
]
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = b'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = b'Scheduler is disabled.'
| <commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = ['SCHEDULER_ENABLED_LOG_LINE', 'SCHEDULER_DISABLED_LOG_LINE']
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = 'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = 'Scheduler is disabled.'
<commit_msg>Fix st2actions tests so they pass under Python 3.<commit_after># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use 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.
__all__ = [
'SCHEDULER_ENABLED_LOG_LINE',
'SCHEDULER_DISABLED_LOG_LINE'
]
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = b'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = b'Scheduler is disabled.'
|
ca348485b0acf2dbc41f2b4e52140d69e318327c | conanfile.py | conanfile.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
exports = "LICENSE"
exports_sources = "include/*"
no_copy_source = True
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
no_copy_source = True
scm = {
"type": "git",
"url": "auto",
"revision": "auto"
}
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
| Use SCM feature to build Conan package | Use SCM feature to build Conan package
- SCM could export all project files helping to build
Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>
| Python | apache-2.0 | hanickadot/compile-time-regular-expressions,hanickadot/syntax-parser,hanickadot/compile-time-regular-expressions,hanickadot/compile-time-regular-expressions | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
exports = "LICENSE"
exports_sources = "include/*"
no_copy_source = True
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
Use SCM feature to build Conan package
- SCM could export all project files helping to build
Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
no_copy_source = True
scm = {
"type": "git",
"url": "auto",
"revision": "auto"
}
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
exports = "LICENSE"
exports_sources = "include/*"
no_copy_source = True
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
<commit_msg>Use SCM feature to build Conan package
- SCM could export all project files helping to build
Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com><commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
no_copy_source = True
scm = {
"type": "git",
"url": "auto",
"revision": "auto"
}
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
exports = "LICENSE"
exports_sources = "include/*"
no_copy_source = True
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
Use SCM feature to build Conan package
- SCM could export all project files helping to build
Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
no_copy_source = True
scm = {
"type": "git",
"url": "auto",
"revision": "auto"
}
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions.git"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
exports = "LICENSE"
exports_sources = "include/*"
no_copy_source = True
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
<commit_msg>Use SCM feature to build Conan package
- SCM could export all project files helping to build
Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com><commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile
class CtreConan(ConanFile):
name = "CTRE"
version = "2.0"
license = "MIT"
url = "https://github.com/hanickadot/compile-time-regular-expressions"
author = "Hana Dusíková (ctre@hanicka.net)"
description = "Compile Time Regular Expression for C++17/20"
homepage = "https://github.com/hanickadot/compile-time-regular-expressions"
no_copy_source = True
scm = {
"type": "git",
"url": "auto",
"revision": "auto"
}
def package(self):
self.copy("LICENSE", "licenses")
self.copy("*.hpp")
def package_id(self):
self.info.header_only()
|
47dd560f71649cc20199089fc680ca81d924d5a1 | livereload/middleware.py | livereload/middleware.py | """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Inject the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if content_type not in ['text/html', 'application/xhtml+xml'] or settings.DEBUG == False:
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
| """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Injects the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if (not settings.DEBUG or
content_type not in ['text/html', 'application/xhtml+xml'] or
not hasattr(response, 'content')):
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
| Check that response is not a StreamingResponse. | Check that response is not a StreamingResponse.
| Python | bsd-3-clause | tjwalch/django-livereload-server | """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Inject the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if content_type not in ['text/html', 'application/xhtml+xml'] or settings.DEBUG == False:
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
Check that response is not a StreamingResponse. | """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Injects the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if (not settings.DEBUG or
content_type not in ['text/html', 'application/xhtml+xml'] or
not hasattr(response, 'content')):
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
| <commit_before>"""
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Inject the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if content_type not in ['text/html', 'application/xhtml+xml'] or settings.DEBUG == False:
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
<commit_msg>Check that response is not a StreamingResponse.<commit_after> | """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Injects the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if (not settings.DEBUG or
content_type not in ['text/html', 'application/xhtml+xml'] or
not hasattr(response, 'content')):
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
| """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Inject the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if content_type not in ['text/html', 'application/xhtml+xml'] or settings.DEBUG == False:
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
Check that response is not a StreamingResponse."""
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Injects the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if (not settings.DEBUG or
content_type not in ['text/html', 'application/xhtml+xml'] or
not hasattr(response, 'content')):
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
| <commit_before>"""
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Inject the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if content_type not in ['text/html', 'application/xhtml+xml'] or settings.DEBUG == False:
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
<commit_msg>Check that response is not a StreamingResponse.<commit_after>"""
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Injects the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if (not settings.DEBUG or
content_type not in ['text/html', 'application/xhtml+xml'] or
not hasattr(response, 'content')):
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
|
e6274c801e9c5233ef40b4f4423072f4626f16e5 | config.py | config.py | from zirc import Sasl
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = "Sorry, you do not have the right permissions to execute this command"
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
| from zirc import Sasl, Caps
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
caps = Caps(sasl, "multi-prefix")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = " ".join(["Sorry,",
"you do not have the right permissions",
"to execute this command"])
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
| Add new caps variable, fix line length | Add new caps variable, fix line length | Python | mit | wolfy1339/Python-IRC-Bot | from zirc import Sasl
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = "Sorry, you do not have the right permissions to execute this command"
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
Add new caps variable, fix line length | from zirc import Sasl, Caps
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
caps = Caps(sasl, "multi-prefix")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = " ".join(["Sorry,",
"you do not have the right permissions",
"to execute this command"])
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
| <commit_before>from zirc import Sasl
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = "Sorry, you do not have the right permissions to execute this command"
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
<commit_msg>Add new caps variable, fix line length<commit_after> | from zirc import Sasl, Caps
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
caps = Caps(sasl, "multi-prefix")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = " ".join(["Sorry,",
"you do not have the right permissions",
"to execute this command"])
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
| from zirc import Sasl
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = "Sorry, you do not have the right permissions to execute this command"
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
Add new caps variable, fix line lengthfrom zirc import Sasl, Caps
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
caps = Caps(sasl, "multi-prefix")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = " ".join(["Sorry,",
"you do not have the right permissions",
"to execute this command"])
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
| <commit_before>from zirc import Sasl
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = "Sorry, you do not have the right permissions to execute this command"
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
<commit_msg>Add new caps variable, fix line length<commit_after>from zirc import Sasl, Caps
# zIRC
sasl = Sasl(username="BigWolfy1339", password="")
caps = Caps(sasl, "multi-prefix")
# IRC
channels = ["##wolfy1339", "##powder-bots", "##jeffl35"]
# Logging
logFormat = '%(levelname)s %(asctime)s %(message)s'
colorized = True
timestampFormat = '%Y-%m-%dT%H:%M:%S'
logLevel = 20 # INFO
# Bot
commandChar = '?'
owners = ['botters/wolfy1339']
admins = []
trusted = []
bots = {
'hosts': ['botters/wolf1339/bot/bigwolfy1339'],
'channels': ['##jeffl35', '##wolfy1339']
}
ignores = {
'global': [],
'channels': {
"##powder-bots": [],
"##wolfy1339": [],
}
}
# Error messages
noPerms = " ".join(["Sorry,",
"you do not have the right permissions",
"to execute this command"])
argsMissing = "Oops, looks like you forgot an argument there."
invalidCmd = 'Invalid command {0}'
tracebackPostError = "An error happened while trying to post the traceback"
|
d1330eb44b1842571ff7deacef175b9aa92e09c0 | openacademy/models/res_partner.py | openacademy/models/res_partner.py | # -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(help="This partner give train our course")
| # -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(default=False,help="This partner give train our course")
sessions = fields.Many2many('session', string="Session as instructor", readonly=True)
| Add partner view injerit and model inherit | [REF] openacademy: Add partner view injerit and model inherit
| Python | apache-2.0 | juancr83/DockerOpenacademy-proyect | # -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(help="This partner give train our course")
[REF] openacademy: Add partner view injerit and model inherit | # -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(default=False,help="This partner give train our course")
sessions = fields.Many2many('session', string="Session as instructor", readonly=True)
| <commit_before># -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(help="This partner give train our course")
<commit_msg>[REF] openacademy: Add partner view injerit and model inherit<commit_after> | # -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(default=False,help="This partner give train our course")
sessions = fields.Many2many('session', string="Session as instructor", readonly=True)
| # -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(help="This partner give train our course")
[REF] openacademy: Add partner view injerit and model inherit# -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(default=False,help="This partner give train our course")
sessions = fields.Many2many('session', string="Session as instructor", readonly=True)
| <commit_before># -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(help="This partner give train our course")
<commit_msg>[REF] openacademy: Add partner view injerit and model inherit<commit_after># -*- coding: utf-8 -*-
from openerp import models, fields
class Partner(models.Model):
_inherit = 'res.partner'
instructor = fields.Boolean(default=False,help="This partner give train our course")
sessions = fields.Many2many('session', string="Session as instructor", readonly=True)
|
ac0267d318939e4e7a62342b5dc6a09c3264ea74 | flocker/node/_deploy.py | flocker/node/_deploy.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
class Deployment(object):
"""
"""
_gear_client = None
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
from .gear import GearClient
class Deployment(object):
"""
"""
def __init__(self, gear_client=None):
"""
:param IGearClient gear_client: The gear client API to use in deployment
operations. Default ``GearClient``.
"""
if gear_client is None:
gear_client = GearClient(hostname=b'127.0.0.1')
self._gear_client = gear_client
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
| Allow a fake gear client to be supplied | Allow a fake gear client to be supplied
| Python | apache-2.0 | wallnerryan/flocker-profiles,hackday-profilers/flocker,lukemarsden/flocker,Azulinho/flocker,w4ngyi/flocker,hackday-profilers/flocker,LaynePeng/flocker,lukemarsden/flocker,AndyHuu/flocker,beni55/flocker,mbrukman/flocker,1d4Nf6/flocker,w4ngyi/flocker,beni55/flocker,adamtheturtle/flocker,hackday-profilers/flocker,achanda/flocker,moypray/flocker,achanda/flocker,runcom/flocker,LaynePeng/flocker,achanda/flocker,agonzalezro/flocker,1d4Nf6/flocker,LaynePeng/flocker,jml/flocker,beni55/flocker,jml/flocker,Azulinho/flocker,runcom/flocker,adamtheturtle/flocker,moypray/flocker,lukemarsden/flocker,agonzalezro/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,agonzalezro/flocker,AndyHuu/flocker,w4ngyi/flocker,moypray/flocker,Azulinho/flocker,1d4Nf6/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,mbrukman/flocker,jml/flocker,runcom/flocker,AndyHuu/flocker | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
class Deployment(object):
"""
"""
_gear_client = None
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
Allow a fake gear client to be supplied | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
from .gear import GearClient
class Deployment(object):
"""
"""
def __init__(self, gear_client=None):
"""
:param IGearClient gear_client: The gear client API to use in deployment
operations. Default ``GearClient``.
"""
if gear_client is None:
gear_client = GearClient(hostname=b'127.0.0.1')
self._gear_client = gear_client
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
| <commit_before># Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
class Deployment(object):
"""
"""
_gear_client = None
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
<commit_msg>Allow a fake gear client to be supplied<commit_after> | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
from .gear import GearClient
class Deployment(object):
"""
"""
def __init__(self, gear_client=None):
"""
:param IGearClient gear_client: The gear client API to use in deployment
operations. Default ``GearClient``.
"""
if gear_client is None:
gear_client = GearClient(hostname=b'127.0.0.1')
self._gear_client = gear_client
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
class Deployment(object):
"""
"""
_gear_client = None
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
Allow a fake gear client to be supplied# Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
from .gear import GearClient
class Deployment(object):
"""
"""
def __init__(self, gear_client=None):
"""
:param IGearClient gear_client: The gear client API to use in deployment
operations. Default ``GearClient``.
"""
if gear_client is None:
gear_client = GearClient(hostname=b'127.0.0.1')
self._gear_client = gear_client
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
| <commit_before># Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
class Deployment(object):
"""
"""
_gear_client = None
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
<commit_msg>Allow a fake gear client to be supplied<commit_after># Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.node.test.test_deploy -*-
"""
Deploy applications on nodes.
"""
from .gear import GearClient
class Deployment(object):
"""
"""
def __init__(self, gear_client=None):
"""
:param IGearClient gear_client: The gear client API to use in deployment
operations. Default ``GearClient``.
"""
if gear_client is None:
gear_client = GearClient(hostname=b'127.0.0.1')
self._gear_client = gear_client
def start_container(self, application):
"""
Launch the supplied application as a `gear` unit.
"""
def stop_container(self, application):
"""
Stop and disable the application.
"""
|
20bcdcfd2eee5e20e76299a81a71ac80c09f2b56 | post_office/test_settings.py | post_office/test_settings.py | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
)
#TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
| # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
| Make tests pass in Django 1.4. | Make tests pass in Django 1.4.
| Python | mit | JostCrow/django-post_office,ekohl/django-post_office,fapelhanz/django-post_office,ui/django-post_office,jrief/django-post_office,RafRaf/django-post_office,yprez/django-post_office,ui/django-post_office | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
)
#TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
Make tests pass in Django 1.4. | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
| <commit_before># -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
)
#TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
<commit_msg>Make tests pass in Django 1.4.<commit_after> | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
| # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
)
#TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
Make tests pass in Django 1.4.# -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
| <commit_before># -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
)
#TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
<commit_msg>Make tests pass in Django 1.4.<commit_after># -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
}
}
POST_OFFICE = {
# 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField',
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'post_office',
)
SECRET_KEY = 'a'
ROOT_URLCONF = 'post_office.test_urls'
DEFAULT_FROM_EMAIL = 'webmaster@example.com'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
|
550befeed6ff3b2c64454c05f9e05b586d16ff64 | googlevoice/__init__.py | googlevoice/__init__.py | """
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
__version__ = '0.5'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
| """
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
try:
__version__ = (
__import__('pkg_resources').get_distribution('googlevoice').version
)
except Exception:
__version__ = 'unknown'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
| Load the version from the package metadata. | Load the version from the package metadata.
| Python | bsd-3-clause | pettazz/pygooglevoice | """
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
__version__ = '0.5'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
Load the version from the package metadata. | """
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
try:
__version__ = (
__import__('pkg_resources').get_distribution('googlevoice').version
)
except Exception:
__version__ = 'unknown'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
| <commit_before>"""
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
__version__ = '0.5'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
<commit_msg>Load the version from the package metadata.<commit_after> | """
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
try:
__version__ = (
__import__('pkg_resources').get_distribution('googlevoice').version
)
except Exception:
__version__ = 'unknown'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
| """
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
__version__ = '0.5'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
Load the version from the package metadata."""
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
try:
__version__ = (
__import__('pkg_resources').get_distribution('googlevoice').version
)
except Exception:
__version__ = 'unknown'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
| <commit_before>"""
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
__version__ = '0.5'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
<commit_msg>Load the version from the package metadata.<commit_after>"""
This project aims to bring the power of the Google Voice API to
the Python language in a simple,
easy-to-use manner. Currently it allows you to place calls, send sms,
download voicemails/recorded messages, and search the various
folders of your Google Voice Accounts.
You can use the Python API or command line script to schedule
calls, check for new received calls/sms,
or even sync your recorded voicemails/calls.
Works for Python 2 and Python 3
"""
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
try:
__version__ = (
__import__('pkg_resources').get_distribution('googlevoice').version
)
except Exception:
__version__ = 'unknown'
from .voice import Voice
from .util import Phone, Message, Folder
__all__ = ['Voice', 'Phone', 'Message', 'Folder']
|
bb347838ad78d61e6a81a1c14657323ad7eeb82b | analysis/smooth-data.py | analysis/smooth-data.py | import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, accuracy=0.005, threshold=1000, frames=5):
for trial in database.Experiment(root).trials_matching('*'):
t.reindex()
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
| import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
frame_rate=('reindex frames to this rate', 'option', None, float),
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5):
for t in database.Experiment(root).trials_matching('*'):
t.reindex(frame_rate=frame_rate)
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
| Add parameter for frame rate. | Add parameter for frame rate.
| Python | mit | lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment | import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, accuracy=0.005, threshold=1000, frames=5):
for trial in database.Experiment(root).trials_matching('*'):
t.reindex()
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
Add parameter for frame rate. | import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
frame_rate=('reindex frames to this rate', 'option', None, float),
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5):
for t in database.Experiment(root).trials_matching('*'):
t.reindex(frame_rate=frame_rate)
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
| <commit_before>import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, accuracy=0.005, threshold=1000, frames=5):
for trial in database.Experiment(root).trials_matching('*'):
t.reindex()
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
<commit_msg>Add parameter for frame rate.<commit_after> | import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
frame_rate=('reindex frames to this rate', 'option', None, float),
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5):
for t in database.Experiment(root).trials_matching('*'):
t.reindex(frame_rate=frame_rate)
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
| import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, accuracy=0.005, threshold=1000, frames=5):
for trial in database.Experiment(root).trials_matching('*'):
t.reindex()
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
Add parameter for frame rate.import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
frame_rate=('reindex frames to this rate', 'option', None, float),
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5):
for t in database.Experiment(root).trials_matching('*'):
t.reindex(frame_rate=frame_rate)
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
| <commit_before>import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, accuracy=0.005, threshold=1000, frames=5):
for trial in database.Experiment(root).trials_matching('*'):
t.reindex()
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
<commit_msg>Add parameter for frame rate.<commit_after>import climate
import database
@climate.annotate(
root='load data files from this directory tree',
output='save smoothed data files to this directory tree',
frame_rate=('reindex frames to this rate', 'option', None, float),
accuracy=('fit SVT with this accuracy', 'option', None, float),
threshold=('SVT threshold', 'option', None, float),
frames=('number of frames for SVT', 'option', None, int),
)
def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5):
for t in database.Experiment(root).trials_matching('*'):
t.reindex(frame_rate=frame_rate)
t.svt(threshold, accuracy, frames)
t.save(t.root.replace(root, output))
if __name__ == '__main__':
climate.call(main)
|
dc7a1566fdb581c592554af9c5e7193d06e3724e | tests/query_test/test_hbase_queries.py | tests/query_test/test_hbase_queries.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
self.run_test_case('QueryTest/hbase-inserts', vector)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
| #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
try:
self.run_test_case('QueryTest/hbase-inserts', vector)
except AssertionError:
msg = ('IMPALA-579 - Insert into a binary encoded hbase table produces'
' incorrect results')
pytest.xfail(msg)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
| Disable some tests in test_hbase_insert to fix the build. | Disable some tests in test_hbase_insert to fix the build.
Change-Id: I037b292d0eb93c5c743a201b2045eb2ba0712ae7
Reviewed-on: http://gerrit.ent.cloudera.com:8080/387
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Tested-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
| Python | apache-2.0 | michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
self.run_test_case('QueryTest/hbase-inserts', vector)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
Disable some tests in test_hbase_insert to fix the build.
Change-Id: I037b292d0eb93c5c743a201b2045eb2ba0712ae7
Reviewed-on: http://gerrit.ent.cloudera.com:8080/387
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Tested-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com> | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
try:
self.run_test_case('QueryTest/hbase-inserts', vector)
except AssertionError:
msg = ('IMPALA-579 - Insert into a binary encoded hbase table produces'
' incorrect results')
pytest.xfail(msg)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
| <commit_before>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
self.run_test_case('QueryTest/hbase-inserts', vector)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
<commit_msg>Disable some tests in test_hbase_insert to fix the build.
Change-Id: I037b292d0eb93c5c743a201b2045eb2ba0712ae7
Reviewed-on: http://gerrit.ent.cloudera.com:8080/387
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Tested-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com><commit_after> | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
try:
self.run_test_case('QueryTest/hbase-inserts', vector)
except AssertionError:
msg = ('IMPALA-579 - Insert into a binary encoded hbase table produces'
' incorrect results')
pytest.xfail(msg)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
| #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
self.run_test_case('QueryTest/hbase-inserts', vector)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
Disable some tests in test_hbase_insert to fix the build.
Change-Id: I037b292d0eb93c5c743a201b2045eb2ba0712ae7
Reviewed-on: http://gerrit.ent.cloudera.com:8080/387
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Tested-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
try:
self.run_test_case('QueryTest/hbase-inserts', vector)
except AssertionError:
msg = ('IMPALA-579 - Insert into a binary encoded hbase table produces'
' incorrect results')
pytest.xfail(msg)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
| <commit_before>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
self.run_test_case('QueryTest/hbase-inserts', vector)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
<commit_msg>Disable some tests in test_hbase_insert to fix the build.
Change-Id: I037b292d0eb93c5c743a201b2045eb2ba0712ae7
Reviewed-on: http://gerrit.ent.cloudera.com:8080/387
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Tested-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com><commit_after>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestHBaseQueries, cls).add_test_dimensions()
cls.TestMatrix.add_constraint(\
lambda v: v.get_value('table_format').file_format == 'hbase')
def test_hbase_scan_node(self, vector):
self.run_test_case('QueryTest/hbase-scan-node', vector)
def test_hbase_row_key(self, vector):
self.run_test_case('QueryTest/hbase-rowkeys', vector)
def test_hbase_filters(self, vector):
self.run_test_case('QueryTest/hbase-filters', vector)
def test_hbase_inserts(self, vector):
try:
self.run_test_case('QueryTest/hbase-inserts', vector)
except AssertionError:
msg = ('IMPALA-579 - Insert into a binary encoded hbase table produces'
' incorrect results')
pytest.xfail(msg)
def test_hbase_subquery(self, vector):
self.run_test_case('QueryTest/hbase-subquery', vector)
|
6fd4e2e4158c968a095832f3bf669109dc9f1481 | mopidy_mpris/__init__.py | mopidy_mpris/__init__.py | import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| Use pathlib to read ext.conf | Use pathlib to read ext.conf
| Python | apache-2.0 | mopidy/mopidy-mpris | import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
Use pathlib to read ext.conf | import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| <commit_before>import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
<commit_msg>Use pathlib to read ext.conf<commit_after> | import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
Use pathlib to read ext.confimport pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| <commit_before>import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
<commit_msg>Use pathlib to read ext.conf<commit_after>import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
|
ac2b2f54eef719d633a4135e244497cbc499a70f | wapps/templatetags/commons.py | wapps/templatetags/commons.py | from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page, *data]
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
| from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page] + list(data)
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
| Fix Syntax error for Python<3.5 | Fix Syntax error for Python<3.5
| Python | mit | apihackers/wapps,apihackers/wapps,apihackers/wapps,apihackers/wapps | from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page, *data]
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
Fix Syntax error for Python<3.5 | from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page] + list(data)
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
| <commit_before>from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page, *data]
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
<commit_msg>Fix Syntax error for Python<3.5<commit_after> | from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page] + list(data)
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
| from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page, *data]
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
Fix Syntax error for Python<3.5from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page] + list(data)
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
| <commit_before>from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page, *data]
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
<commit_msg>Fix Syntax error for Python<3.5<commit_after>from datetime import datetime
import jinja2
from django.utils.safestring import mark_safe
from django_jinja import library
from .. import json
from ..jsonld import graph
@library.filter(name='json')
def json_encode(data):
return json.dumps(data)
@library.filter
@library.global_function
@jinja2.contextfunction
def jsonld(context, *data):
if 'page' in context and hasattr(context['page'], '__jsonld__'):
page = context['page']
if page not in data:
data = [page] + list(data)
return mark_safe(''.join((
'<script type="application/ld+json">',
json.dumps(graph(context, *data)),
'</script>'
)))
@library.global_function
def now():
return datetime.now()
@library.global_function
@library.render_with('includes/pager.html')
@jinja2.contextfunction
def pager_for(page, previous_label=None, next_label=None):
return {
"page": page,
'previous_label': previous_label,
'next_label': next_label,
# "querystring": querystring,
}
|
f473ebe7ce68560952a68247341bde46c2f26c97 | shoop/core/order_creator/_modifier.py | shoop/core/order_creator/_modifier.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.delete()
return self.finalize_creation(order, order_source)
| # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.taxes.all().delete() # Delete all tax lines before OrderLine's
line.delete()
return self.finalize_creation(order, order_source)
| Enable modifying orders with taxes | Core: Enable modifying orders with taxes
Refs SHOOP-2338 / SHOOP-2578
| Python | agpl-3.0 | shawnadelic/shuup,shoopio/shoop,suutari/shoop,hrayr-artunyan/shuup,shawnadelic/shuup,suutari/shoop,hrayr-artunyan/shuup,suutari-ai/shoop,suutari-ai/shoop,suutari-ai/shoop,suutari/shoop,hrayr-artunyan/shuup,shoopio/shoop,shawnadelic/shuup,shoopio/shoop | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.delete()
return self.finalize_creation(order, order_source)
Core: Enable modifying orders with taxes
Refs SHOOP-2338 / SHOOP-2578 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.taxes.all().delete() # Delete all tax lines before OrderLine's
line.delete()
return self.finalize_creation(order, order_source)
| <commit_before># -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.delete()
return self.finalize_creation(order, order_source)
<commit_msg>Core: Enable modifying orders with taxes
Refs SHOOP-2338 / SHOOP-2578<commit_after> | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.taxes.all().delete() # Delete all tax lines before OrderLine's
line.delete()
return self.finalize_creation(order, order_source)
| # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.delete()
return self.finalize_creation(order, order_source)
Core: Enable modifying orders with taxes
Refs SHOOP-2338 / SHOOP-2578# -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.taxes.all().delete() # Delete all tax lines before OrderLine's
line.delete()
return self.finalize_creation(order, order_source)
| <commit_before># -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.delete()
return self.finalize_creation(order, order_source)
<commit_msg>Core: Enable modifying orders with taxes
Refs SHOOP-2338 / SHOOP-2578<commit_after># -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.transaction import atomic
from shoop.core.models import Order
from ._creator import OrderProcessor
class OrderModifier(OrderProcessor):
@atomic
def update_order_from_source(self, order_source, order):
data = self.get_source_base_data(order_source)
Order.objects.filter(pk=order.pk).update(**data)
order = Order.objects.get(pk=order.pk)
for line in order.lines.all():
line.taxes.all().delete() # Delete all tax lines before OrderLine's
line.delete()
return self.finalize_creation(order, order_source)
|
5c806fbd52da5ddb006c24b922967e6468e73221 | zerver/tornado/application.py | zerver/tornado/application.py | import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
# Application is an instance of Django's standard wsgi handler.
return tornado.web.Application([(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None)
| import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
return tornado.web.Application(
[(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None
)
| Remove a misleading comment and reformat. | tornado: Remove a misleading comment and reformat.
tornado.web.Application does not share any inheritance with Django at
all; it has a similar router interface, but tornado.web.Application is
not an instance of Django anything.
Refold the long lines that follow it.
| Python | apache-2.0 | zulip/zulip,rht/zulip,kou/zulip,zulip/zulip,kou/zulip,rht/zulip,rht/zulip,eeshangarg/zulip,andersk/zulip,showell/zulip,hackerkid/zulip,punchagan/zulip,showell/zulip,rht/zulip,rht/zulip,zulip/zulip,zulip/zulip,andersk/zulip,andersk/zulip,eeshangarg/zulip,eeshangarg/zulip,kou/zulip,eeshangarg/zulip,hackerkid/zulip,andersk/zulip,punchagan/zulip,zulip/zulip,hackerkid/zulip,hackerkid/zulip,punchagan/zulip,punchagan/zulip,kou/zulip,hackerkid/zulip,showell/zulip,eeshangarg/zulip,zulip/zulip,eeshangarg/zulip,andersk/zulip,showell/zulip,eeshangarg/zulip,punchagan/zulip,kou/zulip,kou/zulip,punchagan/zulip,zulip/zulip,showell/zulip,andersk/zulip,hackerkid/zulip,rht/zulip,andersk/zulip,punchagan/zulip,showell/zulip,hackerkid/zulip,showell/zulip,kou/zulip,rht/zulip | import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
# Application is an instance of Django's standard wsgi handler.
return tornado.web.Application([(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None)
tornado: Remove a misleading comment and reformat.
tornado.web.Application does not share any inheritance with Django at
all; it has a similar router interface, but tornado.web.Application is
not an instance of Django anything.
Refold the long lines that follow it. | import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
return tornado.web.Application(
[(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None
)
| <commit_before>import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
# Application is an instance of Django's standard wsgi handler.
return tornado.web.Application([(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None)
<commit_msg>tornado: Remove a misleading comment and reformat.
tornado.web.Application does not share any inheritance with Django at
all; it has a similar router interface, but tornado.web.Application is
not an instance of Django anything.
Refold the long lines that follow it.<commit_after> | import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
return tornado.web.Application(
[(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None
)
| import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
# Application is an instance of Django's standard wsgi handler.
return tornado.web.Application([(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None)
tornado: Remove a misleading comment and reformat.
tornado.web.Application does not share any inheritance with Django at
all; it has a similar router interface, but tornado.web.Application is
not an instance of Django anything.
Refold the long lines that follow it.import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
return tornado.web.Application(
[(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None
)
| <commit_before>import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
# Application is an instance of Django's standard wsgi handler.
return tornado.web.Application([(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None)
<commit_msg>tornado: Remove a misleading comment and reformat.
tornado.web.Application does not share any inheritance with Django at
all; it has a similar router interface, but tornado.web.Application is
not an instance of Django anything.
Refold the long lines that follow it.<commit_after>import atexit
import tornado.web
from django.conf import settings
from zerver.lib.queue import get_queue_client
from zerver.tornado import autoreload
from zerver.tornado.handlers import AsyncDjangoHandler
def setup_tornado_rabbitmq() -> None: # nocoverage
# When tornado is shut down, disconnect cleanly from rabbitmq
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application() -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/events/internal",
)
return tornado.web.Application(
[(url, AsyncDjangoHandler) for url in urls],
debug=settings.DEBUG,
autoreload=False,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None
)
|
0c327e17dba29a4e94213f264fe7ea931bb26782 | invoke/parser/argument.py | invoke/parser/argument.py | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
| class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None, help=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
self.help = help
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
| Add support for per Argument help data | Add support for per Argument help data
| Python | bsd-2-clause | kejbaly2/invoke,mattrobenolt/invoke,pyinvoke/invoke,pfmoore/invoke,sophacles/invoke,kejbaly2/invoke,pfmoore/invoke,mkusz/invoke,mattrobenolt/invoke,mkusz/invoke,tyewang/invoke,pyinvoke/invoke,singingwolfboy/invoke,frol/invoke,frol/invoke,alex/invoke | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
Add support for per Argument help data | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None, help=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
self.help = help
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
| <commit_before>class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
<commit_msg>Add support for per Argument help data<commit_after> | class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None, help=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
self.help = help
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
| class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
Add support for per Argument help dataclass Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None, help=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
self.help = help
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
| <commit_before>class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
<commit_msg>Add support for per Argument help data<commit_after>class Argument(object):
def __init__(self, name=None, names=(), kind=str, default=None, help=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at least one name.")
self.names = names if names else (name,)
self.kind = kind
self.raw_value = self._value = None
self.default = default
self.help = help
def __str__(self):
return "Arg: %r (%s)" % (self.names, self.kind)
@property
def takes_value(self):
return self.kind is not bool
@property
def value(self):
return self._value if self._value is not None else self.default
@value.setter
def value(self, arg):
self.raw_value = arg
self._value = self.kind(arg)
|
0d8cd57b6d5d4755709ca853856eb14b4b63f437 | servant.py | servant.py | import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
try:
os.remove("coverage/tracer.so")
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
| import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
| Make tox with with py3.2: the .so is named differently there. | Make tox with with py3.2: the .so is named differently there.
| Python | apache-2.0 | nedbat/coveragepy,nedbat/coveragepy,larsbutler/coveragepy,larsbutler/coveragepy,blueyed/coveragepy,blueyed/coveragepy,hugovk/coveragepy,7WebPages/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,hugovk/coveragepy,7WebPages/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,jayhetee/coveragepy,hugovk/coveragepy,jayhetee/coveragepy,hugovk/coveragepy,blueyed/coveragepy,7WebPages/coveragepy,7WebPages/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,hugovk/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,nedbat/coveragepy | import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
try:
os.remove("coverage/tracer.so")
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
Make tox with with py3.2: the .so is named differently there. | import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
| <commit_before>import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
try:
os.remove("coverage/tracer.so")
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
<commit_msg>Make tox with with py3.2: the .so is named differently there.<commit_after> | import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
| import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
try:
os.remove("coverage/tracer.so")
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
Make tox with with py3.2: the .so is named differently there.import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
| <commit_before>import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
try:
os.remove("coverage/tracer.so")
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
<commit_msg>Make tox with with py3.2: the .so is named differently there.<commit_after>import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
|
172c0123d5ce59ce4f162d806fc706dc50eb4312 | distarray/tests/test_client.py | distarray/tests/test_client.py | import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
def test_setitem(self):
self.dap[35] = 9999
print self.dap[35]
if __name__ == '__main__':
unittest.main(verbosity=2)
| import unittest
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
def test_set_and_getitem_(self):
dap = self.dac.empty((100,))
for val in xrange(100):
dap[val] = val
for val in xrange(100):
self.assertEqual(dap[val], val)
if __name__ == '__main__':
unittest.main(verbosity=2)
| Test DAP getitem and setitem together. | Test DAP getitem and setitem together. | Python | bsd-3-clause | RaoUmer/distarray,enthought/distarray,RaoUmer/distarray,enthought/distarray | import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
def test_setitem(self):
self.dap[35] = 9999
print self.dap[35]
if __name__ == '__main__':
unittest.main(verbosity=2)
Test DAP getitem and setitem together. | import unittest
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
def test_set_and_getitem_(self):
dap = self.dac.empty((100,))
for val in xrange(100):
dap[val] = val
for val in xrange(100):
self.assertEqual(dap[val], val)
if __name__ == '__main__':
unittest.main(verbosity=2)
| <commit_before>import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
def test_setitem(self):
self.dap[35] = 9999
print self.dap[35]
if __name__ == '__main__':
unittest.main(verbosity=2)
<commit_msg>Test DAP getitem and setitem together.<commit_after> | import unittest
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
def test_set_and_getitem_(self):
dap = self.dac.empty((100,))
for val in xrange(100):
dap[val] = val
for val in xrange(100):
self.assertEqual(dap[val], val)
if __name__ == '__main__':
unittest.main(verbosity=2)
| import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
def test_setitem(self):
self.dap[35] = 9999
print self.dap[35]
if __name__ == '__main__':
unittest.main(verbosity=2)
Test DAP getitem and setitem together.import unittest
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
def test_set_and_getitem_(self):
dap = self.dac.empty((100,))
for val in xrange(100):
dap[val] = val
for val in xrange(100):
self.assertEqual(dap[val], val)
if __name__ == '__main__':
unittest.main(verbosity=2)
| <commit_before>import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
self.dap = self.dac.fromndarray(np.arange(100))
def test_getitem(self):
self.assertEqual(self.dap[55], 55)
def test_setitem(self):
self.dap[35] = 9999
print self.dap[35]
if __name__ == '__main__':
unittest.main(verbosity=2)
<commit_msg>Test DAP getitem and setitem together.<commit_after>import unittest
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
dac = DistArrayContext(self.dv)
self.assertIs(dac.view, self.dv)
def test_create_DAC_with_targets(self):
'''Can we create a context with a subset of engines?'''
dac = DistArrayContext(self.dv, targets=[0, 1])
self.assertIs(dac.view, self.dv)
class TestDistArrayProxy(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
self.dac = DistArrayContext(self.dv)
def test_set_and_getitem_(self):
dap = self.dac.empty((100,))
for val in xrange(100):
dap[val] = val
for val in xrange(100):
self.assertEqual(dap[val], val)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
ff3b4ebfa2a493460532b9a21a661d99fb17df54 | orchestrator/__init__.py | orchestrator/__init__.py | from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.0'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.1'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| Update to next dev version | Update to next dev version | Python | mit | totem/cluster-orchestrator,totem/cluster-orchestrator,totem/cluster-orchestrator | from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.0'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
Update to next dev version | from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.1'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| <commit_before>from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.0'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
<commit_msg>Update to next dev version<commit_after> | from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.1'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.0'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
Update to next dev versionfrom __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.1'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
| <commit_before>from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.0'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
<commit_msg>Update to next dev version<commit_after>from __future__ import absolute_import
from celery.signals import setup_logging
import orchestrator.logger
__version__ = '0.5.1'
__author__ = 'sukrit'
orchestrator.logger.init_logging()
setup_logging.connect(orchestrator.logger.init_celery_logging)
|
0f24e70486b60e27535479c856f41b8ec18ee0f9 | entity_networks/activations.py | entity_networks/activations.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha',
shape=features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = tf.clip_by_value(alpha, 0, 1) * (features - tf.abs(features)) * 0.5 # TODO: Clipping may not be necessary
return pos + neg
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha', features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = alpha * (features - tf.abs(features)) * 0.5
return pos + neg
| Remove alpha clipping as it did not help | Remove alpha clipping as it did not help
| Python | mit | jimfleming/recurrent-entity-networks,jimfleming/recurrent-entity-networks,mikalyoung/recurrent-entity-networks,mikalyoung/recurrent-entity-networks | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha',
shape=features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = tf.clip_by_value(alpha, 0, 1) * (features - tf.abs(features)) * 0.5 # TODO: Clipping may not be necessary
return pos + neg
Remove alpha clipping as it did not help | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha', features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = alpha * (features - tf.abs(features)) * 0.5
return pos + neg
| <commit_before>from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha',
shape=features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = tf.clip_by_value(alpha, 0, 1) * (features - tf.abs(features)) * 0.5 # TODO: Clipping may not be necessary
return pos + neg
<commit_msg>Remove alpha clipping as it did not help<commit_after> | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha', features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = alpha * (features - tf.abs(features)) * 0.5
return pos + neg
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha',
shape=features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = tf.clip_by_value(alpha, 0, 1) * (features - tf.abs(features)) * 0.5 # TODO: Clipping may not be necessary
return pos + neg
Remove alpha clipping as it did not helpfrom __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha', features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = alpha * (features - tf.abs(features)) * 0.5
return pos + neg
| <commit_before>from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha',
shape=features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = tf.clip_by_value(alpha, 0, 1) * (features - tf.abs(features)) * 0.5 # TODO: Clipping may not be necessary
return pos + neg
<commit_msg>Remove alpha clipping as it did not help<commit_after>from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def prelu(features, initializer=None, scope=None):
"""
Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras.
"""
with tf.variable_scope(scope, 'PReLU', initializer=initializer):
alpha = tf.get_variable('alpha', features.get_shape().as_list()[1:])
pos = tf.nn.relu(features)
neg = alpha * (features - tf.abs(features)) * 0.5
return pos + neg
|
c38598f5a6afe6057869dccf65e2950d9fd49fe1 | scripts/validate-resources.py | scripts/validate-resources.py | import sys
import json
from openshift3.resources import load, dumps
resources = load(sys.argv[1])
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
| import sys
import json
from openshift3.resources import load, dumps
path = len(sys.argv) >= 2 and sys.argv[1] or None
resources = load(path)
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
| Allow resource definitions from standard input. | Allow resource definitions from standard input.
| Python | bsd-2-clause | getwarped/powershift | import sys
import json
from openshift3.resources import load, dumps
resources = load(sys.argv[1])
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
Allow resource definitions from standard input. | import sys
import json
from openshift3.resources import load, dumps
path = len(sys.argv) >= 2 and sys.argv[1] or None
resources = load(path)
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
| <commit_before>import sys
import json
from openshift3.resources import load, dumps
resources = load(sys.argv[1])
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
<commit_msg>Allow resource definitions from standard input.<commit_after> | import sys
import json
from openshift3.resources import load, dumps
path = len(sys.argv) >= 2 and sys.argv[1] or None
resources = load(path)
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
| import sys
import json
from openshift3.resources import load, dumps
resources = load(sys.argv[1])
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
Allow resource definitions from standard input.import sys
import json
from openshift3.resources import load, dumps
path = len(sys.argv) >= 2 and sys.argv[1] or None
resources = load(path)
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
| <commit_before>import sys
import json
from openshift3.resources import load, dumps
resources = load(sys.argv[1])
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
<commit_msg>Allow resource definitions from standard input.<commit_after>import sys
import json
from openshift3.resources import load, dumps
path = len(sys.argv) >= 2 and sys.argv[1] or None
resources = load(path)
print(repr(resources))
import pprint
pprint.pprint(json.loads(dumps(resources)))
|
3588f5e30e40f82fb085d01063af64b838528b6a | scripts/fix_merged_user_quickfiles.py | scripts/fix_merged_user_quickfiles.py | import logging
import sys
from django.db import transaction
from django.db.models import F
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator'))
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
# There should only be one contributor, will error if this assumption is false
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
| import logging
import sys
from django.db import transaction
from django.db.models import F, Count
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator')).annotate(contrib_count=Count('_contributors')).exclude(contrib_count=0)
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
| Exclude QuickFilesNodes that don't have contributors | Exclude QuickFilesNodes that don't have contributors
| Python | apache-2.0 | TomBaxter/osf.io,leb2dg/osf.io,cslzchen/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,aaxelb/osf.io,felliott/osf.io,sloria/osf.io,cslzchen/osf.io,cslzchen/osf.io,baylee-d/osf.io,adlius/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,mattclark/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,felliott/osf.io,HalcyonChimera/osf.io,icereval/osf.io,TomBaxter/osf.io,chennan47/osf.io,sloria/osf.io,laurenrevere/osf.io,mattclark/osf.io,pattisdr/osf.io,adlius/osf.io,erinspace/osf.io,icereval/osf.io,crcresearch/osf.io,chennan47/osf.io,brianjgeiger/osf.io,felliott/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,erinspace/osf.io,pattisdr/osf.io,crcresearch/osf.io,baylee-d/osf.io,pattisdr/osf.io,mfraezz/osf.io,sloria/osf.io,caseyrollins/osf.io,caseyrollins/osf.io,mfraezz/osf.io,binoculars/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,cslzchen/osf.io,crcresearch/osf.io,mattclark/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,laurenrevere/osf.io,aaxelb/osf.io,felliott/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,icereval/osf.io,erinspace/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,aaxelb/osf.io,caseyrollins/osf.io,binoculars/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io | import logging
import sys
from django.db import transaction
from django.db.models import F
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator'))
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
# There should only be one contributor, will error if this assumption is false
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
Exclude QuickFilesNodes that don't have contributors | import logging
import sys
from django.db import transaction
from django.db.models import F, Count
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator')).annotate(contrib_count=Count('_contributors')).exclude(contrib_count=0)
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
| <commit_before>import logging
import sys
from django.db import transaction
from django.db.models import F
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator'))
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
# There should only be one contributor, will error if this assumption is false
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
<commit_msg>Exclude QuickFilesNodes that don't have contributors<commit_after> | import logging
import sys
from django.db import transaction
from django.db.models import F, Count
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator')).annotate(contrib_count=Count('_contributors')).exclude(contrib_count=0)
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
| import logging
import sys
from django.db import transaction
from django.db.models import F
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator'))
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
# There should only be one contributor, will error if this assumption is false
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
Exclude QuickFilesNodes that don't have contributorsimport logging
import sys
from django.db import transaction
from django.db.models import F, Count
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator')).annotate(contrib_count=Count('_contributors')).exclude(contrib_count=0)
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
| <commit_before>import logging
import sys
from django.db import transaction
from django.db.models import F
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator'))
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
# There should only be one contributor, will error if this assumption is false
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
<commit_msg>Exclude QuickFilesNodes that don't have contributors<commit_after>import logging
import sys
from django.db import transaction
from django.db.models import F, Count
from website.app import setup_django
setup_django()
from osf.models import QuickFilesNode
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
dry = '--dry' in sys.argv
if not dry:
# If we're not running in dry mode log everything to a file
script_utils.add_file_logger(logger, __file__)
with transaction.atomic():
qs = QuickFilesNode.objects.exclude(_contributors=F('creator')).annotate(contrib_count=Count('_contributors')).exclude(contrib_count=0)
logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count()))
for node in qs:
bad_contrib = node._contributors.get()
logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id))
node.contributor_set.filter(user=bad_contrib).update(user=node.creator)
node.save()
if dry:
raise Exception('Abort Transaction - Dry Run')
print('Done')
if __name__ == '__main__':
main()
|
6c29d671f95668e5f4a337bfe1df23d3bc6b5b0e | arxiv_vanity/sitemaps.py | arxiv_vanity/sitemaps.py | from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 5000
def items(self):
return Paper.objects.all()
def lastmod(self, obj):
return obj.updated
| from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 1000
def items(self):
return Paper.objects.only("arxiv_id", "updated").all()
def lastmod(self, obj):
return obj.updated
| Make sitemap yet more efficient | Make sitemap yet more efficient
| Python | apache-2.0 | arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity | from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 5000
def items(self):
return Paper.objects.all()
def lastmod(self, obj):
return obj.updated
Make sitemap yet more efficient | from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 1000
def items(self):
return Paper.objects.only("arxiv_id", "updated").all()
def lastmod(self, obj):
return obj.updated
| <commit_before>from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 5000
def items(self):
return Paper.objects.all()
def lastmod(self, obj):
return obj.updated
<commit_msg>Make sitemap yet more efficient<commit_after> | from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 1000
def items(self):
return Paper.objects.only("arxiv_id", "updated").all()
def lastmod(self, obj):
return obj.updated
| from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 5000
def items(self):
return Paper.objects.all()
def lastmod(self, obj):
return obj.updated
Make sitemap yet more efficientfrom django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 1000
def items(self):
return Paper.objects.only("arxiv_id", "updated").all()
def lastmod(self, obj):
return obj.updated
| <commit_before>from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 5000
def items(self):
return Paper.objects.all()
def lastmod(self, obj):
return obj.updated
<commit_msg>Make sitemap yet more efficient<commit_after>from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 1000
def items(self):
return Paper.objects.only("arxiv_id", "updated").all()
def lastmod(self, obj):
return obj.updated
|
d6832747545a541eba13f823a38e7fca054cab9d | labelingbot/__init__.py | labelingbot/__init__.py | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'template')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
| import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'templates')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
| Fix templates path error (template -> templates) | Fix templates path error (template -> templates)
| Python | mit | Lee-W/Sentence-Labeling-Bot,Lee-W/Sentence-Labeling-Bot | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'template')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
Fix templates path error (template -> templates) | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'templates')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
| <commit_before>import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'template')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
<commit_msg>Fix templates path error (template -> templates)<commit_after> | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'templates')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
| import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'template')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
Fix templates path error (template -> templates)import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'templates')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
| <commit_before>import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'template')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
<commit_msg>Fix templates path error (template -> templates)<commit_after>import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'templates')
bot = None
db = SQLAlchemy()
bootstarp = Bootstrap()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
global bot
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bot = telegram.Bot(config[config_name].BOT_API_TOKEN)
db.init_app(app)
bootstarp.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .systemdesign import system_design as system_design_blurprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(system_design_blurprint, url_prefix='/system-design')
return app
|
c99ea848a39d22cb4347606b6cba97b98ce627fd | timesketch/api/v1/resources/information.py | timesketch/api/v1/resources/information.py | # Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
List of usernames
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| # Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| Fix method docstring (copy paste error) | Fix method docstring (copy paste error)
Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47
As the method does not return user info. | Python | apache-2.0 | google/timesketch,google/timesketch,google/timesketch,google/timesketch | # Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
List of usernames
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
Fix method docstring (copy paste error)
Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47
As the method does not return user info. | # Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| <commit_before># Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
List of usernames
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
<commit_msg>Fix method docstring (copy paste error)
Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47
As the method does not return user info.<commit_after> | # Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| # Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
List of usernames
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
Fix method docstring (copy paste error)
Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47
As the method does not return user info.# Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| <commit_before># Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
List of usernames
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
<commit_msg>Fix method docstring (copy paste error)
Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47
As the method does not return user info.<commit_after># Copyright 2020 Google 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.
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
|
185d66fa562f931e9910f845e8986620da142c49 | tests/test_api_views.py | tests/test_api_views.py | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import pytest
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
# TODO - make this work without Django.
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
# @pytest.mark.postgres
@pytest.mark.django_db
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
| import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_source_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_individual_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/dudley1'
)
response = view(request)
self.assertEqual(response.status_code, 200)
| Add some more views tests | Add some more views tests
| Python | apache-2.0 | mehanig/scrapi,erinspace/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,mehanig/scrapi,erinspace/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import pytest
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
# TODO - make this work without Django.
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
# @pytest.mark.postgres
@pytest.mark.django_db
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
Add some more views tests | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_source_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_individual_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/dudley1'
)
response = view(request)
self.assertEqual(response.status_code, 200)
| <commit_before>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import pytest
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
# TODO - make this work without Django.
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
# @pytest.mark.postgres
@pytest.mark.django_db
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
<commit_msg>Add some more views tests<commit_after> | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_source_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_individual_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/dudley1'
)
response = view(request)
self.assertEqual(response.status_code, 200)
| import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import pytest
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
# TODO - make this work without Django.
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
# @pytest.mark.postgres
@pytest.mark.django_db
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
Add some more views testsimport os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_source_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_individual_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/dudley1'
)
response = view(request)
self.assertEqual(response.status_code, 200)
| <commit_before>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import pytest
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
# TODO - make this work without Django.
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
# @pytest.mark.postgres
@pytest.mark.django_db
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
<commit_msg>Add some more views tests<commit_after>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
def test_document_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_source_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/'
)
response = view(request)
self.assertEqual(response.status_code, 200)
def test_individual_view(self):
view = DocumentList.as_view()
request = self.factory.get(
'/documents/dudley_weekly/dudley1'
)
response = view(request)
self.assertEqual(response.status_code, 200)
|
e830aae894ac2256e70d1bef1d3784dff4cb8bdb | metaci/repository/urls.py | metaci/repository/urls.py | from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
| from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
| Support -'s in github repo and owner name | Support -'s in github repo and owner name
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci | from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
Support -'s in github repo and owner name | from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
| <commit_before>from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
<commit_msg>Support -'s in github repo and owner name<commit_after> | from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
| from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
Support -'s in github repo and owner namefrom django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
| <commit_before>from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>\w+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
<commit_msg>Support -'s in github repo and owner name<commit_after>from django.conf.urls import url
from metaci.repository import views as repository_views
urlpatterns = [
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$',
repository_views.branch_detail,
name='branch_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$',
repository_views.commit_detail,
name='commit_detail',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/branches',
repository_views.repo_branches,
name='repo_branches',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/plans',
repository_views.repo_plans,
name='repo_plans',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/orgs',
repository_views.repo_orgs,
name='repo_orgs',
),
url(
r'(?P<owner>[-\w]+)/(?P<name>[^/].*)/*$',
repository_views.repo_detail,
name='repo_detail',
),
url(
r'webhook/github/push$',
repository_views.github_push_webhook,
name='github_push_webhook',
),
url(
r'$', repository_views.repo_list,
name='repo_list',
),
]
|
8631a61b9b243e5c1724fb2df06f33b1400fb59e | tests/test_koji_sign.py | tests/test_koji_sign.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
| Fix failing tests by injecting an empty koji module. | Fix failing tests by injecting an empty koji module.
| Python | mit | release-engineering/releng-sop,release-engineering/releng-sop | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
Fix failing tests by injecting an empty koji module. | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
<commit_msg>Fix failing tests by injecting an empty koji module.<commit_after> | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
Fix failing tests by injecting an empty koji module.#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
<commit_msg>Fix failing tests by injecting an empty koji module.<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402
RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")
class TestRPMSignClass(unittest.TestCase):
"""
Tests related to RPMSign classes.
"""
longMessage = True
def test_get_rpmsign_class(self):
"""Test if a RPMSign class can be properly loaded based on env settings."""
env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
cls = get_rpmsign_class(env)
self.assertEqual(cls, LocalRPMSign)
if __name__ == "__main__":
unittest.main()
|
648e2907a5ea5f9157b5aabe4cec10a3d952f5a7 | tests/test_scale.py | tests/test_scale.py | from hypothesis import assume, given
from ppb_vector import Vector
from utils import angle_isclose, floats, isclose, lengths, vectors
@given(x=vectors(), length=floats())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, Vector.scale_to may raise:
- ZeroDivisionError if the vector is null;
- ValueError if the desired length is negative.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
except ValueError:
assert length < 0
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
| from hypothesis import assume, given, strategies as st
from pytest import raises # type: ignore
from ppb_vector import Vector
from utils import angle_isclose, isclose, lengths, vectors
@given(v=vectors(), length=st.floats(max_value=0))
def test_scale_negative_length(v: Vector, length: float):
"""Test that Vector.scale_to raises ValueError on negative lengths."""
assume(length < 0)
with raises(ValueError):
v.scale_to(length)
@given(x=vectors(), length=lengths())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, scale_to may raise ZeroDivisionError if the vector is null.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
| Make a separate test for negative lengths | tests/scale: Make a separate test for negative lengths
Previously, we didn't check that negative lengths raise a ValueError,
but that *if* a ValueError was raised, then the length was negative.
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | from hypothesis import assume, given
from ppb_vector import Vector
from utils import angle_isclose, floats, isclose, lengths, vectors
@given(x=vectors(), length=floats())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, Vector.scale_to may raise:
- ZeroDivisionError if the vector is null;
- ValueError if the desired length is negative.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
except ValueError:
assert length < 0
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
tests/scale: Make a separate test for negative lengths
Previously, we didn't check that negative lengths raise a ValueError,
but that *if* a ValueError was raised, then the length was negative. | from hypothesis import assume, given, strategies as st
from pytest import raises # type: ignore
from ppb_vector import Vector
from utils import angle_isclose, isclose, lengths, vectors
@given(v=vectors(), length=st.floats(max_value=0))
def test_scale_negative_length(v: Vector, length: float):
"""Test that Vector.scale_to raises ValueError on negative lengths."""
assume(length < 0)
with raises(ValueError):
v.scale_to(length)
@given(x=vectors(), length=lengths())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, scale_to may raise ZeroDivisionError if the vector is null.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
| <commit_before>from hypothesis import assume, given
from ppb_vector import Vector
from utils import angle_isclose, floats, isclose, lengths, vectors
@given(x=vectors(), length=floats())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, Vector.scale_to may raise:
- ZeroDivisionError if the vector is null;
- ValueError if the desired length is negative.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
except ValueError:
assert length < 0
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
<commit_msg>tests/scale: Make a separate test for negative lengths
Previously, we didn't check that negative lengths raise a ValueError,
but that *if* a ValueError was raised, then the length was negative.<commit_after> | from hypothesis import assume, given, strategies as st
from pytest import raises # type: ignore
from ppb_vector import Vector
from utils import angle_isclose, isclose, lengths, vectors
@given(v=vectors(), length=st.floats(max_value=0))
def test_scale_negative_length(v: Vector, length: float):
"""Test that Vector.scale_to raises ValueError on negative lengths."""
assume(length < 0)
with raises(ValueError):
v.scale_to(length)
@given(x=vectors(), length=lengths())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, scale_to may raise ZeroDivisionError if the vector is null.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
| from hypothesis import assume, given
from ppb_vector import Vector
from utils import angle_isclose, floats, isclose, lengths, vectors
@given(x=vectors(), length=floats())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, Vector.scale_to may raise:
- ZeroDivisionError if the vector is null;
- ValueError if the desired length is negative.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
except ValueError:
assert length < 0
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
tests/scale: Make a separate test for negative lengths
Previously, we didn't check that negative lengths raise a ValueError,
but that *if* a ValueError was raised, then the length was negative.from hypothesis import assume, given, strategies as st
from pytest import raises # type: ignore
from ppb_vector import Vector
from utils import angle_isclose, isclose, lengths, vectors
@given(v=vectors(), length=st.floats(max_value=0))
def test_scale_negative_length(v: Vector, length: float):
"""Test that Vector.scale_to raises ValueError on negative lengths."""
assume(length < 0)
with raises(ValueError):
v.scale_to(length)
@given(x=vectors(), length=lengths())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, scale_to may raise ZeroDivisionError if the vector is null.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
| <commit_before>from hypothesis import assume, given
from ppb_vector import Vector
from utils import angle_isclose, floats, isclose, lengths, vectors
@given(x=vectors(), length=floats())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, Vector.scale_to may raise:
- ZeroDivisionError if the vector is null;
- ValueError if the desired length is negative.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
except ValueError:
assert length < 0
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
<commit_msg>tests/scale: Make a separate test for negative lengths
Previously, we didn't check that negative lengths raise a ValueError,
but that *if* a ValueError was raised, then the length was negative.<commit_after>from hypothesis import assume, given, strategies as st
from pytest import raises # type: ignore
from ppb_vector import Vector
from utils import angle_isclose, isclose, lengths, vectors
@given(v=vectors(), length=st.floats(max_value=0))
def test_scale_negative_length(v: Vector, length: float):
"""Test that Vector.scale_to raises ValueError on negative lengths."""
assume(length < 0)
with raises(ValueError):
v.scale_to(length)
@given(x=vectors(), length=lengths())
def test_scale_to_length(x: Vector, length: float):
"""Test that the length of x.scale_to(length) is length.
Additionally, scale_to may raise ZeroDivisionError if the vector is null.
"""
try:
assert isclose(x.scale_to(length).length, length)
except ZeroDivisionError:
assert x == (0, 0)
@given(x=vectors(), length=lengths())
def test_scale_aligned(x: Vector, length: float):
"""Test that x.scale_to(length) is aligned with x."""
assume(length > 0)
try:
assert angle_isclose(x.scale_to(length).angle(x), 0)
except ZeroDivisionError:
assert x == (0, 0)
|
e3fe8c01855e3462ae5e4fd51473a75355fe416d | tests/test_utils.py | tests/test_utils.py | from parsel.utils import shorten
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
| from parsel.utils import shorten, extract_regex
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
@mark.parametrize('regex, text, replace_entities, expected', (
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25, 2019', True, ['October', '25', '2019']],
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October', '25', '2019']],
[r'(?P<extract>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October']],
[r'\w+\s*\d+\s*\,?\s*\d+', 'October 25 2019', True, ['October 25 2019']],
[r'^.*$', '"sometext" & "moretext"', True, ['"sometext" & "moretext"']],
[r'^.*$', '"sometext" & "moretext"', False, ['"sometext" & "moretext"']],
))
def test_extract_regex(regex, text, replace_entities, expected):
assert extract_regex(regex, text, replace_entities) == expected
| Add tests for `extract_regex` function. | Add tests for `extract_regex` function.
| Python | bsd-3-clause | scrapy/parsel | from parsel.utils import shorten
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
Add tests for `extract_regex` function. | from parsel.utils import shorten, extract_regex
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
@mark.parametrize('regex, text, replace_entities, expected', (
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25, 2019', True, ['October', '25', '2019']],
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October', '25', '2019']],
[r'(?P<extract>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October']],
[r'\w+\s*\d+\s*\,?\s*\d+', 'October 25 2019', True, ['October 25 2019']],
[r'^.*$', '"sometext" & "moretext"', True, ['"sometext" & "moretext"']],
[r'^.*$', '"sometext" & "moretext"', False, ['"sometext" & "moretext"']],
))
def test_extract_regex(regex, text, replace_entities, expected):
assert extract_regex(regex, text, replace_entities) == expected
| <commit_before>from parsel.utils import shorten
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
<commit_msg>Add tests for `extract_regex` function.<commit_after> | from parsel.utils import shorten, extract_regex
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
@mark.parametrize('regex, text, replace_entities, expected', (
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25, 2019', True, ['October', '25', '2019']],
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October', '25', '2019']],
[r'(?P<extract>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October']],
[r'\w+\s*\d+\s*\,?\s*\d+', 'October 25 2019', True, ['October 25 2019']],
[r'^.*$', '"sometext" & "moretext"', True, ['"sometext" & "moretext"']],
[r'^.*$', '"sometext" & "moretext"', False, ['"sometext" & "moretext"']],
))
def test_extract_regex(regex, text, replace_entities, expected):
assert extract_regex(regex, text, replace_entities) == expected
| from parsel.utils import shorten
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
Add tests for `extract_regex` function.from parsel.utils import shorten, extract_regex
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
@mark.parametrize('regex, text, replace_entities, expected', (
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25, 2019', True, ['October', '25', '2019']],
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October', '25', '2019']],
[r'(?P<extract>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October']],
[r'\w+\s*\d+\s*\,?\s*\d+', 'October 25 2019', True, ['October 25 2019']],
[r'^.*$', '"sometext" & "moretext"', True, ['"sometext" & "moretext"']],
[r'^.*$', '"sometext" & "moretext"', False, ['"sometext" & "moretext"']],
))
def test_extract_regex(regex, text, replace_entities, expected):
assert extract_regex(regex, text, replace_entities) == expected
| <commit_before>from parsel.utils import shorten
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
<commit_msg>Add tests for `extract_regex` function.<commit_after>from parsel.utils import shorten, extract_regex
from pytest import mark, raises
import six
@mark.parametrize(
'width,expected',
(
(-1, ValueError),
(0, u''),
(1, u'.'),
(2, u'..'),
(3, u'...'),
(4, u'f...'),
(5, u'fo...'),
(6, u'foobar'),
(7, u'foobar'),
)
)
def test_shorten(width, expected):
if isinstance(expected, six.string_types):
assert shorten(u'foobar', width) == expected
else:
with raises(expected):
shorten(u'foobar', width)
@mark.parametrize('regex, text, replace_entities, expected', (
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25, 2019', True, ['October', '25', '2019']],
[r'(?P<month>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October', '25', '2019']],
[r'(?P<extract>\w+)\s*(?P<day>\d+)\s*\,?\s*(?P<year>\d+)', 'October 25 2019', True, ['October']],
[r'\w+\s*\d+\s*\,?\s*\d+', 'October 25 2019', True, ['October 25 2019']],
[r'^.*$', '"sometext" & "moretext"', True, ['"sometext" & "moretext"']],
[r'^.*$', '"sometext" & "moretext"', False, ['"sometext" & "moretext"']],
))
def test_extract_regex(regex, text, replace_entities, expected):
assert extract_regex(regex, text, replace_entities) == expected
|
bea03e81141dcb912e1697fbf22b7ca1d5fd0d4d | tingbot/__init__.py | tingbot/__init__.py | from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
| try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
| Add import-time check for pygame (since we can't install automatically) | Add import-time check for pygame (since we can't install automatically)
| Python | bsd-2-clause | furbrain/tingbot-python | from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
Add import-time check for pygame (since we can't install automatically) | try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
| <commit_before>from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
<commit_msg>Add import-time check for pygame (since we can't install automatically)<commit_after> | try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
| from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
Add import-time check for pygame (since we can't install automatically)try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
| <commit_before>from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
<commit_msg>Add import-time check for pygame (since we can't install automatically)<commit_after>try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
|
df55e36869789e3b4b94114a339dd2390156fc0b | account/urls.py | account/urls.py | from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
| from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^profile/$', AccountView.as_view(), name='profile'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
| Add profile view - default login redirect | Add profile view - default login redirect
| Python | mit | uda/djaccount,uda/djaccount | from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
Add profile view - default login redirect | from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^profile/$', AccountView.as_view(), name='profile'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
| <commit_before>from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
<commit_msg>Add profile view - default login redirect<commit_after> | from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^profile/$', AccountView.as_view(), name='profile'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
| from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
Add profile view - default login redirectfrom django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^profile/$', AccountView.as_view(), name='profile'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
| <commit_before>from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
<commit_msg>Add profile view - default login redirect<commit_after>from django.conf.urls import url
from django.contrib.auth.views import (
password_change,
password_change_done,
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
LoginView,
LogoutView,
)
from .views import AccountView
urlpatterns = [
url(r'^$', AccountView.as_view(), name='view'),
url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'),
url(r'^profile/$', AccountView.as_view(), name='profile'),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
url(r'^password/change/$', password_change, name='password-change',
kwargs={'post_change_redirect': 'account:password-change-done'}),
url(r'^password/change/done/$', password_change_done, name='password-change-done'),
url(r'^password/reset/$', password_reset, name='password-reset',
kwargs={'post_reset_redirect': 'account:password-reset-done'}),
url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'),
url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm',
kwargs={'post_reset_redirect': 'account:password-reset-complete'}),
url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'),
]
|
aacb30d2d87cf83c3f09225532c06d81e399cae2 | spanky/commands/cmd_roster.py | spanky/commands/cmd_roster.py | import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
click.echo(json.dumps(list(roster(config, name))))
| import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
members = list(roster(config, name))
click.echo(json.dumps({'memebers': members}))
| Return members in roster cmd out. | Return members in roster cmd out.
| Python | bsd-3-clause | pglbutt/spanky,pglbutt/spanky,pglbutt/spanky | import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
click.echo(json.dumps(list(roster(config, name))))
Return members in roster cmd out. | import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
members = list(roster(config, name))
click.echo(json.dumps({'memebers': members}))
| <commit_before>import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
click.echo(json.dumps(list(roster(config, name))))
<commit_msg>Return members in roster cmd out.<commit_after> | import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
members = list(roster(config, name))
click.echo(json.dumps({'memebers': members}))
| import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
click.echo(json.dumps(list(roster(config, name))))
Return members in roster cmd out.import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
members = list(roster(config, name))
click.echo(json.dumps({'memebers': members}))
| <commit_before>import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
click.echo(json.dumps(list(roster(config, name))))
<commit_msg>Return members in roster cmd out.<commit_after>import json
import click
from spanky.cli import pass_context
from spanky.lib.enroll import roster
@click.command('roster', short_help='Enroll / leave')
@click.argument('name')
@pass_context
def cli(ctx, name):
config = ctx.config.load('enroll.yml')
members = list(roster(config, name))
click.echo(json.dumps({'memebers': members}))
|
3da17f4732d0b1987f3a9362eb8dfa70fb21e39b | rabbitpy/utils.py | rabbitpy/utils.py | """Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
__since__ = '2013-03-24'
from pamqp import PYTHON3
if PYTHON3:
from urllib import parse as urlparse
else:
import urlparse
def parse_qs(query_string):
return urlparse.parse_qs(query_string)
def urlparse(url):
return urlparse.urlparse(url)
def unquote(value):
return urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
| """Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
from pamqp import PYTHON3
try:
from urllib import parse as _urlparse
except ImportError:
import urlparse as _urlparse
def parse_qs(query_string):
return _urlparse.parse_qs(query_string)
def urlparse(url):
return _urlparse.urlparse(url)
def unquote(value):
return _urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
| Fix urlparse name collision with method | Fix urlparse name collision with method
| Python | bsd-3-clause | gmr/rabbitpy,gmr/rabbitpy,jonahbull/rabbitpy | """Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
__since__ = '2013-03-24'
from pamqp import PYTHON3
if PYTHON3:
from urllib import parse as urlparse
else:
import urlparse
def parse_qs(query_string):
return urlparse.parse_qs(query_string)
def urlparse(url):
return urlparse.urlparse(url)
def unquote(value):
return urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
Fix urlparse name collision with method | """Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
from pamqp import PYTHON3
try:
from urllib import parse as _urlparse
except ImportError:
import urlparse as _urlparse
def parse_qs(query_string):
return _urlparse.parse_qs(query_string)
def urlparse(url):
return _urlparse.urlparse(url)
def unquote(value):
return _urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
| <commit_before>"""Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
__since__ = '2013-03-24'
from pamqp import PYTHON3
if PYTHON3:
from urllib import parse as urlparse
else:
import urlparse
def parse_qs(query_string):
return urlparse.parse_qs(query_string)
def urlparse(url):
return urlparse.urlparse(url)
def unquote(value):
return urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
<commit_msg>Fix urlparse name collision with method<commit_after> | """Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
from pamqp import PYTHON3
try:
from urllib import parse as _urlparse
except ImportError:
import urlparse as _urlparse
def parse_qs(query_string):
return _urlparse.parse_qs(query_string)
def urlparse(url):
return _urlparse.urlparse(url)
def unquote(value):
return _urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
| """Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
__since__ = '2013-03-24'
from pamqp import PYTHON3
if PYTHON3:
from urllib import parse as urlparse
else:
import urlparse
def parse_qs(query_string):
return urlparse.parse_qs(query_string)
def urlparse(url):
return urlparse.urlparse(url)
def unquote(value):
return urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
Fix urlparse name collision with method"""Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
from pamqp import PYTHON3
try:
from urllib import parse as _urlparse
except ImportError:
import urlparse as _urlparse
def parse_qs(query_string):
return _urlparse.parse_qs(query_string)
def urlparse(url):
return _urlparse.urlparse(url)
def unquote(value):
return _urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
| <commit_before>"""Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
__since__ = '2013-03-24'
from pamqp import PYTHON3
if PYTHON3:
from urllib import parse as urlparse
else:
import urlparse
def parse_qs(query_string):
return urlparse.parse_qs(query_string)
def urlparse(url):
return urlparse.urlparse(url)
def unquote(value):
return urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
<commit_msg>Fix urlparse name collision with method<commit_after>"""Utilities to make Python 3 support easier, providing wrapper methods which
can call the appropriate method for either Python 2 or Python 3 but creating
a single API point for rabbitpy to use.
"""
from pamqp import PYTHON3
try:
from urllib import parse as _urlparse
except ImportError:
import urlparse as _urlparse
def parse_qs(query_string):
return _urlparse.parse_qs(query_string)
def urlparse(url):
return _urlparse.urlparse(url)
def unquote(value):
return _urlparse.unquote(value)
def is_string(value):
if PYTHON3:
return isinstance(value, str) or isinstance(value, bytes)
return isinstance(value, basestring)
|
c7c47fe11de8ddf43bd007b240b7d9b97a92bbf3 | zerver/lib/url_preview/parsers/base.py | zerver/lib/url_preview/parsers/base.py | from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplemented
| from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplementedError()
| Replace buggy NotImplemented with NotImplementedError(). | Replace buggy NotImplemented with NotImplementedError().
| Python | apache-2.0 | brainwane/zulip,rishig/zulip,brainwane/zulip,kou/zulip,eeshangarg/zulip,andersk/zulip,Galexrt/zulip,christi3k/zulip,rishig/zulip,rishig/zulip,jackrzhang/zulip,vabs22/zulip,rht/zulip,brockwhittaker/zulip,tommyip/zulip,amanharitsh123/zulip,showell/zulip,jackrzhang/zulip,amanharitsh123/zulip,rishig/zulip,jrowan/zulip,punchagan/zulip,tommyip/zulip,vabs22/zulip,andersk/zulip,timabbott/zulip,mahim97/zulip,verma-varsha/zulip,punchagan/zulip,rishig/zulip,vaidap/zulip,j831/zulip,verma-varsha/zulip,brockwhittaker/zulip,j831/zulip,shubhamdhama/zulip,showell/zulip,andersk/zulip,zulip/zulip,timabbott/zulip,kou/zulip,rht/zulip,timabbott/zulip,dhcrzf/zulip,christi3k/zulip,j831/zulip,vabs22/zulip,jackrzhang/zulip,dhcrzf/zulip,j831/zulip,christi3k/zulip,synicalsyntax/zulip,shubhamdhama/zulip,hackerkid/zulip,synicalsyntax/zulip,kou/zulip,kou/zulip,punchagan/zulip,zulip/zulip,mahim97/zulip,amanharitsh123/zulip,timabbott/zulip,brainwane/zulip,amanharitsh123/zulip,timabbott/zulip,hackerkid/zulip,jrowan/zulip,kou/zulip,zulip/zulip,showell/zulip,synicalsyntax/zulip,rht/zulip,zulip/zulip,showell/zulip,punchagan/zulip,jrowan/zulip,rishig/zulip,synicalsyntax/zulip,brainwane/zulip,mahim97/zulip,shubhamdhama/zulip,jackrzhang/zulip,andersk/zulip,Galexrt/zulip,tommyip/zulip,showell/zulip,jrowan/zulip,j831/zulip,tommyip/zulip,rishig/zulip,timabbott/zulip,verma-varsha/zulip,Galexrt/zulip,eeshangarg/zulip,eeshangarg/zulip,shubhamdhama/zulip,punchagan/zulip,zulip/zulip,vaidap/zulip,mahim97/zulip,verma-varsha/zulip,vaidap/zulip,christi3k/zulip,brainwane/zulip,dhcrzf/zulip,andersk/zulip,brockwhittaker/zulip,jackrzhang/zulip,shubhamdhama/zulip,verma-varsha/zulip,brockwhittaker/zulip,showell/zulip,amanharitsh123/zulip,vaidap/zulip,dhcrzf/zulip,kou/zulip,brainwane/zulip,hackerkid/zulip,tommyip/zulip,amanharitsh123/zulip,timabbott/zulip,christi3k/zulip,mahim97/zulip,j831/zulip,rht/zulip,andersk/zulip,kou/zulip,rht/zulip,vaidap/zulip,tommyip/zulip,vabs22/zulip,mahim97/zulip,synicalsyntax/zulip,rht/zulip,synicalsyntax/zulip,dhcrzf/zulip,andersk/zulip,zulip/zulip,dhcrzf/zulip,zulip/zulip,vabs22/zulip,jackrzhang/zulip,Galexrt/zulip,brockwhittaker/zulip,hackerkid/zulip,synicalsyntax/zulip,rht/zulip,verma-varsha/zulip,Galexrt/zulip,showell/zulip,brockwhittaker/zulip,eeshangarg/zulip,vaidap/zulip,Galexrt/zulip,shubhamdhama/zulip,Galexrt/zulip,dhcrzf/zulip,jrowan/zulip,hackerkid/zulip,jackrzhang/zulip,shubhamdhama/zulip,hackerkid/zulip,eeshangarg/zulip,punchagan/zulip,vabs22/zulip,jrowan/zulip,eeshangarg/zulip,eeshangarg/zulip,punchagan/zulip,hackerkid/zulip,christi3k/zulip,brainwane/zulip,tommyip/zulip | from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplemented
Replace buggy NotImplemented with NotImplementedError(). | from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplementedError()
| <commit_before>from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplemented
<commit_msg>Replace buggy NotImplemented with NotImplementedError().<commit_after> | from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplementedError()
| from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplemented
Replace buggy NotImplemented with NotImplementedError().from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplementedError()
| <commit_before>from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplemented
<commit_msg>Replace buggy NotImplemented with NotImplementedError().<commit_after>from __future__ import absolute_import
from typing import Any, Text
from bs4 import BeautifulSoup
class BaseParser(object):
def __init__(self, html_source):
# type: (Text) -> None
self._soup = BeautifulSoup(html_source, "lxml")
def extract_data(self):
# type: () -> Any
raise NotImplementedError()
|
b89f6c766e976a182a958e74859c2df8862c7361 | pale/fields/resource.py | pale/fields/resource.py | from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=DebugResource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
| from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
| Use normal Resource as default for ResourceList | Use normal Resource as default for ResourceList
to avoid potential circular import.
| Python | mit | Loudr/pale | from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=DebugResource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
Use normal Resource as default for ResourceList
to avoid potential circular import. | from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
| <commit_before>from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=DebugResource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
<commit_msg>Use normal Resource as default for ResourceList
to avoid potential circular import.<commit_after> | from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
| from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=DebugResource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
Use normal Resource as default for ResourceList
to avoid potential circular import.from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
| <commit_before>from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=DebugResource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
<commit_msg>Use normal Resource as default for ResourceList
to avoid potential circular import.<commit_after>from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
|
3d399d33302c004122773af52a740da1c736540e | test/functional/test_miscellaneous.py | test/functional/test_miscellaneous.py | import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
for _ in range(10000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
| import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
#
#XXX: 10s is apparently not enough for slow Travis CI on Windows.
for _ in range(20000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
| Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs | Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs | Python | mit | ipfs/py-ipfs-api,ipfs/py-ipfs-api | import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
for _ in range(10000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs | import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
#
#XXX: 10s is apparently not enough for slow Travis CI on Windows.
for _ in range(20000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
| <commit_before>import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
for _ in range(10000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
<commit_msg>Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs<commit_after> | import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
#
#XXX: 10s is apparently not enough for slow Travis CI on Windows.
for _ in range(20000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
| import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
for _ in range(10000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runsimport time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
#
#XXX: 10s is apparently not enough for slow Travis CI on Windows.
for _ in range(20000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
| <commit_before>import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
for _ in range(10000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
<commit_msg>Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs<commit_after>import time
import pytest
def test_version(client):
expected_keys = {"Repo", "Commit", "Version"}
resp_version = client.version()
assert set(resp_version.keys()).issuperset(expected_keys)
def test_id(client):
expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
resp_id = client.id()
assert set(resp_id.keys()).issuperset(expected_keys)
#################
# Shutdown test #
#################
@pytest.mark.last
def test_daemon_stop(daemon, client):
# The value for the `daemon` “fixture” is injected using a pytest plugin
# with access to the created daemon subprocess object defined directly
# in the `test/run-test.py` file
if not daemon:
pytest.skip("Not started using `test/run-test.py`")
def daemon_is_running():
return daemon.poll() is None
# Daemon should still be running at this point
assert daemon_is_running()
# Send stop request
client.stop()
# Wait for daemon process to disappear
#
#XXX: 10s is apparently not enough for slow Travis CI on Windows.
for _ in range(20000):
if not daemon_is_running():
break
time.sleep(0.001)
# Daemon should not be running anymore
assert not daemon_is_running()
|
6bd8ecf5719e15674ef67100b92822be3cf8e5ec | dataportal/tests/test_replay_persistance.py | dataportal/tests/test_replay_persistance.py | import nose
from dataportal.replay.persist import History
h = None
def setup():
h = History(':memory:')
def test_history():
pass
| from nose.tools import assert_equal
from dataportal.replay.persist import History
import dataportal.replay.persist
OBJ_ID_LEN = 36
h = None
def setup():
global h
h = History(':memory:')
def test_history():
run_id = ''.join(['a'] * OBJ_ID_LEN)
# Simple round-trip: put and get
config1 = {'plot_x': 'long', 'plot_y': 'island'}
h.put(run_id, config1)
result1 = h.get(run_id)
assert_equal(result1, config1)
# Put a second entry. Check that get returns most recent.
config2 = {'plot_x': 'new', 'plot_y': 'york'}
h.put(run_id, config2)
result2 = h.get(run_id)
assert_equal(result2, config2)
# And get(..., 1) returns previous.
result1 = h.get(run_id, 1)
assert_equal(result1, config1)
| Add real tests of replay History. | TST: Add real tests of replay History.
| Python | bsd-3-clause | tacaswell/dataportal,danielballan/datamuxer,danielballan/datamuxer,NSLS-II/dataportal,ericdill/datamuxer,danielballan/dataportal,NSLS-II/datamuxer,danielballan/dataportal,ericdill/databroker,tacaswell/dataportal,NSLS-II/dataportal,ericdill/datamuxer,ericdill/databroker | import nose
from dataportal.replay.persist import History
h = None
def setup():
h = History(':memory:')
def test_history():
pass
TST: Add real tests of replay History. | from nose.tools import assert_equal
from dataportal.replay.persist import History
import dataportal.replay.persist
OBJ_ID_LEN = 36
h = None
def setup():
global h
h = History(':memory:')
def test_history():
run_id = ''.join(['a'] * OBJ_ID_LEN)
# Simple round-trip: put and get
config1 = {'plot_x': 'long', 'plot_y': 'island'}
h.put(run_id, config1)
result1 = h.get(run_id)
assert_equal(result1, config1)
# Put a second entry. Check that get returns most recent.
config2 = {'plot_x': 'new', 'plot_y': 'york'}
h.put(run_id, config2)
result2 = h.get(run_id)
assert_equal(result2, config2)
# And get(..., 1) returns previous.
result1 = h.get(run_id, 1)
assert_equal(result1, config1)
| <commit_before>import nose
from dataportal.replay.persist import History
h = None
def setup():
h = History(':memory:')
def test_history():
pass
<commit_msg>TST: Add real tests of replay History.<commit_after> | from nose.tools import assert_equal
from dataportal.replay.persist import History
import dataportal.replay.persist
OBJ_ID_LEN = 36
h = None
def setup():
global h
h = History(':memory:')
def test_history():
run_id = ''.join(['a'] * OBJ_ID_LEN)
# Simple round-trip: put and get
config1 = {'plot_x': 'long', 'plot_y': 'island'}
h.put(run_id, config1)
result1 = h.get(run_id)
assert_equal(result1, config1)
# Put a second entry. Check that get returns most recent.
config2 = {'plot_x': 'new', 'plot_y': 'york'}
h.put(run_id, config2)
result2 = h.get(run_id)
assert_equal(result2, config2)
# And get(..., 1) returns previous.
result1 = h.get(run_id, 1)
assert_equal(result1, config1)
| import nose
from dataportal.replay.persist import History
h = None
def setup():
h = History(':memory:')
def test_history():
pass
TST: Add real tests of replay History.from nose.tools import assert_equal
from dataportal.replay.persist import History
import dataportal.replay.persist
OBJ_ID_LEN = 36
h = None
def setup():
global h
h = History(':memory:')
def test_history():
run_id = ''.join(['a'] * OBJ_ID_LEN)
# Simple round-trip: put and get
config1 = {'plot_x': 'long', 'plot_y': 'island'}
h.put(run_id, config1)
result1 = h.get(run_id)
assert_equal(result1, config1)
# Put a second entry. Check that get returns most recent.
config2 = {'plot_x': 'new', 'plot_y': 'york'}
h.put(run_id, config2)
result2 = h.get(run_id)
assert_equal(result2, config2)
# And get(..., 1) returns previous.
result1 = h.get(run_id, 1)
assert_equal(result1, config1)
| <commit_before>import nose
from dataportal.replay.persist import History
h = None
def setup():
h = History(':memory:')
def test_history():
pass
<commit_msg>TST: Add real tests of replay History.<commit_after>from nose.tools import assert_equal
from dataportal.replay.persist import History
import dataportal.replay.persist
OBJ_ID_LEN = 36
h = None
def setup():
global h
h = History(':memory:')
def test_history():
run_id = ''.join(['a'] * OBJ_ID_LEN)
# Simple round-trip: put and get
config1 = {'plot_x': 'long', 'plot_y': 'island'}
h.put(run_id, config1)
result1 = h.get(run_id)
assert_equal(result1, config1)
# Put a second entry. Check that get returns most recent.
config2 = {'plot_x': 'new', 'plot_y': 'york'}
h.put(run_id, config2)
result2 = h.get(run_id)
assert_equal(result2, config2)
# And get(..., 1) returns previous.
result1 = h.get(run_id, 1)
assert_equal(result1, config1)
|
334c23e313cef141b6a18e8bf34be0fea662043f | cla_public/libs/call_centre_availability.py | cla_public/libs/call_centre_availability.py | import datetime
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return "th"
return {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (day.strftime("%A"), day.strftime("%d").lstrip("0"), suffix(day.day))
| import datetime
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
| Allow for Day name and ordinal suffix to be translated | Allow for Day name and ordinal suffix to be translated
| Python | mit | ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public | import datetime
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return "th"
return {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (day.strftime("%A"), day.strftime("%d").lstrip("0"), suffix(day.day))
Allow for Day name and ordinal suffix to be translated | import datetime
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
| <commit_before>import datetime
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return "th"
return {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (day.strftime("%A"), day.strftime("%d").lstrip("0"), suffix(day.day))
<commit_msg>Allow for Day name and ordinal suffix to be translated<commit_after> | import datetime
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
| import datetime
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return "th"
return {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (day.strftime("%A"), day.strftime("%d").lstrip("0"), suffix(day.day))
Allow for Day name and ordinal suffix to be translatedimport datetime
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
| <commit_before>import datetime
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return "th"
return {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (day.strftime("%A"), day.strftime("%d").lstrip("0"), suffix(day.day))
<commit_msg>Allow for Day name and ordinal suffix to be translated<commit_after>import datetime
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
|
b85935bf2dd2b4c92c7aee660c1dbfa175545c16 | moksha/lib/app_globals.py | moksha/lib/app_globals.py | """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
def __getattribute__(self, *args, **kw):
# @@ TODO: Namespace moksha app's Global objects
# load them in the middlware...
# ensure that this object is always in pylons.g, even if we are
# running a full moksha stack, or as middleware
# proxy to them on incoming request
print "Globals.__getattr__(%s)" % locals()
frame = inspect.currentframe()
caller = frame.f_back.f_back.f_globals['__name__']
print "caller = ", caller
return object.__getattribute__(self, *args, **kw)
| """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
#def __getattribute__(self, *args, **kw):
# # @@ TODO: Namespace moksha app's Global objects
# # load them in the middlware...
# # ensure that this object is always in pylons.g, even if we are
# # running a full moksha stack, or as middleware
# # proxy to them on incoming request
# print "Globals.__getattr__(%s)" % locals()
# frame = inspect.currentframe()
# caller = frame.f_back.f_back.f_globals['__name__']
# print "caller = ", caller
# return object.__getattribute__(self, *args, **kw)
| Comment out our global stuff for now | Comment out our global stuff for now
| Python | apache-2.0 | mokshaproject/moksha,ralphbean/moksha,mokshaproject/moksha,lmacken/moksha,pombredanne/moksha,lmacken/moksha,mokshaproject/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha,pombredanne/moksha,mokshaproject/moksha | """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
def __getattribute__(self, *args, **kw):
# @@ TODO: Namespace moksha app's Global objects
# load them in the middlware...
# ensure that this object is always in pylons.g, even if we are
# running a full moksha stack, or as middleware
# proxy to them on incoming request
print "Globals.__getattr__(%s)" % locals()
frame = inspect.currentframe()
caller = frame.f_back.f_back.f_globals['__name__']
print "caller = ", caller
return object.__getattribute__(self, *args, **kw)
Comment out our global stuff for now | """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
#def __getattribute__(self, *args, **kw):
# # @@ TODO: Namespace moksha app's Global objects
# # load them in the middlware...
# # ensure that this object is always in pylons.g, even if we are
# # running a full moksha stack, or as middleware
# # proxy to them on incoming request
# print "Globals.__getattr__(%s)" % locals()
# frame = inspect.currentframe()
# caller = frame.f_back.f_back.f_globals['__name__']
# print "caller = ", caller
# return object.__getattribute__(self, *args, **kw)
| <commit_before>"""The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
def __getattribute__(self, *args, **kw):
# @@ TODO: Namespace moksha app's Global objects
# load them in the middlware...
# ensure that this object is always in pylons.g, even if we are
# running a full moksha stack, or as middleware
# proxy to them on incoming request
print "Globals.__getattr__(%s)" % locals()
frame = inspect.currentframe()
caller = frame.f_back.f_back.f_globals['__name__']
print "caller = ", caller
return object.__getattribute__(self, *args, **kw)
<commit_msg>Comment out our global stuff for now<commit_after> | """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
#def __getattribute__(self, *args, **kw):
# # @@ TODO: Namespace moksha app's Global objects
# # load them in the middlware...
# # ensure that this object is always in pylons.g, even if we are
# # running a full moksha stack, or as middleware
# # proxy to them on incoming request
# print "Globals.__getattr__(%s)" % locals()
# frame = inspect.currentframe()
# caller = frame.f_back.f_back.f_globals['__name__']
# print "caller = ", caller
# return object.__getattribute__(self, *args, **kw)
| """The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
def __getattribute__(self, *args, **kw):
# @@ TODO: Namespace moksha app's Global objects
# load them in the middlware...
# ensure that this object is always in pylons.g, even if we are
# running a full moksha stack, or as middleware
# proxy to them on incoming request
print "Globals.__getattr__(%s)" % locals()
frame = inspect.currentframe()
caller = frame.f_back.f_back.f_globals['__name__']
print "caller = ", caller
return object.__getattribute__(self, *args, **kw)
Comment out our global stuff for now"""The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
#def __getattribute__(self, *args, **kw):
# # @@ TODO: Namespace moksha app's Global objects
# # load them in the middlware...
# # ensure that this object is always in pylons.g, even if we are
# # running a full moksha stack, or as middleware
# # proxy to them on incoming request
# print "Globals.__getattr__(%s)" % locals()
# frame = inspect.currentframe()
# caller = frame.f_back.f_back.f_globals['__name__']
# print "caller = ", caller
# return object.__getattribute__(self, *args, **kw)
| <commit_before>"""The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
def __getattribute__(self, *args, **kw):
# @@ TODO: Namespace moksha app's Global objects
# load them in the middlware...
# ensure that this object is always in pylons.g, even if we are
# running a full moksha stack, or as middleware
# proxy to them on incoming request
print "Globals.__getattr__(%s)" % locals()
frame = inspect.currentframe()
caller = frame.f_back.f_back.f_globals['__name__']
print "caller = ", caller
return object.__getattribute__(self, *args, **kw)
<commit_msg>Comment out our global stuff for now<commit_after>"""The application's Globals object"""
import logging
import inspect
from tg import config
from shove import Shove
from moksha.exc import CacheBackendException
from moksha.lib.cache import Cache
log = logging.getLogger(__name__)
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
timeout = int(config.get('beaker.cache.timeout', '0'))
try:
self.cache = Cache(config['beaker.cache.url'], timeout)
except CacheBackendException, e:
log.warning(str(e))
self.cache = None
#def __getattribute__(self, *args, **kw):
# # @@ TODO: Namespace moksha app's Global objects
# # load them in the middlware...
# # ensure that this object is always in pylons.g, even if we are
# # running a full moksha stack, or as middleware
# # proxy to them on incoming request
# print "Globals.__getattr__(%s)" % locals()
# frame = inspect.currentframe()
# caller = frame.f_back.f_back.f_globals['__name__']
# print "caller = ", caller
# return object.__getattribute__(self, *args, **kw)
|
c5128bb5dd059580f46647cfe881f1b2c154f62f | tests/config_test.py | tests/config_test.py | import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
| import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False).encode('utf-8'))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
| Fix python3 build: Set byte encoding when writing to file. | Fix python3 build: Set byte encoding when writing to file.
| Python | apache-2.0 | mbruggmann/i2ssh | import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
Fix python3 build: Set byte encoding when writing to file. | import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False).encode('utf-8'))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
| <commit_before>import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
<commit_msg>Fix python3 build: Set byte encoding when writing to file.<commit_after> | import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False).encode('utf-8'))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
| import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
Fix python3 build: Set byte encoding when writing to file.import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False).encode('utf-8'))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
| <commit_before>import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
<commit_msg>Fix python3 build: Set byte encoding when writing to file.<commit_after>import os
from testfixtures import tempdir
import unittest
import yaml
from i2ssh.config import Config
FILENAME = '.i2sshrc'
class ConfigTest(unittest.TestCase):
@tempdir()
def test_cluster(self, tmpdir):
cluster_config = {'hosts': ['host1']}
full_config = {'mycluster': cluster_config}
tmpdir.write(FILENAME, yaml.dump(full_config, default_flow_style=False).encode('utf-8'))
config = Config(os.path.join(tmpdir.path, FILENAME))
self.assertEquals(cluster_config, config.cluster('mycluster'))
|
da5386234ec66968a1010d073af56ab7f01e4792 | openshift/ose_object.py | openshift/ose_object.py | class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._response.json()['data'][attr]
| class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._json['data'][attr]
| Use the extracted json for getting data from OSEObject to not extract it every time | Use the extracted json for getting data from OSEObject to not extract it every time
| Python | mit | atodorov/python-openshift,atodorov/python-openshift | class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._response.json()['data'][attr]
Use the extracted json for getting data from OSEObject to not extract it every time | class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._json['data'][attr]
| <commit_before>class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._response.json()['data'][attr]
<commit_msg>Use the extracted json for getting data from OSEObject to not extract it every time<commit_after> | class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._json['data'][attr]
| class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._response.json()['data'][attr]
Use the extracted json for getting data from OSEObject to not extract it every timeclass OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._json['data'][attr]
| <commit_before>class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._response.json()['data'][attr]
<commit_msg>Use the extracted json for getting data from OSEObject to not extract it every time<commit_after>class OSEObject(object):
"""Superclass to all OSE objects that hold data about remote API."""
def __init__(self, ose):
self.ose = ose
self.refresh()
def refresh(self):
"""Reloads all info about this object.
Uses _request_fresh() method defined by subclasses to obtain
fresh response.
"""
self._response = self._request_fresh()
self._json = self._response.json()
def _request_fresh(self):
raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\
format(cls=type(self)))
def __getattr__(self, attr):
return self._json['data'][attr]
|
2970f7b866fdf3a6db6bb0f92f0c14780a58a4e4 | tests/test_config.py | tests/test_config.py | from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
| import os
from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
def test_testing_config():
app = create_app('testing')
assert app.config['TESTING'] is True
| Add test for testing config | :hammer: Add test for testing config
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys | from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
:hammer: Add test for testing config | import os
from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
def test_testing_config():
app = create_app('testing')
assert app.config['TESTING'] is True
| <commit_before>from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
<commit_msg>:hammer: Add test for testing config<commit_after> | import os
from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
def test_testing_config():
app = create_app('testing')
assert app.config['TESTING'] is True
| from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
:hammer: Add test for testing configimport os
from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
def test_testing_config():
app = create_app('testing')
assert app.config['TESTING'] is True
| <commit_before>from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
<commit_msg>:hammer: Add test for testing config<commit_after>import os
from labsys.app import create_app
def test_production_config():
app = create_app('production')
assert app.config['DEBUG'] is False
def test_development_config():
app = create_app('development')
assert app.config['DEBUG'] is True
def test_testing_config():
app = create_app('testing')
assert app.config['TESTING'] is True
|
86c74e03a4f0038aea8f4cef7f7f75314a43cfe0 | admin_views/templatetags/admin_views.py | admin_views/templatetags/admin_views.py | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
| from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
u"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
| Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well. | Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well.
Fixes #2. Translated labels are now displayed correctly.
| Python | bsd-3-clause | frankwiles/django-admin-views,mikeumus/django-admin-views,frankwiles/django-admin-views,mikeumus/django-admin-views | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well.
Fixes #2. Translated labels are now displayed correctly. | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
u"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
| <commit_before>from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
<commit_msg>Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well.
Fixes #2. Translated labels are now displayed correctly.<commit_after> | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
u"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
| from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well.
Fixes #2. Translated labels are now displayed correctly.from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
u"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
| <commit_before>from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
<commit_msg>Use an Unicode object format string when building HTML for the admin, since the arguments can be Unicode as well.
Fixes #2. Translated labels are now displayed correctly.<commit_after>from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.admin import site
from ..admin import AdminViews
register = template.Library()
@register.simple_tag
def get_admin_views(app_name):
output = []
STATIC_URL = settings.STATIC_URL
for k, v in site._registry.items():
if app_name.lower() not in str(k._meta):
continue
if isinstance(v, AdminViews):
for type, name, link in v.output_urls:
if type == 'url':
img_url = "%sadmin_views/icons/link.png" % STATIC_URL
alt_text = "Link to '%s'" % name
else:
img_url = "%sadmin_views/icons/view.png" % STATIC_URL
alt_text = "Custom admin view '%s'" % name
output.append(
u"""<tr>
<th scope="row">
<img src="%s" alt="%s" />
<a href="%s">%s</a></th>
<td> </td>
<td> </td>
</tr>
""" % (img_url, alt_text, link, name)
)
return "".join(output)
|
1af4c1889c55a2ed6e32e8b59ecd2f0be2eb8fea | tests/test_replay.py | tests/test_replay.py | # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
| # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
def test_dump_make_sure_dir_exists(mocker, template_name, context):
mock_ensure = mocker.patch(
'cookiecutter.replay.make_sure_path_exists',
return_value=True
)
replay.dump(template_name, context)
mock_ensure.assert_called_once_with(template_name)
| Implement test to ensure the replay dir existence is verified | Implement test to ensure the replay dir existence is verified
| Python | bsd-3-clause | venumech/cookiecutter,agconti/cookiecutter,dajose/cookiecutter,benthomasson/cookiecutter,moi65/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter,agconti/cookiecutter,moi65/cookiecutter,stevepiercy/cookiecutter,audreyr/cookiecutter,luzfcb/cookiecutter,cguardia/cookiecutter,dajose/cookiecutter,audreyr/cookiecutter,cguardia/cookiecutter,michaeljoseph/cookiecutter,hackebrot/cookiecutter,stevepiercy/cookiecutter,venumech/cookiecutter,Springerle/cookiecutter,christabor/cookiecutter,hackebrot/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,ramiroluz/cookiecutter,michaeljoseph/cookiecutter,terryjbates/cookiecutter,terryjbates/cookiecutter,christabor/cookiecutter,willingc/cookiecutter,benthomasson/cookiecutter,takeflight/cookiecutter,Springerle/cookiecutter,takeflight/cookiecutter | # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
Implement test to ensure the replay dir existence is verified | # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
def test_dump_make_sure_dir_exists(mocker, template_name, context):
mock_ensure = mocker.patch(
'cookiecutter.replay.make_sure_path_exists',
return_value=True
)
replay.dump(template_name, context)
mock_ensure.assert_called_once_with(template_name)
| <commit_before># -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
<commit_msg>Implement test to ensure the replay dir existence is verified<commit_after> | # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
def test_dump_make_sure_dir_exists(mocker, template_name, context):
mock_ensure = mocker.patch(
'cookiecutter.replay.make_sure_path_exists',
return_value=True
)
replay.dump(template_name, context)
mock_ensure.assert_called_once_with(template_name)
| # -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
Implement test to ensure the replay dir existence is verified# -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
def test_dump_make_sure_dir_exists(mocker, template_name, context):
mock_ensure = mocker.patch(
'cookiecutter.replay.make_sure_path_exists',
return_value=True
)
replay.dump(template_name, context)
mock_ensure.assert_called_once_with(template_name)
| <commit_before># -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
<commit_msg>Implement test to ensure the replay dir existence is verified<commit_after># -*- coding: utf-8 -*-
"""
test_replay
-----------
"""
import os
import pytest
from cookiecutter import replay
from cookiecutter.config import get_user_config
def test_get_user_config():
config_dict = get_user_config()
assert 'replay_dir' in config_dict
expected_dir = os.path.expanduser('~/.cookiecutter_replay/')
assert config_dict['replay_dir'] == expected_dir
@pytest.fixture
def template_name():
return 'cookiedozer'
@pytest.fixture
def context():
return {
u'email': u'raphael@hackebrot.de',
u'full_name': u'Raphael Pierzina',
u'github_username': u'hackebrot',
u'version': u'0.1.0',
}
def test_dump_value_error_if_no_template_name(context):
with pytest.raises(ValueError):
replay.dump(None, context)
def test_dump_type_error_if_not_dict_context(template_name):
with pytest.raises(TypeError):
replay.dump(template_name, 'not_a_dict')
def test_dump_make_sure_dir_exists(mocker, template_name, context):
mock_ensure = mocker.patch(
'cookiecutter.replay.make_sure_path_exists',
return_value=True
)
replay.dump(template_name, context)
mock_ensure.assert_called_once_with(template_name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.