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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b44d54c7f1af5e7dca1ca5c05e4e248c180ccb3
|
students/models.py
|
students/models.py
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
def __str__(self):
return "%s: %s - %s" % (self.user, self.start_time, self.end_time)
|
Add __str__ method to pretty print the Booking model.
|
Add __str__ method to pretty print the Booking model.
|
Python
|
mit
|
muhummadPatel/raspied,muhummadPatel/raspied,muhummadPatel/raspied
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
Add __str__ method to pretty print the Booking model.
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
def __str__(self):
return "%s: %s - %s" % (self.user, self.start_time, self.end_time)
|
<commit_before>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
<commit_msg>Add __str__ method to pretty print the Booking model.<commit_after>
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
def __str__(self):
return "%s: %s - %s" % (self.user, self.start_time, self.end_time)
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
Add __str__ method to pretty print the Booking model.from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
def __str__(self):
return "%s: %s - %s" % (self.user, self.start_time, self.end_time)
|
<commit_before>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
<commit_msg>Add __str__ method to pretty print the Booking model.<commit_after>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class WhitelistedUsername(models.Model):
# TODO: change this username field to only allow usernames matching the UCT
# student number regex
username = models.CharField(max_length=50)
def __str__(self):
return self.username
def save(self, *args, **kwargs):
self.username = self.username.lower()
super(WhitelistedUsername, self).save(*args, **kwargs)
class Booking(models.Model):
user = models.ForeignKey(User, editable=False, default=None, blank=False)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
def __str__(self):
return "%s: %s - %s" % (self.user, self.start_time, self.end_time)
|
2f57fd6422c68657b10b0b26118b9598f30cb27a
|
dash/orgs/migrations/0019_resctructure_org_config.py
|
dash/orgs/migrations/0019_resctructure_org_config.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
if not org.config:
old_config = dict()
else:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
|
Check config if not null in migrations
|
Check config if not null in migrations
|
Python
|
bsd-3-clause
|
rapidpro/dash,rapidpro/dash
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
Check config if not null in migrations
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
if not org.config:
old_config = dict()
else:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
<commit_msg>Check config if not null in migrations<commit_after>
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
if not org.config:
old_config = dict()
else:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
Check config if not null in migrations# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
if not org.config:
old_config = dict()
else:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
<commit_msg>Check config if not null in migrations<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
if not org.config:
old_config = dict()
else:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
|
e45005c72cecd54a40e57a3aef92a3fc353f5227
|
flask_limiter/errors.py
|
flask_limiter/errors.py
|
"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response]) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
|
"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response] = None) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
|
Fix missing default value for RateLimitExceeded constructor
|
Fix missing default value for RateLimitExceeded constructor
|
Python
|
mit
|
alisaifee/flask-limiter,alisaifee/flask-limiter
|
"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response]) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
Fix missing default value for RateLimitExceeded constructor
|
"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response] = None) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
|
<commit_before>"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response]) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
<commit_msg>Fix missing default value for RateLimitExceeded constructor<commit_after>
|
"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response] = None) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
|
"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response]) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
Fix missing default value for RateLimitExceeded constructor"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response] = None) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
|
<commit_before>"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response]) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
<commit_msg>Fix missing default value for RateLimitExceeded constructor<commit_after>"""errors and exceptions."""
from flask.wrappers import Response
from werkzeug import exceptions
from .typing import Optional
from .wrappers import Limit
class RateLimitExceeded(exceptions.TooManyRequests):
"""Exception raised when a rate limit is hit."""
def __init__(self, limit: Limit, response: Optional[Response] = None) -> None:
"""
:param limit: The actual rate limit that was hit.
Used to construct the default response message
:param response: Optional pre constructed response. If provided
it will be rendered by flask instead of the default error response
of :class:`~werkzeug.exceptions.HTTPException`
"""
self.limit = limit
self.response = response
if limit.error_message:
description = (
limit.error_message
if not callable(limit.error_message)
else limit.error_message()
)
else:
description = str(limit.limit)
super().__init__(description=description, response=response)
|
47c6c9b4c7d0b86bc47ac0177d8f91e7bf4c72fe
|
akwriters/urls.py
|
akwriters/urls.py
|
from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
|
from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView,RedirectView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', RedirectView.as_view(pattern_name='forum:index'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
|
Bring the forum to the foreground
|
Bring the forum to the foreground
The default landing page is now the forum, to hopefully encourage people to use it
|
Python
|
mit
|
Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters
|
from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
Bring the forum to the foreground
The default landing page is now the forum, to hopefully encourage people to use it
|
from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView,RedirectView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', RedirectView.as_view(pattern_name='forum:index'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
|
<commit_before>from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
<commit_msg>Bring the forum to the foreground
The default landing page is now the forum, to hopefully encourage people to use it<commit_after>
|
from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView,RedirectView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', RedirectView.as_view(pattern_name='forum:index'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
|
from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
Bring the forum to the foreground
The default landing page is now the forum, to hopefully encourage people to use itfrom django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView,RedirectView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', RedirectView.as_view(pattern_name='forum:index'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
|
<commit_before>from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
<commit_msg>Bring the forum to the foreground
The default landing page is now the forum, to hopefully encourage people to use it<commit_after>from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView,RedirectView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', RedirectView.as_view(pattern_name='forum:index'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
|
9fd4c69ac1dc4644c35687423dd4fe3e2f73fe63
|
mistral/tests/unit/engine/actions/test_fake_action.py
|
mistral/tests/unit/engine/actions/test_fake_action.py
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_send_email_real(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_fake_action(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
|
Correct fake action test name
|
Correct fake action test name
Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9
|
Python
|
apache-2.0
|
openstack/mistral,StackStorm/mistral,TimurNurlygayanov/mistral,dennybaa/mistral,openstack/mistral,StackStorm/mistral,dennybaa/mistral
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_send_email_real(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
Correct fake action test name
Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_fake_action(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_send_email_real(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
<commit_msg>Correct fake action test name
Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9<commit_after>
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_fake_action(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_send_email_real(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
Correct fake action test name
Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9# -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_fake_action(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_send_email_real(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
<commit_msg>Correct fake action test name
Change-Id: Ibb2322139fd8d7f3365d3522afde622def910fe9<commit_after># -*- coding: utf-8 -*-
#
# Copyright 2013 - StackStorm, Inc.
#
# 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 mistral.engine.actions import actions
from mistral.engine.actions import action_types
from mistral.tests import base
class FakeActionTest(base.BaseTest):
def test_fake_action(self):
expected = "my output"
action = actions.EchoAction(action_types.ECHO, "test", output=expected)
self.assertEqual(action.run(), expected)
|
784136c8e04c67ae5a6f4b027096ee94b4c57ee9
|
py_naca0020_3d_openfoam/processing.py
|
py_naca0020_3d_openfoam/processing.py
|
"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
|
"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
def load_sampled_set(name="spanwise", quantity="p"):
"""Load sampled set sampled from latest time."""
timedir = max(os.listdir("postProcessing/sets"))
fpath = "postProcessing/sets/{}/{}_{}.csv".format(timedir, name, quantity)
df = pd.read_csv(fpath)
return df
|
Add function for loading sampled set
|
Add function for loading sampled set
|
Python
|
mit
|
petebachant/actuatorLine-3D-turbinesFoam,petebachant/NACA0020-3D-OpenFOAM,petebachant/NACA0020-3D-OpenFOAM,petebachant/NACA0020-3D-OpenFOAM,petebachant/actuatorLine-3D-turbinesFoam,petebachant/actuatorLine-3D-turbinesFoam
|
"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
Add function for loading sampled set
|
"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
def load_sampled_set(name="spanwise", quantity="p"):
"""Load sampled set sampled from latest time."""
timedir = max(os.listdir("postProcessing/sets"))
fpath = "postProcessing/sets/{}/{}_{}.csv".format(timedir, name, quantity)
df = pd.read_csv(fpath)
return df
|
<commit_before>"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
<commit_msg>Add function for loading sampled set<commit_after>
|
"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
def load_sampled_set(name="spanwise", quantity="p"):
"""Load sampled set sampled from latest time."""
timedir = max(os.listdir("postProcessing/sets"))
fpath = "postProcessing/sets/{}/{}_{}.csv".format(timedir, name, quantity)
df = pd.read_csv(fpath)
return df
|
"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
Add function for loading sampled set"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
def load_sampled_set(name="spanwise", quantity="p"):
"""Load sampled set sampled from latest time."""
timedir = max(os.listdir("postProcessing/sets"))
fpath = "postProcessing/sets/{}/{}_{}.csv".format(timedir, name, quantity)
df = pd.read_csv(fpath)
return df
|
<commit_before>"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
<commit_msg>Add function for loading sampled set<commit_after>"""
This module contains processing functions.
"""
import numpy as np
import pandas as pd
import os
def load_force_coeffs(steady=False):
"""
Load force coefficients from file. If steady, the file from the `0`
directory is used, and the last values are returned. Otherwise, arrays are
loaded from the latest file.
"""
if steady:
timedir = "0"
else:
timedir = max(os.listdir("postProcessing/forceCoeffs"))
fpath = "postProcessing/forceCoeffs/{}/forceCoeffs.dat".format(timedir)
data = np.loadtxt(fpath, skiprows=9)
df = pd.DataFrame()
df["time"] = data[:, 0]
df["cl"] = data[:, 3]
df["cd"] = data[:, 2]
df["cm"] = data[:, 1]
return df
def load_sampled_set(name="spanwise", quantity="p"):
"""Load sampled set sampled from latest time."""
timedir = max(os.listdir("postProcessing/sets"))
fpath = "postProcessing/sets/{}/{}_{}.csv".format(timedir, name, quantity)
df = pd.read_csv(fpath)
return df
|
fb0f5e5e9ae0473bed1387bd4151055614b2d5c5
|
alerte_blanche.py
|
alerte_blanche.py
|
import os
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
|
import os
from flask import Flask
from flask import jsonify
from flask import request
from flask import session
app = Flask(__name__)
app.secret_key = b'\xb5\xf2v\xba\x8d\x1b\x86\xabO\xc9\x8e\x1a<m\x17mC1\xf4<\x18\xbeR\xd1'
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
USERS = [{
"id": 1,
"email": "tartempion@generique.com",
}, {
"id": 2,
"email": "individu@lambda.net",
}]
def get_user_id(email):
for user in USERS:
if user['email'] == email:
return user['id']
else:
return None
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
@app.route("/login", methods=['POST'])
def login():
"""Secure, PCI-compliant login"""
email = request.json['email']
session['email'] = email
session['user_id'] = get_user_id(email)
return jsonify({'user_id': session['user_id']})
@app.route('/logout', methods=['POST'])
def logout():
session.pop('email', None)
session.pop('user_id', None)
return ('', 204)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
|
Add dummy implementation for login"
|
Add dummy implementation for login"
|
Python
|
mit
|
HackQC2017-BoltTeam/alerte-blanche-api
|
import os
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
Add dummy implementation for login"
|
import os
from flask import Flask
from flask import jsonify
from flask import request
from flask import session
app = Flask(__name__)
app.secret_key = b'\xb5\xf2v\xba\x8d\x1b\x86\xabO\xc9\x8e\x1a<m\x17mC1\xf4<\x18\xbeR\xd1'
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
USERS = [{
"id": 1,
"email": "tartempion@generique.com",
}, {
"id": 2,
"email": "individu@lambda.net",
}]
def get_user_id(email):
for user in USERS:
if user['email'] == email:
return user['id']
else:
return None
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
@app.route("/login", methods=['POST'])
def login():
"""Secure, PCI-compliant login"""
email = request.json['email']
session['email'] = email
session['user_id'] = get_user_id(email)
return jsonify({'user_id': session['user_id']})
@app.route('/logout', methods=['POST'])
def logout():
session.pop('email', None)
session.pop('user_id', None)
return ('', 204)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
|
<commit_before>import os
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
<commit_msg>Add dummy implementation for login"<commit_after>
|
import os
from flask import Flask
from flask import jsonify
from flask import request
from flask import session
app = Flask(__name__)
app.secret_key = b'\xb5\xf2v\xba\x8d\x1b\x86\xabO\xc9\x8e\x1a<m\x17mC1\xf4<\x18\xbeR\xd1'
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
USERS = [{
"id": 1,
"email": "tartempion@generique.com",
}, {
"id": 2,
"email": "individu@lambda.net",
}]
def get_user_id(email):
for user in USERS:
if user['email'] == email:
return user['id']
else:
return None
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
@app.route("/login", methods=['POST'])
def login():
"""Secure, PCI-compliant login"""
email = request.json['email']
session['email'] = email
session['user_id'] = get_user_id(email)
return jsonify({'user_id': session['user_id']})
@app.route('/logout', methods=['POST'])
def logout():
session.pop('email', None)
session.pop('user_id', None)
return ('', 204)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
|
import os
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
Add dummy implementation for login"import os
from flask import Flask
from flask import jsonify
from flask import request
from flask import session
app = Flask(__name__)
app.secret_key = b'\xb5\xf2v\xba\x8d\x1b\x86\xabO\xc9\x8e\x1a<m\x17mC1\xf4<\x18\xbeR\xd1'
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
USERS = [{
"id": 1,
"email": "tartempion@generique.com",
}, {
"id": 2,
"email": "individu@lambda.net",
}]
def get_user_id(email):
for user in USERS:
if user['email'] == email:
return user['id']
else:
return None
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
@app.route("/login", methods=['POST'])
def login():
"""Secure, PCI-compliant login"""
email = request.json['email']
session['email'] = email
session['user_id'] = get_user_id(email)
return jsonify({'user_id': session['user_id']})
@app.route('/logout', methods=['POST'])
def logout():
session.pop('email', None)
session.pop('user_id', None)
return ('', 204)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
|
<commit_before>import os
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
<commit_msg>Add dummy implementation for login"<commit_after>import os
from flask import Flask
from flask import jsonify
from flask import request
from flask import session
app = Flask(__name__)
app.secret_key = b'\xb5\xf2v\xba\x8d\x1b\x86\xabO\xc9\x8e\x1a<m\x17mC1\xf4<\x18\xbeR\xd1'
FLASK_DEBUG = os.environ.get('FLASK_DEBUG', False)
USERS = [{
"id": 1,
"email": "tartempion@generique.com",
}, {
"id": 2,
"email": "individu@lambda.net",
}]
def get_user_id(email):
for user in USERS:
if user['email'] == email:
return user['id']
else:
return None
@app.route("/version")
def ping():
version_dict = {
"version": "0.0.1",
"debug": bool(FLASK_DEBUG),
}
return jsonify(version_dict)
@app.route("/login", methods=['POST'])
def login():
"""Secure, PCI-compliant login"""
email = request.json['email']
session['email'] = email
session['user_id'] = get_user_id(email)
return jsonify({'user_id': session['user_id']})
@app.route('/logout', methods=['POST'])
def logout():
session.pop('email', None)
session.pop('user_id', None)
return ('', 204)
if __name__ == "__main__":
app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=5000)
|
6d23f3bd1ccd45a6e739264e8d041282e6baaf0b
|
hassio/dock/util.py
|
hassio/dock/util.py
|
"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "resin/armhf-alpine:3.5",
ARCH_AARCH64: "resin/aarch64-alpine:3.5",
ARCH_I386: "resin/i386-alpine:3.5",
ARCH_AMD64: "resin/amd64-alpine:3.5",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
|
"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "homeassistant/armhf-base:latest",
ARCH_AARCH64: "homeassistant/aarch64-base:latest",
ARCH_I386: "homeassistant/i386-base:latest",
ARCH_AMD64: "homeassistant/amd64-base:latest",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
|
Use our new base image
|
Use our new base image
|
Python
|
bsd-3-clause
|
pvizeli/hassio,pvizeli/hassio
|
"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "resin/armhf-alpine:3.5",
ARCH_AARCH64: "resin/aarch64-alpine:3.5",
ARCH_I386: "resin/i386-alpine:3.5",
ARCH_AMD64: "resin/amd64-alpine:3.5",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
Use our new base image
|
"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "homeassistant/armhf-base:latest",
ARCH_AARCH64: "homeassistant/aarch64-base:latest",
ARCH_I386: "homeassistant/i386-base:latest",
ARCH_AMD64: "homeassistant/amd64-base:latest",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
|
<commit_before>"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "resin/armhf-alpine:3.5",
ARCH_AARCH64: "resin/aarch64-alpine:3.5",
ARCH_I386: "resin/i386-alpine:3.5",
ARCH_AMD64: "resin/amd64-alpine:3.5",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
<commit_msg>Use our new base image<commit_after>
|
"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "homeassistant/armhf-base:latest",
ARCH_AARCH64: "homeassistant/aarch64-base:latest",
ARCH_I386: "homeassistant/i386-base:latest",
ARCH_AMD64: "homeassistant/amd64-base:latest",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
|
"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "resin/armhf-alpine:3.5",
ARCH_AARCH64: "resin/aarch64-alpine:3.5",
ARCH_I386: "resin/i386-alpine:3.5",
ARCH_AMD64: "resin/amd64-alpine:3.5",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
Use our new base image"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "homeassistant/armhf-base:latest",
ARCH_AARCH64: "homeassistant/aarch64-base:latest",
ARCH_I386: "homeassistant/i386-base:latest",
ARCH_AMD64: "homeassistant/amd64-base:latest",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
|
<commit_before>"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "resin/armhf-alpine:3.5",
ARCH_AARCH64: "resin/aarch64-alpine:3.5",
ARCH_I386: "resin/i386-alpine:3.5",
ARCH_AMD64: "resin/amd64-alpine:3.5",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
<commit_msg>Use our new base image<commit_after>"""HassIO docker utilitys."""
import re
from ..const import ARCH_AARCH64, ARCH_ARMHF, ARCH_I386, ARCH_AMD64
RESIN_BASE_IMAGE = {
ARCH_ARMHF: "homeassistant/armhf-base:latest",
ARCH_AARCH64: "homeassistant/aarch64-base:latest",
ARCH_I386: "homeassistant/i386-base:latest",
ARCH_AMD64: "homeassistant/amd64-base:latest",
}
TMPL_IMAGE = re.compile(r"%%BASE_IMAGE%%")
def dockerfile_template(dockerfile, arch, version, meta_type):
"""Prepare a Hass.IO dockerfile."""
buff = []
resin_image = RESIN_BASE_IMAGE[arch]
# read docker
with dockerfile.open('r') as dock_input:
for line in dock_input:
line = TMPL_IMAGE.sub(resin_image, line)
buff.append(line)
# add metadata
buff.append(create_metadata(version, arch, meta_type))
# write docker
with dockerfile.open('w') as dock_output:
dock_output.writelines(buff)
def create_metadata(version, arch, meta_type):
"""Generate docker label layer for hassio."""
return ('LABEL io.hass.version="{}" '
'io.hass.arch="{}" '
'io.hass.type="{}"').format(version, arch, meta_type)
|
6f0dc07d16162095553590a3fc66f1c90098cf88
|
config_sample.py
|
config_sample.py
|
# App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
DEFAULT_NAME = 'Anonymous'
SHOW_BOARDS_AT_TOP = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
|
# App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
|
Update config sample to remove unused config items
|
Update config sample to remove unused config items
|
Python
|
mit
|
Floens/uchan,Floens/uchan,Floens/uchan,Floens/uchan,Floens/uchan
|
# App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
DEFAULT_NAME = 'Anonymous'
SHOW_BOARDS_AT_TOP = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
Update config sample to remove unused config items
|
# App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
|
<commit_before># App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
DEFAULT_NAME = 'Anonymous'
SHOW_BOARDS_AT_TOP = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
<commit_msg>Update config sample to remove unused config items<commit_after>
|
# App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
|
# App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
DEFAULT_NAME = 'Anonymous'
SHOW_BOARDS_AT_TOP = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
Update config sample to remove unused config items# App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
|
<commit_before># App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
DEFAULT_NAME = 'Anonymous'
SHOW_BOARDS_AT_TOP = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
<commit_msg>Update config sample to remove unused config items<commit_after># App
APP_NAME = 'uchan'
SITE_NAME = 'µchan'
SITE_URL = 'http://127.0.0.1'
DEBUG = True
# Flask
DATABASE_CONNECT_STRING = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/unichan'
DATABASE_POOL_SIZE = 5
# Generate with `import os` `os.urandom(32)`
SECRET_KEY = None
|
21d062ef148b75d00dba6c2873a627e87723e93b
|
PyFVCOM/__init__.py
|
PyFVCOM/__init__.py
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import coast
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
|
Remove the old coast import.
|
Remove the old coast import.
|
Python
|
mit
|
pwcazenave/PyFVCOM
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import coast
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
Remove the old coast import.
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
|
<commit_before>"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import coast
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
<commit_msg>Remove the old coast import.<commit_after>
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import coast
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
Remove the old coast import."""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
|
<commit_before>"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import coast
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
<commit_msg>Remove the old coast import.<commit_after>"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import everything! Eventually, we're going to hit a circular dependency here...
from PyFVCOM import buoy
from PyFVCOM import ctd
from PyFVCOM import current
from PyFVCOM import grid
from PyFVCOM import coordinate
from PyFVCOM import ocean
from PyFVCOM import stats
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide
from PyFVCOM import plot
from PyFVCOM import preproc
from PyFVCOM import read
from PyFVCOM import validation
if sys.version_info.major < 3 and sys.version_info.minor < 6:
raise Exception('Must be using Python 3.6 or greater')
|
d1c18841d8a028f76283b9779da61d482df75973
|
plumeria/plugins/youtube.py
|
plumeria/plugins/youtube.py
|
from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@channel_only
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
|
from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
|
Allow YouTube plugin to be used in PMs.
|
Allow YouTube plugin to be used in PMs.
|
Python
|
mit
|
sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria
|
from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@channel_only
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
Allow YouTube plugin to be used in PMs.
|
from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
|
<commit_before>from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@channel_only
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
<commit_msg>Allow YouTube plugin to be used in PMs.<commit_after>
|
from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
|
from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@channel_only
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
Allow YouTube plugin to be used in PMs.from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
|
<commit_before>from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@channel_only
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
<commit_msg>Allow YouTube plugin to be used in PMs.<commit_after>from plumeria.api.youtube import YouTube
from plumeria.command import commands, CommandError, channel_only
from plumeria.message import Response
from plumeria.util.ratelimit import rate_limit
youtube = YouTube()
@commands.register('youtube', 'yt', 'ytsearch', cost=2, category='Search')
@rate_limit()
async def yt(message):
"""
Search YouTube for a video.
Example::
/yt knuckle puck copacetic
"""
if len(message.content.strip()):
videos = await youtube.search(message.content)
if len(videos):
return Response(videos[0].url)
else:
raise CommandError("No video found!")
|
96b4040e3508d55abf1857209e9820cff7ab3478
|
geotrek/feedback/management/commands/erase_emails.py
|
geotrek/feedback/management/commands/erase_emails.py
|
import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
# def add_arguments(self, parser):
# parser.add_argument('sample', nargs='+')
def handle(self, *args, **options):
one_year = timezone.now() - timedelta(days=365)
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
|
import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
def add_arguments(self, parser):
parser.add_argument('-d', '--days',
help="Erase mails older than DAYS (default: %(default)s)",
type=int,
default=365)
parser.add_argument('--dry-run',
action='store_true',
default=False,
help="Show only how many reports will be modified")
def handle(self, *args, **options):
"""Handle method for `erase_email` command"""
one_year = timezone.now() - timedelta(days=options['days'])
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
if not options['dry_run']:
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
else:
logger.info('Dry run mode,{0} report(s) should be modified'.format(updated_reports,))
|
Add options dry-run mode and days
|
Add options dry-run mode and days
|
Python
|
bsd-2-clause
|
makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin
|
import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
# def add_arguments(self, parser):
# parser.add_argument('sample', nargs='+')
def handle(self, *args, **options):
one_year = timezone.now() - timedelta(days=365)
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
Add options dry-run mode and days
|
import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
def add_arguments(self, parser):
parser.add_argument('-d', '--days',
help="Erase mails older than DAYS (default: %(default)s)",
type=int,
default=365)
parser.add_argument('--dry-run',
action='store_true',
default=False,
help="Show only how many reports will be modified")
def handle(self, *args, **options):
"""Handle method for `erase_email` command"""
one_year = timezone.now() - timedelta(days=options['days'])
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
if not options['dry_run']:
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
else:
logger.info('Dry run mode,{0} report(s) should be modified'.format(updated_reports,))
|
<commit_before>import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
# def add_arguments(self, parser):
# parser.add_argument('sample', nargs='+')
def handle(self, *args, **options):
one_year = timezone.now() - timedelta(days=365)
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
<commit_msg>Add options dry-run mode and days<commit_after>
|
import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
def add_arguments(self, parser):
parser.add_argument('-d', '--days',
help="Erase mails older than DAYS (default: %(default)s)",
type=int,
default=365)
parser.add_argument('--dry-run',
action='store_true',
default=False,
help="Show only how many reports will be modified")
def handle(self, *args, **options):
"""Handle method for `erase_email` command"""
one_year = timezone.now() - timedelta(days=options['days'])
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
if not options['dry_run']:
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
else:
logger.info('Dry run mode,{0} report(s) should be modified'.format(updated_reports,))
|
import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
# def add_arguments(self, parser):
# parser.add_argument('sample', nargs='+')
def handle(self, *args, **options):
one_year = timezone.now() - timedelta(days=365)
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
Add options dry-run mode and daysimport logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
def add_arguments(self, parser):
parser.add_argument('-d', '--days',
help="Erase mails older than DAYS (default: %(default)s)",
type=int,
default=365)
parser.add_argument('--dry-run',
action='store_true',
default=False,
help="Show only how many reports will be modified")
def handle(self, *args, **options):
"""Handle method for `erase_email` command"""
one_year = timezone.now() - timedelta(days=options['days'])
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
if not options['dry_run']:
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
else:
logger.info('Dry run mode,{0} report(s) should be modified'.format(updated_reports,))
|
<commit_before>import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
# def add_arguments(self, parser):
# parser.add_argument('sample', nargs='+')
def handle(self, *args, **options):
one_year = timezone.now() - timedelta(days=365)
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
<commit_msg>Add options dry-run mode and days<commit_after>import logging
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from geotrek.feedback.models import Report
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Erase emails older than 1 year from feedbacks."
def add_arguments(self, parser):
parser.add_argument('-d', '--days',
help="Erase mails older than DAYS (default: %(default)s)",
type=int,
default=365)
parser.add_argument('--dry-run',
action='store_true',
default=False,
help="Show only how many reports will be modified")
def handle(self, *args, **options):
"""Handle method for `erase_email` command"""
one_year = timezone.now() - timedelta(days=options['days'])
older_reports = Report.objects.filter(date_insert__lt=one_year).exclude(email='')
if not options['dry_run']:
updated_reports = older_reports.update(email='')
logger.info('{0} email(s) erased'.format(updated_reports,))
else:
logger.info('Dry run mode,{0} report(s) should be modified'.format(updated_reports,))
|
94cd1300a4ccf66488120092dfe880eabc7f06df
|
tests/test_dump.py
|
tests/test_dump.py
|
""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file__))
exe_pth = pjoin(downpath, 'gitwash_dumper.py')
tmpdir = mkdtemp()
try:
call([exe_pth,
tmpdir,
'my_project'])
finally:
shutil.rmtree(tmpdir)
|
""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
|
TEST - setup teardown for test
|
TEST - setup teardown for test
|
Python
|
bsd-2-clause
|
QuLogic/gitwash,QuLogic/gitwash
|
""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file__))
exe_pth = pjoin(downpath, 'gitwash_dumper.py')
tmpdir = mkdtemp()
try:
call([exe_pth,
tmpdir,
'my_project'])
finally:
shutil.rmtree(tmpdir)
TEST - setup teardown for test
|
""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
|
<commit_before>""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file__))
exe_pth = pjoin(downpath, 'gitwash_dumper.py')
tmpdir = mkdtemp()
try:
call([exe_pth,
tmpdir,
'my_project'])
finally:
shutil.rmtree(tmpdir)
<commit_msg>TEST - setup teardown for test<commit_after>
|
""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
|
""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file__))
exe_pth = pjoin(downpath, 'gitwash_dumper.py')
tmpdir = mkdtemp()
try:
call([exe_pth,
tmpdir,
'my_project'])
finally:
shutil.rmtree(tmpdir)
TEST - setup teardown for test""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
|
<commit_before>""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
def test_dumper():
downpath, _ = psplit(dirname(__file__))
exe_pth = pjoin(downpath, 'gitwash_dumper.py')
tmpdir = mkdtemp()
try:
call([exe_pth,
tmpdir,
'my_project'])
finally:
shutil.rmtree(tmpdir)
<commit_msg>TEST - setup teardown for test<commit_after>""" Testing gitwash dumper
"""
from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call
from nose.tools import assert_true, assert_equal, assert_raises
_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None
def setup():
global TMPDIR
TMPDIR = mkdtemp()
def teardown():
shutil.rmtree(TMPDIR)
def test_dumper():
call([EXE_PTH,
TMPDIR,
'my_project'])
|
8c9cc7f3e8d39007eab076c1bb34715d37716fc9
|
tests/test_rmap.py
|
tests/test_rmap.py
|
from skrt.utils import rmap
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, lambda x: x**2, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, lambda x: x**2, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, lambda x: x**2, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, lambda x: x**2, int) == {'a': 1, 'b': 4, 'c': 9}
|
from skrt.utils import rmap
def square(x):
return x ** 2
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, square, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, square, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, square, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, square, int) == {'a': 1, 'b': 4, 'c': 9}
def test_complex_nested():
obj = ['1', 2, ({3: 4}, {5, '6'})]
assert rmap(obj, square, int) == ['1', 4, ({3: 16}, {'6', 25})]
|
Add complex test for rmap
|
Add complex test for rmap
|
Python
|
mit
|
nvander1/skrt
|
from skrt.utils import rmap
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, lambda x: x**2, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, lambda x: x**2, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, lambda x: x**2, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, lambda x: x**2, int) == {'a': 1, 'b': 4, 'c': 9}
Add complex test for rmap
|
from skrt.utils import rmap
def square(x):
return x ** 2
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, square, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, square, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, square, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, square, int) == {'a': 1, 'b': 4, 'c': 9}
def test_complex_nested():
obj = ['1', 2, ({3: 4}, {5, '6'})]
assert rmap(obj, square, int) == ['1', 4, ({3: 16}, {'6', 25})]
|
<commit_before>from skrt.utils import rmap
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, lambda x: x**2, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, lambda x: x**2, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, lambda x: x**2, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, lambda x: x**2, int) == {'a': 1, 'b': 4, 'c': 9}
<commit_msg>Add complex test for rmap<commit_after>
|
from skrt.utils import rmap
def square(x):
return x ** 2
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, square, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, square, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, square, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, square, int) == {'a': 1, 'b': 4, 'c': 9}
def test_complex_nested():
obj = ['1', 2, ({3: 4}, {5, '6'})]
assert rmap(obj, square, int) == ['1', 4, ({3: 16}, {'6', 25})]
|
from skrt.utils import rmap
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, lambda x: x**2, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, lambda x: x**2, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, lambda x: x**2, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, lambda x: x**2, int) == {'a': 1, 'b': 4, 'c': 9}
Add complex test for rmapfrom skrt.utils import rmap
def square(x):
return x ** 2
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, square, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, square, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, square, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, square, int) == {'a': 1, 'b': 4, 'c': 9}
def test_complex_nested():
obj = ['1', 2, ({3: 4}, {5, '6'})]
assert rmap(obj, square, int) == ['1', 4, ({3: 16}, {'6', 25})]
|
<commit_before>from skrt.utils import rmap
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, lambda x: x**2, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, lambda x: x**2, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, lambda x: x**2, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, lambda x: x**2, int) == {'a': 1, 'b': 4, 'c': 9}
<commit_msg>Add complex test for rmap<commit_after>from skrt.utils import rmap
def square(x):
return x ** 2
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(list_, square, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(tuple_, square, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
assert rmap(set_, square, int) == {1, 4, 9, 16, 25}
def test_dict():
dict_ = {'a': 1, 'b': 2, 'c': 3}
assert rmap(dict_, square, int) == {'a': 1, 'b': 4, 'c': 9}
def test_complex_nested():
obj = ['1', 2, ({3: 4}, {5, '6'})]
assert rmap(obj, square, int) == ['1', 4, ({3: 16}, {'6', 25})]
|
00fe6161c7c26d25f52fa6cf374c3fd767cf7cf7
|
conllu/compat.py
|
conllu/compat.py
|
from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
from io import StringIO
from contextlib import redirect_stdout
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
Remove special case for redirect_stdout.
|
Remove special case for redirect_stdout.
|
Python
|
mit
|
EmilStenstrom/conllu
|
from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
Remove special case for redirect_stdout.
|
from io import StringIO
from contextlib import redirect_stdout
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
<commit_before>from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
<commit_msg>Remove special case for redirect_stdout.<commit_after>
|
from io import StringIO
from contextlib import redirect_stdout
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
Remove special case for redirect_stdout.from io import StringIO
from contextlib import redirect_stdout
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
<commit_before>from io import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
<commit_msg>Remove special case for redirect_stdout.<commit_after>from io import StringIO
from contextlib import redirect_stdout
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
dc755e07516e1cbbcd01f01e8be59abf8f1a6329
|
humfrey/update/management/commands/update_dataset.py
|
humfrey/update/management/commands/update_dataset.py
|
import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': 'manual',
'queued_at': datetime.datetime.now(),
})))
|
import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
trigger = args[1] if len(args) > 1 else 'manual'
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': trigger,
'queued_at': datetime.datetime.now(),
})))
if __name__ == '__main__':
import sys
Command().handle(*sys.argv[1:])
|
Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.
|
Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.
|
Python
|
bsd-3-clause
|
ox-it/humfrey,ox-it/humfrey,ox-it/humfrey
|
import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': 'manual',
'queued_at': datetime.datetime.now(),
})))
Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.
|
import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
trigger = args[1] if len(args) > 1 else 'manual'
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': trigger,
'queued_at': datetime.datetime.now(),
})))
if __name__ == '__main__':
import sys
Command().handle(*sys.argv[1:])
|
<commit_before>import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': 'manual',
'queued_at': datetime.datetime.now(),
})))
<commit_msg>Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.<commit_after>
|
import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
trigger = args[1] if len(args) > 1 else 'manual'
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': trigger,
'queued_at': datetime.datetime.now(),
})))
if __name__ == '__main__':
import sys
Command().handle(*sys.argv[1:])
|
import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': 'manual',
'queued_at': datetime.datetime.now(),
})))
Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
trigger = args[1] if len(args) > 1 else 'manual'
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': trigger,
'queued_at': datetime.datetime.now(),
})))
if __name__ == '__main__':
import sys
Command().handle(*sys.argv[1:])
|
<commit_before>import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': 'manual',
'queued_at': datetime.datetime.now(),
})))
<commit_msg>Update trigger can now be specified on the command line as the second argument, and the module can now be run as a script.<commit_after>import base64
import datetime
import os
import pickle
from lxml import etree
import redis
from django.core.management.base import BaseCommand
from django.conf import settings
from humfrey.update.longliving.updater import Updater
class Command(BaseCommand):
def handle(self, *args, **options):
config_filename = os.path.abspath(args[0])
trigger = args[1] if len(args) > 1 else 'manual'
with open(config_filename, 'r') as f:
config_file = etree.parse(f)
dataset_name = config_file.xpath('meta/name')[0].text
client = redis.client.Redis(**settings.REDIS_PARAMS)
client.rpush(Updater.QUEUE_NAME, base64.b64encode(pickle.dumps({
'config_filename': config_filename,
'name': dataset_name,
'trigger': trigger,
'queued_at': datetime.datetime.now(),
})))
if __name__ == '__main__':
import sys
Command().handle(*sys.argv[1:])
|
0c42fdc90e3d4dfcf0a1b353be1abbe34e820f85
|
bills/tests.py
|
bills/tests.py
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from opencivicdata.models import Bill, LegislativeSession, Person
from tot import settings
from preferences.models import Preferences
BILL_FULL_FIELDS = ('abstracts', 'other_titles', 'other_identifiers',
'actions', 'related_bills', 'sponsorships',
'documents', 'versions', 'sources')
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
def test_by_topic_view_selected(self):
response = self.client.get(reverse('by_topic_selected'))
self.assertEqual(response.status_code, 200)
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from preferences.models import Preferences
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
# def test_by_topic_view_selected(self):
# response = self.client.get(reverse('by_topic_selected'))
# self.assertEqual(response.status_code, 200)
|
Remove failing test for now
|
Remove failing test for now
|
Python
|
mit
|
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from opencivicdata.models import Bill, LegislativeSession, Person
from tot import settings
from preferences.models import Preferences
BILL_FULL_FIELDS = ('abstracts', 'other_titles', 'other_identifiers',
'actions', 'related_bills', 'sponsorships',
'documents', 'versions', 'sources')
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
def test_by_topic_view_selected(self):
response = self.client.get(reverse('by_topic_selected'))
self.assertEqual(response.status_code, 200)
Remove failing test for now
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from preferences.models import Preferences
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
# def test_by_topic_view_selected(self):
# response = self.client.get(reverse('by_topic_selected'))
# self.assertEqual(response.status_code, 200)
|
<commit_before>from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from opencivicdata.models import Bill, LegislativeSession, Person
from tot import settings
from preferences.models import Preferences
BILL_FULL_FIELDS = ('abstracts', 'other_titles', 'other_identifiers',
'actions', 'related_bills', 'sponsorships',
'documents', 'versions', 'sources')
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
def test_by_topic_view_selected(self):
response = self.client.get(reverse('by_topic_selected'))
self.assertEqual(response.status_code, 200)
<commit_msg>Remove failing test for now<commit_after>
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from preferences.models import Preferences
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
# def test_by_topic_view_selected(self):
# response = self.client.get(reverse('by_topic_selected'))
# self.assertEqual(response.status_code, 200)
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from opencivicdata.models import Bill, LegislativeSession, Person
from tot import settings
from preferences.models import Preferences
BILL_FULL_FIELDS = ('abstracts', 'other_titles', 'other_identifiers',
'actions', 'related_bills', 'sponsorships',
'documents', 'versions', 'sources')
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
def test_by_topic_view_selected(self):
response = self.client.get(reverse('by_topic_selected'))
self.assertEqual(response.status_code, 200)
Remove failing test for nowfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from preferences.models import Preferences
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
# def test_by_topic_view_selected(self):
# response = self.client.get(reverse('by_topic_selected'))
# self.assertEqual(response.status_code, 200)
|
<commit_before>from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from opencivicdata.models import Bill, LegislativeSession, Person
from tot import settings
from preferences.models import Preferences
BILL_FULL_FIELDS = ('abstracts', 'other_titles', 'other_identifiers',
'actions', 'related_bills', 'sponsorships',
'documents', 'versions', 'sources')
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
def test_by_topic_view_selected(self):
response = self.client.get(reverse('by_topic_selected'))
self.assertEqual(response.status_code, 200)
<commit_msg>Remove failing test for now<commit_after>from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from preferences.models import Preferences
class BillViewTests(StaticLiveServerTestCase):
fixtures = ['fl_testdata.json']
def setUp(self):
u = User.objects.create_user('test')
p = Preferences.objects.create(user=u)
self.apikey = p.apikey
def test_by_topic_view(self):
response = self.client.get(reverse('by_topic'))
self.assertEqual(response.status_code, 200)
# def test_by_topic_view_selected(self):
# response = self.client.get(reverse('by_topic_selected'))
# self.assertEqual(response.status_code, 200)
|
e4ea9426a75828c6fce924b895ee3e4603595dc7
|
tests/templates/components/test_radios_with_images.py
|
tests/templates/components/test_radios_with_images.py
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are.
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0")
correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0")
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.14.0") == govuk_frontend_version
correct_govuk_frontend_jinja_version = Version("1.5.1") == govuk_frontend_jinja_version
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
Update test for GOVUK Frontend libraries parity
|
Update test for GOVUK Frontend libraries parity
|
Python
|
mit
|
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are.
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0")
correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0")
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
Update test for GOVUK Frontend libraries parity
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.14.0") == govuk_frontend_version
correct_govuk_frontend_jinja_version = Version("1.5.1") == govuk_frontend_jinja_version
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
<commit_before>import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are.
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0")
correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0")
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
<commit_msg>Update test for GOVUK Frontend libraries parity<commit_after>
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.14.0") == govuk_frontend_version
correct_govuk_frontend_jinja_version = Version("1.5.1") == govuk_frontend_jinja_version
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are.
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0")
correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0")
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
Update test for GOVUK Frontend libraries parityimport json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.14.0") == govuk_frontend_version
correct_govuk_frontend_jinja_version = Version("1.5.1") == govuk_frontend_jinja_version
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
<commit_before>import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are.
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0")
correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0")
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
<commit_msg>Update test for GOVUK Frontend libraries parity<commit_after>import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.14.0") == govuk_frontend_version
correct_govuk_frontend_jinja_version = Version("1.5.1") == govuk_frontend_jinja_version
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
e0ae123f3e1c17b112bbcc6020c661d252c0afd9
|
tox_run_command.py
|
tox_run_command.py
|
import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs['py27']._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
|
import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs[env]._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
|
Use the environment in envlist instead of the contant py27
|
Use the environment in envlist instead of the contant py27
|
Python
|
apache-2.0
|
dstanek/tox-run-command
|
import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs['py27']._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
Use the environment in envlist instead of the contant py27
|
import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs[env]._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
|
<commit_before>import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs['py27']._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
<commit_msg>Use the environment in envlist instead of the contant py27<commit_after>
|
import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs[env]._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
|
import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs['py27']._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
Use the environment in envlist instead of the contant py27import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs[env]._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
|
<commit_before>import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs['py27']._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
<commit_msg>Use the environment in envlist instead of the contant py27<commit_after>import tox.config
from tox import hookimpl
def getargvlist(reader, command):
return tox.config._ArgvlistReader.getargvlist(reader, command)
@hookimpl
def tox_addoption(parser):
parser.add_argument('--run-command', help='run this command instead of configured commands')
@hookimpl
def tox_configure(config):
alternative_cmd = config.option.run_command
if alternative_cmd:
for env in config.envlist:
reader = config.envconfigs[env]._reader
env_commands = getargvlist(reader, alternative_cmd)
config.envconfigs[env].commands = env_commands
|
8fdd6f8c2eb463b4d7bf9bb7372d141b97af8f1f
|
tviserrys/views.py
|
tviserrys/views.py
|
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
class IndexView(View):
template_name = 'tviit/index.html'
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
context = RequestContext(request, {
})
return render(request, self.template_name, context)
|
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
from tviit.models import Tviit, TviitForm
class IndexView(View):
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
template = loader.get_template('tviit/index.html')
context = {
'tviit_form': TviitForm,
}
return HttpResponse(template.render(context, request))
|
Add TviitForm into main View
|
Add TviitForm into main View
|
Python
|
mit
|
DeWaster/Tviserrys,DeWaster/Tviserrys
|
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
class IndexView(View):
template_name = 'tviit/index.html'
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
context = RequestContext(request, {
})
return render(request, self.template_name, context)
Add TviitForm into main View
|
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
from tviit.models import Tviit, TviitForm
class IndexView(View):
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
template = loader.get_template('tviit/index.html')
context = {
'tviit_form': TviitForm,
}
return HttpResponse(template.render(context, request))
|
<commit_before>from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
class IndexView(View):
template_name = 'tviit/index.html'
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
context = RequestContext(request, {
})
return render(request, self.template_name, context)
<commit_msg>Add TviitForm into main View<commit_after>
|
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
from tviit.models import Tviit, TviitForm
class IndexView(View):
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
template = loader.get_template('tviit/index.html')
context = {
'tviit_form': TviitForm,
}
return HttpResponse(template.render(context, request))
|
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
class IndexView(View):
template_name = 'tviit/index.html'
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
context = RequestContext(request, {
})
return render(request, self.template_name, context)
Add TviitForm into main Viewfrom django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
from tviit.models import Tviit, TviitForm
class IndexView(View):
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
template = loader.get_template('tviit/index.html')
context = {
'tviit_form': TviitForm,
}
return HttpResponse(template.render(context, request))
|
<commit_before>from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
class IndexView(View):
template_name = 'tviit/index.html'
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
context = RequestContext(request, {
})
return render(request, self.template_name, context)
<commit_msg>Add TviitForm into main View<commit_after>from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
from tviit.models import Tviit, TviitForm
class IndexView(View):
@method_decorator(login_required(login_url='/login/'))
def get(self, request, *args, **kwargs):
template = loader.get_template('tviit/index.html')
context = {
'tviit_form': TviitForm,
}
return HttpResponse(template.render(context, request))
|
31b7ad0eaf4f74503a970e0cee303eb3bc5ea460
|
charity_server.py
|
charity_server.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/")
def gci():
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
Switch to datetime based on calls for updates.
|
Switch to datetime based on calls for updates.
|
Python
|
mit
|
colmcoughlan/alchemy-server
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/")
def gci():
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
Switch to datetime based on calls for updates.
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/")
def gci():
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
<commit_msg>Switch to datetime based on calls for updates.<commit_after>
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/")
def gci():
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
Switch to datetime based on calls for updates.#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/")
def gci():
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
<commit_msg>Switch to datetime based on calls for updates.<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 30 01:14:12 2017
@author: colm
"""
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
855c65b15b9490830e997fc2d8ce5c033eecbddb
|
logger.py
|
logger.py
|
#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'w')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
|
#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'a')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
|
Append instead of truncating log file
|
Append instead of truncating log file
|
Python
|
mit
|
wapcaplet/ardiff
|
#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'w')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
Append instead of truncating log file
|
#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'a')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
|
<commit_before>#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'w')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
<commit_msg>Append instead of truncating log file<commit_after>
|
#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'a')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
|
#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'w')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
Append instead of truncating log file#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'a')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
|
<commit_before>#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'w')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
<commit_msg>Append instead of truncating log file<commit_after>#! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
from datetime import datetime
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'a')
try:
while True:
line = ser.readline()
now = datetime.now()
print("%s, %s" % (now, line))
outfile.write("%s, %s" % (now, line))
except KeyboardInterrupt:
print("Quitting!")
outfile.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: logger.py <filename>")
filename = sys.argv[1]
log_serial(filename)
|
f5ba363de4777e2d594261214913f5d480cb04b6
|
Heuristics/AbstactHeuristic.py
|
Heuristics/AbstactHeuristic.py
|
from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % length + 1
solution.append(value)
return solution
|
from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % (length + 1)
if value == 0:
value = 1
solution.append(value)
return solution
|
Fix on function generate random solution
|
Fix on function generate random solution
|
Python
|
mit
|
DiegoReiriz/MetaHeuristics,DiegoReiriz/MetaHeuristics
|
from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % length + 1
solution.append(value)
return solution
Fix on function generate random solution
|
from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % (length + 1)
if value == 0:
value = 1
solution.append(value)
return solution
|
<commit_before>from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % length + 1
solution.append(value)
return solution
<commit_msg>Fix on function generate random solution<commit_after>
|
from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % (length + 1)
if value == 0:
value = 1
solution.append(value)
return solution
|
from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % length + 1
solution.append(value)
return solution
Fix on function generate random solutionfrom abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % (length + 1)
if value == 0:
value = 1
solution.append(value)
return solution
|
<commit_before>from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % length + 1
solution.append(value)
return solution
<commit_msg>Fix on function generate random solution<commit_after>from abc import ABC, abstractmethod
import random as random
class AbstractHeuristic(ABC):
@abstractmethod
def calculate(self, solution):
pass
def calculateCost(self, dataset, solution):
cost = 0
i = 0
cost += dataset.getValueXY(0, solution[0])
for i in range(0, len(solution)-1):
cost += dataset.getValueXY(solution[i], solution[i + 1])
i += 1
cost += dataset.getValueXY(i,solution[0])
return cost
def generateRandomSolution(self, dataset):
length = len(dataset[-1])-1
solution = []
for i in range(length):
value = random.randint(1, length)
while value in solution:
value = (value + 1) % (length + 1)
if value == 0:
value = 1
solution.append(value)
return solution
|
703b67c2ac1753133c00d5cd4a859752830b578a
|
kokekunster/urls.py
|
kokekunster/urls.py
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^$', semester, {'program_code': 'mtfyma', 'semester_number': 1}),
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
|
Set homepage to first semester fysmat
|
Set homepage to first semester fysmat
|
Python
|
mit
|
afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
Set homepage to first semester fysmat
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^$', semester, {'program_code': 'mtfyma', 'semester_number': 1}),
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
|
<commit_before>"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
<commit_msg>Set homepage to first semester fysmat<commit_after>
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^$', semester, {'program_code': 'mtfyma', 'semester_number': 1}),
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
Set homepage to first semester fysmat"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^$', semester, {'program_code': 'mtfyma', 'semester_number': 1}),
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
|
<commit_before>"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
<commit_msg>Set homepage to first semester fysmat<commit_after>"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester
urlpatterns = [
url(r'^$', semester, {'program_code': 'mtfyma', 'semester_number': 1}),
url(r'^admin/', include(admin.site.urls)),
url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester),
]
|
9de5a1935ceb3f39b17807096c800cdf01b219bf
|
Scripts/multi_process_files.py
|
Scripts/multi_process_files.py
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
inputpath = '/data/amnh/darwin/images'
segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
Fix paths for local execution different from cloud server.
|
Fix paths for local execution different from cloud server.
|
Python
|
apache-2.0
|
HackTheStacks/darwin-notes-image-processing,HackTheStacks/darwin-notes-image-processing
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
inputpath = '/data/amnh/darwin/images'
segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
Fix paths for local execution different from cloud server.
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
<commit_before>#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
inputpath = '/data/amnh/darwin/images'
segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
<commit_msg>Fix paths for local execution different from cloud server.<commit_after>
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
inputpath = '/data/amnh/darwin/images'
segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
Fix paths for local execution different from cloud server.#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
<commit_before>#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
inputpath = '/data/amnh/darwin/images'
segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
<commit_msg>Fix paths for local execution different from cloud server.<commit_after>#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
8e58b413801a0dbbcd3e48a5ef94201a24af7e8e
|
are_there_spiders/are_there_spiders/custom_storages.py
|
are_there_spiders/are_there_spiders/custom_storages.py
|
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
|
import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (See http://stackoverflow.com/questions/11820566/inconsistent-
# signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
class PatchedCachedFilesMixin(CachedFilesMixin):
def url(self, *a, **kw):
s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
if isinstance(s, unicode):
s = s.encode('utf-8', 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
Revert "Improvement to custom storage."
|
Revert "Improvement to custom storage."
This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.
|
Python
|
mit
|
wlonk/are_there_spiders,wlonk/are_there_spiders,wlonk/are_there_spiders
|
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
Revert "Improvement to custom storage."
This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.
|
import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (See http://stackoverflow.com/questions/11820566/inconsistent-
# signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
class PatchedCachedFilesMixin(CachedFilesMixin):
def url(self, *a, **kw):
s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
if isinstance(s, unicode):
s = s.encode('utf-8', 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
<commit_before>from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
<commit_msg>Revert "Improvement to custom storage."
This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.<commit_after>
|
import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (See http://stackoverflow.com/questions/11820566/inconsistent-
# signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
class PatchedCachedFilesMixin(CachedFilesMixin):
def url(self, *a, **kw):
s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
if isinstance(s, unicode):
s = s.encode('utf-8', 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
Revert "Improvement to custom storage."
This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (See http://stackoverflow.com/questions/11820566/inconsistent-
# signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
class PatchedCachedFilesMixin(CachedFilesMixin):
def url(self, *a, **kw):
s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
if isinstance(s, unicode):
s = s.encode('utf-8', 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
<commit_before>from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
class S3PipelineStorage(PipelineMixin, CachedFilesMixin, S3BotoStorage):
pass
<commit_msg>Revert "Improvement to custom storage."
This reverts commit 6f185ac7398f30653dff9403d5ebf5539d222f4c.<commit_after>import urllib
import urlparse
from django.contrib.staticfiles.storage import CachedFilesMixin
from pipeline.storage import PipelineMixin
from storages.backends.s3boto import S3BotoStorage
# CachedFilesMixin doesn't play well with Boto and S3. It over-quotes things,
# causing erratic failures. So we subclass.
# (See http://stackoverflow.com/questions/11820566/inconsistent-
# signaturedoesnotmatch-amazon-s3-with-django-pipeline-s3boto-and-st)
class PatchedCachedFilesMixin(CachedFilesMixin):
def url(self, *a, **kw):
s = super(PatchedCachedFilesMixin, self).url(*a, **kw)
if isinstance(s, unicode):
s = s.encode('utf-8', 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
class S3PipelineStorage(PipelineMixin, PatchedCachedFilesMixin, S3BotoStorage):
pass
|
7c09368b3322144c9cb2b0e18f0b4264acb88eb7
|
blaze/__init__.py
|
blaze/__init__.py
|
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
|
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
def test(verbosity=1, xunitfile=None, exit=False):
"""
Runs the full Blaze test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to discover which tests to
run, and runs tests in any 'tests' subdirectory
within the Blaze module.
Parameters
----------
Value 0 prints very little, 1 prints a little bit,
and 2 prints the test names while testing.
xunitfile : string, optional
If provided, writes the test results to an xunit
style xml file. This is useful for running the tests
in a CI server such as Jenkins.
exit : bool, optional
If True, the function will call sys.exit with an
error code after the tests are finished.
"""
import nose
import os
argv = ['nosetests', '--verbosity=%d' % verbosity]
# Output an xunit file if requested
if xunitfile:
argv.extend(['--with-xunit', '--xunit-file=%s' % xunitfile])
# Add all 'tests' subdirectories to the options
rootdir = os.path.dirname(__file__)
for root, dirs, files in os.walk(rootdir):
if 'tests' in dirs:
testsdir = os.path.join(root, 'tests')
argv.append(testsdir)
print('Test dir: %s' % testsdir[len(rootdir)+1:])
# Ask nose to do its thing
return nose.main(argv=argv,
exit=exit)
|
Add a nose-based blaze.test() function as a placeholder
|
Add a nose-based blaze.test() function as a placeholder
Hopefully we find something better, but this at least gives
us behavior similar to NumPy as a start.
|
Python
|
bsd-3-clause
|
AbhiAgarwal/blaze,dwillmer/blaze,mrocklin/blaze,jdmcbr/blaze,mwiebe/blaze,mwiebe/blaze,ChinaQuants/blaze,xlhtc007/blaze,markflorisson/blaze-core,ContinuumIO/blaze,dwillmer/blaze,cpcloud/blaze,FrancescAlted/blaze,cowlicks/blaze,maxalbert/blaze,caseyclements/blaze,aterrel/blaze,cowlicks/blaze,ChinaQuants/blaze,FrancescAlted/blaze,FrancescAlted/blaze,ContinuumIO/blaze,jcrist/blaze,AbhiAgarwal/blaze,alexmojaki/blaze,jcrist/blaze,maxalbert/blaze,scls19fr/blaze,jdmcbr/blaze,markflorisson/blaze-core,AbhiAgarwal/blaze,markflorisson/blaze-core,nkhuyu/blaze,aterrel/blaze,cpcloud/blaze,nkhuyu/blaze,mrocklin/blaze,LiaoPan/blaze,AbhiAgarwal/blaze,LiaoPan/blaze,mwiebe/blaze,FrancescAlted/blaze,markflorisson/blaze-core,scls19fr/blaze,alexmojaki/blaze,caseyclements/blaze,xlhtc007/blaze,mwiebe/blaze,aterrel/blaze
|
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
Add a nose-based blaze.test() function as a placeholder
Hopefully we find something better, but this at least gives
us behavior similar to NumPy as a start.
|
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
def test(verbosity=1, xunitfile=None, exit=False):
"""
Runs the full Blaze test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to discover which tests to
run, and runs tests in any 'tests' subdirectory
within the Blaze module.
Parameters
----------
Value 0 prints very little, 1 prints a little bit,
and 2 prints the test names while testing.
xunitfile : string, optional
If provided, writes the test results to an xunit
style xml file. This is useful for running the tests
in a CI server such as Jenkins.
exit : bool, optional
If True, the function will call sys.exit with an
error code after the tests are finished.
"""
import nose
import os
argv = ['nosetests', '--verbosity=%d' % verbosity]
# Output an xunit file if requested
if xunitfile:
argv.extend(['--with-xunit', '--xunit-file=%s' % xunitfile])
# Add all 'tests' subdirectories to the options
rootdir = os.path.dirname(__file__)
for root, dirs, files in os.walk(rootdir):
if 'tests' in dirs:
testsdir = os.path.join(root, 'tests')
argv.append(testsdir)
print('Test dir: %s' % testsdir[len(rootdir)+1:])
# Ask nose to do its thing
return nose.main(argv=argv,
exit=exit)
|
<commit_before>
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
<commit_msg>Add a nose-based blaze.test() function as a placeholder
Hopefully we find something better, but this at least gives
us behavior similar to NumPy as a start.<commit_after>
|
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
def test(verbosity=1, xunitfile=None, exit=False):
"""
Runs the full Blaze test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to discover which tests to
run, and runs tests in any 'tests' subdirectory
within the Blaze module.
Parameters
----------
Value 0 prints very little, 1 prints a little bit,
and 2 prints the test names while testing.
xunitfile : string, optional
If provided, writes the test results to an xunit
style xml file. This is useful for running the tests
in a CI server such as Jenkins.
exit : bool, optional
If True, the function will call sys.exit with an
error code after the tests are finished.
"""
import nose
import os
argv = ['nosetests', '--verbosity=%d' % verbosity]
# Output an xunit file if requested
if xunitfile:
argv.extend(['--with-xunit', '--xunit-file=%s' % xunitfile])
# Add all 'tests' subdirectories to the options
rootdir = os.path.dirname(__file__)
for root, dirs, files in os.walk(rootdir):
if 'tests' in dirs:
testsdir = os.path.join(root, 'tests')
argv.append(testsdir)
print('Test dir: %s' % testsdir[len(rootdir)+1:])
# Ask nose to do its thing
return nose.main(argv=argv,
exit=exit)
|
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
Add a nose-based blaze.test() function as a placeholder
Hopefully we find something better, but this at least gives
us behavior similar to NumPy as a start.
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
def test(verbosity=1, xunitfile=None, exit=False):
"""
Runs the full Blaze test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to discover which tests to
run, and runs tests in any 'tests' subdirectory
within the Blaze module.
Parameters
----------
Value 0 prints very little, 1 prints a little bit,
and 2 prints the test names while testing.
xunitfile : string, optional
If provided, writes the test results to an xunit
style xml file. This is useful for running the tests
in a CI server such as Jenkins.
exit : bool, optional
If True, the function will call sys.exit with an
error code after the tests are finished.
"""
import nose
import os
argv = ['nosetests', '--verbosity=%d' % verbosity]
# Output an xunit file if requested
if xunitfile:
argv.extend(['--with-xunit', '--xunit-file=%s' % xunitfile])
# Add all 'tests' subdirectories to the options
rootdir = os.path.dirname(__file__)
for root, dirs, files in os.walk(rootdir):
if 'tests' in dirs:
testsdir = os.path.join(root, 'tests')
argv.append(testsdir)
print('Test dir: %s' % testsdir[len(rootdir)+1:])
# Ask nose to do its thing
return nose.main(argv=argv,
exit=exit)
|
<commit_before>
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
<commit_msg>Add a nose-based blaze.test() function as a placeholder
Hopefully we find something better, but this at least gives
us behavior similar to NumPy as a start.<commit_after>
# build the blaze namespace with selected functions
from constructors import array, open
from datashape import dshape
def test(verbosity=1, xunitfile=None, exit=False):
"""
Runs the full Blaze test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to discover which tests to
run, and runs tests in any 'tests' subdirectory
within the Blaze module.
Parameters
----------
Value 0 prints very little, 1 prints a little bit,
and 2 prints the test names while testing.
xunitfile : string, optional
If provided, writes the test results to an xunit
style xml file. This is useful for running the tests
in a CI server such as Jenkins.
exit : bool, optional
If True, the function will call sys.exit with an
error code after the tests are finished.
"""
import nose
import os
argv = ['nosetests', '--verbosity=%d' % verbosity]
# Output an xunit file if requested
if xunitfile:
argv.extend(['--with-xunit', '--xunit-file=%s' % xunitfile])
# Add all 'tests' subdirectories to the options
rootdir = os.path.dirname(__file__)
for root, dirs, files in os.walk(rootdir):
if 'tests' in dirs:
testsdir = os.path.join(root, 'tests')
argv.append(testsdir)
print('Test dir: %s' % testsdir[len(rootdir)+1:])
# Ask nose to do its thing
return nose.main(argv=argv,
exit=exit)
|
018172a47450eb5500d330803a2e5a7429891016
|
migrations/versions/177_add_run_state_eas_folderstatus.py
|
migrations/versions/177_add_run_state_eas_folderstatus.py
|
"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
op.drop_column('easfoldersyncstatus', 'sync_should_run')
|
"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.drop_column('easfoldersyncstatus', 'sync_should_run')
|
Update migration 177 to check for table existence first
|
Update migration 177 to check for table existence first
|
Python
|
agpl-3.0
|
ErinCall/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,closeio/nylas,gale320/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,jobscore/sync-engine,jobscore/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,wakermahmud/sync-engine,closeio/nylas,wakermahmud/sync-engine,jobscore/sync-engine,closeio/nylas,ErinCall/sync-engine,gale320/sync-engine,wakermahmud/sync-engine,closeio/nylas,nylas/sync-engine,ErinCall/sync-engine,Eagles2F/sync-engine,Eagles2F/sync-engine,jobscore/sync-engine,nylas/sync-engine,gale320/sync-engine,gale320/sync-engine,Eagles2F/sync-engine,ErinCall/sync-engine,gale320/sync-engine
|
"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
op.drop_column('easfoldersyncstatus', 'sync_should_run')
Update migration 177 to check for table existence first
|
"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.drop_column('easfoldersyncstatus', 'sync_should_run')
|
<commit_before>"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
op.drop_column('easfoldersyncstatus', 'sync_should_run')
<commit_msg>Update migration 177 to check for table existence first<commit_after>
|
"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.drop_column('easfoldersyncstatus', 'sync_should_run')
|
"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
op.drop_column('easfoldersyncstatus', 'sync_should_run')
Update migration 177 to check for table existence first"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.drop_column('easfoldersyncstatus', 'sync_should_run')
|
<commit_before>"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
op.drop_column('easfoldersyncstatus', 'sync_should_run')
<commit_msg>Update migration 177 to check for table existence first<commit_after>"""add run state to eas folders
Revision ID: 2b9dd6f7593a
Revises: 48a1991e5dbd
Create Date: 2015-05-28 00:47:47.636511
"""
# revision identifiers, used by Alembic.
revision = '2b9dd6f7593a'
down_revision = '48a1991e5dbd'
from alembic import op
import sqlalchemy as sa
def upgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.add_column('easfoldersyncstatus', sa.Column('sync_should_run',
sa.Boolean(), server_default=sa.sql.expression.true(),
nullable=False))
def downgrade():
from inbox.ignition import main_engine
engine = main_engine(pool_size=1, max_overflow=0)
if not engine.has_table('easfoldersyncstatus'):
return
op.drop_column('easfoldersyncstatus', 'sync_should_run')
|
4597935c29ec9cd2679254dbb8ee648ab5b2d75e
|
busshaming/api.py
|
busshaming/api.py
|
from rest_framework import mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
|
from rest_framework import filters, mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('short_name', 'long_name', 'description')
|
Add search feature to the Route API.
|
Add search feature to the Route API.
|
Python
|
mit
|
katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming,katharosada/bus-shaming
|
from rest_framework import mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
Add search feature to the Route API.
|
from rest_framework import filters, mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('short_name', 'long_name', 'description')
|
<commit_before>from rest_framework import mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
<commit_msg>Add search feature to the Route API.<commit_after>
|
from rest_framework import filters, mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('short_name', 'long_name', 'description')
|
from rest_framework import mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
Add search feature to the Route API.from rest_framework import filters, mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('short_name', 'long_name', 'description')
|
<commit_before>from rest_framework import mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
<commit_msg>Add search feature to the Route API.<commit_after>from rest_framework import filters, mixins, serializers, viewsets
from .models import Route, Trip
class TripSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Trip
fields = ('id', 'gtfs_trip_id', 'version', 'route', 'trip_headsign', 'trip_short_name', 'direction', 'wheelchair_accessible', 'bikes_allowed', 'notes', 'created_at')
class TripViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Trip.objects.all()
serializer_class = TripSerializer
class RouteSerializer(serializers.HyperlinkedModelSerializer):
trip_set = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='trip-detail'
)
class Meta:
model = Route
fields = ('id', 'url', 'gtfs_route_id', 'short_name', 'long_name', 'description', 'color', 'text_color', 'route_url', 'trip_set')
class RouteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('short_name', 'long_name', 'description')
|
7d59df357c34f910914baa0bb030e1ec3793f980
|
capnp/__init__.py
|
capnp/__init__.py
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
import capnp as _capnp
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
Add _capnp for original Cython module. Meant for testing.
|
Add _capnp for original Cython module. Meant for testing.
|
Python
|
bsd-2-clause
|
SymbiFlow/pycapnp,rcrowder/pycapnp,rcrowder/pycapnp,rcrowder/pycapnp,SymbiFlow/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,SymbiFlow/pycapnp,rcrowder/pycapnp,tempbottle/pycapnp,jparyani/pycapnp,tempbottle/pycapnp,jparyani/pycapnp,SymbiFlow/pycapnp
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
Add _capnp for original Cython module. Meant for testing.
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
import capnp as _capnp
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
<commit_before>"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
<commit_msg>Add _capnp for original Cython module. Meant for testing.<commit_after>
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
import capnp as _capnp
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
Add _capnp for original Cython module. Meant for testing."""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
import capnp as _capnp
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
<commit_before>"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
<commit_msg>Add _capnp for original Cython module. Meant for testing.<commit_after>"""A python library wrapping the Cap'n Proto C++ library
Example Usage::
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
capnp.writePackedMessageToFd(f.fileno(), message)
f.close()
# Reading
f = open('example.bin')
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
"""
from .version import version as __version__
import capnp as _capnp
from .capnp import *
from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan
del capnp
|
085697bbf2bc4507cdacca04a24eda318940133d
|
amivapi/settings.py
|
amivapi/settings.py
|
"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
|
"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
|
Revert "Change DATE_FORMAT to be equivalent to datetime.isoformat()"
|
Revert "Change DATE_FORMAT to be equivalent to datetime.isoformat()"
This reverts commit 2085cf0c103df44c500bae9bccdc2ce16cd8710f.
See discussion of the original commit https://github.com/amiv-eth/amivapi/commit/2085cf0c103df44c500bae9bccdc2ce16cd8710f
|
Python
|
agpl-3.0
|
amiv-eth/amivapi,amiv-eth/amivapi,amiv-eth/amivapi
|
"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
Revert "Change DATE_FORMAT to be equivalent to datetime.isoformat()"
This reverts commit 2085cf0c103df44c500bae9bccdc2ce16cd8710f.
See discussion of the original commit https://github.com/amiv-eth/amivapi/commit/2085cf0c103df44c500bae9bccdc2ce16cd8710f
|
"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
|
<commit_before>"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
<commit_msg>Revert "Change DATE_FORMAT to be equivalent to datetime.isoformat()"
This reverts commit 2085cf0c103df44c500bae9bccdc2ce16cd8710f.
See discussion of the original commit https://github.com/amiv-eth/amivapi/commit/2085cf0c103df44c500bae9bccdc2ce16cd8710f<commit_after>
|
"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
|
"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
Revert "Change DATE_FORMAT to be equivalent to datetime.isoformat()"
This reverts commit 2085cf0c103df44c500bae9bccdc2ce16cd8710f.
See discussion of the original commit https://github.com/amiv-eth/amivapi/commit/2085cf0c103df44c500bae9bccdc2ce16cd8710f"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
|
<commit_before>"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
<commit_msg>Revert "Change DATE_FORMAT to be equivalent to datetime.isoformat()"
This reverts commit 2085cf0c103df44c500bae9bccdc2ce16cd8710f.
See discussion of the original commit https://github.com/amiv-eth/amivapi/commit/2085cf0c103df44c500bae9bccdc2ce16cd8710f<commit_after>"""Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Flask
DEBUG = False
TESTING = False
# Flask-SQLALchemy
# Eve
ID_FIELD = "id"
AUTH_FIELD = "_author"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
BANDWIDTH_SAVER = False
RESOURCE_METHODS = ['GET', 'POST']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
PUBLIC_METHODS = ['GET'] # This is the only way to make / public
XML = False
# Eve, file storage options
RETURN_MEDIA_AS_BASE64_STRING = False
EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url']
STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump'
STORAGE_URL = r'/storage'
|
18ffd356559525909a87f2f06398b9cad861acf9
|
addic7ed_cli/request.py
|
addic7ed_cli/request.py
|
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close'
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
|
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
from addic7ed_cli.error import Error
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if self.status_code >= 300:
raise Error("HTTP request to '{}' has failed with status {}"
.format(self.url, self.status_code))
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close',
# Without any user agent, addic7ed.com sometimes returns a 304 status code
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36',
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
|
Fix occasional error when querying addic7ed
|
Fix occasional error when querying addic7ed
|
Python
|
mit
|
BenoitZugmeyer/addic7ed-cli,BenoitZugmeyer/addic7ed-cli
|
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close'
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
Fix occasional error when querying addic7ed
|
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
from addic7ed_cli.error import Error
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if self.status_code >= 300:
raise Error("HTTP request to '{}' has failed with status {}"
.format(self.url, self.status_code))
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close',
# Without any user agent, addic7ed.com sometimes returns a 304 status code
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36',
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
|
<commit_before>
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close'
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
<commit_msg>Fix occasional error when querying addic7ed<commit_after>
|
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
from addic7ed_cli.error import Error
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if self.status_code >= 300:
raise Error("HTTP request to '{}' has failed with status {}"
.format(self.url, self.status_code))
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close',
# Without any user agent, addic7ed.com sometimes returns a 304 status code
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36',
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
|
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close'
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
Fix occasional error when querying addic7ed
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
from addic7ed_cli.error import Error
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if self.status_code >= 300:
raise Error("HTTP request to '{}' has failed with status {}"
.format(self.url, self.status_code))
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close',
# Without any user agent, addic7ed.com sometimes returns a 304 status code
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36',
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
|
<commit_before>
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close'
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
<commit_msg>Fix occasional error when querying addic7ed<commit_after>
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import requests
from pyquery import PyQuery
from addic7ed_cli.error import Error
__all__ = ['session']
class Response(object):
def __init__(self, response):
self._response = response
self._query = None
def __getattr__(self, name):
return getattr(self._response, name)
def __call__(self, query):
if self.status_code >= 300:
raise Error("HTTP request to '{}' has failed with status {}"
.format(self.url, self.status_code))
if not self._query:
self._query = PyQuery(self.content)
return self._query(query)
class Session(requests.Session):
last_url = 'http://www.addic7ed.com/'
def request(self, method, url, *args, **kwargs):
url = urljoin(self.last_url, url)
self.headers = {
'Referer': self.last_url,
# Don't use Keep-Alive requests as requests/urllib3 currently has a bug
# https://github.com/kennethreitz/requests/issues/2568
'Connection': 'close',
# Without any user agent, addic7ed.com sometimes returns a 304 status code
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36',
}
response = super(Session, self).request(method, url, *args, **kwargs)
self.last_url = response.url
return Response(response)
session = Session()
|
d61714022eb191294373519e41d6c1ec3252ed39
|
organizer/forms.py
|
organizer/forms.py
|
from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
def save(self):
new_tag = Tag.objects.create(
name=self.cleaned_data['name'],
slug=self.cleaned_data['slug'])
return new_tag
|
from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = '__all__'
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
|
Refactor TagForm to inherit ModelForm.
|
Ch07: Refactor TagForm to inherit ModelForm.
|
Python
|
bsd-2-clause
|
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
|
from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
def save(self):
new_tag = Tag.objects.create(
name=self.cleaned_data['name'],
slug=self.cleaned_data['slug'])
return new_tag
Ch07: Refactor TagForm to inherit ModelForm.
|
from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = '__all__'
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
|
<commit_before>from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
def save(self):
new_tag = Tag.objects.create(
name=self.cleaned_data['name'],
slug=self.cleaned_data['slug'])
return new_tag
<commit_msg>Ch07: Refactor TagForm to inherit ModelForm.<commit_after>
|
from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = '__all__'
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
|
from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
def save(self):
new_tag = Tag.objects.create(
name=self.cleaned_data['name'],
slug=self.cleaned_data['slug'])
return new_tag
Ch07: Refactor TagForm to inherit ModelForm.from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = '__all__'
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
|
<commit_before>from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
def save(self):
new_tag = Tag.objects.create(
name=self.cleaned_data['name'],
slug=self.cleaned_data['slug'])
return new_tag
<commit_msg>Ch07: Refactor TagForm to inherit ModelForm.<commit_after>from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.ModelForm):
class Meta:
model = Tag
fields = '__all__'
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
|
1c05408187b0a93407be5500381c654ea5c3af11
|
pyluos/modules/l0_servo.py
|
pyluos/modules/l0_servo.py
|
from .module import Module, interact
from .gpio import Pwm
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.pwm_1 = Pwm('p1', self, max=180.0)
self.pwm_2 = Pwm('p2', self, max=180.0)
self.pwm_3 = Pwm('p3', self, max=180.0)
self.pwm_4 = Pwm('p4', self, max=180.0)
def control(self):
def change_pin(p1, p2, p3, p4):
self.p1._push(p1)
self.p2._push(p2)
self.p3._push(p3)
self.p4._push(p4)
return interact(change_pin,
p1=lambda: self.pwm_1.duty_cycle,
p2=lambda: self.pwm_2.duty_cycle,
p3=lambda: self.pwm_3.duty_cycle,
p4=lambda: self.pwm_4.duty_cycle)
|
from .module import Module, interact
from .gpio import Pwm
class PositionServo(object):
def __init__(self, alias, delegate, default= 0.0, min=0.0, max=180.0):
self._pos = None
self._pwm = Pwm(alias, delegate, default, min, max)
@property
def target_position(self):
return self._pos
@target_position.setter
def target_position(self, pos):
if pos != self._pos:
self._pwm.duty_cycle = pos
self._pos = pos
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.m1 = PositionServo('p1', self)
self.m2 = PositionServo('p2', self)
self.m3 = PositionServo('p3', self)
self.m4 = PositionServo('p4', self)
def control(self):
def change_pos(p1, p2, p3, p4):
self.m1.target_position = p1
self.m2.target_position = p2
self.m3.target_position = p3
self.m4.target_position = p4
return interact(change_pos,
p1=lambda: self.m1.target_position,
p2=lambda: self.m2.target_position,
p3=lambda: self.m3.target_position,
p4=lambda: self.m4.target_position)
|
Improve l0 servo api with target_position accessor.
|
Improve l0 servo api with target_position accessor.
|
Python
|
mit
|
pollen/pyrobus
|
from .module import Module, interact
from .gpio import Pwm
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.pwm_1 = Pwm('p1', self, max=180.0)
self.pwm_2 = Pwm('p2', self, max=180.0)
self.pwm_3 = Pwm('p3', self, max=180.0)
self.pwm_4 = Pwm('p4', self, max=180.0)
def control(self):
def change_pin(p1, p2, p3, p4):
self.p1._push(p1)
self.p2._push(p2)
self.p3._push(p3)
self.p4._push(p4)
return interact(change_pin,
p1=lambda: self.pwm_1.duty_cycle,
p2=lambda: self.pwm_2.duty_cycle,
p3=lambda: self.pwm_3.duty_cycle,
p4=lambda: self.pwm_4.duty_cycle)
Improve l0 servo api with target_position accessor.
|
from .module import Module, interact
from .gpio import Pwm
class PositionServo(object):
def __init__(self, alias, delegate, default= 0.0, min=0.0, max=180.0):
self._pos = None
self._pwm = Pwm(alias, delegate, default, min, max)
@property
def target_position(self):
return self._pos
@target_position.setter
def target_position(self, pos):
if pos != self._pos:
self._pwm.duty_cycle = pos
self._pos = pos
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.m1 = PositionServo('p1', self)
self.m2 = PositionServo('p2', self)
self.m3 = PositionServo('p3', self)
self.m4 = PositionServo('p4', self)
def control(self):
def change_pos(p1, p2, p3, p4):
self.m1.target_position = p1
self.m2.target_position = p2
self.m3.target_position = p3
self.m4.target_position = p4
return interact(change_pos,
p1=lambda: self.m1.target_position,
p2=lambda: self.m2.target_position,
p3=lambda: self.m3.target_position,
p4=lambda: self.m4.target_position)
|
<commit_before>from .module import Module, interact
from .gpio import Pwm
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.pwm_1 = Pwm('p1', self, max=180.0)
self.pwm_2 = Pwm('p2', self, max=180.0)
self.pwm_3 = Pwm('p3', self, max=180.0)
self.pwm_4 = Pwm('p4', self, max=180.0)
def control(self):
def change_pin(p1, p2, p3, p4):
self.p1._push(p1)
self.p2._push(p2)
self.p3._push(p3)
self.p4._push(p4)
return interact(change_pin,
p1=lambda: self.pwm_1.duty_cycle,
p2=lambda: self.pwm_2.duty_cycle,
p3=lambda: self.pwm_3.duty_cycle,
p4=lambda: self.pwm_4.duty_cycle)
<commit_msg>Improve l0 servo api with target_position accessor.<commit_after>
|
from .module import Module, interact
from .gpio import Pwm
class PositionServo(object):
def __init__(self, alias, delegate, default= 0.0, min=0.0, max=180.0):
self._pos = None
self._pwm = Pwm(alias, delegate, default, min, max)
@property
def target_position(self):
return self._pos
@target_position.setter
def target_position(self, pos):
if pos != self._pos:
self._pwm.duty_cycle = pos
self._pos = pos
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.m1 = PositionServo('p1', self)
self.m2 = PositionServo('p2', self)
self.m3 = PositionServo('p3', self)
self.m4 = PositionServo('p4', self)
def control(self):
def change_pos(p1, p2, p3, p4):
self.m1.target_position = p1
self.m2.target_position = p2
self.m3.target_position = p3
self.m4.target_position = p4
return interact(change_pos,
p1=lambda: self.m1.target_position,
p2=lambda: self.m2.target_position,
p3=lambda: self.m3.target_position,
p4=lambda: self.m4.target_position)
|
from .module import Module, interact
from .gpio import Pwm
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.pwm_1 = Pwm('p1', self, max=180.0)
self.pwm_2 = Pwm('p2', self, max=180.0)
self.pwm_3 = Pwm('p3', self, max=180.0)
self.pwm_4 = Pwm('p4', self, max=180.0)
def control(self):
def change_pin(p1, p2, p3, p4):
self.p1._push(p1)
self.p2._push(p2)
self.p3._push(p3)
self.p4._push(p4)
return interact(change_pin,
p1=lambda: self.pwm_1.duty_cycle,
p2=lambda: self.pwm_2.duty_cycle,
p3=lambda: self.pwm_3.duty_cycle,
p4=lambda: self.pwm_4.duty_cycle)
Improve l0 servo api with target_position accessor.from .module import Module, interact
from .gpio import Pwm
class PositionServo(object):
def __init__(self, alias, delegate, default= 0.0, min=0.0, max=180.0):
self._pos = None
self._pwm = Pwm(alias, delegate, default, min, max)
@property
def target_position(self):
return self._pos
@target_position.setter
def target_position(self, pos):
if pos != self._pos:
self._pwm.duty_cycle = pos
self._pos = pos
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.m1 = PositionServo('p1', self)
self.m2 = PositionServo('p2', self)
self.m3 = PositionServo('p3', self)
self.m4 = PositionServo('p4', self)
def control(self):
def change_pos(p1, p2, p3, p4):
self.m1.target_position = p1
self.m2.target_position = p2
self.m3.target_position = p3
self.m4.target_position = p4
return interact(change_pos,
p1=lambda: self.m1.target_position,
p2=lambda: self.m2.target_position,
p3=lambda: self.m3.target_position,
p4=lambda: self.m4.target_position)
|
<commit_before>from .module import Module, interact
from .gpio import Pwm
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.pwm_1 = Pwm('p1', self, max=180.0)
self.pwm_2 = Pwm('p2', self, max=180.0)
self.pwm_3 = Pwm('p3', self, max=180.0)
self.pwm_4 = Pwm('p4', self, max=180.0)
def control(self):
def change_pin(p1, p2, p3, p4):
self.p1._push(p1)
self.p2._push(p2)
self.p3._push(p3)
self.p4._push(p4)
return interact(change_pin,
p1=lambda: self.pwm_1.duty_cycle,
p2=lambda: self.pwm_2.duty_cycle,
p3=lambda: self.pwm_3.duty_cycle,
p4=lambda: self.pwm_4.duty_cycle)
<commit_msg>Improve l0 servo api with target_position accessor.<commit_after>from .module import Module, interact
from .gpio import Pwm
class PositionServo(object):
def __init__(self, alias, delegate, default= 0.0, min=0.0, max=180.0):
self._pos = None
self._pwm = Pwm(alias, delegate, default, min, max)
@property
def target_position(self):
return self._pos
@target_position.setter
def target_position(self, pos):
if pos != self._pos:
self._pwm.duty_cycle = pos
self._pos = pos
class L0Servo(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0Servo', id, alias, robot)
self.m1 = PositionServo('p1', self)
self.m2 = PositionServo('p2', self)
self.m3 = PositionServo('p3', self)
self.m4 = PositionServo('p4', self)
def control(self):
def change_pos(p1, p2, p3, p4):
self.m1.target_position = p1
self.m2.target_position = p2
self.m3.target_position = p3
self.m4.target_position = p4
return interact(change_pos,
p1=lambda: self.m1.target_position,
p2=lambda: self.m2.target_position,
p3=lambda: self.m3.target_position,
p4=lambda: self.m4.target_position)
|
a1bb113dc30de7afe20146311a99b3454de0056e
|
STC_Path_Testing/commission.py
|
STC_Path_Testing/commission.py
|
class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales
|
class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales
|
Fix PEP8: W292 no newline at end of file
|
Fix PEP8: W292 no newline at end of file
|
Python
|
mit
|
aweimeow/STC-Path-Testing
|
class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * salesFix PEP8: W292 no newline at end of file
|
class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales
|
<commit_before>class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales<commit_msg>Fix PEP8: W292 no newline at end of file<commit_after>
|
class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales
|
class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * salesFix PEP8: W292 no newline at end of fileclass Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales
|
<commit_before>class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales<commit_msg>Fix PEP8: W292 no newline at end of file<commit_after>class Commission(object):
def __init__(self, locks, stocks, barrels):
self.locks = locks
self.stocks = stocks
self.barrels = barrels
@property
def bonus(self):
if self.locks == -1:
return "Terminate"
if self.locks < 1 or self.locks > 70:
return "Invalid"
elif self.stocks < 1 or self.stocks > 80:
return "Invalid"
elif self.barrels < 1 or self.barrels > 90:
return "Invalid"
sales = self.locks * 45 + self.stocks * 30 + self.barrels * 25
if sales >= 1800:
return 220 + 0.2 * (sales - 1800)
elif sales >= 1000:
return 100 + 0.15 * (sales - 1000)
else:
return 0.1 * sales
|
ae21001fea38e9b8e4af34654c48b415e419f319
|
core/utils.py
|
core/utils.py
|
from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
print split
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
|
from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
|
Remove debugging print statement, opps
|
Remove debugging print statement, opps
|
Python
|
bsd-2-clause
|
muhleder/timestrap,muhleder/timestrap,overshard/timestrap,cdubz/timestrap,Leahelisabeth/timestrap,Leahelisabeth/timestrap,Leahelisabeth/timestrap,cdubz/timestrap,Leahelisabeth/timestrap,overshard/timestrap,muhleder/timestrap,cdubz/timestrap,overshard/timestrap
|
from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
print split
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
Remove debugging print statement, opps
|
from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
|
<commit_before>from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
print split
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
<commit_msg>Remove debugging print statement, opps<commit_after>
|
from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
|
from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
print split
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
Remove debugging print statement, oppsfrom django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
|
<commit_before>from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
print split
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
<commit_msg>Remove debugging print statement, opps<commit_after>from django.utils.duration import _get_duration_components
from datetime import timedelta
def duration_string_from_delta(delta):
seconds = delta.total_seconds()
split = str(seconds/3600).split('.')
hours = int(split[0])
minutes = int(float('.'+split[1])*60)
string = '{}:{:02d}'.format(hours, minutes)
return string
def parse_duration(duration):
hours = None
minutes = None
if duration.isdigit():
hours = int(duration)
elif ':' in duration:
duration_split = duration.split(':')
hours = int(duration_split[0])
minutes = int(duration_split[1])
elif '.' in duration:
duration_split = duration.split('.')
hours = int(duration_split[0])
minutes = int(60 * float('.' + duration_split[1]))
if hours is None:
hours = 0
if minutes is None:
minutes = 0
if hours or minutes:
return timedelta(hours=hours, minutes=minutes)
else:
raise ValueError('Could not parse duration.')
def duration_string(duration):
days, hours, minutes, seconds, microseconds = _get_duration_components(duration) # noqa: E501
hours += days * 24
string = '{}:{:02d}'.format(hours, minutes)
return string
|
34bf8d82580b83b1e0409db8636877a22203996b
|
cryptex/trade.py
|
cryptex/trade.py
|
class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == 0:
ts = 'Buy'
else:
ts ='Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
|
class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == Trade.BUY:
ts = 'Buy'
else:
ts = 'Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
|
Remove magic number check in Trade str method
|
Remove magic number check in Trade str method
|
Python
|
mit
|
coink/cryptex
|
class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == 0:
ts = 'Buy'
else:
ts ='Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
Remove magic number check in Trade str method
|
class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == Trade.BUY:
ts = 'Buy'
else:
ts = 'Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
|
<commit_before>class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == 0:
ts = 'Buy'
else:
ts ='Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
<commit_msg>Remove magic number check in Trade str method<commit_after>
|
class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == Trade.BUY:
ts = 'Buy'
else:
ts = 'Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
|
class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == 0:
ts = 'Buy'
else:
ts ='Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
Remove magic number check in Trade str methodclass Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == Trade.BUY:
ts = 'Buy'
else:
ts = 'Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
|
<commit_before>class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == 0:
ts = 'Buy'
else:
ts ='Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
<commit_msg>Remove magic number check in Trade str method<commit_after>class Trade(object):
BUY = 0
SELL = 1
def __init__(self, trade_id, trade_type, base_currency, counter_currency,
time, order_id, amount, price, fee=None):
self.trade_id = trade_id
self.trade_type = trade_type
self.base_currency = base_currency
self.counter_currency = counter_currency
self.time = time
self.order_id = order_id
self.amount = amount
self.price = price
self.fee = fee
def __str__(self):
if self.trade_type == Trade.BUY:
ts = 'Buy'
else:
ts = 'Sell'
return '<%s of %.8f %s>' % (ts, self.amount, self.base_currency)
|
c1de3bddb7e440064f15fd2a340cfea41f9e7be4
|
heltour/tournament/management/commands/cleanupcomments.py
|
heltour/tournament/management/commands/cleanupcomments.py
|
import random
import string
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
for badword in ['mark', 'cheat', 'alt', 'tos violation']:
Comment.objects.filter(
content_type_id__in=ct_pks,
comment__icontains=badword,
).delete()
|
import random
import string
from datetime import datetime
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
jan_01_2021 = timezone.make_aware(datetime(2021, 1, 1))
Comment.objects.filter(
content_type_id__in=ct_pks,
submit_date__lte=jan_01_2021
).exclude(
user_name="System"
).delete()
|
Remove all moderator made comments before 2021/01/01
|
Remove all moderator made comments before 2021/01/01
|
Python
|
mit
|
cyanfish/heltour,cyanfish/heltour,cyanfish/heltour,cyanfish/heltour
|
import random
import string
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
for badword in ['mark', 'cheat', 'alt', 'tos violation']:
Comment.objects.filter(
content_type_id__in=ct_pks,
comment__icontains=badword,
).delete()
Remove all moderator made comments before 2021/01/01
|
import random
import string
from datetime import datetime
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
jan_01_2021 = timezone.make_aware(datetime(2021, 1, 1))
Comment.objects.filter(
content_type_id__in=ct_pks,
submit_date__lte=jan_01_2021
).exclude(
user_name="System"
).delete()
|
<commit_before>import random
import string
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
for badword in ['mark', 'cheat', 'alt', 'tos violation']:
Comment.objects.filter(
content_type_id__in=ct_pks,
comment__icontains=badword,
).delete()
<commit_msg>Remove all moderator made comments before 2021/01/01<commit_after>
|
import random
import string
from datetime import datetime
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
jan_01_2021 = timezone.make_aware(datetime(2021, 1, 1))
Comment.objects.filter(
content_type_id__in=ct_pks,
submit_date__lte=jan_01_2021
).exclude(
user_name="System"
).delete()
|
import random
import string
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
for badword in ['mark', 'cheat', 'alt', 'tos violation']:
Comment.objects.filter(
content_type_id__in=ct_pks,
comment__icontains=badword,
).delete()
Remove all moderator made comments before 2021/01/01import random
import string
from datetime import datetime
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
jan_01_2021 = timezone.make_aware(datetime(2021, 1, 1))
Comment.objects.filter(
content_type_id__in=ct_pks,
submit_date__lte=jan_01_2021
).exclude(
user_name="System"
).delete()
|
<commit_before>import random
import string
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
for badword in ['mark', 'cheat', 'alt', 'tos violation']:
Comment.objects.filter(
content_type_id__in=ct_pks,
comment__icontains=badword,
).delete()
<commit_msg>Remove all moderator made comments before 2021/01/01<commit_after>import random
import string
from datetime import datetime
from django.core.management import BaseCommand
from django.utils import timezone
from heltour.tournament.models import *
from django_comments.models import Comment
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
help = "Removes ALL emails from the database."
def handle(self, *args, **options):
letters = ''.join([random.choice(string.ascii_letters) for x in range(4)])
value = input(f"Are you sure you want to clean up all comments? Type: {letters} to confirm: ")
if letters != value:
print("You got it wrong, exiting")
return
print("Cleaning up all comments")
models = [
"player",
"registration",
"seasonplayer",
"playerpairing",
"loneplayerpairing",
"alternate",
"alternateassignment",
"playeravailability",
"playerlateregistration",
"playerbye",
"playerwithdrawal",
"playerwarning",
]
ct_pks = [
ct.pk for ct in ContentType.objects.filter(model__in=models)
]
assert(len(ct_pks) == len(models))
jan_01_2021 = timezone.make_aware(datetime(2021, 1, 1))
Comment.objects.filter(
content_type_id__in=ct_pks,
submit_date__lte=jan_01_2021
).exclude(
user_name="System"
).delete()
|
eaa907d5d8e4bb4e8514c719b3c11a4a30442694
|
vpr/muxes/logic/mux2/tests/test_mux2.py
|
vpr/muxes/logic/mux2/tests/test_mux2.py
|
# Simple tests for an adder module
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
#from adder_model import adder_model
#import random
@cocotb.test()
def mux2_test(dut):
"""Test for MUX2 options"""
opts = [(x,y,z, x&~z | y&z) for x in [0,1] for y in [0,1] for z in [0,1]]
yield Timer(2)
for I0, I1, S0, _ in opts:
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
|
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
from cocotb.regression import TestFactory
@cocotb.coroutine
def mux2_basic_test(dut, inputs=(1,0,0)):
"""Test for MUX2 options"""
yield Timer(2)
I0, I1, S0 = inputs
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
factory = TestFactory(mux2_basic_test)
input_permutations = [(x, y, z) for x in [0,1] for y in [0,1] for z in [0,1]]
factory.add_option("inputs", input_permutations)
factory.generate_tests()
|
Use factory to iterate over permutations
|
Use factory to iterate over permutations
Signed-off-by: Jeffrey Elms <23ce84ca7a7de9dc17ad8e8b0bbd717d4f9f9884@freshred.net>
|
Python
|
isc
|
SymbiFlow/symbiflow-arch-defs,SymbiFlow/symbiflow-arch-defs
|
# Simple tests for an adder module
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
#from adder_model import adder_model
#import random
@cocotb.test()
def mux2_test(dut):
"""Test for MUX2 options"""
opts = [(x,y,z, x&~z | y&z) for x in [0,1] for y in [0,1] for z in [0,1]]
yield Timer(2)
for I0, I1, S0, _ in opts:
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
Use factory to iterate over permutations
Signed-off-by: Jeffrey Elms <23ce84ca7a7de9dc17ad8e8b0bbd717d4f9f9884@freshred.net>
|
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
from cocotb.regression import TestFactory
@cocotb.coroutine
def mux2_basic_test(dut, inputs=(1,0,0)):
"""Test for MUX2 options"""
yield Timer(2)
I0, I1, S0 = inputs
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
factory = TestFactory(mux2_basic_test)
input_permutations = [(x, y, z) for x in [0,1] for y in [0,1] for z in [0,1]]
factory.add_option("inputs", input_permutations)
factory.generate_tests()
|
<commit_before># Simple tests for an adder module
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
#from adder_model import adder_model
#import random
@cocotb.test()
def mux2_test(dut):
"""Test for MUX2 options"""
opts = [(x,y,z, x&~z | y&z) for x in [0,1] for y in [0,1] for z in [0,1]]
yield Timer(2)
for I0, I1, S0, _ in opts:
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
<commit_msg>Use factory to iterate over permutations
Signed-off-by: Jeffrey Elms <23ce84ca7a7de9dc17ad8e8b0bbd717d4f9f9884@freshred.net><commit_after>
|
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
from cocotb.regression import TestFactory
@cocotb.coroutine
def mux2_basic_test(dut, inputs=(1,0,0)):
"""Test for MUX2 options"""
yield Timer(2)
I0, I1, S0 = inputs
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
factory = TestFactory(mux2_basic_test)
input_permutations = [(x, y, z) for x in [0,1] for y in [0,1] for z in [0,1]]
factory.add_option("inputs", input_permutations)
factory.generate_tests()
|
# Simple tests for an adder module
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
#from adder_model import adder_model
#import random
@cocotb.test()
def mux2_test(dut):
"""Test for MUX2 options"""
opts = [(x,y,z, x&~z | y&z) for x in [0,1] for y in [0,1] for z in [0,1]]
yield Timer(2)
for I0, I1, S0, _ in opts:
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
Use factory to iterate over permutations
Signed-off-by: Jeffrey Elms <23ce84ca7a7de9dc17ad8e8b0bbd717d4f9f9884@freshred.net>import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
from cocotb.regression import TestFactory
@cocotb.coroutine
def mux2_basic_test(dut, inputs=(1,0,0)):
"""Test for MUX2 options"""
yield Timer(2)
I0, I1, S0 = inputs
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
factory = TestFactory(mux2_basic_test)
input_permutations = [(x, y, z) for x in [0,1] for y in [0,1] for z in [0,1]]
factory.add_option("inputs", input_permutations)
factory.generate_tests()
|
<commit_before># Simple tests for an adder module
import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
#from adder_model import adder_model
#import random
@cocotb.test()
def mux2_test(dut):
"""Test for MUX2 options"""
opts = [(x,y,z, x&~z | y&z) for x in [0,1] for y in [0,1] for z in [0,1]]
yield Timer(2)
for I0, I1, S0, _ in opts:
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
<commit_msg>Use factory to iterate over permutations
Signed-off-by: Jeffrey Elms <23ce84ca7a7de9dc17ad8e8b0bbd717d4f9f9884@freshred.net><commit_after>import cocotb
from cocotb.triggers import Timer
from cocotb.result import TestFailure
from cocotb.regression import TestFactory
@cocotb.coroutine
def mux2_basic_test(dut, inputs=(1,0,0)):
"""Test for MUX2 options"""
yield Timer(2)
I0, I1, S0 = inputs
dut.I0 = I0
dut.I1 = I1
dut.S0 = S0
if S0:
expected = I1
else:
expected = I0
yield Timer(2)
if dut.O != expected:
raise TestFailure(
'Result is incorrect for I0(%d) I1(%d) S0(%d): %s(O) != %s (expected)' % (I0, I1, S0, dut.O, expected))
else:
dut._log.info('I0(%d) I1(%d) S0(%d) output(%d) Ok!'%(I0, I1, S0, dut.O))
factory = TestFactory(mux2_basic_test)
input_permutations = [(x, y, z) for x in [0,1] for y in [0,1] for z in [0,1]]
factory.add_option("inputs", input_permutations)
factory.generate_tests()
|
ea2bf30629dd7986d0e20041c8633897b2b1a324
|
main.py
|
main.py
|
import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
print data.get_state_by_name('Mizoram')
print data.get_state_by_abbreviation('KA')
#for state in data.get_all_states():
# print state.to_dict()
|
import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
def demonstrate_queries():
mizoram = data.get_state_by_name('Mizoram')
karnataka = data.get_state_by_abbreviation('KA')
print mizoram
print karnataka
mizoram_districts = data.get_districts_by_state_name('Mizoram')
same_mizoram_districts = data.get_districts_by_state_name(mizoram.name)
also_same_mizoram_districts = data.get_districts_by_state(mizoram)
print mizoram_districts
print mizoram_districts == also_same_mizoram_districts
#for state in data.get_all_states():
# print state.to_dict()
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
demonstrate_queries()
|
Put many demos in demonstrate_queries()
|
Put many demos in demonstrate_queries()
|
Python
|
bsd-3-clause
|
rkawauchi/IHK,rkawauchi/IHK
|
import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
print data.get_state_by_name('Mizoram')
print data.get_state_by_abbreviation('KA')
#for state in data.get_all_states():
# print state.to_dict()
Put many demos in demonstrate_queries()
|
import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
def demonstrate_queries():
mizoram = data.get_state_by_name('Mizoram')
karnataka = data.get_state_by_abbreviation('KA')
print mizoram
print karnataka
mizoram_districts = data.get_districts_by_state_name('Mizoram')
same_mizoram_districts = data.get_districts_by_state_name(mizoram.name)
also_same_mizoram_districts = data.get_districts_by_state(mizoram)
print mizoram_districts
print mizoram_districts == also_same_mizoram_districts
#for state in data.get_all_states():
# print state.to_dict()
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
demonstrate_queries()
|
<commit_before>import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
print data.get_state_by_name('Mizoram')
print data.get_state_by_abbreviation('KA')
#for state in data.get_all_states():
# print state.to_dict()
<commit_msg>Put many demos in demonstrate_queries()<commit_after>
|
import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
def demonstrate_queries():
mizoram = data.get_state_by_name('Mizoram')
karnataka = data.get_state_by_abbreviation('KA')
print mizoram
print karnataka
mizoram_districts = data.get_districts_by_state_name('Mizoram')
same_mizoram_districts = data.get_districts_by_state_name(mizoram.name)
also_same_mizoram_districts = data.get_districts_by_state(mizoram)
print mizoram_districts
print mizoram_districts == also_same_mizoram_districts
#for state in data.get_all_states():
# print state.to_dict()
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
demonstrate_queries()
|
import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
print data.get_state_by_name('Mizoram')
print data.get_state_by_abbreviation('KA')
#for state in data.get_all_states():
# print state.to_dict()
Put many demos in demonstrate_queries()import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
def demonstrate_queries():
mizoram = data.get_state_by_name('Mizoram')
karnataka = data.get_state_by_abbreviation('KA')
print mizoram
print karnataka
mizoram_districts = data.get_districts_by_state_name('Mizoram')
same_mizoram_districts = data.get_districts_by_state_name(mizoram.name)
also_same_mizoram_districts = data.get_districts_by_state(mizoram)
print mizoram_districts
print mizoram_districts == also_same_mizoram_districts
#for state in data.get_all_states():
# print state.to_dict()
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
demonstrate_queries()
|
<commit_before>import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
print data.get_state_by_name('Mizoram')
print data.get_state_by_abbreviation('KA')
#for state in data.get_all_states():
# print state.to_dict()
<commit_msg>Put many demos in demonstrate_queries()<commit_after>import argparse
import io
#Define commmand line arguments which can be passed to main.py
#Currently irrelevant, but could be useful later
def initialize_argument_parser():
parser = argparse.ArgumentParser(description='Simulate Indian health solutions')
parser.add_argument('-s', '--solution', dest='solution',
help='the solution to test', default='health kiosk')
return vars(parser.parse_args())
def demonstrate_queries():
mizoram = data.get_state_by_name('Mizoram')
karnataka = data.get_state_by_abbreviation('KA')
print mizoram
print karnataka
mizoram_districts = data.get_districts_by_state_name('Mizoram')
same_mizoram_districts = data.get_districts_by_state_name(mizoram.name)
also_same_mizoram_districts = data.get_districts_by_state(mizoram)
print mizoram_districts
print mizoram_districts == also_same_mizoram_districts
#for state in data.get_all_states():
# print state.to_dict()
if __name__ == "__main__":
args = initialize_argument_parser()
data = io.Database()
demonstrate_queries()
|
d385d7405b0e08184fa055622c787469f39386cf
|
main.py
|
main.py
|
# -*- coding: utf-8 -*-
#
# The main application file
#
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500
|
# -*- coding: utf-8 -*-
#
# The main application file
#
# Add 3rd-party library folder in to system path
import sys
sys.path.insert(0, 'lib')
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500
|
Add 3rd-party library folder in to system path
|
Add 3rd-party library folder in to system path
|
Python
|
mit
|
opendatapress/open_data_press,opendatapress/open_data_press,opendatapress/open_data_press
|
# -*- coding: utf-8 -*-
#
# The main application file
#
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500Add 3rd-party library folder in to system path
|
# -*- coding: utf-8 -*-
#
# The main application file
#
# Add 3rd-party library folder in to system path
import sys
sys.path.insert(0, 'lib')
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500
|
<commit_before># -*- coding: utf-8 -*-
#
# The main application file
#
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500<commit_msg>Add 3rd-party library folder in to system path<commit_after>
|
# -*- coding: utf-8 -*-
#
# The main application file
#
# Add 3rd-party library folder in to system path
import sys
sys.path.insert(0, 'lib')
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500
|
# -*- coding: utf-8 -*-
#
# The main application file
#
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500Add 3rd-party library folder in to system path# -*- coding: utf-8 -*-
#
# The main application file
#
# Add 3rd-party library folder in to system path
import sys
sys.path.insert(0, 'lib')
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500
|
<commit_before># -*- coding: utf-8 -*-
#
# The main application file
#
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500<commit_msg>Add 3rd-party library folder in to system path<commit_after># -*- coding: utf-8 -*-
#
# The main application file
#
# Add 3rd-party library folder in to system path
import sys
sys.path.insert(0, 'lib')
from webapp2 import WSGIApplication
from helpers.config import load_config
# Explicitly import controller classes
from controllers import root
__author__ = "YOUR NAME"
__website__ = "http://example.com"
__email__ = "you@example.com"
__licence__ = "MIT"
__version__ = "0.1"
# Map route patterns to controller handlers
routes = [
('/', root.HomeRoute)
]
# Load config and set debug flag
debug, config = load_config()
# Create the application
app = WSGIApplication(routes=routes, debug=debug, config=config)
# Define error page handlers for production only
# We want to see full error traces during development
if not debug:
app.error_handlers[404] = root.error_404
app.error_handlers[500] = root.error_500
|
7c1623513151a3c1d81cd42f00efbb8a1b7d09fc
|
board/signals.py
|
board/signals.py
|
from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.signals import email_confirmation_sent, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
|
from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
@receiver(password_changed)
def password_changed_callback(sender, user, **kwargs):
email = EmailAddress.objects.get_primary(user)
if not email.verified:
email.verified = True
email.save()
|
Set user.email_address.verified as true when user changed his password
|
Set user.email_address.verified as true when user changed his password
|
Python
|
mit
|
devunt/hydrocarbon,devunt/hydrocarbon,devunt/hydrocarbon
|
from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.signals import email_confirmation_sent, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
Set user.email_address.verified as true when user changed his password
|
from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
@receiver(password_changed)
def password_changed_callback(sender, user, **kwargs):
email = EmailAddress.objects.get_primary(user)
if not email.verified:
email.verified = True
email.save()
|
<commit_before>from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.signals import email_confirmation_sent, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
<commit_msg>Set user.email_address.verified as true when user changed his password<commit_after>
|
from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
@receiver(password_changed)
def password_changed_callback(sender, user, **kwargs):
email = EmailAddress.objects.get_primary(user)
if not email.verified:
email.verified = True
email.save()
|
from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.signals import email_confirmation_sent, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
Set user.email_address.verified as true when user changed his passwordfrom django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
@receiver(password_changed)
def password_changed_callback(sender, user, **kwargs):
email = EmailAddress.objects.get_primary(user)
if not email.verified:
email.verified = True
email.save()
|
<commit_before>from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.signals import email_confirmation_sent, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
<commit_msg>Set user.email_address.verified as true when user changed his password<commit_after>from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sent)
def email_confirmation_sent_callback(sender, confirmation, **kwargs):
user = confirmation.email_address.user
# Logout user
[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
@receiver(user_signed_up)
def user_signed_up_callback(sender, user, form, **kwargs):
user.is_active = True
user.save()
data = treedict()
data['type'] = 'SITE_ANNOUNCEMENT'
data['message'] = _('New site announcement')
data['text'] = _('Welcome to herocomics! We strongly recommend you read the announcements.')
data['url'] = Board.objects.get(slug='notice').get_absolute_url()
Notification.create(None, user, data)
@receiver(password_changed)
def password_changed_callback(sender, user, **kwargs):
email = EmailAddress.objects.get_primary(user)
if not email.verified:
email.verified = True
email.save()
|
2f27a175ffa777d4fe2aad41396e9da3f2c70216
|
nbs/utils/validators.py
|
nbs/utils/validators.py
|
# -*- coding: utf-8-*-
def validate_cuit(cuit):
"from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart"
# validaciones minimas
if len(cuit) != 13 or cuit[2] != "-" or cuit [11] != "-":
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
cuit = cuit.replace("-", "")
# calculo digito verificador
aux = 0
for i in range(10):
aux += int(cuit[i]*base[i])
aux = 11 - (aux - (int(aux/11) * 11))
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
|
# -*- coding: utf-8-*-
import re
def validate_cuit(cuit):
"""
Validates CUIT (Argentina) - Clave Única de Identificación Triebutaria
from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart
"""
cuit = str(cuit).replace("-", "") # normalize
# validaciones minimas
if not re.match(r'\d{11}$', cuit):
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
# calculo digito verificador
aux = sum([int(cuit[i])*base[i] for i in range(10)])
aux = 11 - (aux % 11)
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
def validate_cbu(cbu):
"Validates CBU (Argentina) - Clave Bancaria Uniforme"
cbu = str(cbu).replace(" ", "") # normalize
# validaciones minimas
if not re.match(r'\d{22}$', cbu):
return False
# calculo digito verificador banco
base = [7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i])*base[i] for i in range(7)])
if (10 - (aux % 10)) != int(cbu[7]):
return False
# calculo digito verificador cuenta
base = [3, 9, 7, 1, 3, 9, 7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i+8])*base[i] for i in range(13)])
return (10 - (aux % 10)) == int(cbu[21])
|
Add cbu validator to utils module
|
Add cbu validator to utils module
|
Python
|
mit
|
coyotevz/nobix-app
|
# -*- coding: utf-8-*-
def validate_cuit(cuit):
"from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart"
# validaciones minimas
if len(cuit) != 13 or cuit[2] != "-" or cuit [11] != "-":
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
cuit = cuit.replace("-", "")
# calculo digito verificador
aux = 0
for i in range(10):
aux += int(cuit[i]*base[i])
aux = 11 - (aux - (int(aux/11) * 11))
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
Add cbu validator to utils module
|
# -*- coding: utf-8-*-
import re
def validate_cuit(cuit):
"""
Validates CUIT (Argentina) - Clave Única de Identificación Triebutaria
from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart
"""
cuit = str(cuit).replace("-", "") # normalize
# validaciones minimas
if not re.match(r'\d{11}$', cuit):
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
# calculo digito verificador
aux = sum([int(cuit[i])*base[i] for i in range(10)])
aux = 11 - (aux % 11)
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
def validate_cbu(cbu):
"Validates CBU (Argentina) - Clave Bancaria Uniforme"
cbu = str(cbu).replace(" ", "") # normalize
# validaciones minimas
if not re.match(r'\d{22}$', cbu):
return False
# calculo digito verificador banco
base = [7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i])*base[i] for i in range(7)])
if (10 - (aux % 10)) != int(cbu[7]):
return False
# calculo digito verificador cuenta
base = [3, 9, 7, 1, 3, 9, 7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i+8])*base[i] for i in range(13)])
return (10 - (aux % 10)) == int(cbu[21])
|
<commit_before># -*- coding: utf-8-*-
def validate_cuit(cuit):
"from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart"
# validaciones minimas
if len(cuit) != 13 or cuit[2] != "-" or cuit [11] != "-":
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
cuit = cuit.replace("-", "")
# calculo digito verificador
aux = 0
for i in range(10):
aux += int(cuit[i]*base[i])
aux = 11 - (aux - (int(aux/11) * 11))
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
<commit_msg>Add cbu validator to utils module<commit_after>
|
# -*- coding: utf-8-*-
import re
def validate_cuit(cuit):
"""
Validates CUIT (Argentina) - Clave Única de Identificación Triebutaria
from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart
"""
cuit = str(cuit).replace("-", "") # normalize
# validaciones minimas
if not re.match(r'\d{11}$', cuit):
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
# calculo digito verificador
aux = sum([int(cuit[i])*base[i] for i in range(10)])
aux = 11 - (aux % 11)
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
def validate_cbu(cbu):
"Validates CBU (Argentina) - Clave Bancaria Uniforme"
cbu = str(cbu).replace(" ", "") # normalize
# validaciones minimas
if not re.match(r'\d{22}$', cbu):
return False
# calculo digito verificador banco
base = [7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i])*base[i] for i in range(7)])
if (10 - (aux % 10)) != int(cbu[7]):
return False
# calculo digito verificador cuenta
base = [3, 9, 7, 1, 3, 9, 7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i+8])*base[i] for i in range(13)])
return (10 - (aux % 10)) == int(cbu[21])
|
# -*- coding: utf-8-*-
def validate_cuit(cuit):
"from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart"
# validaciones minimas
if len(cuit) != 13 or cuit[2] != "-" or cuit [11] != "-":
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
cuit = cuit.replace("-", "")
# calculo digito verificador
aux = 0
for i in range(10):
aux += int(cuit[i]*base[i])
aux = 11 - (aux - (int(aux/11) * 11))
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
Add cbu validator to utils module# -*- coding: utf-8-*-
import re
def validate_cuit(cuit):
"""
Validates CUIT (Argentina) - Clave Única de Identificación Triebutaria
from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart
"""
cuit = str(cuit).replace("-", "") # normalize
# validaciones minimas
if not re.match(r'\d{11}$', cuit):
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
# calculo digito verificador
aux = sum([int(cuit[i])*base[i] for i in range(10)])
aux = 11 - (aux % 11)
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
def validate_cbu(cbu):
"Validates CBU (Argentina) - Clave Bancaria Uniforme"
cbu = str(cbu).replace(" ", "") # normalize
# validaciones minimas
if not re.match(r'\d{22}$', cbu):
return False
# calculo digito verificador banco
base = [7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i])*base[i] for i in range(7)])
if (10 - (aux % 10)) != int(cbu[7]):
return False
# calculo digito verificador cuenta
base = [3, 9, 7, 1, 3, 9, 7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i+8])*base[i] for i in range(13)])
return (10 - (aux % 10)) == int(cbu[21])
|
<commit_before># -*- coding: utf-8-*-
def validate_cuit(cuit):
"from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart"
# validaciones minimas
if len(cuit) != 13 or cuit[2] != "-" or cuit [11] != "-":
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
cuit = cuit.replace("-", "")
# calculo digito verificador
aux = 0
for i in range(10):
aux += int(cuit[i]*base[i])
aux = 11 - (aux - (int(aux/11) * 11))
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
<commit_msg>Add cbu validator to utils module<commit_after># -*- coding: utf-8-*-
import re
def validate_cuit(cuit):
"""
Validates CUIT (Argentina) - Clave Única de Identificación Triebutaria
from: http://python.org.ar/pyar/Recetario/ValidarCuit by Mariano Reingart
"""
cuit = str(cuit).replace("-", "") # normalize
# validaciones minimas
if not re.match(r'\d{11}$', cuit):
return False
base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
# calculo digito verificador
aux = sum([int(cuit[i])*base[i] for i in range(10)])
aux = 11 - (aux % 11)
if aux == 11:
aux = 0
if aux == 10:
aux = 9
return aux == int(cuit[10])
def validate_cbu(cbu):
"Validates CBU (Argentina) - Clave Bancaria Uniforme"
cbu = str(cbu).replace(" ", "") # normalize
# validaciones minimas
if not re.match(r'\d{22}$', cbu):
return False
# calculo digito verificador banco
base = [7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i])*base[i] for i in range(7)])
if (10 - (aux % 10)) != int(cbu[7]):
return False
# calculo digito verificador cuenta
base = [3, 9, 7, 1, 3, 9, 7, 1, 3, 9, 7, 1, 3]
aux = sum([int(cbu[i+8])*base[i] for i in range(13)])
return (10 - (aux % 10)) == int(cbu[21])
|
228b53836e9569fa901de341d7486f85152e67f9
|
txircd/modules/rfc/cmode_t.py
|
txircd/modules/rfc/cmode_t.py
|
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()
|
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if "topic" not in data:
return None
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()
|
Fix non-chanops not being able to query the topic
|
Fix non-chanops not being able to query the topic
|
Python
|
bsd-3-clause
|
Heufneutje/txircd,ElementalAlchemist/txircd
|
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()Fix non-chanops not being able to query the topic
|
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if "topic" not in data:
return None
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()
|
<commit_before>from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()<commit_msg>Fix non-chanops not being able to query the topic<commit_after>
|
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if "topic" not in data:
return None
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()
|
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()Fix non-chanops not being able to query the topicfrom twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if "topic" not in data:
return None
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()
|
<commit_before>from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()<commit_msg>Fix non-chanops not being able to query the topic<commit_after>from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class TopicLockMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "TopicLockMode"
core = True
affectedActions = { "commandpermission-TOPIC": 10 }
def channelModes(self):
return [ ("t", ModeType.NoParam, self) ]
def actions(self):
return [ ("modeactioncheck-channel-t-commandpermission-TOPIC", 10, self.channelHasMode) ]
def channelHasMode(self, channel, user, data):
if "t" in channel.modes:
return ""
return None
def apply(self, actionType, channel, param, user, data):
if "topic" not in data:
return None
if not self.ircd.runActionUntilValue("checkchannellevel", "topic", channel, user):
user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, channel.name, "You do not have access to change the topic on this channel")
return False
return None
topicLockMode = TopicLockMode()
|
46b5b03385d26589a97b6ab156fffd3b1b10fa5b
|
secretstorage/exceptions.py
|
secretstorage/exceptions.py
|
# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(Exception):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
|
# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(SecretStorageException):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
|
Make SecretServiceNotAvailableException a subclass of SecretStorageException
|
Make SecretServiceNotAvailableException a subclass of SecretStorageException
|
Python
|
bsd-3-clause
|
mitya57/secretstorage
|
# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(Exception):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
Make SecretServiceNotAvailableException a subclass of SecretStorageException
|
# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(SecretStorageException):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
|
<commit_before># SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(Exception):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
<commit_msg>Make SecretServiceNotAvailableException a subclass of SecretStorageException<commit_after>
|
# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(SecretStorageException):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
|
# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(Exception):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
Make SecretServiceNotAvailableException a subclass of SecretStorageException# SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(SecretStorageException):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
|
<commit_before># SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(Exception):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
<commit_msg>Make SecretServiceNotAvailableException a subclass of SecretStorageException<commit_after># SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2012
# License: BSD
"""All secretstorage functions may raise various exceptions when
something goes wrong. All exceptions derive from base
:exc:`SecretStorageException` class."""
class SecretStorageException(Exception):
"""All exceptions derive from this class."""
class SecretServiceNotAvailableException(SecretStorageException):
"""Raised by :class:`~secretstorage.item.Item` or
:class:`~secretstorage.collection.Collection` constructors, or by
other functions in the :mod:`secretstorage.collection` module, when
the Secret Service API is not available."""
class LockedException(SecretStorageException):
"""Raised when an action cannot be performed because the collection
is locked. Use :meth:`~secretstorage.collection.Collection.is_locked`
to check if the collection is locked, and
:meth:`~secretstorage.collection.Collection.unlock` to unlock it.
"""
class ItemNotFoundException(SecretStorageException):
"""Raised when an item does not exist or has been deleted. Example of
handling:
>>> try:
... item = secretstorage.Item(item_path)
... except secretstorage.ItemNotFoundException:
... print('Item not found!')
...
'Item not found!'
Also, :func:`~secretstorage.collection.create_collection` may raise
this exception when a prompt was dismissed during creating the
collection.
"""
|
a21fbdff2e04fd6e3cfbac7e75ccb03c81506a1f
|
server.py
|
server.py
|
import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'route': [
{
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
Add waypoint list and landmark names
|
Add waypoint list and landmark names
|
Python
|
mit
|
wtg/RPI_Tours_Server
|
import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'route': [
{
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
Add waypoint list and landmark names
|
import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'route': [
{
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Add waypoint list and landmark names<commit_after>
|
import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'route': [
{
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
Add waypoint list and landmark namesimport flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'route': [
{
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Add waypoint list and landmark names<commit_after>import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
69b4a3aae4ea0ff8ab07a955c2e113cb1a275525
|
setup3.py
|
setup3.py
|
import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
|
import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages, find_package_data)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
setup_args['package_data'] = find_package_data()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
|
Add notebook resources to Python 3 build process.
|
Add notebook resources to Python 3 build process.
|
Python
|
bsd-3-clause
|
ipython/ipython,ipython/ipython
|
import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
Add notebook resources to Python 3 build process.
|
import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages, find_package_data)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
setup_args['package_data'] = find_package_data()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
|
<commit_before>import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
<commit_msg>Add notebook resources to Python 3 build process.<commit_after>
|
import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages, find_package_data)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
setup_args['package_data'] = find_package_data()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
|
import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
Add notebook resources to Python 3 build process.import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages, find_package_data)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
setup_args['package_data'] = find_package_data()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
|
<commit_before>import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
<commit_msg>Add notebook resources to Python 3 build process.<commit_after>import os.path
from setuptools import setup
from setupbase import (setup_args, find_scripts, find_packages, find_package_data)
setup_args['entry_points'] = find_scripts(True, suffix='3')
setup_args['packages'] = find_packages()
setup_args['package_data'] = find_package_data()
def main():
setup(use_2to3 = True, **setup_args)
if __name__ == "__main__":
main()
|
72af62bdf9339c880b0cc0f1e1002cf1961e962b
|
rule.py
|
rule.py
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
def matches(self, exchange):
matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange)
return matches_bool
|
Add matches method to AndRule class.
|
Add matches method to AndRule class.
|
Python
|
mit
|
bsmukasa/stock_alerter
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
Add matches method to AndRule class.
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
def matches(self, exchange):
matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange)
return matches_bool
|
<commit_before>class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
<commit_msg>Add matches method to AndRule class.<commit_after>
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
def matches(self, exchange):
matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange)
return matches_bool
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
Add matches method to AndRule class.class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
def matches(self, exchange):
matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange)
return matches_bool
|
<commit_before>class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
<commit_msg>Add matches method to AndRule class.<commit_after>class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
def matches(self, exchange):
try:
stock = exchange[self.symbol]
except KeyError:
return False
return self.condition(stock) if stock.price else False
def depends_on(self):
return {self.symbol}
class AndRule:
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
def matches(self, exchange):
matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange)
return matches_bool
|
7198133cf9d24f3d29d300366951b7eac8b2547f
|
alburnum/maas/viscera/users.py
|
alburnum/maas/viscera/users.py
|
"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, email, password, *, is_superuser=False):
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_admin = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
|
"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, password, *, email=None, is_superuser=False):
if email is None:
email = "%s@null.maas.io" % username
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_superuser = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
|
Change to is_superuser and make email optional.
|
Change to is_superuser and make email optional.
|
Python
|
agpl-3.0
|
blakerouse/python-libmaas,alburnum/alburnum-maas-client
|
"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, email, password, *, is_superuser=False):
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_admin = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
Change to is_superuser and make email optional.
|
"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, password, *, email=None, is_superuser=False):
if email is None:
email = "%s@null.maas.io" % username
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_superuser = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
|
<commit_before>"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, email, password, *, is_superuser=False):
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_admin = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
<commit_msg>Change to is_superuser and make email optional.<commit_after>
|
"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, password, *, email=None, is_superuser=False):
if email is None:
email = "%s@null.maas.io" % username
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_superuser = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
|
"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, email, password, *, is_superuser=False):
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_admin = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
Change to is_superuser and make email optional."""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, password, *, email=None, is_superuser=False):
if email is None:
email = "%s@null.maas.io" % username
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_superuser = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
|
<commit_before>"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, email, password, *, is_superuser=False):
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_admin = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
<commit_msg>Change to is_superuser and make email optional.<commit_after>"""Objects for users."""
__all__ = [
"User",
"Users",
]
from . import (
check,
Object,
ObjectField,
ObjectSet,
ObjectType,
)
class UsersType(ObjectType):
"""Metaclass for `Users`."""
def __iter__(cls):
return map(cls._object, cls._handler.read())
def create(cls, username, password, *, email=None, is_superuser=False):
if email is None:
email = "%s@null.maas.io" % username
data = cls._handler.create(
username=username, email=email, password=password,
is_superuser='1' if is_superuser else '0')
return cls._object(data)
class Users(ObjectSet, metaclass=UsersType):
"""The set of users."""
@classmethod
def read(cls):
return cls(cls)
class User(Object):
"""A user."""
username = ObjectField.Checked(
"username", check(str), check(str))
email = ObjectField.Checked(
"email", check(str), check(str))
is_superuser = ObjectField.Checked(
"is_superuser", check(bool), check(bool))
|
ef03459429ba878f7c8f0e1d75f716d829250628
|
flaggen.py
|
flaggen.py
|
import random
def random_color():
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', random_color())
else:
raise ValueError('invalid mode')
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
|
import random
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', self.random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', self.random_color())
else:
raise ValueError('invalid mode')
def random_color(self):
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
|
Refactor Random Color as Flag Method
|
Refactor Random Color as Flag Method
|
Python
|
mit
|
Eylrid/flaggen
|
import random
def random_color():
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', random_color())
else:
raise ValueError('invalid mode')
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
Refactor Random Color as Flag Method
|
import random
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', self.random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', self.random_color())
else:
raise ValueError('invalid mode')
def random_color(self):
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
|
<commit_before>import random
def random_color():
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', random_color())
else:
raise ValueError('invalid mode')
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
<commit_msg>Refactor Random Color as Flag Method<commit_after>
|
import random
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', self.random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', self.random_color())
else:
raise ValueError('invalid mode')
def random_color(self):
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
|
import random
def random_color():
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', random_color())
else:
raise ValueError('invalid mode')
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
Refactor Random Color as Flag Methodimport random
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', self.random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', self.random_color())
else:
raise ValueError('invalid mode')
def random_color(self):
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
|
<commit_before>import random
def random_color():
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', random_color())
else:
raise ValueError('invalid mode')
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
<commit_msg>Refactor Random Color as Flag Method<commit_after>import random
class Flag:
def __init__(self, **kwargs):
self.mode = kwargs.get('mode', self.random_mode())
self.bg = kwargs.get('bg', self.random_color())
if self.mode == 'plain':
pass
elif self.mode == 'quarters':
self.quarterpanels = kwargs.get('quarterpanels', None)
if self.quarterpanels == None:
self.quarterpanels = [Flag() for i in range(4)]
elif self.mode == 'canton':
self.canton = kwargs.get('canton', None)
if not self.canton:
self.canton = Flag()
elif self.mode == 'cross':
self.cross = kwargs.get('cross', self.random_color())
else:
raise ValueError('invalid mode')
def random_color(self):
colors = ['white', 'black',
'#cc0033', #red
'#ffcc00', #yellow
'#009933', #green
'#003399', #blue
]
return random.choice(colors)
def random_mode(self):
modes = [(5, 'plain'),
(1, 'quarters'),
(1, 'canton'),
(5, 'cross')]
total = sum([i[0] for i in modes])
choice = random.randint(1, total)
for weight, mode in modes:
if choice <= weight:
return mode
else:
choice -= weight
|
6bb7ba60f217f8a6dd470d084a664cbf65274681
|
software/src/services/open_rocket_simulations.py
|
software/src/services/open_rocket_simulations.py
|
import os
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
from jnius import autoclass
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
|
import os
from jnius import autoclass
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
|
Move specificication of classpath below imports
|
Move specificication of classpath below imports
|
Python
|
mit
|
team-rocket-vuw/base-station,team-rocket-vuw/base-station,team-rocket-vuw/base-station,team-rocket-vuw/base-station
|
import os
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
from jnius import autoclass
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
Move specificication of classpath below imports
|
import os
from jnius import autoclass
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
|
<commit_before>import os
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
from jnius import autoclass
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
<commit_msg>Move specificication of classpath below imports<commit_after>
|
import os
from jnius import autoclass
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
|
import os
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
from jnius import autoclass
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
Move specificication of classpath below importsimport os
from jnius import autoclass
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
|
<commit_before>import os
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
from jnius import autoclass
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
<commit_msg>Move specificication of classpath below imports<commit_after>import os
from jnius import autoclass
JAR_FILE = "/openrocket.jar"
os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE
class OpenRocketSimulations:
ENTRY_CLASS = 'TeamRocket'
ROCKET_FILE = 'teamrocket.ork'
def __init__(self):
TeamRocket = autoclass(self.ENTRY_CLASS)
self.simulation_file = TeamRocket(self.ROCKET_FILE)
def run_simulations(self):
return self.simulation_file.runSimulations()
|
8a36070c76d1552e2d2e61c1e5c47202cc28b329
|
basket/news/backends/common.py
|
basket/news/backends/common.py
|
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
|
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
|
Refactor the timing decorator to be less confusing
|
Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.
|
Python
|
mpl-2.0
|
glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket
|
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.
|
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
|
<commit_before>from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
<commit_msg>Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.<commit_after>
|
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
|
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
|
<commit_before>from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
<commit_msg>Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.<commit_after>from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
|
da50aa9369efbf1d9ae246c40463ae9275857cba
|
opps/core/models/published.py
|
opps/core/models/published.py
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublisherMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
Change name manager Publisher to Published
|
Change name manager Publisher to Published
|
Python
|
mit
|
jeanmask/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublisherMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
Change name manager Publisher to Published
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
<commit_before>#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublisherMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
<commit_msg>Change name manager Publisher to Published<commit_after>
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublisherMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
Change name manager Publisher to Published#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
<commit_before>#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublisherMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
<commit_msg>Change name manager Publisher to Published<commit_after>#!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
775cd06b3e99cef9c777a907fc69c5c20380bb75
|
raspicam/camera.py
|
raspicam/camera.py
|
import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def frame_generator(self):
video = cv2.VideoCapture(1)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
|
import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def __init__(self, index=-1):
self.index = index
def frame_generator(self):
video = cv2.VideoCapture(self.index)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
|
Allow the USB index to be modified
|
Allow the USB index to be modified
|
Python
|
mit
|
exhuma/raspicam,exhuma/raspicam,exhuma/raspicam
|
import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def frame_generator(self):
video = cv2.VideoCapture(1)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
Allow the USB index to be modified
|
import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def __init__(self, index=-1):
self.index = index
def frame_generator(self):
video = cv2.VideoCapture(self.index)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
|
<commit_before>import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def frame_generator(self):
video = cv2.VideoCapture(1)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
<commit_msg>Allow the USB index to be modified<commit_after>
|
import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def __init__(self, index=-1):
self.index = index
def frame_generator(self):
video = cv2.VideoCapture(self.index)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
|
import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def frame_generator(self):
video = cv2.VideoCapture(1)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
Allow the USB index to be modifiedimport logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def __init__(self, index=-1):
self.index = index
def frame_generator(self):
video = cv2.VideoCapture(self.index)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
|
<commit_before>import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def frame_generator(self):
video = cv2.VideoCapture(1)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
<commit_msg>Allow the USB index to be modified<commit_after>import logging
# import picamera
# import picamera.array
from abc import ABCMeta, abstractmethod
import cv2
LOG = logging.getLogger(__name__)
class Camera(metaclass=ABCMeta):
@abstractmethod
def frame_generator(self):
raise NotImplementedError('Not yet implemented')
class USBCam(Camera):
def __init__(self, index=-1):
self.index = index
def frame_generator(self):
video = cv2.VideoCapture(self.index)
if not video.isOpened():
raise Exception('Unable to open camera')
while True:
success, image = video.read()
yield image
video.release()
class PiCamera(Camera):
def frame_generator(self):
with picamera.PiCamera() as camera:
with picamera.array.PiRGBArray(camera) as output:
camera.resolution = (640, 480)
camera.framerate = 32
while True:
camera.capture(output, 'rgb', use_video_port=True)
yield output.array
output.truncate(0)
|
c2562a8cb2e3d5d3f68604c32d4db7e62422e7a5
|
pathvalidate/_symbol.py
|
pathvalidate/_symbol.py
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, is_not_null_string, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
|
Remove an import that no longer used
|
Remove an import that no longer used
|
Python
|
mit
|
thombashi/pathvalidate
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, is_not_null_string, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
Remove an import that no longer used
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
|
<commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, is_not_null_string, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
<commit_msg>Remove an import that no longer used<commit_after>
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, is_not_null_string, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
Remove an import that no longer used# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
|
<commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, is_not_null_string, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
<commit_msg>Remove an import that no longer used<commit_after># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
from ._common import _preprocess, ascii_symbol_list, unprintable_ascii_char_list
from .error import InvalidCharError
__RE_SYMBOL = re.compile(
"[{}]".format(re.escape("".join(ascii_symbol_list + unprintable_ascii_char_list))), re.UNICODE
)
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(_preprocess(text))
if match_list:
raise InvalidCharError("invalid symbols found: {}".format(match_list))
def replace_symbol(text, replacement_text=""):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref:`example-sanitize-symbol`
"""
try:
return __RE_SYMBOL.sub(replacement_text, _preprocess(text))
except (TypeError, AttributeError):
raise TypeError("text must be a string")
|
0e8a5e56c53fed0834982a50b96be0a587a18fcb
|
pebble_tool/__init__.py
|
pebble_tool/__init__.py
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emulator
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
Change the order of the subcommands.
|
Change the order of the subcommands.
|
Python
|
mit
|
gregoiresage/pebble-tool,pebble/pebble-tool,pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
Change the order of the subcommands.
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emulator
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
<commit_before>from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
<commit_msg>Change the order of the subcommands.<commit_after>
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emulator
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
Change the order of the subcommands.from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emulator
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
<commit_before>from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
<commit_msg>Change the order of the subcommands.<commit_after>from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emulator
from .exceptions import ToolError
from .sdk import sdk_version
def run_tool(args=None):
logging.basicConfig()
parser = argparse.ArgumentParser(description="Pebble Tool", prog="pebble")
parser.add_argument("--version", action="version", version="Pebble SDK {}".format(sdk_version()))
register_children(parser)
args = parser.parse_args(args)
try:
args.func(args)
except ToolError as e:
print(str(e))
sys.exit(1)
|
e487761b9eecdc426565db06398d24dac540d4b4
|
sigal/plugins/copyright.py
|
sigal/plugins/copyright.py
|
# -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
TODO: Add more settings (font, size, ...)
"""
import logging
from PIL import ImageDraw
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
draw.text((5, img.size[1] - 15), settings['copyright'])
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
|
# -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
- ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.tff file.
If no font is specified, or specified font is not found, default font is used.
- ``copyright_text_font_size``: the copyright text font-size. If no font is specified, this setting is ignored.
- ``copyright_text_color``: the copyright text color in 3 tuple (R, G, B) Decimal RGB code.
e.g. (255, 255, 255) is White.
- ``copyright_text_position``: the copyright text position in 2 tuple (left, top).
By default text would be positioned at bottom-left corner.
"""
import logging
from PIL import ImageDraw
from PIL import ImageFont
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
text = settings['copyright']
font = settings.get('copyright_text_font', None)
font_size = settings.get('copyright_text_font_size', 10)
assert font_size >= 0
color = settings.get('copyright_text_color', (0, 0, 0))
bottom_margin = 3 # bottom margin for text
text_height = bottom_margin + 12 # default text height (of 15) for default font
if font:
try:
font = ImageFont.truetype(font, font_size)
text_height = font.getsize(text)[1] + bottom_margin
except: # load default font in case of any exception
logger.debug("Exception: Couldn't locate font %s, using default font", font)
font = ImageFont.load_default()
else:
font = ImageFont.load_default()
left, top = settings.get('copyright_text_position', (5, img.size[1] - text_height))
draw.text((left, top), text, fill=color, font=font)
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
|
Update to allow more settings for font, color, position
|
Update to allow more settings for font, color, position
- copyright_text_font: a system or user font name, or absolute path to
.ttf file
- copyright_text_font_size: font size used when
copyright_text_font is set
- copyright_text_color: text color
- copyright_text_position: a 2 tuple (x,y) specifying coordinates of top-left corner of
text
|
Python
|
mit
|
jasuarez/sigal,xouillet/sigal,jasuarez/sigal,jdn06/sigal,kontza/sigal,jdn06/sigal,xouillet/sigal,saimn/sigal,cbosdo/sigal,cbosdo/sigal,xouillet/sigal,elaOnMars/sigal,Ferada/sigal,t-animal/sigal,elaOnMars/sigal,Ferada/sigal,kontza/sigal,jdn06/sigal,cbosdo/sigal,kontza/sigal,Ferada/sigal,saimn/sigal,franek/sigal,t-animal/sigal,jasuarez/sigal,t-animal/sigal,franek/sigal,saimn/sigal
|
# -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
TODO: Add more settings (font, size, ...)
"""
import logging
from PIL import ImageDraw
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
draw.text((5, img.size[1] - 15), settings['copyright'])
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
Update to allow more settings for font, color, position
- copyright_text_font: a system or user font name, or absolute path to
.ttf file
- copyright_text_font_size: font size used when
copyright_text_font is set
- copyright_text_color: text color
- copyright_text_position: a 2 tuple (x,y) specifying coordinates of top-left corner of
text
|
# -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
- ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.tff file.
If no font is specified, or specified font is not found, default font is used.
- ``copyright_text_font_size``: the copyright text font-size. If no font is specified, this setting is ignored.
- ``copyright_text_color``: the copyright text color in 3 tuple (R, G, B) Decimal RGB code.
e.g. (255, 255, 255) is White.
- ``copyright_text_position``: the copyright text position in 2 tuple (left, top).
By default text would be positioned at bottom-left corner.
"""
import logging
from PIL import ImageDraw
from PIL import ImageFont
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
text = settings['copyright']
font = settings.get('copyright_text_font', None)
font_size = settings.get('copyright_text_font_size', 10)
assert font_size >= 0
color = settings.get('copyright_text_color', (0, 0, 0))
bottom_margin = 3 # bottom margin for text
text_height = bottom_margin + 12 # default text height (of 15) for default font
if font:
try:
font = ImageFont.truetype(font, font_size)
text_height = font.getsize(text)[1] + bottom_margin
except: # load default font in case of any exception
logger.debug("Exception: Couldn't locate font %s, using default font", font)
font = ImageFont.load_default()
else:
font = ImageFont.load_default()
left, top = settings.get('copyright_text_position', (5, img.size[1] - text_height))
draw.text((left, top), text, fill=color, font=font)
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
|
<commit_before># -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
TODO: Add more settings (font, size, ...)
"""
import logging
from PIL import ImageDraw
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
draw.text((5, img.size[1] - 15), settings['copyright'])
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
<commit_msg>Update to allow more settings for font, color, position
- copyright_text_font: a system or user font name, or absolute path to
.ttf file
- copyright_text_font_size: font size used when
copyright_text_font is set
- copyright_text_color: text color
- copyright_text_position: a 2 tuple (x,y) specifying coordinates of top-left corner of
text<commit_after>
|
# -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
- ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.tff file.
If no font is specified, or specified font is not found, default font is used.
- ``copyright_text_font_size``: the copyright text font-size. If no font is specified, this setting is ignored.
- ``copyright_text_color``: the copyright text color in 3 tuple (R, G, B) Decimal RGB code.
e.g. (255, 255, 255) is White.
- ``copyright_text_position``: the copyright text position in 2 tuple (left, top).
By default text would be positioned at bottom-left corner.
"""
import logging
from PIL import ImageDraw
from PIL import ImageFont
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
text = settings['copyright']
font = settings.get('copyright_text_font', None)
font_size = settings.get('copyright_text_font_size', 10)
assert font_size >= 0
color = settings.get('copyright_text_color', (0, 0, 0))
bottom_margin = 3 # bottom margin for text
text_height = bottom_margin + 12 # default text height (of 15) for default font
if font:
try:
font = ImageFont.truetype(font, font_size)
text_height = font.getsize(text)[1] + bottom_margin
except: # load default font in case of any exception
logger.debug("Exception: Couldn't locate font %s, using default font", font)
font = ImageFont.load_default()
else:
font = ImageFont.load_default()
left, top = settings.get('copyright_text_position', (5, img.size[1] - text_height))
draw.text((left, top), text, fill=color, font=font)
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
|
# -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
TODO: Add more settings (font, size, ...)
"""
import logging
from PIL import ImageDraw
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
draw.text((5, img.size[1] - 15), settings['copyright'])
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
Update to allow more settings for font, color, position
- copyright_text_font: a system or user font name, or absolute path to
.ttf file
- copyright_text_font_size: font size used when
copyright_text_font is set
- copyright_text_color: text color
- copyright_text_position: a 2 tuple (x,y) specifying coordinates of top-left corner of
text# -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
- ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.tff file.
If no font is specified, or specified font is not found, default font is used.
- ``copyright_text_font_size``: the copyright text font-size. If no font is specified, this setting is ignored.
- ``copyright_text_color``: the copyright text color in 3 tuple (R, G, B) Decimal RGB code.
e.g. (255, 255, 255) is White.
- ``copyright_text_position``: the copyright text position in 2 tuple (left, top).
By default text would be positioned at bottom-left corner.
"""
import logging
from PIL import ImageDraw
from PIL import ImageFont
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
text = settings['copyright']
font = settings.get('copyright_text_font', None)
font_size = settings.get('copyright_text_font_size', 10)
assert font_size >= 0
color = settings.get('copyright_text_color', (0, 0, 0))
bottom_margin = 3 # bottom margin for text
text_height = bottom_margin + 12 # default text height (of 15) for default font
if font:
try:
font = ImageFont.truetype(font, font_size)
text_height = font.getsize(text)[1] + bottom_margin
except: # load default font in case of any exception
logger.debug("Exception: Couldn't locate font %s, using default font", font)
font = ImageFont.load_default()
else:
font = ImageFont.load_default()
left, top = settings.get('copyright_text_position', (5, img.size[1] - text_height))
draw.text((left, top), text, fill=color, font=font)
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
|
<commit_before># -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
TODO: Add more settings (font, size, ...)
"""
import logging
from PIL import ImageDraw
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
draw.text((5, img.size[1] - 15), settings['copyright'])
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
<commit_msg>Update to allow more settings for font, color, position
- copyright_text_font: a system or user font name, or absolute path to
.ttf file
- copyright_text_font_size: font size used when
copyright_text_font is set
- copyright_text_color: text color
- copyright_text_position: a 2 tuple (x,y) specifying coordinates of top-left corner of
text<commit_after># -*- coding: utf-8 -*-
"""Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
- ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.tff file.
If no font is specified, or specified font is not found, default font is used.
- ``copyright_text_font_size``: the copyright text font-size. If no font is specified, this setting is ignored.
- ``copyright_text_color``: the copyright text color in 3 tuple (R, G, B) Decimal RGB code.
e.g. (255, 255, 255) is White.
- ``copyright_text_position``: the copyright text position in 2 tuple (left, top).
By default text would be positioned at bottom-left corner.
"""
import logging
from PIL import ImageDraw
from PIL import ImageFont
from sigal import signals
logger = logging.getLogger(__name__)
def add_copyright(img, settings=None):
logger.debug('Adding copyright to %r', img)
draw = ImageDraw.Draw(img)
text = settings['copyright']
font = settings.get('copyright_text_font', None)
font_size = settings.get('copyright_text_font_size', 10)
assert font_size >= 0
color = settings.get('copyright_text_color', (0, 0, 0))
bottom_margin = 3 # bottom margin for text
text_height = bottom_margin + 12 # default text height (of 15) for default font
if font:
try:
font = ImageFont.truetype(font, font_size)
text_height = font.getsize(text)[1] + bottom_margin
except: # load default font in case of any exception
logger.debug("Exception: Couldn't locate font %s, using default font", font)
font = ImageFont.load_default()
else:
font = ImageFont.load_default()
left, top = settings.get('copyright_text_position', (5, img.size[1] - text_height))
draw.text((left, top), text, fill=color, font=font)
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('Copyright text is not set')
|
7f3c086a953f91ec7f351c56a4f07f38dc0b9eb3
|
exampleCourse/elements/course_element/course_element.py
|
exampleCourse/elements/course_element/course_element.py
|
import random
import chevron
def get_dependencies(element_html, element_index, data):
return {
'styles': ['course_element.css'],
'scripts': ['course_element.js']
}
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
import random
import chevron
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
Remove unneeded get_dependencies from course element
|
Remove unneeded get_dependencies from course element
|
Python
|
agpl-3.0
|
parasgithub/PrairieLearn,rbessick5/PrairieLearn,tbretl/PrairieLearn,parasgithub/PrairieLearn,jakebailey/PrairieLearn,parasgithub/PrairieLearn,tbretl/PrairieLearn,rbessick5/PrairieLearn,jakebailey/PrairieLearn,jakebailey/PrairieLearn,rbessick5/PrairieLearn,mwest1066/PrairieLearn,mwest1066/PrairieLearn,parasgithub/PrairieLearn,mwest1066/PrairieLearn,jakebailey/PrairieLearn,parasgithub/PrairieLearn,tbretl/PrairieLearn,mwest1066/PrairieLearn,rbessick5/PrairieLearn,mwest1066/PrairieLearn,tbretl/PrairieLearn,rbessick5/PrairieLearn,tbretl/PrairieLearn
|
import random
import chevron
def get_dependencies(element_html, element_index, data):
return {
'styles': ['course_element.css'],
'scripts': ['course_element.js']
}
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
Remove unneeded get_dependencies from course element
|
import random
import chevron
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
<commit_before>import random
import chevron
def get_dependencies(element_html, element_index, data):
return {
'styles': ['course_element.css'],
'scripts': ['course_element.js']
}
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
<commit_msg>Remove unneeded get_dependencies from course element<commit_after>
|
import random
import chevron
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
import random
import chevron
def get_dependencies(element_html, element_index, data):
return {
'styles': ['course_element.css'],
'scripts': ['course_element.js']
}
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
Remove unneeded get_dependencies from course elementimport random
import chevron
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
<commit_before>import random
import chevron
def get_dependencies(element_html, element_index, data):
return {
'styles': ['course_element.css'],
'scripts': ['course_element.js']
}
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
<commit_msg>Remove unneeded get_dependencies from course element<commit_after>import random
import chevron
def render(element_html, element_index, data):
html_params = { 'number': random.random() }
with open('course_element.mustache','r') as f:
return chevron.render(f, html_params).strip()
|
cebfd01451a2d78217bffd171ab3bcccbabf895f
|
zerodb/collective/indexing/indexer.py
|
zerodb/collective/indexing/indexer.py
|
from zope.interface import implements
#from Products.Archetypes.CatalogMultiplex import CatalogMultiplex
#from Products.CMFCore.CMFCatalogAware import CMFCatalogAware
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
# container to hold references to the original and "monkeyed" indexing methods
# these are populated by `collective.indexing.monkey`
catalogMultiplexMethods = {}
catalogAwareMethods = {}
monkeyMethods = {}
def getOwnIndexMethod(obj, name):
""" return private indexing method if the given object has one """
attr = getattr(obj.__class__, name, None)
if attr is not None:
method = attr.im_func
monkey = monkeyMethods.get(name.rstrip('Object'), None)
if monkey is not None and method is not monkey:
return method
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
|
from zope.interface import implements
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
|
Remove unused code for monkeyed methods
|
Remove unused code for monkeyed methods
|
Python
|
agpl-3.0
|
zero-db/zerodb,zerodb/zerodb,zero-db/zerodb,zerodb/zerodb
|
from zope.interface import implements
#from Products.Archetypes.CatalogMultiplex import CatalogMultiplex
#from Products.CMFCore.CMFCatalogAware import CMFCatalogAware
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
# container to hold references to the original and "monkeyed" indexing methods
# these are populated by `collective.indexing.monkey`
catalogMultiplexMethods = {}
catalogAwareMethods = {}
monkeyMethods = {}
def getOwnIndexMethod(obj, name):
""" return private indexing method if the given object has one """
attr = getattr(obj.__class__, name, None)
if attr is not None:
method = attr.im_func
monkey = monkeyMethods.get(name.rstrip('Object'), None)
if monkey is not None and method is not monkey:
return method
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
Remove unused code for monkeyed methods
|
from zope.interface import implements
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
|
<commit_before>from zope.interface import implements
#from Products.Archetypes.CatalogMultiplex import CatalogMultiplex
#from Products.CMFCore.CMFCatalogAware import CMFCatalogAware
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
# container to hold references to the original and "monkeyed" indexing methods
# these are populated by `collective.indexing.monkey`
catalogMultiplexMethods = {}
catalogAwareMethods = {}
monkeyMethods = {}
def getOwnIndexMethod(obj, name):
""" return private indexing method if the given object has one """
attr = getattr(obj.__class__, name, None)
if attr is not None:
method = attr.im_func
monkey = monkeyMethods.get(name.rstrip('Object'), None)
if monkey is not None and method is not monkey:
return method
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
<commit_msg>Remove unused code for monkeyed methods<commit_after>
|
from zope.interface import implements
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
|
from zope.interface import implements
#from Products.Archetypes.CatalogMultiplex import CatalogMultiplex
#from Products.CMFCore.CMFCatalogAware import CMFCatalogAware
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
# container to hold references to the original and "monkeyed" indexing methods
# these are populated by `collective.indexing.monkey`
catalogMultiplexMethods = {}
catalogAwareMethods = {}
monkeyMethods = {}
def getOwnIndexMethod(obj, name):
""" return private indexing method if the given object has one """
attr = getattr(obj.__class__, name, None)
if attr is not None:
method = attr.im_func
monkey = monkeyMethods.get(name.rstrip('Object'), None)
if monkey is not None and method is not monkey:
return method
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
Remove unused code for monkeyed methodsfrom zope.interface import implements
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
|
<commit_before>from zope.interface import implements
#from Products.Archetypes.CatalogMultiplex import CatalogMultiplex
#from Products.CMFCore.CMFCatalogAware import CMFCatalogAware
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
# container to hold references to the original and "monkeyed" indexing methods
# these are populated by `collective.indexing.monkey`
catalogMultiplexMethods = {}
catalogAwareMethods = {}
monkeyMethods = {}
def getOwnIndexMethod(obj, name):
""" return private indexing method if the given object has one """
attr = getattr(obj.__class__, name, None)
if attr is not None:
method = attr.im_func
monkey = monkeyMethods.get(name.rstrip('Object'), None)
if monkey is not None and method is not monkey:
return method
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
<commit_msg>Remove unused code for monkeyed methods<commit_after>from zope.interface import implements
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
|
7f8e5913f493582608712244cbfff0bf8d658c51
|
chainerrl/misc/batch_states.py
|
chainerrl/misc/batch_states.py
|
import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
|
import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if chainer.cuda.available and xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
|
Fix error of chainer v3 on chainer.cuda.cupy
|
Fix error of chainer v3 on chainer.cuda.cupy
|
Python
|
mit
|
toslunar/chainerrl,toslunar/chainerrl
|
import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
Fix error of chainer v3 on chainer.cuda.cupy
|
import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if chainer.cuda.available and xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
|
<commit_before>import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
<commit_msg>Fix error of chainer v3 on chainer.cuda.cupy<commit_after>
|
import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if chainer.cuda.available and xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
|
import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
Fix error of chainer v3 on chainer.cuda.cupyimport chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if chainer.cuda.available and xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
|
<commit_before>import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
<commit_msg>Fix error of chainer v3 on chainer.cuda.cupy<commit_after>import chainer
def batch_states(states, xp, phi):
"""The default method for making batch of observations.
Args:
states (list): list of observations from an environment.
xp (module): numpy or cupy
phi (callable): Feature extractor applied to observations
Return:
the object which will be given as input to the model.
"""
if chainer.cuda.available and xp is chainer.cuda.cupy:
# GPU
device = chainer.cuda.Device().id
else:
# CPU
device = -1
features = [phi(s) for s in states]
return chainer.dataset.concat_examples(features, device=device)
|
46aaaf4f2323ec25e87f88ed80435288a31d5b13
|
armstrong/apps/series/admin.py
|
armstrong/apps/series/admin.py
|
from django.contrib import admin
from django.contrib.contenttypes import generic
from . import models
class SeriesNodeInline(generic.GenericTabularInline):
model = models.SeriesNode
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
inlines = [
SeriesNodeInline,
]
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
|
from django.contrib import admin
from . import models
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
|
Remove all of the SeriesNode inline stuff (doesn't work yet)
|
Remove all of the SeriesNode inline stuff (doesn't work yet)
|
Python
|
apache-2.0
|
armstrong/armstrong.apps.series,armstrong/armstrong.apps.series
|
from django.contrib import admin
from django.contrib.contenttypes import generic
from . import models
class SeriesNodeInline(generic.GenericTabularInline):
model = models.SeriesNode
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
inlines = [
SeriesNodeInline,
]
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
Remove all of the SeriesNode inline stuff (doesn't work yet)
|
from django.contrib import admin
from . import models
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
|
<commit_before>from django.contrib import admin
from django.contrib.contenttypes import generic
from . import models
class SeriesNodeInline(generic.GenericTabularInline):
model = models.SeriesNode
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
inlines = [
SeriesNodeInline,
]
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
<commit_msg>Remove all of the SeriesNode inline stuff (doesn't work yet)<commit_after>
|
from django.contrib import admin
from . import models
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
|
from django.contrib import admin
from django.contrib.contenttypes import generic
from . import models
class SeriesNodeInline(generic.GenericTabularInline):
model = models.SeriesNode
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
inlines = [
SeriesNodeInline,
]
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
Remove all of the SeriesNode inline stuff (doesn't work yet)from django.contrib import admin
from . import models
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
|
<commit_before>from django.contrib import admin
from django.contrib.contenttypes import generic
from . import models
class SeriesNodeInline(generic.GenericTabularInline):
model = models.SeriesNode
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
inlines = [
SeriesNodeInline,
]
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
<commit_msg>Remove all of the SeriesNode inline stuff (doesn't work yet)<commit_after>from django.contrib import admin
from . import models
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
|
509cbe502cf9a6fd6c0f86469656c01edd4eddf1
|
pygments/styles/igor.py
|
pygments/styles/igor.py
|
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Class: '#007575',
String: '#009C00'
}
|
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
"""
Pygments version of the official colors for Igor Pro procedures.
"""
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Decorator: '#CC00A3',
Name.Class: '#007575',
String: '#009C00'
}
|
Add class comment and a custom color for the decorator
|
Add class comment and a custom color for the decorator
|
Python
|
bsd-2-clause
|
aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments
|
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Class: '#007575',
String: '#009C00'
}
Add class comment and a custom color for the decorator
|
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
"""
Pygments version of the official colors for Igor Pro procedures.
"""
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Decorator: '#CC00A3',
Name.Class: '#007575',
String: '#009C00'
}
|
<commit_before>from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Class: '#007575',
String: '#009C00'
}
<commit_msg>Add class comment and a custom color for the decorator<commit_after>
|
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
"""
Pygments version of the official colors for Igor Pro procedures.
"""
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Decorator: '#CC00A3',
Name.Class: '#007575',
String: '#009C00'
}
|
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Class: '#007575',
String: '#009C00'
}
Add class comment and a custom color for the decoratorfrom pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
"""
Pygments version of the official colors for Igor Pro procedures.
"""
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Decorator: '#CC00A3',
Name.Class: '#007575',
String: '#009C00'
}
|
<commit_before>from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Class: '#007575',
String: '#009C00'
}
<commit_msg>Add class comment and a custom color for the decorator<commit_after>from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class IgorStyle(Style):
"""
Pygments version of the official colors for Igor Pro procedures.
"""
default_style = ""
styles = {
Comment: 'italic #FF0000',
Keyword: '#0000FF',
Name.Function: '#C34E00',
Name.Decorator: '#CC00A3',
Name.Class: '#007575',
String: '#009C00'
}
|
f5e547ed6ef642406e771a62796d738649c31a0f
|
python/FlatFileTable.py
|
python/FlatFileTable.py
|
#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
|
#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0, skip_until_regex_line=""):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
if skip_n_lines > 0:
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
found_regex = False
if skip_until_regex_line != "":
import re
regex_line = re.compile(skip_until_regex_line)
for line in fin:
match = regex_line.search(line)
if match:
found_regex = line
break
if not found_regex:
print "Warning: Regex "+skip_until_regex_line+" not found in FlatFileTable:record_generator"
if found_regex:
header = found_regex.rstrip().split(sep) # Parse header
else:
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
|
Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes)
|
Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes)
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2377 348d0f76-0448-11de-a6fe-93d51630548a
|
Python
|
mit
|
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
|
#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes)
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2377 348d0f76-0448-11de-a6fe-93d51630548a
|
#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0, skip_until_regex_line=""):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
if skip_n_lines > 0:
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
found_regex = False
if skip_until_regex_line != "":
import re
regex_line = re.compile(skip_until_regex_line)
for line in fin:
match = regex_line.search(line)
if match:
found_regex = line
break
if not found_regex:
print "Warning: Regex "+skip_until_regex_line+" not found in FlatFileTable:record_generator"
if found_regex:
header = found_regex.rstrip().split(sep) # Parse header
else:
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
|
<commit_before>#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
<commit_msg>Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes)
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2377 348d0f76-0448-11de-a6fe-93d51630548a<commit_after>
|
#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0, skip_until_regex_line=""):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
if skip_n_lines > 0:
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
found_regex = False
if skip_until_regex_line != "":
import re
regex_line = re.compile(skip_until_regex_line)
for line in fin:
match = regex_line.search(line)
if match:
found_regex = line
break
if not found_regex:
print "Warning: Regex "+skip_until_regex_line+" not found in FlatFileTable:record_generator"
if found_regex:
header = found_regex.rstrip().split(sep) # Parse header
else:
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
|
#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes)
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2377 348d0f76-0448-11de-a6fe-93d51630548a#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0, skip_until_regex_line=""):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
if skip_n_lines > 0:
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
found_regex = False
if skip_until_regex_line != "":
import re
regex_line = re.compile(skip_until_regex_line)
for line in fin:
match = regex_line.search(line)
if match:
found_regex = line
break
if not found_regex:
print "Warning: Regex "+skip_until_regex_line+" not found in FlatFileTable:record_generator"
if found_regex:
header = found_regex.rstrip().split(sep) # Parse header
else:
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
|
<commit_before>#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
<commit_msg>Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes)
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2377 348d0f76-0448-11de-a6fe-93d51630548a<commit_after>#!/usr/bin/env python
import sys, itertools
def record_generator(filename, sep="\t", skip_n_lines=0, skip_until_regex_line=""):
"""Given a file with field headers on the first line and records on subsequent lines,
generates a dictionary for each line keyed by the header fields"""
fin = open(filename)
if skip_n_lines > 0:
for i in range(skip_n_lines): # Skip a number of lines
fin.readline()
found_regex = False
if skip_until_regex_line != "":
import re
regex_line = re.compile(skip_until_regex_line)
for line in fin:
match = regex_line.search(line)
if match:
found_regex = line
break
if not found_regex:
print "Warning: Regex "+skip_until_regex_line+" not found in FlatFileTable:record_generator"
if found_regex:
header = found_regex.rstrip().split(sep) # Parse header
else:
header = fin.readline().rstrip().split(sep) # Pull off header
for line in fin: #
fields = line.rstrip().split(sep)
record = dict(itertools.izip(header, fields))
yield record
def record_matches_values(record, match_field_values):
for match_field, match_values in match_field_values:
if record[match_field] not in match_values:
return False
return True
|
20079bf375149bb0e8646a2d81dd800028f49faa
|
captura/views.py
|
captura/views.py
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the button to add a new socio-economic study.
Also shows the edit and see feedback buttons to each socio-economic study
shown in the list if this exist for the current user (capturist).
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
Add more comments in capturist dashboard view
|
Add more comments in capturist dashboard view
|
Python
|
mit
|
erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
Add more comments in capturist dashboard view
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the button to add a new socio-economic study.
Also shows the edit and see feedback buttons to each socio-economic study
shown in the list if this exist for the current user (capturist).
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
<commit_before>from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
<commit_msg>Add more comments in capturist dashboard view<commit_after>
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the button to add a new socio-economic study.
Also shows the edit and see feedback buttons to each socio-economic study
shown in the list if this exist for the current user (capturist).
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
Add more comments in capturist dashboard viewfrom django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the button to add a new socio-economic study.
Also shows the edit and see feedback buttons to each socio-economic study
shown in the list if this exist for the current user (capturist).
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
<commit_before>from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
<commit_msg>Add more comments in capturist dashboard view<commit_after>from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the button to add a new socio-economic study.
Also shows the edit and see feedback buttons to each socio-economic study
shown in the list if this exist for the current user (capturist).
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
7e59dc64a8aad61016c0b3f05b467bc4a3e02f57
|
deploy/generate_production_ini.py
|
deploy/generate_production_ini.py
|
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import Deployer
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
Adjust deployer to use new class name for ini file management.
|
Adjust deployer to use new class name for ini file management.
|
Python
|
mit
|
4dn-dcic/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront
|
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import Deployer
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
Adjust deployer to use new class name for ini file management.
|
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
<commit_before>"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import Deployer
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
<commit_msg>Adjust deployer to use new class name for ini file management.<commit_after>
|
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import Deployer
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
Adjust deployer to use new class name for ini file management."""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
<commit_before>"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import Deployer
class FourfrontDeployer(Deployer):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
<commit_msg>Adjust deployer to use new class name for ini file management.<commit_after>"""
Based on environment variables make a config file (production.ini) for our encoded application.
"""
import os
from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager
class FourfrontDeployer(BasicLegacyFourfrontIniFileManager):
_MY_DIR = os.path.dirname(__file__)
TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files")
PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml")
def main():
FourfrontDeployer.main()
if __name__ == '__main__':
main()
|
c4669c8fbaefc0a6e727d6423925f673e7c0a618
|
scripts/examples/02-Board-Control/timer_control.py
|
scripts/examples/02-Board-Control/timer_control.py
|
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
|
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(2, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
|
Update timer test script to use non-reserved timer.
|
Update timer test script to use non-reserved timer.
|
Python
|
mit
|
iabdalkader/openmv,kwagyeman/openmv,kwagyeman/openmv,openmv/openmv,iabdalkader/openmv,kwagyeman/openmv,kwagyeman/openmv,openmv/openmv,openmv/openmv,openmv/openmv,iabdalkader/openmv,iabdalkader/openmv
|
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
Update timer test script to use non-reserved timer.
|
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(2, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
|
<commit_before># Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
<commit_msg>Update timer test script to use non-reserved timer.<commit_after>
|
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(2, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
|
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
Update timer test script to use non-reserved timer.# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(2, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
|
<commit_before># Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
<commit_msg>Update timer test script to use non-reserved timer.<commit_after># Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
tim = Timer(2, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
|
e19357bb91bf3ae794dc239340c68b82d569698d
|
bmi_ilamb/config.py
|
bmi_ilamb/config.py
|
"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def get_arguments(self):
args = []
self._set_model_root()
for k, v in self._config.iteritems():
if k != ilamb_root_key:
args.append('--' + k)
args.append(v)
return args
|
"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
|
Add ability to pass 'models' argument to ilamb-run
|
Add ability to pass 'models' argument to ilamb-run
This is needed to benchmark individual models instead of all the
models under the directory specified by `model_root`.
|
Python
|
mit
|
permamodel/bmi-ilamb
|
"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def get_arguments(self):
args = []
self._set_model_root()
for k, v in self._config.iteritems():
if k != ilamb_root_key:
args.append('--' + k)
args.append(v)
return args
Add ability to pass 'models' argument to ilamb-run
This is needed to benchmark individual models instead of all the
models under the directory specified by `model_root`.
|
"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
|
<commit_before>"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def get_arguments(self):
args = []
self._set_model_root()
for k, v in self._config.iteritems():
if k != ilamb_root_key:
args.append('--' + k)
args.append(v)
return args
<commit_msg>Add ability to pass 'models' argument to ilamb-run
This is needed to benchmark individual models instead of all the
models under the directory specified by `model_root`.<commit_after>
|
"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
|
"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def get_arguments(self):
args = []
self._set_model_root()
for k, v in self._config.iteritems():
if k != ilamb_root_key:
args.append('--' + k)
args.append(v)
return args
Add ability to pass 'models' argument to ilamb-run
This is needed to benchmark individual models instead of all the
models under the directory specified by `model_root`."""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
|
<commit_before>"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def get_arguments(self):
args = []
self._set_model_root()
for k, v in self._config.iteritems():
if k != ilamb_root_key:
args.append('--' + k)
args.append(v)
return args
<commit_msg>Add ability to pass 'models' argument to ilamb-run
This is needed to benchmark individual models instead of all the
models under the directory specified by `model_root`.<commit_after>"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
|
14b8bbf0cade0c31d521e42c6c4c9b57bafaa12a
|
src/amber/hokuyo/hokuyo.py
|
src/amber/hokuyo/hokuyo.py
|
import logging.config
import sys
import os
import time
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
while True:
# noinspection PyBroadException
try:
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
except BaseException as e:
logger.error('error: %s' % str(e))
time.sleep(5)
|
import logging.config
import sys
import os
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
|
Remove auto start in loop with "while True".
|
Remove auto start in loop with "while True".
|
Python
|
mit
|
showmen15/testEEE,showmen15/testEEE
|
import logging.config
import sys
import os
import time
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
while True:
# noinspection PyBroadException
try:
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
except BaseException as e:
logger.error('error: %s' % str(e))
time.sleep(5)Remove auto start in loop with "while True".
|
import logging.config
import sys
import os
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
|
<commit_before>import logging.config
import sys
import os
import time
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
while True:
# noinspection PyBroadException
try:
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
except BaseException as e:
logger.error('error: %s' % str(e))
time.sleep(5)<commit_msg>Remove auto start in loop with "while True".<commit_after>
|
import logging.config
import sys
import os
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
|
import logging.config
import sys
import os
import time
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
while True:
# noinspection PyBroadException
try:
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
except BaseException as e:
logger.error('error: %s' % str(e))
time.sleep(5)Remove auto start in loop with "while True".import logging.config
import sys
import os
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
|
<commit_before>import logging.config
import sys
import os
import time
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
while True:
# noinspection PyBroadException
try:
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
except BaseException as e:
logger.error('error: %s' % str(e))
time.sleep(5)<commit_msg>Remove auto start in loop with "while True".<commit_after>import logging.config
import sys
import os
import serial
from amber.hokuyo.hokuyo_common import HokuyoController
from amber.tools import serial_port, config
__author__ = 'paoolo'
LOGGER_NAME = 'AmberPipes'
pwd = os.path.dirname(os.path.abspath(__file__))
config.add_config_ini('%s/hokuyo.ini' % pwd)
logging.config.fileConfig('%s/hokuyo.ini' % pwd)
SERIAL_PORT = config.HOKUYO_SERIAL_PORT
BAUD_RATE = config.HOKUYO_BAUD_RATE
TIMEOUT = 0.1
if __name__ == '__main__':
logger = logging.getLogger(LOGGER_NAME)
serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT)
port = serial_port.SerialPort(serial)
controller = HokuyoController(sys.stdin, sys.stdout, port)
controller()
|
e2533f5afe00af4ef39c853f919f597f89225b2b
|
uml-to-cpp.py
|
uml-to-cpp.py
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("== UML to CPP ==")
print("Create or modify C++ header and implementation files by plaintext UML.")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("[ UML to CPP ]")
print("Create or modify C++ header and implementation files by plaintext UML.")
print("> Attempting to create files...")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
elif line == "":
continue
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
Fix false bug flag by allowing empty lines
|
Fix false bug flag by allowing empty lines
|
Python
|
mit
|
BranSeals/uml-to-cpp
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("== UML to CPP ==")
print("Create or modify C++ header and implementation files by plaintext UML.")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")Fix false bug flag by allowing empty lines
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("[ UML to CPP ]")
print("Create or modify C++ header and implementation files by plaintext UML.")
print("> Attempting to create files...")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
elif line == "":
continue
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
<commit_before># Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("== UML to CPP ==")
print("Create or modify C++ header and implementation files by plaintext UML.")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")<commit_msg>Fix false bug flag by allowing empty lines<commit_after>
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("[ UML to CPP ]")
print("Create or modify C++ header and implementation files by plaintext UML.")
print("> Attempting to create files...")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
elif line == "":
continue
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("== UML to CPP ==")
print("Create or modify C++ header and implementation files by plaintext UML.")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")Fix false bug flag by allowing empty lines# Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("[ UML to CPP ]")
print("Create or modify C++ header and implementation files by plaintext UML.")
print("> Attempting to create files...")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
elif line == "":
continue
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
<commit_before># Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("== UML to CPP ==")
print("Create or modify C++ header and implementation files by plaintext UML.")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")<commit_msg>Fix false bug flag by allowing empty lines<commit_after># Copyright (C) 2017 Bran Seals. All rights reserved.
# Created: 2017-06-05
from UmlClass import UmlClass
print("[ UML to CPP ]")
print("Create or modify C++ header and implementation files by plaintext UML.")
print("> Attempting to create files...")
#print("Enter a UML filename: ") # file import currently disabled
umlFile = open("UML.txt", 'r')
# TODO: check if file isn't too bonkers, and properly formatted
uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0
for line in uml:
if line[:5] == "class" and line[-1:] == "{":
obj = UmlClass(line[6:-2])
elif line[:1] == "+":
obj.addToPublic(line[1:])
elif line[:1] == "-":
obj.addToPrivate(line[1:])
elif line == "}":
obj.createFiles()
filesCreated += 2
elif line == "":
continue
else:
print("> Syntax error in UML file")
print("> " + str(filesCreated) + " files created")
|
45572b53f66f8c8656664026f0a2e1bb0aa209c5
|
doc/fake_cffi.py
|
doc/fake_cffi.py
|
"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
SFC_GET_FORMAT_INFO = NotImplemented
|
"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
def string(self, _):
return b'not implemented'
def sf_version_string(self):
return NotImplemented
SFC_GET_FORMAT_INFO = NotImplemented
|
Add missing member functions in fake CFFI class
|
DOC: Add missing member functions in fake CFFI class
PR #160 introduced those calls on module load, which broke the Sphinx
autodoc generation.
|
Python
|
bsd-3-clause
|
mgeier/PySoundFile
|
"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
SFC_GET_FORMAT_INFO = NotImplemented
DOC: Add missing member functions in fake CFFI class
PR #160 introduced those calls on module load, which broke the Sphinx
autodoc generation.
|
"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
def string(self, _):
return b'not implemented'
def sf_version_string(self):
return NotImplemented
SFC_GET_FORMAT_INFO = NotImplemented
|
<commit_before>"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
SFC_GET_FORMAT_INFO = NotImplemented
<commit_msg>DOC: Add missing member functions in fake CFFI class
PR #160 introduced those calls on module load, which broke the Sphinx
autodoc generation.<commit_after>
|
"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
def string(self, _):
return b'not implemented'
def sf_version_string(self):
return NotImplemented
SFC_GET_FORMAT_INFO = NotImplemented
|
"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
SFC_GET_FORMAT_INFO = NotImplemented
DOC: Add missing member functions in fake CFFI class
PR #160 introduced those calls on module load, which broke the Sphinx
autodoc generation."""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
def string(self, _):
return b'not implemented'
def sf_version_string(self):
return NotImplemented
SFC_GET_FORMAT_INFO = NotImplemented
|
<commit_before>"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
SFC_GET_FORMAT_INFO = NotImplemented
<commit_msg>DOC: Add missing member functions in fake CFFI class
PR #160 introduced those calls on module load, which broke the Sphinx
autodoc generation.<commit_after>"""Mock module for Sphinx autodoc."""
class FFI(object):
def cdef(self, _):
pass
def dlopen(self, _):
return self
def string(self, _):
return b'not implemented'
def sf_version_string(self):
return NotImplemented
SFC_GET_FORMAT_INFO = NotImplemented
|
e51b5f859c50724952a378680e0b971432a1c918
|
examples/python/insert_event.py
|
examples/python/insert_event.py
|
from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print "==="
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
|
from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print events
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
|
Remove debug prints from tests
|
Remove debug prints from tests
|
Python
|
lgpl-2.1
|
freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist
|
from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print "==="
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
Remove debug prints from tests
|
from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print events
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
|
<commit_before>from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print "==="
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
<commit_msg>Remove debug prints from tests<commit_after>
|
from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print events
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
|
from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print "==="
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
Remove debug prints from testsfrom gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print events
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
|
<commit_before>from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print "==="
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
<commit_msg>Remove debug prints from tests<commit_after>from gi.repository import Zeitgeist, GObject
import time
log = Zeitgeist.Log.get_default()
mainloop = GObject.MainLoop()
def on_events_inserted(log, time_range, events):
print events
ev = Zeitgeist.Event();
ev.set_property("interpretation", "foo://Interp");
ev.set_property("timestamp", time.time()*1000);
ev.debug_print()
log.insert_event(ev, None, on_events_inserted, None)
mainloop.run()
|
7021aabe068f546adb10b8f741656c423cb7eb5a
|
sale_order_mass_confirm/wizard/sale_order_confirm.py
|
sale_order_mass_confirm/wizard/sale_order_confirm.py
|
# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
orders.action_confirm()
|
# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
for order in orders:
if order.state in ['draft', 'sent']:
order.action_confirm()
|
Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)
|
Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)
|
Python
|
agpl-3.0
|
VitalPet/addons-onestein,VitalPet/addons-onestein,VitalPet/addons-onestein
|
# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
orders.action_confirm()
Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)
|
# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
for order in orders:
if order.state in ['draft', 'sent']:
order.action_confirm()
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
orders.action_confirm()
<commit_msg>Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)<commit_after>
|
# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
for order in orders:
if order.state in ['draft', 'sent']:
order.action_confirm()
|
# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
orders.action_confirm()
Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
for order in orders:
if order.state in ['draft', 'sent']:
order.action_confirm()
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
orders.action_confirm()
<commit_msg>Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)<commit_after># -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
for order in orders:
if order.state in ['draft', 'sent']:
order.action_confirm()
|
027fa84469e17ec4b8948de095388ec94ea40941
|
api/identifiers/serializers.py
|
api/identifiers/serializers.py
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
|
Add get_absolute_url method to serializer
|
Add get_absolute_url method to serializer
|
Python
|
apache-2.0
|
abought/osf.io,mfraezz/osf.io,leb2dg/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,mluke93/osf.io,saradbowman/osf.io,cwisecarver/osf.io,aaxelb/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,kwierman/osf.io,brianjgeiger/osf.io,wearpants/osf.io,samchrisinger/osf.io,chennan47/osf.io,caneruguz/osf.io,jnayak1/osf.io,SSJohns/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,emetsger/osf.io,kwierman/osf.io,DanielSBrown/osf.io,abought/osf.io,acshi/osf.io,brianjgeiger/osf.io,adlius/osf.io,kwierman/osf.io,monikagrabowska/osf.io,acshi/osf.io,erinspace/osf.io,TomBaxter/osf.io,zamattiac/osf.io,aaxelb/osf.io,caseyrollins/osf.io,caneruguz/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,amyshi188/osf.io,mattclark/osf.io,binoculars/osf.io,Nesiehr/osf.io,chrisseto/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,wearpants/osf.io,laurenrevere/osf.io,saradbowman/osf.io,cwisecarver/osf.io,acshi/osf.io,sloria/osf.io,samchrisinger/osf.io,mfraezz/osf.io,TomBaxter/osf.io,binoculars/osf.io,mluo613/osf.io,chennan47/osf.io,binoculars/osf.io,icereval/osf.io,emetsger/osf.io,SSJohns/osf.io,amyshi188/osf.io,alexschiller/osf.io,Nesiehr/osf.io,zamattiac/osf.io,adlius/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,crcresearch/osf.io,chrisseto/osf.io,hmoco/osf.io,hmoco/osf.io,wearpants/osf.io,alexschiller/osf.io,baylee-d/osf.io,caseyrollins/osf.io,leb2dg/osf.io,Nesiehr/osf.io,kwierman/osf.io,hmoco/osf.io,aaxelb/osf.io,mfraezz/osf.io,SSJohns/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,mattclark/osf.io,DanielSBrown/osf.io,hmoco/osf.io,adlius/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,pattisdr/osf.io,zamattiac/osf.io,acshi/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,felliott/osf.io,erinspace/osf.io,emetsger/osf.io,baylee-d/osf.io,leb2dg/osf.io,baylee-d/osf.io,aaxelb/osf.io,crcresearch/osf.io,emetsger/osf.io,crcresearch/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,mattclark/osf.io,jnayak1/osf.io,cslzchen/osf.io,rdhyee/osf.io,alexschiller/osf.io,zamattiac/osf.io,Johnetordoff/osf.io,mluke93/osf.io,amyshi188/osf.io,TomBaxter/osf.io,adlius/osf.io,rdhyee/osf.io,samchrisinger/osf.io,chennan47/osf.io,samchrisinger/osf.io,sloria/osf.io,leb2dg/osf.io,mluo613/osf.io,chrisseto/osf.io,abought/osf.io,cslzchen/osf.io,rdhyee/osf.io,amyshi188/osf.io,sloria/osf.io,acshi/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,mluke93/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,caneruguz/osf.io,pattisdr/osf.io,cslzchen/osf.io,jnayak1/osf.io,felliott/osf.io,mluo613/osf.io,icereval/osf.io,felliott/osf.io,abought/osf.io,pattisdr/osf.io,mluo613/osf.io,caneruguz/osf.io,jnayak1/osf.io,alexschiller/osf.io,laurenrevere/osf.io,erinspace/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,wearpants/osf.io,mluke93/osf.io,Johnetordoff/osf.io,icereval/osf.io
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
Add get_absolute_url method to serializer
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
|
<commit_before>from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
<commit_msg>Add get_absolute_url method to serializer<commit_after>
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
Add get_absolute_url method to serializerfrom rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
|
<commit_before>from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
<commit_msg>Add get_absolute_url method to serializer<commit_after>from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = RelationshipField(
related_view='registrations:registration-detail',
related_view_kwargs={'node_id': '<referent._id>'},
)
class Meta:
type_ = 'identifiers'
def get_identifiers(self, obj):
return obj.value
def get_absolute_url(self, obj):
return obj.absolute_api_v2_url
|
13a6808c49474cf8d67240fbfda9c6273e1bfa2b
|
project/settings_live_base.py
|
project/settings_live_base.py
|
from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
|
from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
'CONN_MAX_AGE': 60
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
|
Add CONN_MAX_AGE setting because it makes a huge difference on busy sites
|
Add CONN_MAX_AGE setting because it makes a huge difference on busy sites
|
Python
|
bsd-3-clause
|
praekelt/jmbo-skeleton,praekelt/jmbo-skeleton,praekelt/jmbo-skeleton
|
from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
Add CONN_MAX_AGE setting because it makes a huge difference on busy sites
|
from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
'CONN_MAX_AGE': 60
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
|
<commit_before>from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
<commit_msg>Add CONN_MAX_AGE setting because it makes a huge difference on busy sites<commit_after>
|
from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
'CONN_MAX_AGE': 60
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
|
from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
Add CONN_MAX_AGE setting because it makes a huge difference on busy sitesfrom project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
'CONN_MAX_AGE': 60
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
|
<commit_before>from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
<commit_msg>Add CONN_MAX_AGE setting because it makes a huge difference on busy sites<commit_after>from project.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'skeleton',
'USER': 'skeleton',
'PASSWORD': 'skeleton',
'HOST': 'localhost',
'PORT': '5432',
'CONN_MAX_AGE': 60
}
}
MEDIA_ROOT = abspath("..", "skeleton-media")
STATIC_ROOT = abspath("..", "skeleton-static")
CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads")
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'KEY_PREFIX': 'skeleton_live',
}
}
COMPRESS_ENABLED = True
# Uncomment to use atlas. Remember to change the database engine to GIS aware.
#INSTALLED_APPS += ("atlas", "django.contrib.gis")
SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE'
SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient'
RAVEN_CONFIG = {
'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE',
}
ALLOWED_HOSTS = [
"*"
]
|
47d612aeab78e8d3ceeee8a4769485356194ab81
|
lib/custom_data/character_loader_new.py
|
lib/custom_data/character_loader_new.py
|
"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
CHARACTER_LIST_PATH = 'characters/character_list.txt'
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
|
"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
import os
CHARACTER_LIST_PATH = 'characters/character_list.txt'
CHARACTER_SCHEMA_PATH = os.path.join(os.path.dirname(os.path.realpath(
__file__)),
'character.xsd')
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
|
Add constant for Character Schema file path
|
Add constant for Character Schema file path
|
Python
|
unlicense
|
MarquisLP/Sidewalk-Champion
|
"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
CHARACTER_LIST_PATH = 'characters/character_list.txt'
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
Add constant for Character Schema file path
|
"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
import os
CHARACTER_LIST_PATH = 'characters/character_list.txt'
CHARACTER_SCHEMA_PATH = os.path.join(os.path.dirname(os.path.realpath(
__file__)),
'character.xsd')
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
|
<commit_before>"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
CHARACTER_LIST_PATH = 'characters/character_list.txt'
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
<commit_msg>Add constant for Character Schema file path<commit_after>
|
"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
import os
CHARACTER_LIST_PATH = 'characters/character_list.txt'
CHARACTER_SCHEMA_PATH = os.path.join(os.path.dirname(os.path.realpath(
__file__)),
'character.xsd')
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
|
"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
CHARACTER_LIST_PATH = 'characters/character_list.txt'
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
Add constant for Character Schema file path"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
import os
CHARACTER_LIST_PATH = 'characters/character_list.txt'
CHARACTER_SCHEMA_PATH = os.path.join(os.path.dirname(os.path.realpath(
__file__)),
'character.xsd')
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
|
<commit_before>"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
CHARACTER_LIST_PATH = 'characters/character_list.txt'
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
<commit_msg>Add constant for Character Schema file path<commit_after>"""This module loads character data from XML files and stores them in
CharacterData objects that can be read by the game engine.
Attributes:
CHARACTER_LIST_PATH (String): The filepath for the text file which
lists the paths to all of the characters' XML files.
Each path is separated by a new-line.
FILEPATH_PREFIX (String): The file path of the root directory where
all character data files are kept.
"""
import os
CHARACTER_LIST_PATH = 'characters/character_list.txt'
CHARACTER_SCHEMA_PATH = os.path.join(os.path.dirname(os.path.realpath(
__file__)),
'character.xsd')
FILEPATH_PREFIX = 'characters/'
def get_character_paths():
"""Return a list of all of the filepaths to the XML files for
playable characters.
"""
with open(CHARACTER_LIST_PATH) as f:
character_path_list = [line.rstrip('\n') for line in f]
return character_path_list
|
84acc00a3f6d09b4212b6728667af583b45e5a99
|
km_api/know_me/tests/serializers/test_profile_list_serializer.py
|
km_api/know_me/tests/serializers/test_profile_list_serializer.py
|
from know_me import serializers
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
|
from know_me import serializers
def test_create(user_factory):
"""
Saving a serializer containing valid data should create a new
profile.
"""
user = user_factory()
data = {
'name': 'John',
'quote': "Hi, I'm John",
'welcome_message': 'This is my profile.',
}
serializer = serializers.ProfileListSerializer(data=data)
assert serializer.is_valid()
serializer.save(user=user)
profile = user.profile
assert profile.name == data['name']
assert profile.quote == data['quote']
assert profile.welcome_message == data['welcome_message']
assert profile.user == user
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
|
Add test for creating profile from serializer.
|
Add test for creating profile from serializer.
|
Python
|
apache-2.0
|
knowmetools/km-api,knowmetools/km-api,knowmetools/km-api,knowmetools/km-api
|
from know_me import serializers
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
Add test for creating profile from serializer.
|
from know_me import serializers
def test_create(user_factory):
"""
Saving a serializer containing valid data should create a new
profile.
"""
user = user_factory()
data = {
'name': 'John',
'quote': "Hi, I'm John",
'welcome_message': 'This is my profile.',
}
serializer = serializers.ProfileListSerializer(data=data)
assert serializer.is_valid()
serializer.save(user=user)
profile = user.profile
assert profile.name == data['name']
assert profile.quote == data['quote']
assert profile.welcome_message == data['welcome_message']
assert profile.user == user
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
|
<commit_before>from know_me import serializers
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
<commit_msg>Add test for creating profile from serializer.<commit_after>
|
from know_me import serializers
def test_create(user_factory):
"""
Saving a serializer containing valid data should create a new
profile.
"""
user = user_factory()
data = {
'name': 'John',
'quote': "Hi, I'm John",
'welcome_message': 'This is my profile.',
}
serializer = serializers.ProfileListSerializer(data=data)
assert serializer.is_valid()
serializer.save(user=user)
profile = user.profile
assert profile.name == data['name']
assert profile.quote == data['quote']
assert profile.welcome_message == data['welcome_message']
assert profile.user == user
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
|
from know_me import serializers
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
Add test for creating profile from serializer.from know_me import serializers
def test_create(user_factory):
"""
Saving a serializer containing valid data should create a new
profile.
"""
user = user_factory()
data = {
'name': 'John',
'quote': "Hi, I'm John",
'welcome_message': 'This is my profile.',
}
serializer = serializers.ProfileListSerializer(data=data)
assert serializer.is_valid()
serializer.save(user=user)
profile = user.profile
assert profile.name == data['name']
assert profile.quote == data['quote']
assert profile.welcome_message == data['welcome_message']
assert profile.user == user
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
|
<commit_before>from know_me import serializers
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
<commit_msg>Add test for creating profile from serializer.<commit_after>from know_me import serializers
def test_create(user_factory):
"""
Saving a serializer containing valid data should create a new
profile.
"""
user = user_factory()
data = {
'name': 'John',
'quote': "Hi, I'm John",
'welcome_message': 'This is my profile.',
}
serializer = serializers.ProfileListSerializer(data=data)
assert serializer.is_valid()
serializer.save(user=user)
profile = user.profile
assert profile.name == data['name']
assert profile.quote == data['quote']
assert profile.welcome_message == data['welcome_message']
assert profile.user == user
def test_serialize(profile_factory):
"""
Test serializing a profile.
"""
profile = profile_factory()
serializer = serializers.ProfileListSerializer(profile)
expected = {
'id': profile.id,
'name': profile.name,
'quote': profile.quote,
'welcome_message': profile.welcome_message,
}
assert serializer.data == expected
|
a14b51a2aeaf23daf4b72658de3f40ebd49f6223
|
interrupted_bubble_sort/interrupted_bubble_sort.py
|
interrupted_bubble_sort/interrupted_bubble_sort.py
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = inputL[:]
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = list(inputL)
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
Change list copy to list()
|
Change list copy to list()
|
Python
|
mit
|
bm5w/codeeval
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = inputL[:]
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
Change list copy to list()
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = list(inputL)
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
<commit_before>"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = inputL[:]
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
<commit_msg>Change list copy to list()<commit_after>
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = list(inputL)
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = inputL[:]
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
Change list copy to list()"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = list(inputL)
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
<commit_before>"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = inputL[:]
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
<commit_msg>Change list copy to list()<commit_after>"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = list(inputL)
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
8c1b7f8a5a7403e464938aa0aa6876557ec6a2b3
|
daphne/server.py
|
daphne/server.py
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
Allow signal handlers to be disabled to run in subthread
|
Allow signal handlers to be disabled to run in subthread
|
Python
|
bsd-3-clause
|
django/daphne,maikhoepfel/daphne
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
Allow signal handlers to be disabled to run in subthread
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
<commit_before>import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
<commit_msg>Allow signal handlers to be disabled to run in subthread<commit_after>
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
Allow signal handlers to be disabled to run in subthreadimport time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
<commit_before>import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
<commit_msg>Allow signal handlers to be disabled to run in subthread<commit_after>import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
84ff87fc4ac0e334b2516f7d12944a5eac74964e
|
blinkylib/blinkytape.py
|
blinkylib/blinkytape.py
|
import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [255, 255, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
|
import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [0, 0, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
|
Change update value to produce less thrash on embedded side
|
Change update value to produce less thrash on embedded side
|
Python
|
mit
|
jonspeicher/blinkyfun
|
import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [255, 255, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
Change update value to produce less thrash on embedded side
|
import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [0, 0, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
|
<commit_before>import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [255, 255, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
<commit_msg>Change update value to produce less thrash on embedded side<commit_after>
|
import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [0, 0, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
|
import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [255, 255, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
Change update value to produce less thrash on embedded sideimport blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [0, 0, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
|
<commit_before>import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [255, 255, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
<commit_msg>Change update value to produce less thrash on embedded side<commit_after>import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(self):
return self._pixel_count
def set_pixel(self, index, color):
if index >= self._pixel_count: raise IndexError
self._pixels[index] = color
def set_pixels(self, pixels):
if len(pixels) != self._pixel_count: raise ValueError
self._pixels = pixels
def update(self):
UPDATE_VALUE = [0, 0, 255]
for pixel in self._pixels:
self._serial.write(pixel.raw)
self._serial.write(UPDATE_VALUE)
self._serial.flush()
|
ea7919f5e8de2d045df91fdda892757613ef3211
|
qregexeditor/api/quick_ref.py
|
qregexeditor/api/quick_ref.py
|
"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
|
"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtCore, QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
self.ui.textEditQuickRef.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
self.ui.textEditQuickRef.customContextMenuRequested.connect(
self._show_context_menu)
self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
self.context_menu.addSeparator()
action = self.context_menu.addAction('Zoom in')
action.setShortcut('Ctrl+i')
action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
self.addAction(action)
action = self.context_menu.addAction('Zoom out')
action.setShortcut('Ctrl+o')
self.addAction(action)
action.triggered.connect(self.ui.textEditQuickRef.zoomOut)
def _show_context_menu(self, pos):
self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
|
Add zoom in/out action to the text edit context menu
|
Add zoom in/out action to the text edit context menu
Fix #5
|
Python
|
mit
|
ColinDuquesnoy/QRegexEditor
|
"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
Add zoom in/out action to the text edit context menu
Fix #5
|
"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtCore, QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
self.ui.textEditQuickRef.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
self.ui.textEditQuickRef.customContextMenuRequested.connect(
self._show_context_menu)
self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
self.context_menu.addSeparator()
action = self.context_menu.addAction('Zoom in')
action.setShortcut('Ctrl+i')
action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
self.addAction(action)
action = self.context_menu.addAction('Zoom out')
action.setShortcut('Ctrl+o')
self.addAction(action)
action.triggered.connect(self.ui.textEditQuickRef.zoomOut)
def _show_context_menu(self, pos):
self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
|
<commit_before>"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
<commit_msg>Add zoom in/out action to the text edit context menu
Fix #5<commit_after>
|
"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtCore, QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
self.ui.textEditQuickRef.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
self.ui.textEditQuickRef.customContextMenuRequested.connect(
self._show_context_menu)
self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
self.context_menu.addSeparator()
action = self.context_menu.addAction('Zoom in')
action.setShortcut('Ctrl+i')
action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
self.addAction(action)
action = self.context_menu.addAction('Zoom out')
action.setShortcut('Ctrl+o')
self.addAction(action)
action.triggered.connect(self.ui.textEditQuickRef.zoomOut)
def _show_context_menu(self, pos):
self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
|
"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
Add zoom in/out action to the text edit context menu
Fix #5"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtCore, QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
self.ui.textEditQuickRef.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
self.ui.textEditQuickRef.customContextMenuRequested.connect(
self._show_context_menu)
self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
self.context_menu.addSeparator()
action = self.context_menu.addAction('Zoom in')
action.setShortcut('Ctrl+i')
action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
self.addAction(action)
action = self.context_menu.addAction('Zoom out')
action.setShortcut('Ctrl+o')
self.addAction(action)
action.triggered.connect(self.ui.textEditQuickRef.zoomOut)
def _show_context_menu(self, pos):
self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
|
<commit_before>"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
<commit_msg>Add zoom in/out action to the text edit context menu
Fix #5<commit_after>"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtCore, QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
self._fix_default_font_size()
self.ui.textEditQuickRef.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
self.ui.textEditQuickRef.customContextMenuRequested.connect(
self._show_context_menu)
self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
self.context_menu.addSeparator()
action = self.context_menu.addAction('Zoom in')
action.setShortcut('Ctrl+i')
action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
self.addAction(action)
action = self.context_menu.addAction('Zoom out')
action.setShortcut('Ctrl+o')
self.addAction(action)
action.triggered.connect(self.ui.textEditQuickRef.zoomOut)
def _show_context_menu(self, pos):
self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))
def _fix_default_font_size(self):
# remove fixed font size to allow the user to zoom in/out using
# Ctrl+Mouse Wheel
# Note: Zooming into HTML documents only works if the font-size is not
# set to a fixed size.
# (source: http://qt-project.org/doc/qt-5/qtextedit.html)
html = self.ui.textEditQuickRef.toHtml()
html = re.sub('font-size:\d+pt;', '', html)
self.ui.textEditQuickRef.setHtml(html)
|
65b4c081c3a66ccd373062f8e7c1d63295c8d8d1
|
cache_relation/app_settings.py
|
cache_relation/app_settings.py
|
# Default cache duration
CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3
|
from django.conf import settings
# Default cache timeout
CACHE_RELATION_DEFAULT_DURATION = getattr(
settings,
'CACHE_RELATION_DEFAULT_DURATION',
60 * 60 * 24 * 3,
)
|
Allow global settings to override.
|
Allow global settings to override.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
|
Python
|
bsd-3-clause
|
thread/django-sensible-caching,playfire/django-cache-toolbox,lamby/django-sensible-caching,lamby/django-cache-toolbox
|
# Default cache duration
CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3
Allow global settings to override.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
|
from django.conf import settings
# Default cache timeout
CACHE_RELATION_DEFAULT_DURATION = getattr(
settings,
'CACHE_RELATION_DEFAULT_DURATION',
60 * 60 * 24 * 3,
)
|
<commit_before># Default cache duration
CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3
<commit_msg>Allow global settings to override.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com><commit_after>
|
from django.conf import settings
# Default cache timeout
CACHE_RELATION_DEFAULT_DURATION = getattr(
settings,
'CACHE_RELATION_DEFAULT_DURATION',
60 * 60 * 24 * 3,
)
|
# Default cache duration
CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3
Allow global settings to override.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>from django.conf import settings
# Default cache timeout
CACHE_RELATION_DEFAULT_DURATION = getattr(
settings,
'CACHE_RELATION_DEFAULT_DURATION',
60 * 60 * 24 * 3,
)
|
<commit_before># Default cache duration
CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3
<commit_msg>Allow global settings to override.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com><commit_after>from django.conf import settings
# Default cache timeout
CACHE_RELATION_DEFAULT_DURATION = getattr(
settings,
'CACHE_RELATION_DEFAULT_DURATION',
60 * 60 * 24 * 3,
)
|
3f9e0d0b013a2b652aefdacc6c1b54e26af48b16
|
cmain.py
|
cmain.py
|
#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
sys.path.append(os.getcwd() + "/classes")
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
|
#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
sys.path.append(os.getcwd() + "/classes")
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
|
Store current working directory before import
|
Store current working directory before import
|
Python
|
mit
|
joccing/geoguru,joccing/geoguru
|
#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
sys.path.append(os.getcwd() + "/classes")
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
Store current working directory before import
|
#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
sys.path.append(os.getcwd() + "/classes")
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
|
<commit_before>#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
sys.path.append(os.getcwd() + "/classes")
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
<commit_msg>Store current working directory before import<commit_after>
|
#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
sys.path.append(os.getcwd() + "/classes")
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
|
#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
sys.path.append(os.getcwd() + "/classes")
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
Store current working directory before import#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
sys.path.append(os.getcwd() + "/classes")
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
|
<commit_before>#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
sys.path.append(os.getcwd() + "/classes")
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
<commit_msg>Store current working directory before import<commit_after>#
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
sys.path.append(os.getcwd() + "/classes")
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
def main():
from optparse import OptionParser
usage = "usage: %prog [[option] <Country regex> [attribute regex]] "
version = APP_VERSION
parser = OptionParser(usage=usage, version="%prog " + version)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="Make lots of noise")
parser.add_option("-f", "--file", action="store", dest="filename",
help="Initialize store for country stats")
(options, args) = parser.parse_args()
if len(args) < 1 and options.filename is None:
# interactive mode
CommandDispatcher()
else:
dm = DataManager(options.filename, options.verbose,
excludeList=['Country'])
# command line query mode
if len(args) >= 1 and dm.getSize() > 0:
# Find countries using regular expression match
result = dm.getCountryApprox(args[0])
# if no arguments, then assume all country stats are requested
propertyRE = args[1] if len(args) == 2 else ""
for c in result:
print(c.getPropertyString(propertyRE))
if __name__ == "__main__":
main()
|
f33bdb8313180fd3f2eae3d8b30783755c7d33ec
|
euler/solutions/solution_14.py
|
euler/solutions/solution_14.py
|
"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
|
"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
def collatz_sequence(n):
length = 1
# Implementing this recursively would allow memoization, but Python isn't
# the best language to attempt this in. Doing so causes a RecursionError
# to be raised. Also of note: using a decorator like `functools.lru_cache`
# for memoization causes the recursion limit to be reached more quickly.
# See: http://stackoverflow.com/questions/15239123/maximum-recursion-depth-reached-faster-when-using-functools-lru-cache.
while n > 1:
length += 1
if n%2 == 0:
n /= 2
else:
n = (3 * n) + 1
return length
def longest_collatz_sequence(ceiling):
longest_chain = {
'number': 1,
'length': 1
}
for i in range(ceiling):
length = collatz_sequence(i)
if length > longest_chain['length']:
longest_chain = {
'number': i,
'length': length
}
return longest_chain
|
Add solution for problem 14
|
Add solution for problem 14
Longest Collatz sequence
|
Python
|
mit
|
rlucioni/project-euler
|
"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
Add solution for problem 14
Longest Collatz sequence
|
"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
def collatz_sequence(n):
length = 1
# Implementing this recursively would allow memoization, but Python isn't
# the best language to attempt this in. Doing so causes a RecursionError
# to be raised. Also of note: using a decorator like `functools.lru_cache`
# for memoization causes the recursion limit to be reached more quickly.
# See: http://stackoverflow.com/questions/15239123/maximum-recursion-depth-reached-faster-when-using-functools-lru-cache.
while n > 1:
length += 1
if n%2 == 0:
n /= 2
else:
n = (3 * n) + 1
return length
def longest_collatz_sequence(ceiling):
longest_chain = {
'number': 1,
'length': 1
}
for i in range(ceiling):
length = collatz_sequence(i)
if length > longest_chain['length']:
longest_chain = {
'number': i,
'length': length
}
return longest_chain
|
<commit_before>"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
<commit_msg>Add solution for problem 14
Longest Collatz sequence<commit_after>
|
"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
def collatz_sequence(n):
length = 1
# Implementing this recursively would allow memoization, but Python isn't
# the best language to attempt this in. Doing so causes a RecursionError
# to be raised. Also of note: using a decorator like `functools.lru_cache`
# for memoization causes the recursion limit to be reached more quickly.
# See: http://stackoverflow.com/questions/15239123/maximum-recursion-depth-reached-faster-when-using-functools-lru-cache.
while n > 1:
length += 1
if n%2 == 0:
n /= 2
else:
n = (3 * n) + 1
return length
def longest_collatz_sequence(ceiling):
longest_chain = {
'number': 1,
'length': 1
}
for i in range(ceiling):
length = collatz_sequence(i)
if length > longest_chain['length']:
longest_chain = {
'number': i,
'length': length
}
return longest_chain
|
"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
Add solution for problem 14
Longest Collatz sequence"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
def collatz_sequence(n):
length = 1
# Implementing this recursively would allow memoization, but Python isn't
# the best language to attempt this in. Doing so causes a RecursionError
# to be raised. Also of note: using a decorator like `functools.lru_cache`
# for memoization causes the recursion limit to be reached more quickly.
# See: http://stackoverflow.com/questions/15239123/maximum-recursion-depth-reached-faster-when-using-functools-lru-cache.
while n > 1:
length += 1
if n%2 == 0:
n /= 2
else:
n = (3 * n) + 1
return length
def longest_collatz_sequence(ceiling):
longest_chain = {
'number': 1,
'length': 1
}
for i in range(ceiling):
length = collatz_sequence(i)
if length > longest_chain['length']:
longest_chain = {
'number': i,
'length': length
}
return longest_chain
|
<commit_before>"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
<commit_msg>Add solution for problem 14
Longest Collatz sequence<commit_after>"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
def collatz_sequence(n):
length = 1
# Implementing this recursively would allow memoization, but Python isn't
# the best language to attempt this in. Doing so causes a RecursionError
# to be raised. Also of note: using a decorator like `functools.lru_cache`
# for memoization causes the recursion limit to be reached more quickly.
# See: http://stackoverflow.com/questions/15239123/maximum-recursion-depth-reached-faster-when-using-functools-lru-cache.
while n > 1:
length += 1
if n%2 == 0:
n /= 2
else:
n = (3 * n) + 1
return length
def longest_collatz_sequence(ceiling):
longest_chain = {
'number': 1,
'length': 1
}
for i in range(ceiling):
length = collatz_sequence(i)
if length > longest_chain['length']:
longest_chain = {
'number': i,
'length': length
}
return longest_chain
|
ef5d3c61acdb7538b4338351b8902802142e03a5
|
tests/bindings/python/scoring/test-scoring_result.py
|
tests/bindings/python/scoring/test-scoring_result.py
|
#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.hit_count
result.miss_count
result.truth_count
result.percent_detection()
result.precision()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
|
#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.true_positives
result.false_positives
result.total_trues
result.total_possible
result.percent_detection()
result.precision()
result.specificity()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
|
Update Python tests for scoring_result
|
Update Python tests for scoring_result
|
Python
|
bsd-3-clause
|
linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,Kitware/sprokit,Kitware/sprokit,mathstuf/sprokit,mathstuf/sprokit
|
#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.hit_count
result.miss_count
result.truth_count
result.percent_detection()
result.precision()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
Update Python tests for scoring_result
|
#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.true_positives
result.false_positives
result.total_trues
result.total_possible
result.percent_detection()
result.precision()
result.specificity()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
|
<commit_before>#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.hit_count
result.miss_count
result.truth_count
result.percent_detection()
result.precision()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
<commit_msg>Update Python tests for scoring_result<commit_after>
|
#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.true_positives
result.false_positives
result.total_trues
result.total_possible
result.percent_detection()
result.precision()
result.specificity()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
|
#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.hit_count
result.miss_count
result.truth_count
result.percent_detection()
result.precision()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
Update Python tests for scoring_result#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.true_positives
result.false_positives
result.total_trues
result.total_possible
result.percent_detection()
result.precision()
result.specificity()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
|
<commit_before>#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.hit_count
result.miss_count
result.truth_count
result.percent_detection()
result.precision()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
<commit_msg>Update Python tests for scoring_result<commit_after>#!@PYTHON_EXECUTABLE@
#ckwg +5
# Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_import():
try:
import vistk.pipeline_util.bake
except:
test_error("Failed to import the bake module")
def test_api_calls():
from vistk.scoring import scoring_result
result = scoring_result.ScoringResult(1, 1, 1)
result.true_positives
result.false_positives
result.total_trues
result.total_possible
result.percent_detection()
result.precision()
result.specificity()
result + result
def main(testname):
if testname == 'import':
test_import()
elif testname == 'api_calls':
test_api_calls()
else:
test_error("No such test '%s'" % testname)
if __name__ == '__main__':
import os
import sys
if not len(sys.argv) == 4:
test_error("Expected three arguments")
sys.exit(1)
testname = sys.argv[1]
os.chdir(sys.argv[2])
sys.path.append(sys.argv[3])
from vistk.test.test import *
try:
main(testname)
except BaseException as e:
test_error("Unexpected exception: %s" % str(e))
|
498ab0c125180ba89987e797d0094adc02019a8f
|
numba/exttypes/utils.py
|
numba/exttypes/utils.py
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
|
Add utility to iterate over numba base classes
|
Add utility to iterate over numba base classes
|
Python
|
bsd-2-clause
|
jriehl/numba,cpcloud/numba,stuartarchibald/numba,numba/numba,GaZ3ll3/numba,pombredanne/numba,ssarangi/numba,ssarangi/numba,gdementen/numba,gmarkall/numba,pitrou/numba,shiquanwang/numba,numba/numba,seibert/numba,pitrou/numba,sklam/numba,shiquanwang/numba,IntelLabs/numba,seibert/numba,gdementen/numba,stuartarchibald/numba,stonebig/numba,stonebig/numba,cpcloud/numba,ssarangi/numba,GaZ3ll3/numba,gdementen/numba,stefanseefeld/numba,numba/numba,pombredanne/numba,gmarkall/numba,IntelLabs/numba,sklam/numba,numba/numba,cpcloud/numba,numba/numba,IntelLabs/numba,seibert/numba,pitrou/numba,ssarangi/numba,stonebig/numba,gdementen/numba,ssarangi/numba,jriehl/numba,cpcloud/numba,IntelLabs/numba,stefanseefeld/numba,stuartarchibald/numba,pombredanne/numba,stefanseefeld/numba,jriehl/numba,stonebig/numba,jriehl/numba,stuartarchibald/numba,sklam/numba,gmarkall/numba,gdementen/numba,IntelLabs/numba,pombredanne/numba,stefanseefeld/numba,pombredanne/numba,pitrou/numba,GaZ3ll3/numba,GaZ3ll3/numba,gmarkall/numba,jriehl/numba,pitrou/numba,seibert/numba,shiquanwang/numba,sklam/numba,gmarkall/numba,sklam/numba,seibert/numba,GaZ3ll3/numba,cpcloud/numba,stefanseefeld/numba,stuartarchibald/numba,stonebig/numba
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')Add utility to iterate over numba base classes
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
|
<commit_before>"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')<commit_msg>Add utility to iterate over numba base classes<commit_after>
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')Add utility to iterate over numba base classes"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
|
<commit_before>"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')<commit_msg>Add utility to iterate over numba base classes<commit_after>"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
|
fb26c402c433ac3358dbaadfb71762cfaf506a34
|
jp2_online/settings/production.py
|
jp2_online/settings/production.py
|
# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST = ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")
|
# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org']
CORS_ORIGIN_WHITELIST = (
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")
|
Add subdomain for educacion integral
|
Add subdomain for educacion integral
|
Python
|
mit
|
erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online
|
# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST = ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")Add subdomain for educacion integral
|
# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org']
CORS_ORIGIN_WHITELIST = (
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")
|
<commit_before># -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST = ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")<commit_msg>Add subdomain for educacion integral<commit_after>
|
# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org']
CORS_ORIGIN_WHITELIST = (
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")
|
# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST = ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")Add subdomain for educacion integral# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org']
CORS_ORIGIN_WHITELIST = (
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")
|
<commit_before># -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST = ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")<commit_msg>Add subdomain for educacion integral<commit_after># -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org']
CORS_ORIGIN_WHITELIST = (
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/")
|
fb35425fe36635d3c649eeffa925d7bc9ff08b31
|
grep/__main__.py
|
grep/__main__.py
|
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term[0],
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
|
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term,
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
|
Fix passing the search_term parameter to Searcher
|
Fix passing the search_term parameter to Searcher
|
Python
|
bsd-2-clause
|
florianbegusch/simple_grep,florianbegusch/simple_grep
|
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term[0],
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
Fix passing the search_term parameter to Searcher
|
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term,
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
|
<commit_before>
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term[0],
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
<commit_msg>Fix passing the search_term parameter to Searcher<commit_after>
|
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term,
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
|
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term[0],
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
Fix passing the search_term parameter to Searcher
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term,
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
|
<commit_before>
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term[0],
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
<commit_msg>Fix passing the search_term parameter to Searcher<commit_after>
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display full/absolute paths.
-e Use the search term as a regex pattern.
-n Display line numbers for matches.
"""
import os
from docopt import docopt
import grep as grep_
def main():
"""Entry point for grep_redone."""
try:
args = docopt(__doc__)
search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""]
searcher = grep_.Searcher(
caller_dir=os.path.abspath(os.path.curdir),
search_term=search_term,
is_recursive=args['-r'],
is_abs_path=args['-f'],
is_regex_pattern=args['-e'],
is_search_line_by_line=args['-n']
)
searcher.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
|
2ec894680f4af616ae531227e389c66535b8f143
|
feeds.py
|
feeds.py
|
from webapp2 import RequestHandler, WSGIApplication
from src.news_feed import get_news_feed
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Editorials!')
news = get_news_feed()
for n in news:
self.response.write("\n\n{}\n{}\n{}\n{}".format(n['title']
, n['author'], n['print_time'], n['link']))
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
|
from time import mktime
from datetime import datetime
from webapp2 import RequestHandler, WSGIApplication
from google.appengine.ext import ndb
from src.news_feed import get_news_feed
import hashlib
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
news_list = get_news_feed()
num_stored = 0
for n in news_list:
dt = datetime.fromtimestamp(mktime(n['datetime']))
title = n['title']
ky = hashlib.md5(title + n['print_time']).hexdigest()
new_key = ndb.Key(News, ky)
entry = new_key.get()
if entry is None:
news = News(title=n['title'], date=dt, link=n['link'],
author=n['author'])
news.key = ndb.Key(News, ky)
news.put()
num_stored += 1
self.response.write("Number of editorials stored = " +
str(num_stored))
class News(ndb.Model):
"""Class to store news items in GAE NDB"""
title = ndb.StringProperty(required=True)
date = ndb.DateTimeProperty(required=True)
create_date = ndb.DateTimeProperty(auto_now=True)
link = ndb.StringProperty(required=True)
author = ndb.StringProperty()
text = ndb.TextProperty()
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
|
Add the newsitems to GAE NDB
|
Add the newsitems to GAE NDB
If not present, add the news item to the non relational database of google app
engine.
For deciding unique keys, md5 hashing using the news item title and date is
used.
Signed-off-by: Venkatesh Shukla <8349e50bec2939976da648e286d7e261bcd17fa3@iitbhu.ac.in>
|
Python
|
mit
|
venkateshshukla/th-editorials-server
|
from webapp2 import RequestHandler, WSGIApplication
from src.news_feed import get_news_feed
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Editorials!')
news = get_news_feed()
for n in news:
self.response.write("\n\n{}\n{}\n{}\n{}".format(n['title']
, n['author'], n['print_time'], n['link']))
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
Add the newsitems to GAE NDB
If not present, add the news item to the non relational database of google app
engine.
For deciding unique keys, md5 hashing using the news item title and date is
used.
Signed-off-by: Venkatesh Shukla <8349e50bec2939976da648e286d7e261bcd17fa3@iitbhu.ac.in>
|
from time import mktime
from datetime import datetime
from webapp2 import RequestHandler, WSGIApplication
from google.appengine.ext import ndb
from src.news_feed import get_news_feed
import hashlib
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
news_list = get_news_feed()
num_stored = 0
for n in news_list:
dt = datetime.fromtimestamp(mktime(n['datetime']))
title = n['title']
ky = hashlib.md5(title + n['print_time']).hexdigest()
new_key = ndb.Key(News, ky)
entry = new_key.get()
if entry is None:
news = News(title=n['title'], date=dt, link=n['link'],
author=n['author'])
news.key = ndb.Key(News, ky)
news.put()
num_stored += 1
self.response.write("Number of editorials stored = " +
str(num_stored))
class News(ndb.Model):
"""Class to store news items in GAE NDB"""
title = ndb.StringProperty(required=True)
date = ndb.DateTimeProperty(required=True)
create_date = ndb.DateTimeProperty(auto_now=True)
link = ndb.StringProperty(required=True)
author = ndb.StringProperty()
text = ndb.TextProperty()
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
|
<commit_before>from webapp2 import RequestHandler, WSGIApplication
from src.news_feed import get_news_feed
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Editorials!')
news = get_news_feed()
for n in news:
self.response.write("\n\n{}\n{}\n{}\n{}".format(n['title']
, n['author'], n['print_time'], n['link']))
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
<commit_msg>Add the newsitems to GAE NDB
If not present, add the news item to the non relational database of google app
engine.
For deciding unique keys, md5 hashing using the news item title and date is
used.
Signed-off-by: Venkatesh Shukla <8349e50bec2939976da648e286d7e261bcd17fa3@iitbhu.ac.in><commit_after>
|
from time import mktime
from datetime import datetime
from webapp2 import RequestHandler, WSGIApplication
from google.appengine.ext import ndb
from src.news_feed import get_news_feed
import hashlib
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
news_list = get_news_feed()
num_stored = 0
for n in news_list:
dt = datetime.fromtimestamp(mktime(n['datetime']))
title = n['title']
ky = hashlib.md5(title + n['print_time']).hexdigest()
new_key = ndb.Key(News, ky)
entry = new_key.get()
if entry is None:
news = News(title=n['title'], date=dt, link=n['link'],
author=n['author'])
news.key = ndb.Key(News, ky)
news.put()
num_stored += 1
self.response.write("Number of editorials stored = " +
str(num_stored))
class News(ndb.Model):
"""Class to store news items in GAE NDB"""
title = ndb.StringProperty(required=True)
date = ndb.DateTimeProperty(required=True)
create_date = ndb.DateTimeProperty(auto_now=True)
link = ndb.StringProperty(required=True)
author = ndb.StringProperty()
text = ndb.TextProperty()
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
|
from webapp2 import RequestHandler, WSGIApplication
from src.news_feed import get_news_feed
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Editorials!')
news = get_news_feed()
for n in news:
self.response.write("\n\n{}\n{}\n{}\n{}".format(n['title']
, n['author'], n['print_time'], n['link']))
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
Add the newsitems to GAE NDB
If not present, add the news item to the non relational database of google app
engine.
For deciding unique keys, md5 hashing using the news item title and date is
used.
Signed-off-by: Venkatesh Shukla <8349e50bec2939976da648e286d7e261bcd17fa3@iitbhu.ac.in>from time import mktime
from datetime import datetime
from webapp2 import RequestHandler, WSGIApplication
from google.appengine.ext import ndb
from src.news_feed import get_news_feed
import hashlib
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
news_list = get_news_feed()
num_stored = 0
for n in news_list:
dt = datetime.fromtimestamp(mktime(n['datetime']))
title = n['title']
ky = hashlib.md5(title + n['print_time']).hexdigest()
new_key = ndb.Key(News, ky)
entry = new_key.get()
if entry is None:
news = News(title=n['title'], date=dt, link=n['link'],
author=n['author'])
news.key = ndb.Key(News, ky)
news.put()
num_stored += 1
self.response.write("Number of editorials stored = " +
str(num_stored))
class News(ndb.Model):
"""Class to store news items in GAE NDB"""
title = ndb.StringProperty(required=True)
date = ndb.DateTimeProperty(required=True)
create_date = ndb.DateTimeProperty(auto_now=True)
link = ndb.StringProperty(required=True)
author = ndb.StringProperty()
text = ndb.TextProperty()
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
|
<commit_before>from webapp2 import RequestHandler, WSGIApplication
from src.news_feed import get_news_feed
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Editorials!')
news = get_news_feed()
for n in news:
self.response.write("\n\n{}\n{}\n{}\n{}".format(n['title']
, n['author'], n['print_time'], n['link']))
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
<commit_msg>Add the newsitems to GAE NDB
If not present, add the news item to the non relational database of google app
engine.
For deciding unique keys, md5 hashing using the news item title and date is
used.
Signed-off-by: Venkatesh Shukla <8349e50bec2939976da648e286d7e261bcd17fa3@iitbhu.ac.in><commit_after>from time import mktime
from datetime import datetime
from webapp2 import RequestHandler, WSGIApplication
from google.appengine.ext import ndb
from src.news_feed import get_news_feed
import hashlib
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
news_list = get_news_feed()
num_stored = 0
for n in news_list:
dt = datetime.fromtimestamp(mktime(n['datetime']))
title = n['title']
ky = hashlib.md5(title + n['print_time']).hexdigest()
new_key = ndb.Key(News, ky)
entry = new_key.get()
if entry is None:
news = News(title=n['title'], date=dt, link=n['link'],
author=n['author'])
news.key = ndb.Key(News, ky)
news.put()
num_stored += 1
self.response.write("Number of editorials stored = " +
str(num_stored))
class News(ndb.Model):
"""Class to store news items in GAE NDB"""
title = ndb.StringProperty(required=True)
date = ndb.DateTimeProperty(required=True)
create_date = ndb.DateTimeProperty(auto_now=True)
link = ndb.StringProperty(required=True)
author = ndb.StringProperty()
text = ndb.TextProperty()
app = WSGIApplication([ ('/feeds', Feeds), ], debug=True)
|
096b9783dc5b8cb0f2a20e9d3d57d3897d36b1ff
|
charat2/views/guides.py
|
charat2/views/guides.py
|
import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
return r.text, r.status_code
|
import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
|
Set response encoding based on apparent_encoding.
|
Set response encoding based on apparent_encoding.
Headers from drweeaboo.net incorrectly tell us ISO-8859-1.
|
Python
|
agpl-3.0
|
MSPARP/newparp,MSPARP/newparp,MSPARP/newparp
|
import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
return r.text, r.status_code
Set response encoding based on apparent_encoding.
Headers from drweeaboo.net incorrectly tell us ISO-8859-1.
|
import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
|
<commit_before>import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
return r.text, r.status_code
<commit_msg>Set response encoding based on apparent_encoding.
Headers from drweeaboo.net incorrectly tell us ISO-8859-1.<commit_after>
|
import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
|
import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
return r.text, r.status_code
Set response encoding based on apparent_encoding.
Headers from drweeaboo.net incorrectly tell us ISO-8859-1.import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
|
<commit_before>import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
return r.text, r.status_code
<commit_msg>Set response encoding based on apparent_encoding.
Headers from drweeaboo.net incorrectly tell us ISO-8859-1.<commit_after>import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
|
c6d1a929f747a76155cce73e8c1a1358cf226f0e
|
constellation_forms/__init__.py
|
constellation_forms/__init__.py
|
"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
More advanced features such as form approval status are planned. This
will allow for advanced tracking of forms used for internal processes
such as purchase approvals, access requests, and even appeals to
normal form processes.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
|
"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
Advanced features are also available such as form approval and commenting.
These features can help support more advanced use cases where simply creating,
distributing, filing, and reading submissions is not a sufficient workflow.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
|
Update front page of the documentation
|
Update front page of the documentation
|
Python
|
isc
|
ConstellationApps/Forms,ConstellationApps/Forms,ConstellationApps/Forms
|
"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
More advanced features such as form approval status are planned. This
will allow for advanced tracking of forms used for internal processes
such as purchase approvals, access requests, and even appeals to
normal form processes.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
Update front page of the documentation
|
"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
Advanced features are also available such as form approval and commenting.
These features can help support more advanced use cases where simply creating,
distributing, filing, and reading submissions is not a sufficient workflow.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
|
<commit_before>"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
More advanced features such as form approval status are planned. This
will allow for advanced tracking of forms used for internal processes
such as purchase approvals, access requests, and even appeals to
normal form processes.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
<commit_msg>Update front page of the documentation<commit_after>
|
"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
Advanced features are also available such as form approval and commenting.
These features can help support more advanced use cases where simply creating,
distributing, filing, and reading submissions is not a sufficient workflow.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
|
"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
More advanced features such as form approval status are planned. This
will allow for advanced tracking of forms used for internal processes
such as purchase approvals, access requests, and even appeals to
normal form processes.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
Update front page of the documentation"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
Advanced features are also available such as form approval and commenting.
These features can help support more advanced use cases where simply creating,
distributing, filing, and reading submissions is not a sufficient workflow.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
|
<commit_before>"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
More advanced features such as form approval status are planned. This
will allow for advanced tracking of forms used for internal processes
such as purchase approvals, access requests, and even appeals to
normal form processes.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
<commit_msg>Update front page of the documentation<commit_after>"""
This module implements a forms system for creating, filling out, and
reviewing forms within an organization. This module depends on the
Constellation-Base package to function correctly.
Constellation Forms implements a fairly standard forms system. The
core features include:
* Click-to-Build form builder
* Form Lifecycles
* Form Versions
Advanced features are also available such as form approval and commenting.
These features can help support more advanced use cases where simply creating,
distributing, filing, and reading submissions is not a sufficient workflow.
This documentation is designed to be read by two distinct groups. The
primary group consuming this documentation are the developers of the
Forms module. While most of the source code is documented and the
files contain extensive inline comments, this documentation serves to
provide more in depth discussions of key features of components. This
also provides information on core design choices and why certain
choices have been made.
The second group of people expected to read
this documentation are end users of the system who would like to know
how to use components. This includes people who are managing the
forms system, and people who are tasked with creating forms.
"""
|
25724a77c19828d52cba2b6e682c67f67013590e
|
django_counter_field/fields.py
|
django_counter_field/fields.py
|
from django.db import models
class CounterField(models.IntegerField):
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^pomoji\.django_counter_field\.fields\.CounterField"])
|
from django.db import models
class CounterField(models.IntegerField):
"""
CounterField wraps the standard django IntegerField. It exists primarily to allow for easy validation of
counter fields. The default value of a counter field is 0.
"""
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^django_counter_field\.fields\.CounterField"])
|
Fix bug in introspection rule
|
Fix bug in introspection rule
|
Python
|
mit
|
kajic/django-counter-field
|
from django.db import models
class CounterField(models.IntegerField):
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^pomoji\.django_counter_field\.fields\.CounterField"])
Fix bug in introspection rule
|
from django.db import models
class CounterField(models.IntegerField):
"""
CounterField wraps the standard django IntegerField. It exists primarily to allow for easy validation of
counter fields. The default value of a counter field is 0.
"""
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^django_counter_field\.fields\.CounterField"])
|
<commit_before>from django.db import models
class CounterField(models.IntegerField):
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^pomoji\.django_counter_field\.fields\.CounterField"])
<commit_msg>Fix bug in introspection rule<commit_after>
|
from django.db import models
class CounterField(models.IntegerField):
"""
CounterField wraps the standard django IntegerField. It exists primarily to allow for easy validation of
counter fields. The default value of a counter field is 0.
"""
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^django_counter_field\.fields\.CounterField"])
|
from django.db import models
class CounterField(models.IntegerField):
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^pomoji\.django_counter_field\.fields\.CounterField"])
Fix bug in introspection rulefrom django.db import models
class CounterField(models.IntegerField):
"""
CounterField wraps the standard django IntegerField. It exists primarily to allow for easy validation of
counter fields. The default value of a counter field is 0.
"""
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^django_counter_field\.fields\.CounterField"])
|
<commit_before>from django.db import models
class CounterField(models.IntegerField):
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^pomoji\.django_counter_field\.fields\.CounterField"])
<commit_msg>Fix bug in introspection rule<commit_after>from django.db import models
class CounterField(models.IntegerField):
"""
CounterField wraps the standard django IntegerField. It exists primarily to allow for easy validation of
counter fields. The default value of a counter field is 0.
"""
def __init__(self, *args, **kwargs):
kwargs['default'] = kwargs.get('default', 0)
super(CounterField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^django_counter_field\.fields\.CounterField"])
|
afc94c1a1ebf14dbb393234233055915132a9fb8
|
django_ethereum_events/apps.py
|
django_ethereum_events/apps.py
|
from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
def ready(self):
super(EthereumEventsConfig, self).ready()
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)
|
from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
|
Fix for the previous commit (Celery app removal)
|
Fix for the previous commit (Celery app removal)
Haven't paid enough attention and missed what ready method does.
Removed the code. Libraries shouldn't do this - it's main project responsibility.
|
Python
|
mit
|
artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events
|
from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
def ready(self):
super(EthereumEventsConfig, self).ready()
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)
Fix for the previous commit (Celery app removal)
Haven't paid enough attention and missed what ready method does.
Removed the code. Libraries shouldn't do this - it's main project responsibility.
|
from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
|
<commit_before>from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
def ready(self):
super(EthereumEventsConfig, self).ready()
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)
<commit_msg>Fix for the previous commit (Celery app removal)
Haven't paid enough attention and missed what ready method does.
Removed the code. Libraries shouldn't do this - it's main project responsibility.<commit_after>
|
from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
|
from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
def ready(self):
super(EthereumEventsConfig, self).ready()
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)
Fix for the previous commit (Celery app removal)
Haven't paid enough attention and missed what ready method does.
Removed the code. Libraries shouldn't do this - it's main project responsibility.from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
|
<commit_before>from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
def ready(self):
super(EthereumEventsConfig, self).ready()
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)
<commit_msg>Fix for the previous commit (Celery app removal)
Haven't paid enough attention and missed what ready method does.
Removed the code. Libraries shouldn't do this - it's main project responsibility.<commit_after>from django.apps import AppConfig
from django.conf import settings
class EthereumEventsConfig(AppConfig):
name = 'django_ethereum_events'
|
36fb88bf5f60a656defaafc7626c373e59a70e05
|
tests/util.py
|
tests/util.py
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). When test fail, all environment variables appear in the error log in some case. Use credential file(~/.aws/credential) configuration for testing.
|
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing.
|
Python
|
mit
|
laughingman7743/PyAthenaJDBC,laughingman7743/PyAthenaJDBC
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing.
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
<commit_before>#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
<commit_msg>Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing.<commit_after>
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing.#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
<commit_before>#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
assert self.user, \
'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
assert self.password, \
'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
<commit_msg>Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
When test fail, all environment variables appear in the error log in some case.
Use credential file(~/.aws/credential) configuration for testing.<commit_after>#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
import codecs
import contextlib
import functools
import os
class Env(object):
def __init__(self):
# self.user = os.getenv('AWS_ACCESS_KEY_ID', None)
# assert self.user, \
# 'Required environment variable `AWS_ACCESS_KEY_ID` not found.'
# self.password = os.getenv('AWS_SECRET_ACCESS_KEY', None)
# assert self.password, \
# 'Required environment variable `AWS_SECRET_ACCESS_KEY` not found.'
self.region_name = os.getenv('AWS_DEFAULT_REGION', None)
assert self.region_name, \
'Required environment variable `AWS_DEFAULT_REGION` not found.'
self.s3_staging_dir = os.getenv('AWS_ATHENA_S3_STAGING_DIR', None)
assert self.s3_staging_dir, \
'Required environment variable `AWS_ATHENA_S3_STAGING_DIR` not found.'
def with_cursor(fn):
@functools.wraps(fn)
def wrapped_fn(self, *args, **kwargs):
with contextlib.closing(self.connect()) as conn:
with conn.cursor() as cursor:
fn(self, cursor, *args, **kwargs)
return wrapped_fn
def read_query(path):
with codecs.open(path, 'rb', 'utf-8') as f:
query = f.read()
return [q.strip() for q in query.split(';') if q and q.strip()]
|
c8bc1a79c3a82415e8ccad6395fcb0313d2c3685
|
ffmpeg_process.py
|
ffmpeg_process.py
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
Fix type: NoneType --> bool
|
Fix type: NoneType --> bool
|
Python
|
mit
|
dkrikun/ffmpeg-rcd
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
Fix type: NoneType --> bool
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
<commit_before># coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
<commit_msg>Fix type: NoneType --> bool<commit_after>
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
Fix type: NoneType --> bool# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
<commit_before># coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
<commit_msg>Fix type: NoneType --> bool<commit_after># coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if not self._cmdline:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.running:
logging.debug('stopping ffmpeg process')
self._process.resume()
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
6e80afd8f4317101a94f0d0114901da736f9912d
|
infect/infect.py
|
infect/infect.py
|
#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self):
pass
def upload(self):
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self):
pass
def main():
print('Running infect main()')
return 0
if __name__ == "__main__":
sys.exit(main())
|
#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self): # pragma: nocover
pass
def upload(self): # pragma: nocover
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self): # pragma: nocover
pass
def main(): # pragma: nocover
print('Running infect main()')
return 0
if __name__ == "__main__": # pragma: nocover
sys.exit(main())
|
Add pragma: nocover to non-implemented methods
|
Add pragma: nocover to non-implemented methods
|
Python
|
mit
|
thiderman/infect
|
#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self):
pass
def upload(self):
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self):
pass
def main():
print('Running infect main()')
return 0
if __name__ == "__main__":
sys.exit(main())
Add pragma: nocover to non-implemented methods
|
#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self): # pragma: nocover
pass
def upload(self): # pragma: nocover
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self): # pragma: nocover
pass
def main(): # pragma: nocover
print('Running infect main()')
return 0
if __name__ == "__main__": # pragma: nocover
sys.exit(main())
|
<commit_before>#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self):
pass
def upload(self):
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self):
pass
def main():
print('Running infect main()')
return 0
if __name__ == "__main__":
sys.exit(main())
<commit_msg>Add pragma: nocover to non-implemented methods<commit_after>
|
#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self): # pragma: nocover
pass
def upload(self): # pragma: nocover
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self): # pragma: nocover
pass
def main(): # pragma: nocover
print('Running infect main()')
return 0
if __name__ == "__main__": # pragma: nocover
sys.exit(main())
|
#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self):
pass
def upload(self):
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self):
pass
def main():
print('Running infect main()')
return 0
if __name__ == "__main__":
sys.exit(main())
Add pragma: nocover to non-implemented methods#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self): # pragma: nocover
pass
def upload(self): # pragma: nocover
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self): # pragma: nocover
pass
def main(): # pragma: nocover
print('Running infect main()')
return 0
if __name__ == "__main__": # pragma: nocover
sys.exit(main())
|
<commit_before>#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self):
pass
def upload(self):
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self):
pass
def main():
print('Running infect main()')
return 0
if __name__ == "__main__":
sys.exit(main())
<commit_msg>Add pragma: nocover to non-implemented methods<commit_after>#!/usr/bin/env python
# coding: utf-8
import sys
import os
# import argparse
class Infect(object):
class Codes:
symlink = {
'success': 0,
'target_not_found': 1,
'destination_already_linked': 2,
'destination_exists': 3,
}
def __init__(self):
pass
def install(self): # pragma: nocover
pass
def upload(self): # pragma: nocover
pass
def symlink(self, target, dest):
"""
Symlink a file and its destination
Will return a return code from `Infect.Codes.symlink`.
"""
if not os.path.isfile(target):
return self.Codes.symlink['target_not_found']
if os.path.islink(dest):
return self.Codes.symlink['destination_already_linked']
if os.path.isfile(dest) or os.path.isdir(dest):
return self.Codes.symlink['destination_exists']
os.symlink(target, dest)
return self.Codes.symlink['success']
def uninstall(self): # pragma: nocover
pass
def main(): # pragma: nocover
print('Running infect main()')
return 0
if __name__ == "__main__": # pragma: nocover
sys.exit(main())
|
5e27b6166a205239b5d075f5568ca5edf86051cb
|
download-xflux.py
|
download-xflux.py
|
from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print "Downloading 32-bit xflux ..."
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print "Downloading 64-bit xflux ..."
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
|
from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print("Downloading 32-bit xflux ...")
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print("Downloading 64-bit xflux ...")
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
|
Make download script work with Python 3.
|
Make download script work with Python 3.
Closes #47.
|
Python
|
mit
|
xflux-gui/xflux-gui
|
from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print "Downloading 32-bit xflux ..."
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print "Downloading 64-bit xflux ..."
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
Make download script work with Python 3.
Closes #47.
|
from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print("Downloading 32-bit xflux ...")
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print("Downloading 64-bit xflux ...")
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
|
<commit_before>from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print "Downloading 32-bit xflux ..."
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print "Downloading 64-bit xflux ..."
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
<commit_msg>Make download script work with Python 3.
Closes #47.<commit_after>
|
from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print("Downloading 32-bit xflux ...")
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print("Downloading 64-bit xflux ...")
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
|
from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print "Downloading 32-bit xflux ..."
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print "Downloading 64-bit xflux ..."
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
Make download script work with Python 3.
Closes #47.from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print("Downloading 32-bit xflux ...")
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print("Downloading 64-bit xflux ...")
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
|
<commit_before>from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print "Downloading 32-bit xflux ..."
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print "Downloading 64-bit xflux ..."
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
<commit_msg>Make download script work with Python 3.
Closes #47.<commit_after>from sys import maxsize
import os
# There is similar code in ./debian/postinst. If you are changing this
# you probably want to change that too.
def download_xflux():
# Determines which is the appropriate executable for 32-bit
if maxsize == 2147483647:
print("Downloading 32-bit xflux ...")
url = "https://justgetflux.com/linux/xflux-pre.tgz"
elif maxsize == 9223372036854775807:
print("Downloading 64-bit xflux ...")
url = "https://justgetflux.com/linux/xflux64.tgz"
tarchive = "/tmp/xflux.tgz"
os.system("wget '%s' -O'%s'" % (url, tarchive))
os.system("tar -xvf '%s'" % tarchive)
if __name__ == '__main__':
download_xflux()
|
ce5b83d802e1b3aa40dc7de7ea7a5db61a91a210
|
taarifa_backend/__init__.py
|
taarifa_backend/__init__.py
|
from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
|
from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': environ.get("DBNAME", "taarifa_backend")}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
|
Allow overriding database name with DBNAME environment variable
|
Allow overriding database name with DBNAME environment variable
|
Python
|
bsd-3-clause
|
taarifa/taarifa_backend,taarifa/taarifa_backend,taarifa/taarifa_backend,taarifa/taarifa_backend
|
from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
Allow overriding database name with DBNAME environment variable
|
from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': environ.get("DBNAME", "taarifa_backend")}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
|
<commit_before>from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
<commit_msg>Allow overriding database name with DBNAME environment variable<commit_after>
|
from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': environ.get("DBNAME", "taarifa_backend")}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
|
from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
Allow overriding database name with DBNAME environment variablefrom flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': environ.get("DBNAME", "taarifa_backend")}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
|
<commit_before>from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
<commit_msg>Allow overriding database name with DBNAME environment variable<commit_after>from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI'):
url = urlparse.urlparse(environ['MONGOLAB_URI'])
app.config['MONGODB_SETTINGS'] = {'username': url.username,
'password': url.password,
'host': url.hostname,
'port': url.port,
'db': url.path[1:]}
else:
app.config['MONGODB_SETTINGS'] = {'db': environ.get("DBNAME", "taarifa_backend")}
app.config['SECRET_KEY'] = 'hush'
db = MongoEngine(app)
def register_views():
"""
to avoid circular dependencies and register the routes
"""
from api import receive_report # noqa: needed for app to see the routes
register_views()
app.logger.debug('Registered views are: \n' +
app.view_functions.keys().__repr__())
if __name__ == '__main__':
app.run()
|
d50043e27e490528c3065603b6f9ad102fd5948e
|
ceraon/assets.py
|
ceraon/assets.py
|
# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jquery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jQuery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
Revert "Renames jQuery to jquery."
|
Revert "Renames jQuery to jquery."
This reverts commit c1a1ad720326cd6c2877a89698534c9762d17df3.
|
Python
|
bsd-3-clause
|
Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound
|
# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jquery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
Revert "Renames jQuery to jquery."
This reverts commit c1a1ad720326cd6c2877a89698534c9762d17df3.
|
# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jQuery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
<commit_before># -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jquery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
<commit_msg>Revert "Renames jQuery to jquery."
This reverts commit c1a1ad720326cd6c2877a89698534c9762d17df3.<commit_after>
|
# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jQuery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jquery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
Revert "Renames jQuery to jquery."
This reverts commit c1a1ad720326cd6c2877a89698534c9762d17df3.# -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jQuery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
<commit_before># -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jquery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
<commit_msg>Revert "Renames jQuery to jquery."
This reverts commit c1a1ad720326cd6c2877a89698534c9762d17df3.<commit_after># -*- coding: utf-8 -*-
"""Application assets."""
from flask_assets import Bundle, Environment
css = Bundle(
'libs/font-awesome/css/font-awesome.min.css',
'libs/bootstrap/dist/css/bootstrap.css',
'css/style.css',
filters='cssmin',
output='public/css/common.css'
)
js = Bundle(
'libs/jQuery/dist/jquery.js',
'libs/bootstrap/dist/js/bootstrap.js',
'js/plugins.js',
filters='jsmin',
output='public/js/common.js'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
186567fdc127e5c08131ebbf49b76a7f7430de6a
|
pathvalidate/_common.py
|
pathvalidate/_common.py
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text):
if dataproperty.is_empty_string(text):
raise NullNameError("null name")
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text, error_msg="null name"):
if dataproperty.is_empty_string(text):
raise NullNameError(error_msg)
|
Change to modifiable error message
|
Change to modifiable error message
|
Python
|
mit
|
thombashi/pathvalidate
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text):
if dataproperty.is_empty_string(text):
raise NullNameError("null name")
Change to modifiable error message
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text, error_msg="null name"):
if dataproperty.is_empty_string(text):
raise NullNameError(error_msg)
|
<commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text):
if dataproperty.is_empty_string(text):
raise NullNameError("null name")
<commit_msg>Change to modifiable error message<commit_after>
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text, error_msg="null name"):
if dataproperty.is_empty_string(text):
raise NullNameError(error_msg)
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text):
if dataproperty.is_empty_string(text):
raise NullNameError("null name")
Change to modifiable error message# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text, error_msg="null name"):
if dataproperty.is_empty_string(text):
raise NullNameError(error_msg)
|
<commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text):
if dataproperty.is_empty_string(text):
raise NullNameError("null name")
<commit_msg>Change to modifiable error message<commit_after># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import dataproperty
from ._error import NullNameError
def _validate_null_string(text, error_msg="null name"):
if dataproperty.is_empty_string(text):
raise NullNameError(error_msg)
|
d84a6f51b6431db78e1d894b99e48f346fbf8214
|
accelerator/migrations/0019_add_deferred_user_role.py
|
accelerator/migrations/0019_add_deferred_user_role.py
|
# Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(user=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
|
# Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(name=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
|
Change the user role key from userv to name
|
[AC-7743] Change the user role key from userv to name
|
Python
|
mit
|
masschallenge/django-accelerator,masschallenge/django-accelerator
|
# Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(user=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
[AC-7743] Change the user role key from userv to name
|
# Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(name=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
|
<commit_before># Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(user=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
<commit_msg>[AC-7743] Change the user role key from userv to name<commit_after>
|
# Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(name=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
|
# Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(user=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
[AC-7743] Change the user role key from userv to name# Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(name=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
|
<commit_before># Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(user=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
<commit_msg>[AC-7743] Change the user role key from userv to name<commit_after># Generated by Django 2.2.10 on 2020-04-09 21:24
from django.db import migrations
def add_deferred_user_role(apps, schema_editor):
DEFERRED_MENTOR = 'Deferred Mentor'
UserRole = apps.get_model('accelerator', 'UserRole')
Program = apps.get_model('accelerator', 'Program')
ProgramRole = apps.get_model('accelerator', 'ProgramRole')
if UserRole.objects.filter(name=DEFERRED_MENTOR).exists():
user_role = UserRole.objects.filter(name=DEFERRED_MENTOR)[0]
else:
user_role = UserRole.objects.create(name=DEFERRED_MENTOR,
sort_order=17)
for program in Program.objects.all():
if not ProgramRole.objects.filter(user_role=user_role,
program=program).exists():
name = "{} {} ({}-{})".format(
(program.end_date.year if program.end_date else ""),
DEFERRED_MENTOR,
program.program_family.url_slug.upper(),
program.pk)
ProgramRole.objects.get_or_create(
program=program,
user_role=user_role,
name=name)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0018_make_location_nonrequired'),
]
operations = [
migrations.RunPython(add_deferred_user_role,
migrations.RunPython.noop)
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.