commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
bf96bf9d71f432f2db75b0c62b49098235d75661
|
cryptography/bindings/openssl/pkcs12.py
|
cryptography/bindings/openssl/pkcs12.py
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
INCLUDES = """
#include <openssl/pkcs12.h>
"""
TYPES = """
typedef ... PKCS12;
"""
FUNCTIONS = """
int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **,
struct stack_st_X509 **);
PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *,
struct stack_st_X509 *, int, int, int, int, int);
void PKCS12_free(PKCS12 *);
PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **);
int i2d_PKCS12_bio(BIO *, PKCS12 *);
"""
MACROS = """
"""
|
# 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.
INCLUDES = """
#include <openssl/pkcs12.h>
"""
TYPES = """
typedef ... PKCS12;
"""
FUNCTIONS = """
void PKCS12_free(PKCS12 *);
PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **);
int i2d_PKCS12_bio(BIO *, PKCS12 *);
"""
MACROS = """
int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **,
struct stack_st_X509 **);
PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *,
struct stack_st_X509 *, int, int, int, int, int);
"""
|
Move these to macros, the exact type of these functions changes by deifne
|
Move these to macros, the exact type of these functions changes by deifne
|
Python
|
bsd-3-clause
|
Lukasa/cryptography,kimvais/cryptography,skeuomorf/cryptography,sholsapp/cryptography,dstufft/cryptography,bwhmather/cryptography,glyph/cryptography,dstufft/cryptography,bwhmather/cryptography,kimvais/cryptography,dstufft/cryptography,Ayrx/cryptography,Lukasa/cryptography,skeuomorf/cryptography,sholsapp/cryptography,Hasimir/cryptography,kimvais/cryptography,skeuomorf/cryptography,Ayrx/cryptography,skeuomorf/cryptography,bwhmather/cryptography,Hasimir/cryptography,bwhmather/cryptography,sholsapp/cryptography,Hasimir/cryptography,Lukasa/cryptography,dstufft/cryptography,Ayrx/cryptography,Ayrx/cryptography,sholsapp/cryptography,Hasimir/cryptography,glyph/cryptography,kimvais/cryptography,dstufft/cryptography
|
bcaf887ccad40adf2cb09627c12f2a3e1b4b006d
|
redis_cache/client/__init__.py
|
redis_cache/client/__init__.py
|
# -*- coding: utf-8 -*-
from .default import DefaultClient
from .sharded import ShardClient
from .herd import HerdClient
from .experimental import SimpleFailoverClient
from .sentinel import SentinelClient
__all__ = ['DefaultClient', 'ShardClient',
'HerdClient', 'SimpleFailoverClient',
'SentinelClient']
|
# -*- coding: utf-8 -*-
import warnings
from .default import DefaultClient
from .sharded import ShardClient
from .herd import HerdClient
from .experimental import SimpleFailoverClient
__all__ = ['DefaultClient', 'ShardClient',
'HerdClient', 'SimpleFailoverClient',]
try:
from .sentinel import SentinelClient
__all__.append("SentinelClient")
except ImportError:
warnings.warn("sentinel client is unsuported with redis-py<2.9",
RuntimeWarning)
|
Disable Sentinel client with redis-py < 2.9
|
Disable Sentinel client with redis-py < 2.9
|
Python
|
bsd-3-clause
|
zl352773277/django-redis,smahs/django-redis,yanheng/django-redis,lucius-feng/django-redis,GetAmbassador/django-redis
|
684ac5e6e6011581d5abcb42a7c0e54742f20606
|
Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py
|
Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py
|
# -------------------------------------------------------
import socket, traceback
import time
import json
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
print(message)
json.loads(message.decode("utf-8"))
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# -------------------------------------------------------
|
# -------------------------------------------------------
import socket, traceback
import time
import json
import numpy as np
from scipy.spatial.transform import Rotation as R
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
# Place IMU x-axis into wind going direction when launching script
is_init_done = False
wind_yaw = 0
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
#print(message)
msg = json.loads(message.decode("utf-8"))
if is_init_done==False:
wind_yaw = msg["Yaw"]
is_init_done = True
msg['Yaw'] = msg['Yaw']-wind_yaw
print(msg)
ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']]
seq = 'ZYX' # small letters from intrinsic rotations
r = R.from_euler(seq, ypr, degrees=True)
# Compute coordinates in NED (could be useful to compare position with GPS position for example)
line_length = 10
base_to_kite = [0, 0, line_length]
base_to_kite_in_NED = r.apply(base_to_kite)
# Express kite coordinates as great roll, great pitch and small yaw angles
grpy=r.as_euler(seq="XYZ")
print(grpy*180/np.pi)
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# -------------------------------------------------------
|
Add computations of great roll, pitch and small yaw angle (kite angles)
|
Add computations of great roll, pitch and small yaw angle (kite angles)
|
Python
|
mit
|
baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite
|
0254ad22680d32a451d1faf4b21809394a399311
|
packages/pegasus-python/src/Pegasus/cli/startup-validation.py
|
packages/pegasus-python/src/Pegasus/cli/startup-validation.py
|
#!/usr/bin/python3
import sys
if not sys.version_info >= (3, 5):
sys.stderr.write("Pegasus requires Python 3.5 or above\n")
sys.exit(1)
try:
pass
except:
sys.stderr.write("Pegasus requires the Python3 YAML module to be installed\n")
sys.exit(1)
|
#!/usr/bin/python3
import sys
if not sys.version_info >= (3, 5):
sys.stderr.write("Pegasus requires Python 3.5 or above\n")
sys.exit(1)
try:
import yaml # noqa
except:
sys.stderr.write("Pegasus requires the Python3 YAML module to be installed\n")
sys.exit(1)
|
Add noqa comment so unused import does not get removed by code lint steps
|
Add noqa comment so unused import does not get removed by code lint steps
|
Python
|
apache-2.0
|
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
|
6d18ff715a5fa3059ddb609c1abdbbb06b15ad63
|
fuel/downloaders/celeba.py
|
fuel/downloaders/celeba.py
|
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
|
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
|
Update download links for CelebA files
|
Update download links for CelebA files
|
Python
|
mit
|
mila-udem/fuel,dmitriy-serdyuk/fuel,dmitriy-serdyuk/fuel,mila-udem/fuel,vdumoulin/fuel,vdumoulin/fuel
|
e818860af87cad796699e27f8dfb4ff6fc9354e8
|
h2o-py/h2o/model/autoencoder.py
|
h2o-py/h2o/model/autoencoder.py
|
"""
AutoEncoder Models
"""
from model_base import *
from metrics_base import *
class H2OAutoEncoderModel(ModelBase):
"""
Class for AutoEncoder models.
"""
def __init__(self, dest_key, model_json):
super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics)
def anomaly(self,test_data):
"""
Obtain the reconstruction error for the input test_data.
:param test_data: The dataset upon which the reconstruction error is computed.
:return: Return the reconstruction error.
"""
if not test_data: raise ValueError("Must specify test data")
j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True)
return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
|
"""
AutoEncoder Models
"""
from model_base import *
from metrics_base import *
class H2OAutoEncoderModel(ModelBase):
"""
Class for AutoEncoder models.
"""
def __init__(self, dest_key, model_json):
super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics)
def anomaly(self,test_data,per_feature=False):
"""
Obtain the reconstruction error for the input test_data.
:param test_data: The dataset upon which the reconstruction error is computed.
:param per_feature: Whether to return the square reconstruction error per feature. Otherwise, return the mean square error.
:return: Return the reconstruction error.
"""
if not test_data: raise ValueError("Must specify test data")
j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True, reconstruction_error_per_feature=per_feature)
return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
|
Add extra argument to get per-feature reconstruction error for anomaly detection from Python.
|
PUBDEV-2078: Add extra argument to get per-feature reconstruction error for
anomaly detection from Python.
|
Python
|
apache-2.0
|
kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,brightchen/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,datachand/h2o-3,kyoren/https-github.com-h2oai-h2o-3,printedheart/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,YzPaul3/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,printedheart/h2o-3,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,pchmieli/h2o-3,datachand/h2o-3,junwucs/h2o-3,mathemage/h2o-3,h2oai/h2o-3,printedheart/h2o-3,junwucs/h2o-3,kyoren/https-github.com-h2oai-h2o-3,YzPaul3/h2o-3,madmax983/h2o-3,michalkurka/h2o-3,junwucs/h2o-3,printedheart/h2o-3,datachand/h2o-3,pchmieli/h2o-3,michalkurka/h2o-3,printedheart/h2o-3,brightchen/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,madmax983/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,brightchen/h2o-3,pchmieli/h2o-3,brightchen/h2o-3,spennihana/h2o-3,junwucs/h2o-3,mathemage/h2o-3,printedheart/h2o-3,madmax983/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,kyoren/https-github.com-h2oai-h2o-3,madmax983/h2o-3,datachand/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,brightchen/h2o-3,jangorecki/h2o-3,madmax983/h2o-3,junwucs/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,pchmieli/h2o-3,junwucs/h2o-3,mathemage/h2o-3,datachand/h2o-3,kyoren/https-github.com-h2oai-h2o-3,jangorecki/h2o-3,spennihana/h2o-3,spennihana/h2o-3,spennihana/h2o-3,madmax983/h2o-3,spennihana/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,brightchen/h2o-3,pchmieli/h2o-3,h2oai/h2o-dev,brightchen/h2o-3,kyoren/https-github.com-h2oai-h2o-3,michalkurka/h2o-3,pchmieli/h2o-3,mathemage/h2o-3,printedheart/h2o-3
|
ea1c095fb12c4062616ee0d38818ab1baaabd1eb
|
ipywidgets/widgets/tests/test_widget_upload.py
|
ipywidgets/widgets/tests/test_widget_upload.py
|
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from unittest import TestCase
from traitlets import TraitError
from ipywidgets import FileUpload
class TestFileUpload(TestCase):
def test_construction(self):
uploader = FileUpload()
# Default
assert uploader.accept == ''
assert not uploader.multiple
assert not uploader.disabled
def test_construction_with_params(self):
uploader = FileUpload(
accept='.txt', multiple=True, disabled=True)
assert uploader.accept == '.txt'
assert uploader.multiple
assert uploader.disabled
def test_empty_initial_value(self):
uploader = FileUpload()
assert uploader.value == []
|
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from unittest import TestCase
from traitlets import TraitError
from ipywidgets import FileUpload
class TestFileUpload(TestCase):
def test_construction(self):
uploader = FileUpload()
# Default
assert uploader.accept == ''
assert not uploader.multiple
assert not uploader.disabled
def test_construction_with_params(self):
uploader = FileUpload(
accept='.txt', multiple=True, disabled=True)
assert uploader.accept == '.txt'
assert uploader.multiple
assert uploader.disabled
def test_empty_initial_value(self):
uploader = FileUpload()
assert uploader.value == []
def test_receive_single_file(self):
uploader = FileUpload()
content = memoryview(b"file content")
message = {
"value": [
{
"name": "file-name.txt",
"type": "text/plain",
"size": 20760,
"lastModified": 1578578296434,
"error": "",
"content": content,
}
]
}
uploader.set_state(message)
assert len(uploader.value) == 1
[uploaded_file] = uploader.value
assert uploaded_file.name == "file-name.txt"
assert uploaded_file.type == "text/plain"
assert uploaded_file.size == 20760
assert uploaded_file.content.tobytes() == b"file content"
|
Test deserialization of comm message following upload
|
Test deserialization of comm message following upload
|
Python
|
bsd-3-clause
|
ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets
|
c5730d19d41f7221c4108f340d0ff8be26c24c74
|
auxiliary/tag_suggestions/__init__.py
|
auxiliary/tag_suggestions/__init__.py
|
from tagging.models import Tag, TaggedItem
from django.contrib.contenttypes.models import ContentType
from auxiliary.models import TagSuggestion
from django.db import IntegrityError
def approve(admin, request, tag_suggestions):
for tag_suggestion in tag_suggestions:
object = tag_suggestion.object
try:
tag = Tag.objects.create(name=tag_suggestion.name)
TaggedItem.objects.create(tag=tag, object=object)
except IntegrityError as e:
if str(e) != 'column name is not unique':
raise
tag_suggestion.delete()
|
from tagging.models import Tag, TaggedItem
from django.contrib.contenttypes.models import ContentType
def approve(admin, request, tag_suggestions):
for tag_suggestion in tag_suggestions:
obj = tag_suggestion.object
ct = ContentType.objects.get_for_model(obj)
tag, t_created = Tag.objects.get_or_create(name=tag_suggestion.name)
ti, ti_created = TaggedItem.objects.get_or_create(
tag=tag, object_id=obj.pk, content_type=ct)
tag_suggestion.delete()
|
Make tag_suggestions test less flaky
|
Make tag_suggestions test less flaky
Failed on Python 2.7.6 as it was dependant on an error string returned
|
Python
|
bsd-3-clause
|
noamelf/Open-Knesset,otadmor/Open-Knesset,habeanf/Open-Knesset,habeanf/Open-Knesset,daonb/Open-Knesset,navotsil/Open-Knesset,noamelf/Open-Knesset,navotsil/Open-Knesset,navotsil/Open-Knesset,otadmor/Open-Knesset,noamelf/Open-Knesset,otadmor/Open-Knesset,ofri/Open-Knesset,Shrulik/Open-Knesset,jspan/Open-Knesset,jspan/Open-Knesset,MeirKriheli/Open-Knesset,otadmor/Open-Knesset,alonisser/Open-Knesset,daonb/Open-Knesset,ofri/Open-Knesset,OriHoch/Open-Knesset,DanaOshri/Open-Knesset,ofri/Open-Knesset,MeirKriheli/Open-Knesset,alonisser/Open-Knesset,DanaOshri/Open-Knesset,alonisser/Open-Knesset,DanaOshri/Open-Knesset,OriHoch/Open-Knesset,MeirKriheli/Open-Knesset,jspan/Open-Knesset,habeanf/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset,OriHoch/Open-Knesset,Shrulik/Open-Knesset,habeanf/Open-Knesset,ofri/Open-Knesset,OriHoch/Open-Knesset,DanaOshri/Open-Knesset,noamelf/Open-Knesset,Shrulik/Open-Knesset,Shrulik/Open-Knesset,jspan/Open-Knesset,MeirKriheli/Open-Knesset,daonb/Open-Knesset,navotsil/Open-Knesset
|
85b269bde76af2b8d15dc3b1e9f7cf882fc18dc2
|
labcalc/tests/test_functions.py
|
labcalc/tests/test_functions.py
|
#!/usr/bin/env python3
from labcalc.run import *
from labcalc import gibson
# labcalc.gibson
def test_gibson_one_insert():
d = {'insert1': [300, 50], 'vector': [5000, 50]}
assert gibson.gibson_calc(d) == {'insert1': 0.24, 'vector': 2.0}
|
#!/usr/bin/env python3
from labcalc.run import *
from labcalc import gibson
# labcalc.gibson
def test_gibson_one_insert():
d = {'vector': [5000, 50], 'insert1': [300, 50]}
assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24}
def test_gibson_two_inserts():
d = {'vector': [5000, 50], 'insert1': [300, 50], 'insert2': [600, 50]}
assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24, 'insert2': 0.48}
def test_gibson_four_inserts():
d = {'vector': [5000, 50],
'insert1': [300, 50], 'insert2': [600, 50], 'insert3': [300, 50], 'insert4': [600, 50]}
assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.12, 'insert2': 0.24, 'insert3': 0.12, 'insert4': 0.24}
|
Add tests for multiple gibson inserts
|
Add tests for multiple gibson inserts
|
Python
|
bsd-3-clause
|
dtarnowski16/labcalc,mandel01/labcalc,mjmlab/labcalc
|
caaa807a4226bfdeb18681f8ccb6119bd2caa609
|
pombola/core/context_processors.py
|
pombola/core/context_processors.py
|
from django.conf import settings
import logging
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'STAGING': settings.STAGING,
'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER,
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID,
'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME,
'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS,
'TWITTER_USERNAME': settings.TWITTER_USERNAME,
'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID,
'BLOG_RSS_FEED': settings.BLOG_RSS_FEED,
'ENABLED_FEATURES': settings.ENABLED_FEATURES,
'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH,
'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST,
'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH,
'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST,
}
}
|
from django.conf import settings
import logging
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'STAGING': settings.STAGING,
'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER,
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID,
'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME,
'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS,
'TWITTER_USERNAME': settings.TWITTER_USERNAME,
'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID,
'BLOG_RSS_FEED': settings.BLOG_RSS_FEED,
'ENABLED_FEATURES': settings.ENABLED_FEATURES,
'COUNTRY_APP': settings.COUNTRY_APP,
'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH,
'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST,
'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH,
'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST,
}
}
|
Add COUNTRY_APP to settings exposed to the templates
|
Add COUNTRY_APP to settings exposed to the templates
|
Python
|
agpl-3.0
|
hzj123/56th,mysociety/pombola,hzj123/56th,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,geoffkilpin/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola
|
47d9a8df136e235f49921d4782c5e392b0101107
|
migrations/versions/147_add_cleaned_subject.py
|
migrations/versions/147_add_cleaned_subject.py
|
"""add cleaned subject
Revision ID: 486c7fa5b533
Revises: 1d7a72222b7c
Create Date: 2015-03-10 16:33:41.740387
"""
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.add_column('thread', sa.Column('_cleaned_subject',
sa.String(length=255), nullable=True))
op.create_index('ix_cleaned_subject', 'thread',
['namespace_id', '_cleaned_subject'], unique=False)
def downgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.drop_index('ix_cleaned_subject', table_name='thread')
op.drop_column('thread', '_cleaned_subject')
|
"""add cleaned subject
Revision ID: 486c7fa5b533
Revises: 1d7a72222b7c
Create Date: 2015-03-10 16:33:41.740387
"""
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.add_column('thread', sa.Column('_cleaned_subject',
sa.String(length=255), nullable=True))
op.create_index('ix_cleaned_subject', 'thread', ['_cleaned_subject'],
unique=False)
def downgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.drop_index('ix_cleaned_subject', table_name='thread')
op.drop_column('thread', '_cleaned_subject')
|
Make _cleaned_subject migration match declared schema.
|
Make _cleaned_subject migration match declared schema.
Test Plan: Upgrade old database to head.
Reviewers: kav-ya
Reviewed By: kav-ya
Differential Revision: https://review.inboxapp.com/D1394
|
Python
|
agpl-3.0
|
Eagles2F/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,closeio/nylas,nylas/sync-engine,gale320/sync-engine,gale320/sync-engine,gale320/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,wakermahmud/sync-engine,ErinCall/sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,closeio/nylas,jobscore/sync-engine,gale320/sync-engine,ErinCall/sync-engine,EthanBlackburn/sync-engine,closeio/nylas,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,Eagles2F/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine
|
8910a61025062a40a3129f7a4330964b20337ec2
|
insanity/core.py
|
insanity/core.py
|
import numpy as np
import theano
import theano.tensor as T
|
import numpy as np
import theano
import theano.tensor as T
class NeuralNetwork(object):
def __init__(self, layers, miniBatchSize):
self.miniBatchSize = miniBatchSize
#Initialize layers.
self.layers = layers
self.numLayers = len(self.layers)
self.firstLayer = self.layers[0]
self.lastLayer = self.layers[-1]
#Populate self.learningParams with a complete list of weights and biases from all layers.
self.learningParams = []
for layer in self.layers:
for param in layer.learningParams:
self.learningParams.append(param)
#Connect each layer's input to the previous layer's output.
for i in xrange(1, self.numLayers):
nextLayer = layers[i]
previousLayer = layers[i-1]
nextLayer.input = previousLayer.output
|
Add first code for NeuralNetwork class.
|
Add first code for NeuralNetwork class.
|
Python
|
cc0-1.0
|
cn04/insanity
|
cdaeb29474df423e66cbc79fffa74d937fe2193c
|
justitie/just/pipelines.py
|
justitie/just/pipelines.py
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import requests
import json
from just.items import JustPublication
import logging
API_KEY = 'justitie-very-secret-key'
API_PUBLICATIONS = 'http://czl-api.code4.ro/api/publications/'
class JustPublicationsToApiPipeline(object):
def process_item(self, item, spider):
if type(item) != JustPublication:
return item
r = requests.post(API_PUBLICATIONS, json=dict(item), headers={'Authorization': 'Token %s' % (API_KEY,) } )
return item
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import requests
import json
import logging
from just.items import JustPublication
import logging
API_KEY = 'justitie-very-secret-key'
API_PUBLICATIONS = 'http://czl-api.code4.ro/api/publications/'
class JustPublicationsToApiPipeline(object):
def process_item(self, item, spider):
if type(item) != JustPublication:
return item
r = requests.post(API_PUBLICATIONS, json=dict(item), headers={'Authorization': 'Token %s' % (API_KEY,) } )
api_log = logging.getLogger('api-log.txt')
if r.status_code == 200 or r.status_code == '200':
api_log.log(r.status_code, level=logging.INFO)
else:
api_log.log(r.status_code, level=logging.ERROR)
api_log.log(r.content, level=logging.INFO)
return item
|
Add logging for api calls.
|
Add logging for api calls.
|
Python
|
mpl-2.0
|
mgax/czl-scrape,margelatu/czl-scrape,costibleotu/czl-scrape,mgax/czl-scrape,code4romania/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,lbogdan/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,code4romania/czl-scrape,code4romania/czl-scrape,code4romania/czl-scrape,lbogdan/czl-scrape,margelatu/czl-scrape,margelatu/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,costibleotu/czl-scrape,margelatu/czl-scrape,costibleotu/czl-scrape,costibleotu/czl-scrape
|
837efcddd6c111dabf14a6017d0ae2f6aacbddac
|
konstrukteur/HtmlParser.py
|
konstrukteur/HtmlParser.py
|
#
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
__all__ = ["parse"]
from jasy.env.State import session
from jasy.core import Console
from bs4 import BeautifulSoup
def parse(filename):
""" HTML parser class for Konstrukteur """
page = {}
parsedContent = BeautifulSoup(open(filename, "rt").read())
body = parsedContent.find("body")
page["content"] = "".join([str(tag) for tag in body.contents])
page["title"] = parsedContent.title.string
page["summary"] = body.p.get_text()
for meta in parsedContent.find_all("meta"):
page[meta["name"].lower()] = meta["contents"]
return page
|
#
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
__all__ = ["parse"]
from jasy.env.State import session
from jasy.core import Console
from bs4 import BeautifulSoup
def parse(filename):
""" HTML parser class for Konstrukteur """
page = {}
parsedContent = BeautifulSoup(open(filename, "rt").read())
body = parsedContent.find("body")
page["content"] = "".join([str(tag) for tag in body.contents])
page["title"] = parsedContent.title.string
page["summary"] = body.p.get_text()
for meta in parsedContent.find_all("meta"):
if not hasattr(meta, "name") or not hasattr(meta, "content"):
raise RuntimeError("Meta elements must have attributes name and content : %s" % filename)
page[meta["name"].lower()] = meta["content"]
return page
|
Add detection of wrong meta data
|
Add detection of wrong meta data
|
Python
|
mit
|
fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur
|
a31db91800630520c5b516493bddef76ba8b7edd
|
flask_oauthlib/utils.py
|
flask_oauthlib/utils.py
|
# coding: utf-8
import logging
import base64
from flask import request, Response
from oauthlib.common import to_unicode, bytes_type
log = logging.getLogger('flask_oauthlib')
def extract_params():
"""Extract request params."""
uri = request.url
http_method = request.method
headers = dict(request.headers)
if 'wsgi.input' in headers:
del headers['wsgi.input']
if 'wsgi.errors' in headers:
del headers['wsgi.errors']
if 'Http-Authorization' in headers:
headers['Authorization'] = headers['Http-Authorization']
body = request.form.to_dict()
return uri, http_method, body, headers
def decode_base64(text):
"""Decode base64 string."""
# make sure it is bytes
if not isinstance(text, bytes_type):
text = text.encode('utf-8')
return to_unicode(base64.b64decode(text), 'utf-8')
def create_response(headers, body, status):
"""Create response class for Flask."""
response = Response(body or '')
for k, v in headers.items():
response.headers[k] = v
response.status_code = status
return response
|
# coding: utf-8
import logging
import base64
from flask import request, Response
from oauthlib.common import to_unicode, bytes_type
log = logging.getLogger('flask_oauthlib')
def extract_params():
"""Extract request params."""
uri = request.url
http_method = request.method
headers = dict(request.headers)
if 'wsgi.input' in headers:
del headers['wsgi.input']
if 'wsgi.errors' in headers:
del headers['wsgi.errors']
body = request.form.to_dict()
return uri, http_method, body, headers
def decode_base64(text):
"""Decode base64 string."""
# make sure it is bytes
if not isinstance(text, bytes_type):
text = text.encode('utf-8')
return to_unicode(base64.b64decode(text), 'utf-8')
def create_response(headers, body, status):
"""Create response class for Flask."""
response = Response(body or '')
for k, v in headers.items():
response.headers[k] = v
response.status_code = status
return response
|
Delete useless header transform in extract_params.
|
Delete useless header transform in extract_params.
|
Python
|
bsd-3-clause
|
auerj/flask-oauthlib,auerj/flask-oauthlib,kevin1024/flask-oauthlib,stianpr/flask-oauthlib,CoreyHyllested/flask-oauthlib,lepture/flask-oauthlib,Ryan-K/flask-oauthlib,tonyseek/flask-oauthlib,RealGeeks/flask-oauthlib,adambard/flask-oauthlib,huxuan/flask-oauthlib,PyBossa/flask-oauthlib,Fleurer/flask-oauthlib,CoreyHyllested/flask-oauthlib,RealGeeks/flask-oauthlib,brightforme/flask-oauthlib,huxuan/flask-oauthlib,icook/flask-oauthlib,adambard/flask-oauthlib,CommonsCloud/CommonsCloud-FlaskOAuthlib,PyBossa/flask-oauthlib,icook/flask-oauthlib,tonyseek/flask-oauthlib,brightforme/flask-oauthlib,cogniteev/flask-oauthlib,landler/flask-oauthlib,cogniteev/flask-oauthlib,stianpr/flask-oauthlib,CommonsCloud/CommonsCloud-FlaskOAuthlib,landler/flask-oauthlib,lepture/flask-oauthlib,Fleurer/flask-oauthlib,kevin1024/flask-oauthlib,Ryan-K/flask-oauthlib
|
a91a04af6b95fa600a0b3ce74b5fffc07ecf590e
|
polymorphic/__init__.py
|
polymorphic/__init__.py
|
# -*- coding: utf-8 -*-
"""
Seamless Polymorphic Inheritance for Django Models
Copyright:
This code and affiliated files are (C) by Bert Constantin and individual contributors.
Please see LICENSE and AUTHORS for more information.
"""
# See PEP 440 (https://www.python.org/dev/peps/pep-0440/)
__version__ = "1.3"
|
# -*- coding: utf-8 -*-
"""
Seamless Polymorphic Inheritance for Django Models
Copyright:
This code and affiliated files are (C) by Bert Constantin and individual contributors.
Please see LICENSE and AUTHORS for more information.
"""
import pkg_resources
__version__ = pkg_resources.require("django-polymorphic")[0].version
|
Set polymorphic.__version__ from setuptools metadata
|
Set polymorphic.__version__ from setuptools metadata
|
Python
|
bsd-3-clause
|
skirsdeda/django_polymorphic,skirsdeda/django_polymorphic,skirsdeda/django_polymorphic,chrisglass/django_polymorphic,chrisglass/django_polymorphic
|
8cb680c7fbadfe6cfc245fe1eb1261a00c5ffd6d
|
djmoney/forms/fields.py
|
djmoney/forms/fields.py
|
from __future__ import unicode_literals
from warnings import warn
from django.forms import MultiValueField, DecimalField, ChoiceField
from moneyed.classes import Money
from .widgets import MoneyWidget, CURRENCY_CHOICES
__all__ = ('MoneyField',)
class MoneyField(MultiValueField):
def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES,
max_value=None, min_value=None,
max_digits=None, decimal_places=None, *args, **kwargs):
if currency_choices != CURRENCY_CHOICES:
warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning)
choices = currency_choices
decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs)
choice_field = ChoiceField(choices=currency_choices)
self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget,
currency_widget=choice_field.widget)
fields = (decimal_field, choice_field)
super(MoneyField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
return Money(*data_list[:2])
|
from __future__ import unicode_literals
from warnings import warn
from django.forms import MultiValueField, DecimalField, ChoiceField
from moneyed.classes import Money
from .widgets import MoneyWidget, CURRENCY_CHOICES
__all__ = ('MoneyField',)
class MoneyField(MultiValueField):
def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES,
max_value=None, min_value=None,
max_digits=None, decimal_places=None, *args, **kwargs):
if currency_choices != CURRENCY_CHOICES:
warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning)
choices = currency_choices
decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs)
choice_field = ChoiceField(choices=currency_choices)
self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget,
currency_widget=choice_field.widget)
fields = (decimal_field, choice_field)
super(MoneyField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
try:
if data_list[0] is None:
return None
except IndexError:
return None
return Money(*data_list[:2])
|
Support for value of None in MoneyField.compress. Leaving a MoneyField blank in the Django admin site caused an issue when attempting to save an exception was raised since Money was getting an argument list of None.
|
Support for value of None in MoneyField.compress.
Leaving a MoneyField blank in the Django admin site caused an issue when
attempting to save an exception was raised since Money was getting an
argument list of None.
|
Python
|
bsd-3-clause
|
recklessromeo/django-money,rescale/django-money,iXioN/django-money,AlexRiina/django-money,tsouvarev/django-money,iXioN/django-money,tsouvarev/django-money,recklessromeo/django-money
|
98ca37ed174e281542df2f1026a298387845b524
|
rmgpy/tools/data/generate/input.py
|
rmgpy/tools/data/generate/input.py
|
# Data sources for kinetics
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = 'default',
#this section lists possible reaction families to find reactioons with
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List all species you want reactions between
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
species(
label='H',
reactive=True,
structure=SMILES("[H]"),
)
species(
label='butane',
reactive=True,
structure=SMILES("CCCC"),
)
# you must list reactor conditions (though this may not effect the output)
simpleReactor(
temperature=(650,'K'),
pressure=(10.0,'bar'),
initialMoleFractions={
"ethane": 1,
},
terminationConversion={
'butane': .99,
},
terminationTime=(40,'s'),
)
|
# Data sources for kinetics
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = 'default',
#this section lists possible reaction families to find reactioons with
kineticsFamilies = ['R_Recombination'],
kineticsEstimator = 'rate rules',
)
# List all species you want reactions between
species(
label='Propyl',
reactive=True,
structure=SMILES("CC[CH3]"),
)
species(
label='H',
reactive=True,
structure=SMILES("[H]"),
)
# you must list reactor conditions (though this may not effect the output)
simpleReactor(
temperature=(650,'K'),
pressure=(10.0,'bar'),
initialMoleFractions={
"Propyl": 1,
},
terminationConversion={
'Propyl': .99,
},
terminationTime=(40,'s'),
)
|
Cut down on the loading of families in the normal GenerateReactionsTest
|
Cut down on the loading of families in the normal GenerateReactionsTest
Change generateReactions input reactant to propyl
|
Python
|
mit
|
nickvandewiele/RMG-Py,nyee/RMG-Py,pierrelb/RMG-Py,chatelak/RMG-Py,pierrelb/RMG-Py,nickvandewiele/RMG-Py,chatelak/RMG-Py,nyee/RMG-Py
|
25695e927fbbf46df385b4c68fa4d80b81283ace
|
indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_source_column.py
|
indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_source_column.py
|
"""Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
class _ProfilePictureSource(int, Enum):
standard = 0
identicon = 1
gravatar = 2
custom = 3
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
|
"""Add column for profile picture type to User
Revision ID: f37d509e221c
Revises: c997dc927fbc
Create Date: 2020-09-04 15:43:18.413156
"""
from enum import Enum
import sqlalchemy as sa
from alembic import op
from werkzeug.http import http_date
from indico.core.db.sqlalchemy import PyIntEnum
from indico.util.date_time import now_utc
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
class _ProfilePictureSource(int, Enum):
standard = 0
identicon = 1
gravatar = 2
custom = 3
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
op.execute('''
UPDATE users.users
SET picture_metadata = picture_metadata || '{"lastmod": "%s"}'::jsonb
WHERE picture_source = 3 AND NOT (picture_metadata ? 'lastmod')
''' % http_date(now_utc()))
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
|
Add lastmod to existing profile picture metadata
|
Add lastmod to existing profile picture metadata
|
Python
|
mit
|
pferreir/indico,indico/indico,pferreir/indico,indico/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,ThiefMaster/indico,ThiefMaster/indico,pferreir/indico,pferreir/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,DirkHoffmann/indico,DirkHoffmann/indico
|
6384fd52a4d271f0f3403ae613dd66cbeb217ddf
|
indra/tests/test_biogrid.py
|
indra/tests/test_biogrid.py
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.databases import biogrid_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
from indra.sources.biogrid import process_file
from indra.statements import Complex
import os
this_dir = os.path.dirname(__file__)
test_file = os.path.join(this_dir, 'biogrid_tests_data/biogrid_test.txt')
@attr('webservice', 'nonpublic')
def test_biogrid_request():
results = biogrid_client._send_request(['MAP2K1', 'MAPK1'])
assert results is not None
assert unicode_strs(results)
def test_biogrid_tsv():
# Download biogrid file form the web and process it
bp = process_file(test_file)
# There are 50 statements in that file
statements = bp.statements
assert(len(statements) == 50)
# Any given statement should be a complex, with appropriate evidence
s0 = statements[0]
assert(isinstance(s0, Complex))
ev = s0.evidence[0]
assert(ev.source_api == 'biogrid')
assert(ev.text is None)
assert(ev.pmid is not None)
# The first statement in the file involves MAP2K4 and FLNC
assert(str(s0.members[0]) == 'MAP2K4()')
assert(str(s0.members[1]) == 'FLNC()')
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
from nose.plugins.attrib import attr
from indra.statements import Complex
from indra.databases import biogrid_client
from indra.util import unicode_strs
from indra.sources.biogrid import BiogridProcessor
this_dir = os.path.dirname(__file__)
test_file = os.path.join(this_dir, 'biogrid_tests_data/biogrid_test.txt')
@attr('webservice', 'nonpublic')
def test_biogrid_request():
results = biogrid_client._send_request(['MAP2K1', 'MAPK1'])
assert results is not None
assert unicode_strs(results)
def test_biogrid_tsv():
# Download biogrid file form the web and process it
bp = BiogridProcessor(test_file)
# There are 50 statements in that file
statements = bp.statements
assert(len(statements) == 50)
# Any given statement should be a complex, with appropriate evidence
s0 = statements[0]
assert(isinstance(s0, Complex))
ev = s0.evidence[0]
assert(ev.source_api == 'biogrid')
assert(ev.text is None)
assert(ev.pmid is not None)
# The first statement in the file involves MAP2K4 and FLNC
assert(str(s0.members[0]) == 'MAP2K4()')
assert(str(s0.members[1]) == 'FLNC()')
|
Update test to use new API
|
Update test to use new API
|
Python
|
bsd-2-clause
|
johnbachman/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy
|
79c8d40d8a47a4413540acac671345dd5faed46e
|
suorganizer/urls.py
|
suorganizer/urls.py
|
"""suorganizer 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 organizer.views import homepage, tag_detail
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', homepage),
url(r'^tag/(?P<slug>[\w\-]+)/$',
tag_detail,
),
]
|
"""suorganizer 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 organizer.views import homepage, tag_detail
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', homepage),
url(r'^tag/(?P<slug>[\w\-]+)/$',
tag_detail,
name='organizer_tag_detail'),
]
|
Add name parameter to Tag Detail URL.
|
Ch05: Add name parameter to Tag Detail URL.
|
Python
|
bsd-2-clause
|
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
|
75c48ecbac476fd751e55745cc2935c1dac1f138
|
longest_duplicated_substring.py
|
longest_duplicated_substring.py
|
#!/usr/bin/env python
import sys
# O(n^4) approach: generate all possible substrings and
# compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
# Alternate approach with while loop here and max update outside.
# Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
#!/usr/bin/env python
import sys
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
Move todos into issues tracking on GitHub
|
Move todos into issues tracking on GitHub
|
Python
|
mit
|
taylor-peterson/longest-duplicated-substring
|
847a88c579118f8a0d528284ab3ea029ccca7215
|
git_pre_commit_hook/builtin_plugins/rst_check.py
|
git_pre_commit_hook/builtin_plugins/rst_check.py
|
import os
import fnmatch
import restructuredtext_lint
DEFAULTS = {
'files': '*.rst',
}
def make_message(error):
return '%s %s:%s %s\n' % (
error.type, error.source, error.line, error.message,
)
def check(file_staged_for_commit, options):
basename = os.path.basename(file_staged_for_commit.path)
if not fnmatch.fnmatch(basename, options.rst_files):
return True
errors = restructuredtext_lint.lint(
file_staged_for_commit.contents,
file_staged_for_commit.path,
)
if errors:
print('\n'.join(make_message(e) for e in errors))
return False
else:
return True
|
"""Check that files contains valid ReStructuredText."""
import os
import fnmatch
import restructuredtext_lint
DEFAULTS = {
'files': '*.rst',
}
def make_message(error):
return '%s %s:%s %s\n' % (
error.type, error.source, error.line, error.message,
)
def check(file_staged_for_commit, options):
basename = os.path.basename(file_staged_for_commit.path)
if not fnmatch.fnmatch(basename, options.rst_files):
return True
errors = restructuredtext_lint.lint(
file_staged_for_commit.contents,
file_staged_for_commit.path,
)
if errors:
print('\n'.join(make_message(e) for e in errors))
return False
else:
return True
|
Add description to rst plugin
|
Add description to rst plugin
|
Python
|
mit
|
evvers/git-pre-commit-hook
|
bc7b1fc053150728095ec5d0a41611aa4d4ede45
|
kerrokantasi/settings/__init__.py
|
kerrokantasi/settings/__init__.py
|
from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi":
raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.")
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video,dialog,fakeobjects,iframe',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
|
from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
"element": 'p',
"attributes": {'class': 'lead'},
},
],
'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'],
'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);',
'extraPlugins': 'video,dialog,fakeobjects,iframe',
'toolbar': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'],
['Link', 'Unlink', 'Anchor'],
['BulletedList', 'NumberedList'],
['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'],
['TextColor', 'BGColor'],
['Smiley', 'SpecialChar'],
['Source']
]
},
}
globals().update(settings) # Export the settings for Django to use.
|
Remove JWT_AUTH check from settings
|
Remove JWT_AUTH check from settings
JWT settings has been removed in OpenID change and currently there isn't use for this.
|
Python
|
mit
|
City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi
|
c0fc60aa5fd51ac9a5795017fdc57d5b89b300e7
|
tests/check_locale_format_consistency.py
|
tests/check_locale_format_consistency.py
|
import re
import json
import glob
locale_folder = "../locales/"
locale_files = glob.glob(locale_folder + "*.json")
locale_files = [filename.split("/")[-1] for filename in locale_files]
locale_files.remove("en.json")
reference = json.loads(open(locale_folder + "en.json").read())
for locale_file in locale_files:
this_locale = json.loads(open(locale_folder + locale_file).read())
for key, string in reference.items():
if key in this_locale:
subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string))
subkeys_in_this_locale = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key]))
if any(key not in subkeys_in_ref for key in subkeys_in_this_locale):
print("\n")
print("==========================")
print("Format inconsistency for string %s in %s:" % (key, locale_file))
print("%s -> %s " % ("en.json", string))
print("%s -> %s " % (locale_file, this_locale[key]))
|
import re
import json
import glob
# List all locale files (except en.json being the ref)
locale_folder = "../locales/"
locale_files = glob.glob(locale_folder + "*.json")
locale_files = [filename.split("/")[-1] for filename in locale_files]
locale_files.remove("en.json")
reference = json.loads(open(locale_folder + "en.json").read())
found_inconsistencies = False
# Let's iterate over each locale file
for locale_file in locale_files:
this_locale = json.loads(open(locale_folder + locale_file).read())
# We iterate over all keys/string in en.json
for key, string in reference.items():
# If there is a translation available for this key/string
if key in this_locale:
# Then we check that every "{stuff}" (for python's .format())
# should also be in the translated string, otherwise the .format
# will trigger an exception!
subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string))
subkeys_in_this_locale = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key]))
if any(key not in subkeys_in_ref for key in subkeys_in_this_locale):
found_inconsistencies = True
print("\n")
print("==========================")
print("Format inconsistency for string %s in %s:" % (key, locale_file))
print("%s -> %s " % ("en.json", string))
print("%s -> %s " % (locale_file, this_locale[key]))
if found_inconsistencies:
sys.exit(1)
|
Add comments + return 1 if inconsistencies found
|
Add comments + return 1 if inconsistencies found
|
Python
|
agpl-3.0
|
YunoHost/yunohost,YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost
|
423dcb102fc2b7a1108a0b0fe1e116e8a5d451c9
|
netsecus/korrekturtools.py
|
netsecus/korrekturtools.py
|
from __future__ import unicode_literals
import os
def readStatus(student):
student = student.lower()
if not os.path.exists("attachments"):
return
if not os.path.exists(os.path.join("attachments", student)):
return "Student ohne Abgabe"
if not os.path.exists(os.path.join("attachments", student, "korrekturstatus.txt")):
return "Unbearbeitet"
statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(student, status):
student = student.lower()
status = status.lower()
if not os.path.exists(os.path.join("attachments", student)):
return
statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "w")
statusfile.write(status)
statusfile.close()
|
from __future__ import unicode_literals
import os
from . import helper
def readStatus(student):
student = student.lower()
if not os.path.exists("attachments"):
return
if not os.path.exists(os.path.join("attachments", student)):
return "Student ohne Abgabe"
if not os.path.exists(os.path.join("attachments", student, "korrekturstatus.txt")):
return "Unbearbeitet"
statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(student, status):
student = student.lower()
status = status.lower()
if not os.path.exists(os.path.join("attachments", student)):
logging.error("Requested student '%s' hasn't submitted anything yet.")
return
statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "w")
statusfile.write(status)
statusfile.close()
|
Add error message for malformed request
|
Add error message for malformed request
|
Python
|
mit
|
hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem
|
3cbc3b96d3f91c940c5d762ce08da9814c29b04d
|
utils/gyb_syntax_support/protocolsMap.py
|
utils/gyb_syntax_support/protocolsMap.py
|
SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = {
'ExpressibleByConditionElement': [
'ExpressibleByConditionElementList'
],
'ExpressibleByDeclBuildable': [
'ExpressibleByCodeBlockItem',
'ExpressibleByMemberDeclListItem',
'ExpressibleBySyntaxBuildable'
],
'ExpressibleByStmtBuildable': [
'ExpressibleByCodeBlockItem',
'ExpressibleBySyntaxBuildable'
],
'ExpressibleByExprList': [
'ExpressibleByConditionElement',
'ExpressibleBySyntaxBuildable'
]
}
|
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'ExpressibleAsConditionElement': [
'ExpressibleAsConditionElementList'
],
'ExpressibleAsDeclBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsMemberDeclListItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsStmtBuildable': [
'ExpressibleAsCodeBlockItem',
'ExpressibleAsSyntaxBuildable'
],
'ExpressibleAsExprList': [
'ExpressibleAsConditionElement',
'ExpressibleAsSyntaxBuildable'
]
}
|
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
|
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
|
Python
|
apache-2.0
|
roambotics/swift,glessard/swift,ahoppen/swift,roambotics/swift,apple/swift,roambotics/swift,gregomni/swift,ahoppen/swift,JGiola/swift,JGiola/swift,apple/swift,gregomni/swift,benlangmuir/swift,gregomni/swift,glessard/swift,atrick/swift,benlangmuir/swift,ahoppen/swift,atrick/swift,benlangmuir/swift,gregomni/swift,atrick/swift,glessard/swift,rudkx/swift,benlangmuir/swift,glessard/swift,apple/swift,benlangmuir/swift,ahoppen/swift,rudkx/swift,roambotics/swift,roambotics/swift,glessard/swift,glessard/swift,ahoppen/swift,atrick/swift,apple/swift,JGiola/swift,JGiola/swift,rudkx/swift,atrick/swift,rudkx/swift,gregomni/swift,rudkx/swift,rudkx/swift,roambotics/swift,atrick/swift,gregomni/swift,apple/swift,JGiola/swift,ahoppen/swift,JGiola/swift,apple/swift,benlangmuir/swift
|
1b3f97ff7bc219588b94a2346ac91f10203e44b9
|
matador/commands/deployment/__init__.py
|
matador/commands/deployment/__init__.py
|
from .deploy_sql_script import DeploySqlScript, DeployOraclePackage
from .deploy_report import DeployExceleratorReport
|
from .deploy_sql_script import DeploySqlScript, DeployOraclePackage
from .deploy_report import DeployExceleratorReport, DeployReportFile
|
Add report file deployment to init
|
Add report file deployment to init
|
Python
|
mit
|
Empiria/matador
|
7ea03c6ded823458d7159c05f89d99ee3c4a2e42
|
scripts/tools/botmap.py
|
scripts/tools/botmap.py
|
#!/usr/bin/env python
import os
import sys
path = os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')
sys.path.append(path)
import chromium_utils
slaves = []
for master in chromium_utils.ListMasters():
masterbase = os.path.basename(master)
master_slaves = {}
execfile(os.path.join(master, 'slaves.cfg'), master_slaves)
for slave in master_slaves.get('slaves', []):
slave['master'] = masterbase
slaves.extend(master_slaves.get('slaves', []))
for slave in sorted(slaves, cmp=None, key=lambda x : x.get('hostname', '')):
slavename = slave.get('hostname')
if not slavename:
continue
osname = slave.get('os', '?')
print '%-30s %-35s %-10s' % (slavename, slave.get('master', '?'), osname)
|
#!/usr/bin/env python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Dumps a list of known slaves, along with their OS and master."""
import os
import sys
path = os.path.join(os.path.dirname(__file__), os.path.pardir)
sys.path.append(path)
from common import chromium_utils
slaves = []
for master in chromium_utils.ListMasters():
masterbase = os.path.basename(master)
master_slaves = {}
execfile(os.path.join(master, 'slaves.cfg'), master_slaves)
for slave in master_slaves.get('slaves', []):
slave['master'] = masterbase
slaves.extend(master_slaves.get('slaves', []))
for slave in sorted(slaves, cmp=None, key=lambda x : x.get('hostname', '')):
slavename = slave.get('hostname')
if not slavename:
continue
osname = slave.get('os', '?')
print '%-30s %-35s %-10s' % (slavename, slave.get('master', '?'), osname)
|
Tweak import statement to satisfy presubmit checks.
|
Tweak import statement to satisfy presubmit checks.
Review URL: http://codereview.chromium.org/8292004
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@105578 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
6fc5a47efbd4b760672b13292c5c4886842fbdbd
|
tests/local_test.py
|
tests/local_test.py
|
from nose.tools import istest, assert_equal
from spur import LocalShell
shell = LocalShell()
@istest
def output_of_run_is_stored():
result = shell.run(["echo", "hello"])
assert_equal("hello\n", result.output)
@istest
def cwd_of_run_can_be_set():
result = shell.run(["pwd"], cwd="/")
assert_equal("/\n", result.output)
|
from nose.tools import istest, assert_equal
from spur import LocalShell
shell = LocalShell()
@istest
def output_of_run_is_stored():
result = shell.run(["echo", "hello"])
assert_equal("hello\n", result.output)
@istest
def cwd_of_run_can_be_set():
result = shell.run(["pwd"], cwd="/")
assert_equal("/\n", result.output)
@istest
def environment_variables_can_be_added_for_run():
result = shell.run(["sh", "-c", "echo $NAME"], update_env={"NAME": "Bob"})
assert_equal("Bob\n", result.output)
|
Add test for LocalShell.run with update_env
|
Add test for LocalShell.run with update_env
|
Python
|
bsd-2-clause
|
mwilliamson/spur.py
|
f55d590004874f9ec64c041b5630321e686bf6f9
|
mindbender/plugins/validate_id.py
|
mindbender/plugins/validate_id.py
|
import pyblish.api
class ValidateMindbenderID(pyblish.api.InstancePlugin):
"""All models must have an ID attribute"""
label = "Mindbender ID"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = ["mindbender.model"]
def process(self, instance):
from maya import cmds
nodes = list(instance)
nodes += cmds.listRelatives(instance, allDescendents=True) or list()
missing = list()
for node in nodes:
# Only check transforms with a shape
if not cmds.listRelatives(node, shapes=True):
continue
try:
self.log.info("Checking '%s'" % node)
cmds.getAttr(node + ".mbID")
except ValueError:
missing.append(node)
assert not missing, ("Missing ID attribute on: %s"
% ", ".join(missing))
|
import pyblish.api
class ValidateMindbenderID(pyblish.api.InstancePlugin):
"""All models must have an ID attribute"""
label = "Mindbender ID"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = ["mindbender.model", "mindbender.lookdev"]
def process(self, instance):
from maya import cmds
nodes = list(instance)
nodes += cmds.listRelatives(instance, allDescendents=True) or list()
missing = list()
for node in nodes:
# Only check transforms with a shape
if not cmds.listRelatives(node, shapes=True):
continue
try:
self.log.info("Checking '%s'" % node)
cmds.getAttr(node + ".mbID")
except ValueError:
missing.append(node)
assert not missing, ("Missing ID attribute on: %s"
% ", ".join(missing))
|
Extend ID validator to lookdev
|
Extend ID validator to lookdev
|
Python
|
mit
|
mindbender-studio/core,MoonShineVFX/core,mindbender-studio/core,getavalon/core,MoonShineVFX/core,getavalon/core,pyblish/pyblish-mindbender
|
09be419960d208967771d93025c4f86b80ebe4e9
|
python/qibuild/__init__.py
|
python/qibuild/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" This module contains a few functions for running CMake and building projects. """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
QIBUILD_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
def stringify_env(env):
""" convert each key value pairs to strings in env list"""
return dict(((str(key), str(val)) for key, val in env.items()))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" This module contains a few functions for running CMake and building projects. """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
QIBUILD_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
def stringify_env(env):
""" convert each key value pairs to strings in env list"""
return dict(((str(key), str(val)) for key, val in env.items()))
|
Revert "use utf-8 by default"
|
Revert "use utf-8 by default"
This reverts commit a986aac5e3b4f065d6c2ab70129bde105651d2ca.
|
Python
|
bsd-3-clause
|
aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild
|
c7cb6c1441bcfe359a9179858492044591e80007
|
osgtest/tests/test_10_condor.py
|
osgtest/tests/test_10_condor.py
|
from os.path import join
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.condor as condor
import osgtest.library.osgunittest as osgunittest
import osgtest.library.service as service
personal_condor_config = '''
DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD
CONDOR_HOST = $(FULL_HOSTNAME)
'''
class TestStartCondor(osgunittest.OSGTestCase):
def test_01_start_condor(self):
core.state['condor.running-service'] = False
core.skip_ok_unless_installed('condor')
core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG')
if service.is_running('condor'):
core.state['condor.running-service'] = True
return
core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf')
files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor')
core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog'])
service.check_start('condor')
core.state['condor.started-service'] = True
core.state['condor.running-service'] = True
|
from os.path import join
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.condor as condor
import osgtest.library.osgunittest as osgunittest
import osgtest.library.service as service
personal_condor_config = '''
DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD
CONDOR_HOST = $(FULL_HOSTNAME)
'''
class TestStartCondor(osgunittest.OSGTestCase):
def test_01_start_condor(self):
core.state['condor.running-service'] = False
core.skip_ok_unless_installed('condor')
core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG')
if service.is_running('condor'):
core.state['condor.running-service'] = True
return
core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf')
files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor', chmod=0o644)
core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog'])
service.check_start('condor')
core.state['condor.started-service'] = True
core.state['condor.running-service'] = True
|
Make the personal condor config world readable
|
Make the personal condor config world readable
|
Python
|
apache-2.0
|
efajardo/osg-test,efajardo/osg-test
|
d8b477083866a105947281ca34cb6e215417f44d
|
packs/salt/actions/lib/utils.py
|
packs/salt/actions/lib/utils.py
|
import yaml
action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Runner functions through Salt API",
"enabled": True,
"entry_point": "runner.py"}
def generate_action(module_type, action):
manifest = action_meta
manifest['name'] = "{0}_{1}".format(module_type, action)
manifest['parameters']['action']['default'] = action
fh = open('{0}_{1}.yaml'.format(module_type, action), 'w')
fh.write('---\n')
fh.write(yaml.dump(manifest, default_flow_style=False))
fh.close()
def sanitize_payload(keys_to_sanitize, payload):
data = payload.copy()
map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize)
return data
|
# pylint: disable=line-too-long
import yaml
from .meta import actions
runner_action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Runner functions through Salt API",
"enabled": True,
"entry_point": "runner.py"}
local_action_meta = {
"name": "",
"parameters": {
"action": {
"type": "string",
"immutable": True,
"default": ""
},
"args": {
"type": "array",
"required": False
},
"kwargs": {
"type": "object",
"required": False
}
},
"runner_type": "run-python",
"description": "Run Salt Execution modules through Salt API",
"enabled": True,
"entry_point": "local.py"}
def generate_actions():
def create_file(mt, m, a):
manifest = local_action_meta
manifest['name'] = "{0}_{1}.{2}".format(mt, m, a)
manifest['parameters']['action']['default'] = "{0}.{1}".format(m, a)
fh = open('{0}_{1}.{2}.yaml'.format(mt, m, a), 'w')
fh.write('---\n')
fh.write(yaml.dump(manifest, default_flow_style=False))
fh.close()
for key in actions:
map(lambda l: create_file('local', key, l), actions[key])
def sanitize_payload(keys_to_sanitize, payload):
'''
Removes sensitive data from payloads before
publishing to the logs
'''
data = payload.copy()
map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize)
return data
|
Make distinction between local and runner action payload templates. Added small description for sanitizing the NetAPI payload for logging.
|
Make distinction between local and runner action payload templates.
Added small description for sanitizing the NetAPI payload for logging.
|
Python
|
apache-2.0
|
pidah/st2contrib,StackStorm/st2contrib,psychopenguin/st2contrib,lmEshoo/st2contrib,armab/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,digideskio/st2contrib,digideskio/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,lmEshoo/st2contrib,tonybaloney/st2contrib,psychopenguin/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,StackStorm/st2contrib,pidah/st2contrib
|
60625877a23e26e66c2c97cbeb4f139ede717eda
|
B.py
|
B.py
|
#! /usr/bin/env python3
# coding: utf-8
from collections import namedtuple
import matplotlib.pyplot as plt
BCand = namedtuple('BCand', ['m', 'merr', 'pt', 'p'])
bs = []
with open('B.txt') as f:
for line in f.readlines()[1:]:
bs.append(BCand(*[float(v) for v in line.strip().split(',')]))
masses = [b.m for b in bs]
plt.hist(masses, 60, histtype='stepfilled')
plt.xlabel(r'$m_B / \mathrm{GeV}$')
plt.savefig('mass.pdf')
|
#! /usr/bin/env python3
# coding: utf-8
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
BCand = namedtuple('BCand', ['m', 'merr', 'pt', 'p'])
bs = [BCand(*b) for b in np.genfromtxt('B.txt', skip_header=1, delimiter=',')]
masses = [b.m for b in bs]
ns, bins, _ = plt.hist(masses, 60, histtype='stepfilled', facecolor='r',
edgecolor='none')
centers = bins[:-1] + (bins[1:] - bins[:-1]) / 2
merr = np.sqrt(ns)
plt.errorbar(centers, ns, yerr=merr, fmt='b+')
plt.xlabel(r'$m_B / \mathrm{GeV}$')
plt.savefig('mass.pdf')
|
Use numpy for readin and add errorbars.
|
Use numpy for readin and add errorbars.
|
Python
|
mit
|
bixel/python-introduction
|
2dcb159bdd826ceeb68658cc3760c97dae04289e
|
partner_firstname/exceptions.py
|
partner_firstname/exceptions.py
|
# -*- encoding: utf-8 -*-
# Odoo, Open Source Management Solution
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from openerp import _, exceptions
class EmptyNamesError(exceptions.ValidationError):
def __init__(self, record, value=_("No name is set.")):
self.record = record
self._value = value
self.name = _("Error(s) with partner %d's name.") % record.id
|
# -*- encoding: utf-8 -*-
# Odoo, Open Source Management Solution
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from openerp import _, exceptions
class EmptyNamesError(exceptions.ValidationError):
def __init__(self, record, value=_("No name is set.")):
self.record = record
self._value = value
self.name = _("Error(s) with partner %d's name.") % record.id
self.args = (self.name, value)
|
Add args to exception to display the correct message in the UI.
|
Add args to exception to display the correct message in the UI.
|
Python
|
agpl-3.0
|
BT-ojossen/partner-contact,Ehtaga/partner-contact,BT-fgarbely/partner-contact,acsone/partner-contact,BT-jmichaud/partner-contact,charbeljc/partner-contact,sergiocorato/partner-contact,Antiun/partner-contact,raycarnes/partner-contact,idncom/partner-contact,Endika/partner-contact,gurneyalex/partner-contact,QANSEE/partner-contact,Therp/partner-contact,alanljj/oca-partner-contact,diagramsoftware/partner-contact,akretion/partner-contact,andrius-preimantas/partner-contact,open-synergy/partner-contact
|
7a17facf68a90d246b4bee55491c9495a8c5ca50
|
tg/dottednames/jinja_lookup.py
|
tg/dottednames/jinja_lookup.py
|
"""Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based on Genshi Loader
"""
template_extension = '.html'
def get_source(self, environment, template):
# Check if dottedname
if not template.endswith(self.template_extension):
# Get the actual filename from dotted finder
finder = config['pylons.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
template_name=template,
template_extension=self.template_extension)
else:
return FileSystemLoader.get_source(self, environment, template)
# Check if the template exists
if not exists(template):
raise TemplateNotFound(template)
# Get modification time
mtime = getmtime(template)
# Read the source
with file(template, "r") as fd:
source = fd.read().decode('utf-8')
return source, template, lambda: mtime == getmtime(template)
|
"""Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based on Genshi Loader
"""
template_extension = '.html'
def get_source(self, environment, template):
# Check if dottedname
if not template.endswith(self.template_extension):
# Get the actual filename from dotted finder
finder = config['pylons.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
template_name=template,
template_extension=self.template_extension)
else:
return FileSystemLoader.get_source(self, environment, template)
# Check if the template exists
if not exists(template):
raise TemplateNotFound(template)
# Get modification time
mtime = getmtime(template)
# Read the source
fd = file(template)
try:
source = fd.read().decode('utf-8')
finally:
fd.close()
return source, template, lambda: mtime == getmtime(template)
|
Make JinjaTemplateLoader work with Python 2.4.
|
Make JinjaTemplateLoader work with Python 2.4.
|
Python
|
mit
|
lucius-feng/tg2,lucius-feng/tg2
|
ddb64a0b7a09203c8367c47d34ac29a82af012c0
|
produceEports.py
|
produceEports.py
|
#!/usr/bin/env python
from app.views.export import write_all_measurements_csv
import tempfile
import os
f = open("{0}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w")
try:
write_all_measurements_csv(f)
finally:
f.close
os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv")
|
#!/usr/bin/env python
from app.views.export import write_all_measurements_csv
import tempfile
import os
exportDirectory = "{0}/app/static/exports".format(os.path.dirname(os.path.realpath(__file__))
workingFile = "{0}/AllMeasurements_inprogress.csv".format(exportDirectory)
finalFile = "{0}/AllMeasurements.csv".format(exportDirectory)
f = open(workingFile, "w")
try:
write_all_measurements_csv(f)
finally:
f.close
os.rename(workingFile, finalFile)
|
Use directory for all interaction - duh!
|
Use directory for all interaction - duh!
|
Python
|
mit
|
rabramley/telomere,rabramley/telomere,rabramley/telomere
|
8a544ac2db71d4041c77fdb0ddfe27b84b565bb5
|
salt/utils/saltminionservice.py
|
salt/utils/saltminionservice.py
|
# Import salt libs
from salt.utils.winservice import Service, instart
import salt
# Import third party libs
import win32serviceutil
import win32service
import winerror
import win32api
# Import python libs
import sys
class MinionService(Service):
def start(self):
self.runflag = True
self.log("Starting the Salt Minion")
minion = salt.Minion()
minion.start()
while self.runflag:
pass
#self.sleep(10)
#self.log("I'm alive ...")
def stop(self):
self.runflag = False
self.log("Shutting down the Salt Minion")
def console_event_handler(event):
if event == 5:
# Do nothing on CTRL_LOGOFF_EVENT
return True
return False
def _main():
win32api.SetConsoleCtrlHandler(console_event_handler, 1)
servicename = 'salt-minion'
try:
status = win32serviceutil.QueryServiceStatus(servicename)
except win32service.error as details:
if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
instart(MinionService, servicename, 'Salt Minion')
sys.exit(0)
if status[1] == win32service.SERVICE_RUNNING:
win32serviceutil.StopServiceWithDeps(servicename)
win32serviceutil.StartService(servicename)
else:
win32serviceutil.StartService(servicename)
if __name__ == '__main__':
_main()
|
# Import salt libs
from salt.utils.winservice import Service, instart
import salt
# Import third party libs
import win32serviceutil
import win32service
import winerror
# Import python libs
import sys
class MinionService(Service):
def start(self):
self.runflag = True
self.log("Starting the Salt Minion")
minion = salt.Minion()
minion.start()
while self.runflag:
pass
#self.sleep(10)
#self.log("I'm alive ...")
def stop(self):
self.runflag = False
self.log("Shutting down the Salt Minion")
def _main():
servicename = 'salt-minion'
try:
status = win32serviceutil.QueryServiceStatus(servicename)
except win32service.error as details:
if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
instart(MinionService, servicename, 'Salt Minion')
sys.exit(0)
if status[1] == win32service.SERVICE_RUNNING:
win32serviceutil.StopServiceWithDeps(servicename)
win32serviceutil.StartService(servicename)
else:
win32serviceutil.StartService(servicename)
if __name__ == '__main__':
_main()
|
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service"
|
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service"
This reverts commit a7ddf81b37b578b1448f83b0efb4f7116de0c3fb.
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
eeb8057fb5ff65eb89e3b5a8ff94bf58adc511ee
|
utils/lit/tests/test-output.py
|
utils/lit/tests/test-output.py
|
# RUN: %{lit} -j 1 -v %{inputs}/test-data --output %t.results.out > %t.out
# RUN: FileCheck < %t.results.out %s
# CHECK: {
# CHECK: "__version__"
# CHECK: "elapsed"
# CHECK-NEXT: "tests": [
# CHECK-NEXT: {
# CHECK-NEXT: "code": "PASS",
# CHECK-NEXT: "elapsed": {{[0-9.]+}},
# CHECK-NEXT: "metrics": {
# CHECK-NEXT: "value0": 1,
# CHECK-NEXT: "value1": 2.3456
# CHECK-NEXT: }
# CHECK-NEXT: "name": "test-data :: bad&name.ini",
# CHECK-NEXT: "output": "& < > \""
# CHECK-NEXT: },
# CHECK-NEXT: {
# CHECK-NEXT: "code": "PASS",
# CHECK-NEXT: "elapsed": {{[0-9.]+}},
# CHECK-NEXT: "metrics": {
# CHECK-NEXT: "value0": 1,
# CHECK-NEXT: "value1": 2.3456
# CHECK-NEXT: }
# CHECK-NEXT: "name": "test-data :: metrics.ini",
# CHECK-NEXT: "output": "Test passed."
# CHECK-NEXT: }
# CHECK-NEXT: ]
# CHECK-NEXT: }
|
# RUN: %{lit} -j 1 -v %{inputs}/test-data --output %t.results.out > %t.out
# RUN: FileCheck < %t.results.out %s
# CHECK: {
# CHECK: "__version__"
# CHECK: "elapsed"
# CHECK-NEXT: "tests": [
# CHECK-NEXT: {
# CHECK-NEXT: "code": "PASS",
# CHECK-NEXT: "elapsed": {{[0-9.]+}},
# CHECK-NEXT: "metrics": {
# CHECK-NEXT: "value0": 1,
# CHECK-NEXT: "value1": 2.3456
# CHECK-NEXT: }
# CHECK: "name": "test-data :: bad&name.ini",
# CHECK: "output": "& < > \""
# CHECK: ]
# CHECK-NEXT: }
|
Refactor test incase results are backwards
|
Refactor test incase results are backwards
Looks like results can come in either way in this file. Loosen the ordering constraints.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@331945 91177308-0d34-0410-b5e6-96231b3b80d8
|
Python
|
apache-2.0
|
llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm
|
b367e2919c0de02f3514dfac5c890ffd70603918
|
src/nodeconductor_assembly_waldur/experts/filters.py
|
src/nodeconductor_assembly_waldur/experts/filters.py
|
import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.ExpertProvider
fields = []
class ExpertRequestFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
project = core_filters.URLFilter(view_name='project-detail', name='project__uuid')
project_uuid = django_filters.UUIDFilter(name='project__uuid')
o = django_filters.OrderingFilter(fields=(
'name',
'type',
'state',
'customer_name',
'project_name',
'created',
'modified',
))
class Meta(object):
model = models.ExpertRequest
fields = ['state']
class ExpertBidFilter(django_filters.FilterSet):
request = core_filters.URLFilter(view_name='expert-request-detail', name='request__uuid')
request_uuid = django_filters.UUIDFilter(name='request__uuid')
class Meta(object):
model = models.ExpertBid
fields = []
|
import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.ExpertProvider
fields = []
class ExpertRequestFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
project = core_filters.URLFilter(view_name='project-detail', name='project__uuid')
project_uuid = django_filters.UUIDFilter(name='project__uuid')
o = django_filters.OrderingFilter(fields=(
('name', 'name'),
('type', 'type'),
('state', 'state'),
('project__customer__name', 'customer_name'),
('project__name', 'project_name'),
('created', 'created'),
('modified', 'modified'),
))
class Meta(object):
model = models.ExpertRequest
fields = ['state']
class ExpertBidFilter(django_filters.FilterSet):
request = core_filters.URLFilter(view_name='expert-request-detail', name='request__uuid')
request_uuid = django_filters.UUIDFilter(name='request__uuid')
class Meta(object):
model = models.ExpertBid
fields = []
|
Fix expert request filter by customer and project name.
|
Fix expert request filter by customer and project name.
|
Python
|
mit
|
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur
|
2f8c3ab7ecd0606069d524192c551e7be77ca461
|
zhihudaily/views/with_image.py
|
zhihudaily/views/with_image.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
from flask import render_template, Blueprint
from zhihudaily.utils import make_request
from zhihudaily.cache import cache
image_ui = Blueprint('image_ui', __name__, template_folder='templates')
@image_ui.route('/withimage')
@cache.cached(timeout=900)
def with_image():
"""The page for 图片 UI."""
r = make_request('http://news.at.zhihu.com/api/1.2/news/latest')
(display_date, date, news_list) = get_news_info(r)
news_list = handle_image(news_list)
day_before = (
datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1)
).strftime('%Y%m%d')
return render_template('with_image.html', lists=news_list,
display_date=display_date,
day_before=day_before,
is_today=True)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from flask import render_template, Blueprint, json
from zhihudaily.cache import cache
from zhihudaily.models import Zhihudaily
from zhihudaily.utils import Date
image_ui = Blueprint('image_ui', __name__, template_folder='templates')
@image_ui.route('/withimage')
@cache.cached(timeout=900)
def with_image():
"""The page for 图片 UI."""
day = Date()
news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get()
return render_template('with_image.html',
lists=json.loads(news.json_news),
display_date=news.display_date,
day_before=day.day_before,
is_today=True)
|
Switch to use database for image ui
|
Switch to use database for image ui
|
Python
|
mit
|
lord63/zhihudaily,lord63/zhihudaily,lord63/zhihudaily
|
5c405745c954c2aa6121ddd82fb13ffef11b3150
|
pyp2rpm/utils.py
|
pyp2rpm/utils.py
|
import functools
from pyp2rpm import settings
def memoize_by_args(func):
"""Memoizes return value of a func based on args."""
memory = {}
@functools.wraps(func)
def memoized(*args):
if not args in memory.keys():
value = func(*args)
memory[args] = value
return memory[args]
return memoized
def license_from_trove(trove):
"""Finds out license from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
Fedora name of the package license or empty string, if no licensing information is found in trove classifiers.
"""
license = []
for classifier in trove:
if classifier is None: continue
if 'License' in classifier != -1:
stripped = classifier.strip()
# if taken from EGG-INFO, begins with Classifier:
stripped = stripped[stripped.find('License'):]
if stripped in settings.TROVE_LICENSES:
license.append(settings.TROVE_LICENSES[stripped])
else:
license.append("Unknown License")
return ' and '.join(license)
|
import functools
from pyp2rpm import settings
def memoize_by_args(func):
"""Memoizes return value of a func based on args."""
memory = {}
@functools.wraps(func)
def memoized(*args):
if not args in memory.keys():
value = func(*args)
memory[args] = value
return memory[args]
return memoized
def license_from_trove(trove):
"""Finds out license from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
Fedora name of the package license or empty string, if no licensing information is found in trove classifiers.
"""
license = []
for classifier in trove:
if classifier is None: continue
if 'License' in classifier != -1:
stripped = classifier.strip()
# if taken from EGG-INFO, begins with Classifier:
stripped = stripped[stripped.find('License'):]
if stripped in settings.TROVE_LICENSES:
license.append(settings.TROVE_LICENSES[stripped])
return ' and '.join(license)
|
Revert the commit "bc85b4e" to keep the current solution
|
Revert the commit "bc85b4e" to keep the current solution
|
Python
|
mit
|
henrysher/spec4pypi
|
ab81837b707280b960ca02675a85da7918d17fec
|
setuptools/command/bdist_rpm.py
|
setuptools/command/bdist_rpm.py
|
# This is just a kludge so that bdist_rpm doesn't guess wrong about the
# distribution name and version, if the egg_info command is going to alter
# them, another kludge to allow you to build old-style non-egg RPMs.
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def initialize_options(self):
_bdist_rpm.initialize_options(self)
self.no_egg = None
def run(self):
self.run_command('egg_info') # ensure distro name is up-to-date
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version '+version
line24 = '%define version '+rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23,line24)
for line in spec
]
spec.insert(spec.index(line24)+1, "%define unmangled_version "+version)
return spec
|
# This is just a kludge so that bdist_rpm doesn't guess wrong about the
# distribution name and version, if the egg_info command is going to alter
# them, another kludge to allow you to build old-style non-egg RPMs.
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def initialize_options(self):
_bdist_rpm.initialize_options(self)
self.no_egg = None
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
Adjust to match modern style conventions.
|
Adjust to match modern style conventions.
|
Python
|
mit
|
pypa/setuptools,pypa/setuptools,pypa/setuptools
|
58eb4b2b034d90f45b3daa12900f24a390bb4782
|
setuptools/command/bdist_rpm.py
|
setuptools/command/bdist_rpm.py
|
# This is just a kludge so that bdist_rpm doesn't guess wrong about the
# distribution name and version, if the egg_info command is going to alter
# them, another kludge to allow you to build old-style non-egg RPMs.
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
"""
Override the default bdist_rpm behavior to do the following:
1. Run egg_info to ensure the name and version are properly calculated.
2. Always run 'install' using --single-version-externally-managed to
disable eggs in RPM distributions.
3. Replace dash with underscore in the version numbers for better RPM
compatibility.
"""
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
|
Replace outdated deprecating comments with a proper doc string.
|
Replace outdated deprecating comments with a proper doc string.
|
Python
|
mit
|
pypa/setuptools,pypa/setuptools,pypa/setuptools
|
678532961cbc676fb3b82fa58185b281a8a4a7b3
|
rex/preconstrained_file_stream.py
|
rex/preconstrained_file_stream.py
|
from angr.state_plugins.plugin import SimStatePlugin
from angr.storage.file import SimFileStream
class SimPreconstrainedFileStream(SimFileStream):
def __init__(self, name, preconstraining_handler=None, **kwargs):
super().__init__(name, **kwargs)
self.preconstraining_handler = preconstraining_handler
self._attempted_preconstraining = False
def read(self, pos, size, **kwargs):
if not self._attempted_preconstraining:
self._attempted_preconstraining = True
self.preconstraining_handler(self)
return super().read(pos, size, **kwargs)
@SimStatePlugin.memo
def copy(self, memo):
copied = super().copy(memo)
copied.preconstraining_handler = self.preconstraining_handler
copied._attempted_preconstraining = self._attempted_preconstraining
return copied
|
from angr.state_plugins.plugin import SimStatePlugin
from angr.storage.file import SimFileStream
class SimPreconstrainedFileStream(SimFileStream):
def __init__(self, name, preconstraining_handler=None, **kwargs):
super().__init__(name, **kwargs)
self.preconstraining_handler = preconstraining_handler
self._attempted_preconstraining = False
def read(self, pos, size, **kwargs):
if not self._attempted_preconstraining:
self._attempted_preconstraining = True
self.preconstraining_handler(self)
return super().read(pos, size, **kwargs)
@SimStatePlugin.memo
def copy(self, memo):
copied = super().copy(memo)
copied.preconstraining_handler = self.preconstraining_handler
copied._attempted_preconstraining = self._attempted_preconstraining
return copied
def __setstate__(self, state):
for attr, value in state.items():
setattr(self, attr, value)
def __getstate__(self):
d = super().__getstate__()
d['preconstraining_handler'] = None
return d
|
Fix a bug that leads to failures in pickling.
|
SimPreconstrainedFileStream: Fix a bug that leads to failures in pickling.
|
Python
|
bsd-2-clause
|
shellphish/rex,shellphish/rex
|
91f503cd99dfa6fc6562afc1b627b6f8b0f1d91b
|
addons/l10n_ar/models/res_partner_bank.py
|
addons/l10n_ar/models/res_partner_bank.py
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
import stdnum.ar.cbu
def validate_cbu(cbu):
return stdnum.ar.cbu.validate(cbu)
class ResPartnerBank(models.Model):
_inherit = 'res.partner.bank'
@api.model
def _get_supported_account_types(self):
""" Add new account type named cbu used in Argentina """
res = super()._get_supported_account_types()
res.append(('cbu', _('CBU')))
return res
@api.model
def retrieve_acc_type(self, acc_number):
try:
validate_cbu(acc_number)
except Exception:
return super().retrieve_acc_type(acc_number)
return 'cbu'
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
from odoo.exceptions import ValidationError
import stdnum.ar
import logging
_logger = logging.getLogger(__name__)
def validate_cbu(cbu):
try:
return stdnum.ar.cbu.validate(cbu)
except Exception as error:
msg = _("Argentinian CBU was not validated: %s" % repr(error))
_logger.log(25, msg)
raise ValidationError(msg)
class ResPartnerBank(models.Model):
_inherit = 'res.partner.bank'
@api.model
def _get_supported_account_types(self):
""" Add new account type named cbu used in Argentina """
res = super()._get_supported_account_types()
res.append(('cbu', _('CBU')))
return res
@api.model
def retrieve_acc_type(self, acc_number):
try:
validate_cbu(acc_number)
except Exception:
return super().retrieve_acc_type(acc_number)
return 'cbu'
|
Fix ImportError: No module named 'stdnum.ar.cbu'
|
[FIX] l10n_ar: Fix ImportError: No module named 'stdnum.ar.cbu'
Since stdnum.ar.cbu is not available in odoo saas enviroment because is
using an old version of stdnum package, we add a try exept in order to
catch this and manage the error properly which is raise an exception and
leave a message in the log telling the user that the cbu was not able to
validate.
closes odoo/odoo#40383
X-original-commit: 25d483fc3fc05fd47c72c3d96c02fed12b998b0d
Signed-off-by: Josse Colpaert <1f46e7f017caa89a77c9557ed26b800e8d5d7700@openerp.com>
|
Python
|
agpl-3.0
|
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
|
5cd0507e99d8f78597d225266ec09f6588308396
|
tests/app/public_contracts/test_POST_notification.py
|
tests/app/public_contracts/test_POST_notification.py
|
from flask import json
from . import return_json_from_response, validate_v0
from tests import create_authorization_header
def _post_notification(client, template, url, to):
data = {
'to': to,
'template': str(template.id)
}
auth_header = create_authorization_header(service_id=template.service_id)
return client.post(
path=url,
data=json.dumps(data),
headers=[('Content-Type', 'application/json'), auth_header]
)
def test_post_sms_contract(client, mocker, sample_template):
mocker.patch('app.celery.tasks.send_sms.apply_async')
mocker.patch('app.encryption.encrypt', return_value="something_encrypted")
response_json = return_json_from_response(_post_notification(
client, sample_template, url='/notifications/sms', to='07700 900 855'
))
validate_v0(response_json, 'POST_notification_return_sms.json')
def test_post_email_contract(client, mocker, sample_email_template):
mocker.patch('app.celery.tasks.send_email.apply_async')
mocker.patch('app.encryption.encrypt', return_value="something_encrypted")
response_json = return_json_from_response(_post_notification(
client, sample_email_template, url='/notifications/email', to='foo@bar.com'
))
validate_v0(response_json, 'POST_notification_return_email.json')
|
from flask import json
from . import return_json_from_response, validate_v0
from tests import create_authorization_header
def _post_notification(client, template, url, to):
data = {
'to': to,
'template': str(template.id)
}
auth_header = create_authorization_header(service_id=template.service_id)
return client.post(
path=url,
data=json.dumps(data),
headers=[('Content-Type', 'application/json'), auth_header]
)
def test_post_sms_contract(client, mocker, sample_template):
mocker.patch('app.celery.provider_tasks.deliver_sms.apply_async')
mocker.patch('app.encryption.encrypt', return_value="something_encrypted")
response_json = return_json_from_response(_post_notification(
client, sample_template, url='/notifications/sms', to='07700 900 855'
))
validate_v0(response_json, 'POST_notification_return_sms.json')
def test_post_email_contract(client, mocker, sample_email_template):
mocker.patch('app.celery.provider_tasks.deliver_email.apply_async')
mocker.patch('app.encryption.encrypt', return_value="something_encrypted")
response_json = return_json_from_response(_post_notification(
client, sample_email_template, url='/notifications/email', to='foo@bar.com'
))
validate_v0(response_json, 'POST_notification_return_email.json')
|
Revert "Fixed faoiling jenkins tests. Mocked the required functions"
|
Revert "Fixed faoiling jenkins tests. Mocked the required functions"
This reverts commit 4b60c8dadaa413581cd373c9059ff95ecf751159.
|
Python
|
mit
|
alphagov/notifications-api,alphagov/notifications-api
|
4467ffe669eec09bab16f4e5a3256ed333c5d3d5
|
rcamp/lib/ldap_utils.py
|
rcamp/lib/ldap_utils.py
|
from django.conf import settings
from ldapdb import escape_ldap_filter
import ldap
def authenticate(dn,pwd,ldap_conf_key):
# Setup connection
ldap_conf = settings.LDAPCONFS[ldap_conf_key]
server = ldap_conf['server']
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
conn = ldap.initialize(server)
# Authenticate
try:
conn.simple_bind_s(dn, pwd)
return True
except ldap.INVALID_CREDENTIALS:
return False
def get_suffixed_username(username,organization):
try:
suffix = settings.ORGANIZATION_INFO[organization]['suffix']
except KeyError:
suffix = None
suffixed_username = username
if suffix:
suffixed_username = '{0}@{1}'.format(username,suffix)
return suffixed_username
def get_ldap_username_and_org(suffixed_username):
username = suffixed_username
org = 'ucb'
if '@' in suffixed_username:
username, suffix = suffixed_username.rsplit('@',1)
for k,v in settings.ORGANIZATION_INFO.iteritems():
if v['suffix'] == suffix:
org = k
break
return username, org
|
from django.conf import settings
from ldapdb import escape_ldap_filter
import ldap
def authenticate(dn,pwd,ldap_conf_key):
# Setup connection
ldap_conf = settings.LDAPCONFS[ldap_conf_key]
server = ldap_conf['server']
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
conn = ldap.initialize(server, bytes_mode=False)
# Authenticate
try:
conn.simple_bind_s(dn, pwd)
return True
except ldap.INVALID_CREDENTIALS:
return False
def get_suffixed_username(username,organization):
try:
suffix = settings.ORGANIZATION_INFO[organization]['suffix']
except KeyError:
suffix = None
suffixed_username = username
if suffix:
suffixed_username = '{0}@{1}'.format(username,suffix)
return suffixed_username
def get_ldap_username_and_org(suffixed_username):
username = suffixed_username
org = 'ucb'
if '@' in suffixed_username:
username, suffix = suffixed_username.rsplit('@',1)
for k,v in settings.ORGANIZATION_INFO.iteritems():
if v['suffix'] == suffix:
org = k
break
return username, org
|
Set bytes_mode=False for future compatability with Python3
|
Set bytes_mode=False for future compatability with Python3
|
Python
|
mit
|
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
|
c872b9991ec1a80d03906cebfb43e71335ba9c26
|
tests/run/generator_frame_cycle.py
|
tests/run/generator_frame_cycle.py
|
# mode: run
# tag: generator
import cython
import sys
def test_generator_frame_cycle():
"""
>>> test_generator_frame_cycle()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
del g
if cython.compiled:
# FIXME: this should not be necessary, but I can't see how to do it...
import gc; gc.collect()
return tuple(testit)
def test_generator_frame_cycle_with_outer_exc():
"""
>>> test_generator_frame_cycle_with_outer_exc()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
try:
raise ValueError()
except ValueError as exc:
assert sys.exc_info()[1] is exc, sys.exc_info()
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
assert sys.exc_info()[1] is exc, sys.exc_info()
del g
assert sys.exc_info()[1] is exc, sys.exc_info()
if cython.compiled:
# FIXME: this should not be necessary, but I can't see how to do it...
import gc; gc.collect()
return tuple(testit)
|
# mode: run
# tag: generator
import cython
import sys
def test_generator_frame_cycle():
"""
>>> test_generator_frame_cycle()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
del g
return tuple(testit)
def test_generator_frame_cycle_with_outer_exc():
"""
>>> test_generator_frame_cycle_with_outer_exc()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
try:
raise ValueError()
except ValueError as exc:
assert sys.exc_info()[1] is exc, sys.exc_info()
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
# CPython 3.3 handles this incorrectly itself :)
if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
assert sys.exc_info()[1] is exc, sys.exc_info()
del g
if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
assert sys.exc_info()[1] is exc, sys.exc_info()
return tuple(testit)
|
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later.
|
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later.
|
Python
|
apache-2.0
|
cython/cython,cython/cython,da-woods/cython,scoder/cython,cython/cython,scoder/cython,scoder/cython,cython/cython,da-woods/cython,da-woods/cython,scoder/cython,da-woods/cython
|
88f699690a48bc9e204c561443a53ca03dcf1ae6
|
test/python_api/default-constructor/sb_type.py
|
test/python_api/default-constructor/sb_type.py
|
"""
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.GetName()
obj.GetByteSize()
#obj.GetEncoding(5)
obj.GetNumberChildren(True)
member = lldb.SBTypeMember()
obj.GetChildAtIndex(True, 0, member)
obj.GetChildIndexForName(True, "_member_field")
obj.IsAPointerType()
obj.GetPointeeType()
obj.GetDescription(lldb.SBStream())
|
"""
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.GetName()
obj.GetByteSize()
#obj.GetEncoding(5)
obj.GetNumberChildren(True)
member = lldb.SBTypeMember()
obj.GetChildAtIndex(True, 0, member)
obj.GetChildIndexForName(True, "_member_field")
obj.IsAPointerType()
obj.GetPointeeType()
obj.GetDescription(lldb.SBStream())
obj.IsPointerType(None)
lldb.SBType.IsPointerType(None)
|
Add fuzz calls for SBType::IsPointerType(void *opaque_type).
|
Add fuzz calls for SBType::IsPointerType(void *opaque_type).
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@134551 91177308-0d34-0410-b5e6-96231b3b80d8
|
Python
|
apache-2.0
|
llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb
|
4636c9394138534fc39cc5bdac373b97919ffd01
|
server/info/services.py
|
server/info/services.py
|
"""info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
queryset = Article.objects.filter(column__uid=uid).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
queryset = Column.objects.all().order_by('-id')
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id')
|
"""info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
queryset = Article.objects.filter(
column__uid=uid
).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
queryset = Column.objects.all().only('uid', 'name').order_by('-id')
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id')
|
Modify django orm filter, add only
|
Modify django orm filter, add only
|
Python
|
mit
|
istommao/codingcatweb,istommao/codingcatweb,istommao/codingcatweb
|
b46727a6bf8c1d85e0f9f8828954440bc489f247
|
panoptes_client/user.py
|
panoptes_client/user.py
|
from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = ()
def avatar(self):
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
|
from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = ()
@property
def avatar(self):
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
|
Change User.avatar to be a property
|
Change User.avatar to be a property
|
Python
|
apache-2.0
|
zooniverse/panoptes-python-client
|
437ed5ee5e919186eabd1d71b0c1949adc1cf378
|
src/orca/gnome-terminal.py
|
src/orca/gnome-terminal.py
|
# gnome-terminal script
import a11y
import speech
def onTextInserted (e):
if e.source.role != "terminal":
return
speech.say ("default", e.any_data)
def onTextDeleted (event):
"""Called whenever text is deleted from an object.
Arguments:
- event: the Event
"""
# Ignore text deletions from non-focused objects, unless the
# currently focused object is the parent of the object from which
# text was deleted
#
if (event.source != a11y.focusedObject) \
and (event.source.parent != a11y.focusedObject):
pass
else:
brlUpdateText (event.source)
|
# gnome-terminal script
import a11y
import speech
import default
def onTextInserted (e):
if e.source.role != "terminal":
return
speech.say ("default", e.any_data)
def onTextDeleted (event):
"""Called whenever text is deleted from an object.
Arguments:
- event: the Event
"""
# Ignore text deletions from non-focused objects, unless the
# currently focused object is the parent of the object from which
# text was deleted
#
if (event.source != a11y.focusedObject) \
and (event.source.parent != a11y.focusedObject):
pass
else:
default.brlUpdateText (event.source)
|
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
|
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
|
Python
|
lgpl-2.1
|
GNOME/orca,h4ck3rm1k3/orca-sonar,pvagner/orca,h4ck3rm1k3/orca-sonar,GNOME/orca,pvagner/orca,h4ck3rm1k3/orca-sonar,chrys87/orca-beep,chrys87/orca-beep,pvagner/orca,pvagner/orca,chrys87/orca-beep,GNOME/orca,chrys87/orca-beep,GNOME/orca
|
45b3fc7babfbd922bdb174e5156f54c567a66de4
|
plotly/tests/test_core/test_graph_objs/test_graph_objs_tools.py
|
plotly/tests/test_core/test_graph_objs/test_graph_objs_tools.py
|
from __future__ import absolute_import
from unittest import TestCase
|
from __future__ import absolute_import
from unittest import TestCase
from plotly.graph_objs import graph_objs as go
from plotly.graph_objs import graph_objs_tools as got
class TestGetRole(TestCase):
def test_get_role_no_value(self):
# this is a bit fragile, but we pick a few stable values
# the location in the figure matters for this test!
fig = go.Figure(data=[{}])
fig.data[0].marker.color = 'red'
fig.layout.title = 'some-title'
parent_key_role_tuples = [
(fig.data[0], 'x', 'data'),
(fig.data[0], 'marker', 'object'),
(fig.data[0].marker, 'color', 'style'),
(fig.layout, 'title', 'info'),
(fig, 'data', 'object'),
]
for parent, key, role in parent_key_role_tuples:
self.assertEqual(got.get_role(parent, key), role, msg=key)
def test_get_role_with_value(self):
# some attributes are conditionally considered data if they're arrays
# the location in the figure matters for this test!
fig = go.Figure(data=[{}])
fig.data[0].marker.color = 'red'
parent_key_value_role_tuples = [
(fig.data[0], 'x', 'wh0cares', 'data'),
(fig.data[0], 'marker', 'wh0cares', 'object'),
(fig.data[0].marker, 'color', 'red', 'style'),
(fig.data[0].marker, 'color', ['red'], 'data')
]
for parent, key, value, role in parent_key_value_role_tuples:
self.assertEqual(got.get_role(parent, key, value), role,
msg=(key, value))
|
Add some :tiger2:s for `graph_objs_tools.py`.
|
Add some :tiger2:s for `graph_objs_tools.py`.
|
Python
|
mit
|
plotly/plotly.py,plotly/python-api,plotly/plotly.py,plotly/python-api,plotly/plotly.py,plotly/python-api
|
770781d3ce55a91926b91579e11d79ebb3edf47e
|
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
|
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
|
import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model
"""
def handle(self, *args, **options):
org_groups = GroupProfile.objects.filter(group_type='organization')
for org in org_groups:
data = json.loads(org.data)
migrated_org = Organization.objects.create(
name=data['name'],
display_name=data['display_name'],
contact_name=data['contact_name'],
contact_email=data['contact_email'],
contact_phone=data['contact_phone']
)
group = Group.objects.get(groupprofile=org.id)
users = group.user_set.all()
for user in users:
migrated_org.users.add(user)
linked_groups = group.grouprelationship.get_linked_group_relationships()
for linked_group in linked_groups:
if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component
actual_group = Group.objects.get(id=linked_group.to_group_relationship_id)
migrated_org.groups.add(actual_group)
|
import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model
"""
def handle(self, *args, **options):
org_groups = GroupProfile.objects.filter(group_type='organization')
for org in org_groups:
data = json.loads(org.data)
name = org.name
display_name = data.get('display_name', name)
contact_name = data.get('contact_name', None)
contact_email = data.get('email', None)
if contact_email is None:
contact_email = data.get('contact_email', None)
contact_phone = data.get('phone', None)
if contact_phone is None:
contact_phone = data.get('contact_phone', None)
migrated_org = Organization.objects.create(
name=name,
display_name=display_name,
contact_name=contact_name,
contact_email=contact_email,
contact_phone=contact_phone
)
group = Group.objects.get(groupprofile=org.id)
users = group.user_set.all()
for user in users:
migrated_org.users.add(user)
linked_groups = group.grouprelationship.get_linked_group_relationships()
for linked_group in linked_groups:
if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component
actual_group = Group.objects.get(id=linked_group.to_group_relationship_id)
migrated_org.groups.add(actual_group)
|
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
|
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
|
Python
|
agpl-3.0
|
edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform
|
668a5240c29047d86fe9451f3078bb163bea0db9
|
skan/__init__.py
|
skan/__init__.py
|
from .csr import skeleton_to_csgraph, branch_statistics, summarise
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
|
from .csr import skeleton_to_csgraph, branch_statistics, summarise
__version__ = '0.1-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
|
Add version info to package init
|
Add version info to package init
|
Python
|
bsd-3-clause
|
jni/skan
|
8ad4850941e299d9dad02cac0e300dc2021b81be
|
streak-podium/render.py
|
streak-podium/render.py
|
import pygal
def horizontal_bar(sorted_streaks, sort_attrib):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort_attrib.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1]
chart = pygal.HorizontalStackedBar(show_y_labels=False,
show_x_labels=False,
show_legend=False,
print_values=True,
print_zeroes=False,
print_labels=True)
chart.title = 'Top contributors by {} streak'.format(sort_attrib)
chart.x_labels = users
values = []
for value, user in zip(streaks, users):
if value > 0:
values.append({
'value': value,
'label': user,
'xlink': 'https://github.com/{}'.format(user)
})
else:
values.append(0) # Let zeroes be boring
chart.add('Streaks', values)
chart.render_to_file('top.svg')
|
import pygal
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
users = [user for user, _ in sorted_streaks][::-1]
streaks = [getattr(streak, sort) for _, streak in sorted_streaks][::-1]
chart = pygal.HorizontalStackedBar(show_y_labels=False,
show_x_labels=False,
show_legend=False,
print_values=True,
print_zeroes=False,
print_labels=True)
chart.title = 'Top contributors by {} streak'.format(sort)
chart.x_labels = users
values = []
for value, user in zip(streaks, users):
if value > 0:
values.append({
'value': value,
'label': user,
'xlink': 'https://github.com/{}'.format(user)
})
else:
values.append(0) # Let zeroes be boring
chart.add('Streaks', values)
chart.render_to_file('top_{}.svg'.format(sort))
|
Rename svg output based on sort attribute
|
Rename svg output based on sort attribute
|
Python
|
mit
|
jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-commit-streak,supermitch/streak-podium,supermitch/streak-podium,jollyra/hubot-streak-podium
|
2d9fce5715b2d7d5b920d2e77212f076e9ebd1be
|
staticgen_demo/staticgen_views.py
|
staticgen_demo/staticgen_views.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'sitemap.xml',
'robots.txt',
'page_not_found',
'server_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'sitemap.xml',
'robots.txt',
'page_not_found',
'server_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
try:
from cms.models import Title
except ImportError: # pragma: no cover
# django-cms is not installed.
return super(StaticgenCMSView, self).items()
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
|
Add CMS Pages to staticgen registry.
|
Add CMS Pages to staticgen registry.
|
Python
|
bsd-3-clause
|
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
|
4d73eb2a7e06e1e2607a2abfae1063b9969e70a0
|
strichliste/strichliste/models.py
|
strichliste/strichliste/models.py
|
from django.db import models
from django.db.models import Sum
class User(models.Model):
name = models.CharField(max_length=254, unique=True)
create_date = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
mail_address = models.EmailField(null=True)
@property
def last_transaction(self):
try:
return self.transactions.last().create_date
except AttributeError:
return None
@property
def balance(self):
return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0
def to_full_dict(self):
return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address,
'balance': self.balance, 'last_transaction': self.last_transaction}
def to_dict(self):
return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction}
def __str__(self):
return self.name
class Transaction(models.Model):
user = models.ForeignKey('User', related_name='transactions',
on_delete=models.PROTECT, db_index=True)
create_date = models.DateTimeField(auto_now_add=True)
value = models.IntegerField()
def to_dict(self):
return {'id': self.id,
'create_date': self.create_date,
'value': self.value}
class Meta:
ordering = ('create_date',)
|
from django.db import models
from django.db.models import Sum
class User(models.Model):
name = models.CharField(max_length=254, unique=True)
create_date = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
mail_address = models.EmailField(null=True)
@property
def last_transaction(self):
try:
return self.transactions.last().create_date
except AttributeError:
return None
@property
def balance(self):
return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0
def to_full_dict(self):
return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address,
'balance': self.balance, 'last_transaction': self.last_transaction}
def to_dict(self):
return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction}
def __str__(self):
return self.name
class Transaction(models.Model):
user = models.ForeignKey('User', related_name='transactions',
on_delete=models.PROTECT, db_index=True)
create_date = models.DateTimeField(auto_now_add=True)
value = models.IntegerField()
def to_dict(self):
return {'id': self.id,
'create_date': self.create_date,
'value': self.value,
'user': self.user_id}
class Meta:
ordering = ('create_date',)
|
Add user_id to returned transactions
|
Add user_id to returned transactions
|
Python
|
mit
|
Don42/strichliste-django,hackerspace-bootstrap/strichliste-django
|
0f1cb413503034cbc1e2deddd8327ad1946201fe
|
numba2/compiler/optimizations/throwing.py
|
numba2/compiler/optimizations/throwing.py
|
# -*- coding: utf-8 -*-
"""
Rewrite exceptions that are thrown and caught locally to jumps.
"""
from numba2.compiler import excmodel
from pykit.optimizations import local_exceptions
def rewrite_local_exceptions(func, env):
local_exceptions.run(func, env, exc_model=excmodel.ExcModel(env))
def rewrite_exceptions(func, env):
for op in func.ops:
if op.opcode == 'exc_throw':
raise NotImplementedError("Exception throwing", op, func)
if op.opcode in ('exc_catch', 'exc_setup'):
op.delete()
|
# -*- coding: utf-8 -*-
"""
Rewrite exceptions that are thrown and caught locally to jumps.
"""
from numba2.compiler import excmodel
from pykit.analysis import cfa
from pykit.optimizations import local_exceptions
def rewrite_local_exceptions(func, env):
local_exceptions.run(func, env, exc_model=excmodel.ExcModel(env))
def rewrite_exceptions(func, env):
blocks = set()
for op in func.ops:
if op.opcode == 'exc_throw':
raise NotImplementedError("Exception throwing", op, func)
if op.opcode in ('exc_catch', 'exc_setup'):
blocks.add(op.block)
op.delete()
update_outdated_incoming_blocks(func, blocks)
def update_outdated_incoming_blocks(func, candidates):
"""
Update phi nodes in blocks previously containing 'exc_catch'. 'exc_setup'
may span many blocks, and none, or only a subset of those blocks may be
actual predecessors.
"""
cfg = cfa.cfg(func)
for block in candidates:
preds = cfg.predecessors(block)
for op in block.leaders:
if op.opcode == 'phi':
blocks, values = op.args
newblocks = [block for block in blocks if block in preds]
newvalues = [val for block, val in zip(blocks, values)
if block in preds]
op.set_args([newblocks, newvalues])
|
Rewrite phis from outdated incoming exception blocks
|
Rewrite phis from outdated incoming exception blocks
|
Python
|
bsd-2-clause
|
flypy/flypy,flypy/flypy
|
211b7b28e2d8c7ed0e0f67bea1a1a68b520a53b1
|
pagerduty_events_api/pagerduty_service.py
|
pagerduty_events_api/pagerduty_service.py
|
from pagerduty_events_api.pagerduty_incident import PagerdutyIncident
from pagerduty_events_api.pagerduty_rest_client import PagerdutyRestClient
class PagerdutyService:
def __init__(self, key):
self.__service_key = key
def get_service_key(self):
return self.__service_key
def trigger(self, description, additional_params={}):
payload = {'service_key': self.__service_key,
'event_type': 'trigger',
'description': description}
incident_data = PagerdutyRestClient().post(
self.__append_additional_info_to_payload(payload, additional_params)
)
return PagerdutyIncident(self.__service_key, incident_data['incident_key'])
@staticmethod
def __append_additional_info_to_payload(mandatory_data, additional_data):
return {**additional_data, **mandatory_data}
|
from pagerduty_events_api.pagerduty_incident import PagerdutyIncident
from pagerduty_events_api.pagerduty_rest_client import PagerdutyRestClient
class PagerdutyService:
def __init__(self, key):
self.__service_key = key
def get_service_key(self):
return self.__service_key
def trigger(self, description, additional_params={}):
incident = PagerdutyIncident(self.__service_key)
incident.trigger(description, additional_params)
return incident
|
Use "blank" PD incident instance for triggering through PD service.
|
Use "blank" PD incident instance for triggering through PD service.
|
Python
|
mit
|
BlasiusVonSzerencsi/pagerduty-events-api
|
f90fac30454537ec0727371ffc54bde4a1e2f78d
|
5_control_statements_and_exceptions_hierarchy/guess-a-number-ex.py
|
5_control_statements_and_exceptions_hierarchy/guess-a-number-ex.py
|
"""
This is an example of the control structures.
"""
result = ""
our_number = 21
def test_number(answer):
answer = int(answer)
if answer == our_number:
return "got it right"
elif answer > our_number:
return "nope, lower"
else:
return "nope, higher"
while result != "got it right":
result = test_number(raw_input("Choose a number:"))
print result
|
"""
This is an example of the control structures.
"""
if __name__ == "__main__":
result = ""
our_number = 21
def test_number(answer):
answer = int(answer)
if answer == our_number:
return "got it right"
elif answer > our_number:
return "nope, lower"
else:
return "nope, higher"
while result != "got it right":
result = test_number(raw_input("Choose a number:"))
print result
|
Put the code in __main__ for lesson 5 guess-a-number example.
|
Put the code in __main__ for lesson 5 guess-a-number example.
|
Python
|
mit
|
razzius/PyClassLessons,razzius/PyClassLessons,razzius/PyClassLessons,razzius/PyClassLessons,PyClass/PyClassLessons,noisebridge/PythonClass,noisebridge/PythonClass,noisebridge/PythonClass,PyClass/PyClassLessons,noisebridge/PythonClass,PyClass/PyClassLessons
|
524d5427d54342f26008a5b527140d4158f70edf
|
tests/test_extension.py
|
tests/test_extension.py
|
from __future__ import unicode_literals
import json
from test_helpers import MockTrack, get_websocket, make_frontend, patched_bot
from mopidy_tachikoma import Extension
def test_get_default_config():
ext = Extension()
config = ext.get_default_config()
assert '[tachikoma]' in config
assert 'enabled = true' in config
assert 'slack_token = ' in config
def test_get_config_schema():
ext = Extension()
schema = ext.get_config_schema()
assert 'slack_token' in schema
@patched_bot
def test_can_connect():
make_frontend()
@patched_bot
def test_gets_events():
frontend = make_frontend()
frontend.doSlackLoop(
None, MockTrack(),
[{"type": "message", "channel": "mock_channel"}])
data = json.loads(get_websocket().data)
assert {
'channel': 'mock_channel',
'text': 'Now playing *foo* from *bar*',
'type': 'message'} == data
@patched_bot
def test_says_one_thing_per_channel():
frontend = make_frontend()
song = MockTrack()
frontend.doSlackLoop(
song, song, [{"type": "message", "channel": "mock_channel"}])
assert get_websocket().data is None # same song, no info
|
from __future__ import unicode_literals
import json
from test_helpers import MockTrack, get_websocket, make_frontend, patched_bot
from mopidy_tachikoma import Extension
def test_get_default_config():
ext = Extension()
config = ext.get_default_config()
assert '[tachikoma]' in config
assert 'enabled = true' in config
assert 'slack_token = ' in config
def test_get_config_schema():
ext = Extension()
schema = ext.get_config_schema()
assert 'slack_token' in schema
@patched_bot
def test_can_connect():
make_frontend()
@patched_bot
def test_gets_events():
frontend = make_frontend()
frontend.doSlackLoop(
None, MockTrack(),
[{"type": "message", "channel": "mock_channel"}])
data = json.loads(get_websocket().data)
assert {
'channel': 'mock_channel',
'text': 'Now playing *foo* from *bar*',
'type': 'message'} == data
@patched_bot
def test_says_one_thing_per_channel():
frontend = make_frontend()
song = MockTrack()
get_websocket().data = None # make sure it's cleared
frontend.doSlackLoop(
song, song, [{"type": "message", "channel": "mock_channel"}])
assert get_websocket().data is None # same song, no info
|
Clear websocket data to try and fix Travis
|
Clear websocket data to try and fix Travis
|
Python
|
agpl-3.0
|
palfrey/mopidy-tachikoma,palfrey/mopidy-tachikoma
|
87d2e511b0fedd2a09610c35337336d443a756a4
|
tests/unit/cli/filewatch/test_stat.py
|
tests/unit/cli/filewatch/test_stat.py
|
import os
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
assert len(calls) == 1
|
import os
import time
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
for _ in range(10):
if len(calls) == 1:
break
time.sleep(0.2)
else:
raise AssertionError("Expected callback to be invoked but was not.")
|
Add polling loop to allow time for callback to be invoked
|
Add polling loop to allow time for callback to be invoked
|
Python
|
apache-2.0
|
awslabs/chalice
|
ce12cd0f56997dc6d33a9e4e7c13df27d05a133b
|
Python/Tests/TestData/DebuggerProject/ThreadJoin.py
|
Python/Tests/TestData/DebuggerProject/ThreadJoin.py
|
from threading import Thread
global exit_flag
exit_flag = False
def g():
i = 1
while not exit_flag:
i = (i + 1) % 100000000
if i % 100000 == 0: print("f making progress: {0}".format(i))
def f():
g()
from threading import Thread
def n():
t1 = Thread(target=f,name="F_thread")
t1.start()
t1.join()
def m():
n()
if __name__ == '__main__':
m()
|
from threading import Thread
global exit_flag
exit_flag = False
def g():
i = 1
while not exit_flag:
i = (i + 1) % 100000000
if i % 100000 == 0: print("f making progress: {0}".format(i))
def f():
g()
def n():
t1 = Thread(target=f,name="F_thread")
t1.start()
t1.join()
def m():
n()
if __name__ == '__main__':
m()
|
Remove redundant import from test script.
|
Remove redundant import from test script.
|
Python
|
apache-2.0
|
zooba/PTVS,zooba/PTVS,huguesv/PTVS,int19h/PTVS,huguesv/PTVS,huguesv/PTVS,Microsoft/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,int19h/PTVS,huguesv/PTVS,Microsoft/PTVS,int19h/PTVS,Microsoft/PTVS,zooba/PTVS,Microsoft/PTVS,int19h/PTVS,Microsoft/PTVS,zooba/PTVS,huguesv/PTVS,zooba/PTVS,Microsoft/PTVS,huguesv/PTVS
|
d40fa3554847a239f90a7f7edec8efbf30c753f0
|
scripts/lib/check_for_course_revisions.py
|
scripts/lib/check_for_course_revisions.py
|
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
if diff:
revisions.append(diff)
log('revision in %d:' % (course['clbid']), diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
from collections import OrderedDict
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
Use an ordereddict for sorting revisions
|
Use an ordereddict for sorting revisions
|
Python
|
mit
|
StoDevX/course-data-tools,StoDevX/course-data-tools
|
e7942afdc1e93aec57e4e02d862a91eab9b5c0cb
|
trackingtermites/termite.py
|
trackingtermites/termite.py
|
from collections import namedtuple
class Termite:
def __init__(self, label, color):
self.label = label
self.color = color
self.trail = []
self.tracker = None
def to_csv(self):
with open('data/{}-trail.csv'.format(self.label), mode='w') as trail_out:
trail_out.write('label,frame,time,x,y\n')
for record in self.trail:
trail_out.write('{},{},{},{},{},{},{}\n'.format(self.label,
record.frame, record.time, record.x, record.y,
record.xoffset, record.yoffset))
|
from collections import namedtuple
class Termite:
def __init__(self, label, color):
self.label = label
self.color = color
self.trail = []
self.tracker = None
def to_csv(self):
with open('data/{}-trail.csv'.format(self.label), mode='w') as trail_out:
trail_out.write('label,frame,time,x,y,xoffset,yoffset\n')
for record in self.trail:
trail_out.write('{},{},{},{},{},{},{}\n'.format(self.label,
record.frame, record.time, record.x, record.y,
record.xoffset, record.yoffset))
|
Include missing columns in output
|
Include missing columns in output
|
Python
|
mit
|
dmrib/trackingtermites
|
b0814b95ea854f7b3f0b9db48ae9beee078c2a30
|
versions/software/openjdk.py
|
versions/software/openjdk.py
|
import re
from versions.software.utils import get_command_stderr, get_soup, \
get_text_between
def name():
"""Return the precise name for the software."""
return 'Zulu OpenJDK'
def installed_version():
"""Return the installed version of the jdk, or None if not installed."""
try:
version_string = get_command_stderr(('java', '-version'))
return get_text_between(version_string, '"', '"')
except FileNotFoundError:
pass
def downloadable_version(url):
"""Strip the version out of the Zulu OpenJDK manual download link."""
# example: http://cdn.azul.com/.../zulu8.23.0.3-jdk8.0.144-win_x64.zip
filename = url[url.rfind('/') + 1:]
jdk_version = get_text_between(filename, '-jdk', '-')
version, update = jdk_version.rsplit('.', 1)
return f'1.{version}_{update}'
def latest_version():
"""Return the latest version of Zulu OpenJDK available for download."""
soup = get_soup('http://www.azul.com/downloads/zulu/zulu-windows/')
if soup:
div = soup.find('div', class_='latest_area')
if div:
zip_filename = re.compile('\.zip$')
tag = div.find('a', class_='r-download', href=zip_filename)
if tag:
return downloadable_version(tag.attrs['href'])
return 'Unknown'
|
import re
from versions.software.utils import get_command_stderr, get_soup, \
get_text_between
def name():
"""Return the precise name for the software."""
return 'Zulu OpenJDK'
def installed_version():
"""Return the installed version of the jdk, or None if not installed."""
try:
version_string = get_command_stderr(('java', '-version'))
# "1.8.0_162" or "9.0.4.1" for example
return get_text_between(version_string, '"', '"')
except FileNotFoundError:
pass
def latest_version():
"""Return the latest version of Zulu OpenJDK available for download."""
installed = installed_version()
soup = get_soup('http://www.azul.com/downloads/zulu/zulu-windows/')
if soup:
zip_filename = re.compile('\.zip$')
for tag in soup.find_all('a', class_='r-download', href=zip_filename):
filename = tag.attrs['href']
zulu = get_text_between(filename, 'bin/zulu', '-')
jdk = get_text_between(filename, 'jdk', '-')
if (installed is None) or (installed[0] == '9' and zulu[0] == '9'):
return zulu
elif installed[0] == '1' and jdk[0] == installed[2]:
version, update = jdk.rsplit('.', 1)
return f'1.{version}_{update}'
return 'Unknown'
|
Update OpenJDK version to support both 8 and 9.
|
Update OpenJDK version to support both 8 and 9.
|
Python
|
mit
|
mchung94/latest-versions
|
3b4c645792c1a58cdce3dc25171723e7139d66da
|
workflows/api/permissions.py
|
workflows/api/permissions.py
|
from rest_framework import permissions
from workflows.models import *
class IsAdminOrSelf(permissions.BasePermission):
def has_permission(self, request, view):
if request.user and request.user.is_authenticated():
# Don't allow adding widgets to workflows not owned by the user
if view.model == Widget and 'workflow' in request.data:
serializer = view.serializer_class(data=request.data)
serializer.is_valid()
workflow = serializer.validated_data['workflow']
return workflow.user == request.user
if view.model == Workflow and 'staff_pick' in request.data:
return request.user.is_staff
else:
return True
def has_object_permission(self, request, view, obj):
if request.user and request.user.is_authenticated():
if request.user.is_superuser:
return True
# Allow only editing of the user's workflow objects
if isinstance(obj, Workflow):
return obj.user == request.user
if isinstance(obj, Widget):
return obj.workflow.user == request.user
if isinstance(obj, Connection):
return obj.workflow.user == request.user
if isinstance(obj, Input):
return obj.widget.workflow.user == request.user
if isinstance(obj, Output):
return obj.widget.workflow.user == request.user
return False
|
from rest_framework import permissions
from workflows.models import *
class IsAdminOrSelf(permissions.BasePermission):
def has_permission(self, request, view):
if request.user and request.user.is_authenticated():
# Don't allow adding widgets to workflows not owned by the user
if view.model == Widget and 'workflow' in request.data:
serializer = view.serializer_class(data=request.data)
serializer.is_valid()
workflow = serializer.validated_data['workflow']
if request.GET.get('preview', '0') == '1':
if workflow.public:
return True
return workflow.user == request.user
if view.model == Workflow and 'staff_pick' in request.data:
return request.user.is_staff
else:
return True
def has_object_permission(self, request, view, obj):
if request.user and request.user.is_authenticated():
if request.user.is_superuser:
return True
# Allow only editing of the user's workflow objects
if isinstance(obj, Workflow):
return obj.user == request.user
if isinstance(obj, Widget):
return obj.workflow.user == request.user
if isinstance(obj, Connection):
return obj.workflow.user == request.user
if isinstance(obj, Input):
return obj.widget.workflow.user == request.user
if isinstance(obj, Output):
return obj.widget.workflow.user == request.user
return False
|
Return True for preview if workflow public
|
Return True for preview if workflow public
|
Python
|
mit
|
xflows/clowdflows-backend,xflows/clowdflows-backend,xflows/clowdflows-backend,xflows/clowdflows-backend
|
452ad6f3de797285a50094a4a145714e75204d95
|
bake/cmdline.py
|
bake/cmdline.py
|
#!/usr/bin/env python
# encoding: utf-8
# This is the command line interface for bake. For people who want to take
# bake.py and extend it for their own circumstances, modifying the main routine
# in this module is probably the best place to start.
import api as bake
import sys
# This
def main(args=sys.argv[1:]):
# Set up command line argument options
optparser = bake.make_optparser()
options, arguments = optparser.parse_args()
bake.process_options(options)
## Configuration is stored in the bake.cfg file in the current directory
config = bake.load_config()
## End processing of command line parameters
## Prepare for big loop
# The overwrite command pushes lines onto the top of the bake parameter file
if options.overwrite:
lines = options.overwrite
else:
lines = []
# Load bake parameter file
hin = open(options.file,'r')
lines += hin.readlines()
hin.close()
# This mixIterator object is kind of the core of bake.
(label, tokens,
mixIterator) = bake.make_iterator(config['label']['label_tag'],
config['label']['pattern'],
lines, options.slice_start,
options.slice_end)
## This is the main loop, iterating over each set of values
bake.default_loop(label, tokens, mixIterator, config, options)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# encoding: utf-8
# This is the command line interface for bake. For people who want to take
# bake.py and extend it for their own circumstances, modifying the main routine
# in this module is probably the best place to start.
import api as bake
import sys
def main(args=sys.argv[1:]):
# Set up command line argument options
optparser = bake.make_optparser()
options, arguments = optparser.parse_args()
bake.process_options(options)
## Configuration is stored in the bake.cfg file in the current directory
config = bake.load_config()
## End processing of command line parameters
## Prepare for big loop
# The overwrite command pushes lines onto the top of the bake parameter file
if options.overwrite:
lines = options.overwrite
else:
lines = []
# Load bake parameter file
hin = open(options.file, 'r')
lines += hin.readlines()
hin.close()
# This mixIterator object is kind of the core of bake.
(label, tokens,
mixIterator) = bake.make_iterator(config['label']['label_tag'],
config['label']['pattern'],
lines, options.slice_start,
options.slice_end)
## This is the main loop, iterating over each set of values
bake.default_loop(label, tokens, mixIterator, config, options)
if __name__ == '__main__':
main()
|
Make pep8 run mostly cleanly
|
Make pep8 run mostly cleanly
|
Python
|
mit
|
AlexSzatmary/bake
|
d5cf661b2658d7f9a0f5436444373202e514bf37
|
src/psd_tools2/__init__.py
|
src/psd_tools2/__init__.py
|
from __future__ import absolute_import, unicode_literals
from .api.psd_image import PSDImage
|
from __future__ import absolute_import, unicode_literals
from .api.psd_image import PSDImage
from .api.composer import compose
|
Include compose in the top level
|
Include compose in the top level
|
Python
|
mit
|
kmike/psd-tools,psd-tools/psd-tools,kmike/psd-tools
|
2fea7b008336e1960efb375c63a4cc14053bc590
|
src/wikicurses/__init__.py
|
src/wikicurses/__init__.py
|
import pkgutil
from enum import IntEnum
_data = pkgutil.get_data('wikicurses', 'interwiki.list').decode()
wikis = dict([i.split('|')[0:2] for i in _data.splitlines() if i[0]!='#'])
class formats(IntEnum):
i, b, blockquote = (1<<i for i in range(3))
|
import pkgutil
from enum import Enum
_data = pkgutil.get_data('wikicurses', 'interwiki.list').decode()
wikis = dict([i.split('|')[0:2] for i in _data.splitlines() if i[0]!='#'])
class BitEnum(int, Enum):
def __new__(cls, *args):
value = 1 << len(cls.__members__)
return int.__new__(cls, value)
formats = BitEnum("formats", "i b blockquote")
|
Create BitEnum class for bitfields
|
Create BitEnum class for bitfields
|
Python
|
mit
|
ids1024/wikicurses
|
e3a1d4998494143491b49312673ceb84ea98b7f8
|
RatS/tmdb/tmdb_ratings_inserter.py
|
RatS/tmdb/tmdb_ratings_inserter.py
|
import time
from RatS.base.base_ratings_uploader import RatingsUploader
from RatS.tmdb.tmdb_site import TMDB
class TMDBRatingsInserter(RatingsUploader):
def __init__(self, args):
super(TMDBRatingsInserter, self).__init__(TMDB(args), args)
self.url_for_csv_file_upload = self._get_url_for_csv_upload()
self.css_id_of_file_input_element = 'csv_file'
self.xpath_selector_for_submit_button = "//form[@name='import_csv']//input[@type='submit']"
def _get_url_for_csv_upload(self):
return 'https://www.themoviedb.org/account/{username}/import'.format(
username=self.site.USERNAME
)
def pre_upload_action(self):
cookie_accept_button = self.site.browser.find_element_by_id('cookie_notice')\
.find_elements_by_class_name('accept')
if cookie_accept_button is not None and len(cookie_accept_button) > 0:
cookie_accept_button[0].click()
time.sleep(1)
|
import time
from RatS.base.base_ratings_uploader import RatingsUploader
from RatS.tmdb.tmdb_site import TMDB
class TMDBRatingsInserter(RatingsUploader):
def __init__(self, args):
super(TMDBRatingsInserter, self).__init__(TMDB(args), args)
self.url_for_csv_file_upload = self._get_url_for_csv_upload()
self.css_id_of_file_input_element = 'csv_file'
self.xpath_selector_for_submit_button = "//form[@name='import_csv']//input[@type='submit']"
def _get_url_for_csv_upload(self):
return 'https://www.themoviedb.org/settings/import-list'
def pre_upload_action(self):
cookie_accept_button = self.site.browser.find_element_by_id('cookie_notice')\
.find_elements_by_class_name('accept')
if cookie_accept_button is not None and len(cookie_accept_button) > 0:
cookie_accept_button[0].click()
time.sleep(1)
|
Adjust TMDB import page URL
|
Adjust TMDB import page URL
|
Python
|
agpl-3.0
|
StegSchreck/RatS,StegSchreck/RatS,StegSchreck/RatS
|
989966444e63336b59da04265dbeb901258f75c1
|
us_ignite/snippets/management/commands/snippets_load_fixtures.py
|
us_ignite/snippets/management/commands/snippets_load_fixtures.py
|
from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': 'FEATURED CONTENT',
'body': '',
'url_text': 'FEATURED',
'url': '',
},
{
'slug': 'welcome-email',
'name': 'Welcome to US Ignite',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'blog-sidebar',
'name': 'Dynamic content',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'profile-welcome',
'name': 'Welcome message in the profile',
'body': 'Lorem ipsum',
'url_text': '',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
|
from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': 'FEATURED CONTENT',
'body': '',
'url_text': 'FEATURED',
'url': '',
},
{
'slug': 'welcome-email',
'name': 'Welcome to US Ignite',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'blog-sidebar',
'name': 'Blog sidebar featured content.',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'profile-welcome',
'name': 'Welcome message in the profile',
'body': 'Lorem ipsum',
'url_text': '',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
|
Update description of the blog sidebar snippet.
|
Update description of the blog sidebar snippet.
|
Python
|
bsd-3-clause
|
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
|
2afd2467c16969b10496ae96e17b9dce7911f232
|
db.py
|
db.py
|
import sqlite3
connection = sqlite3.connect('data.db')
class SavedRoll:
@staticmethod
def save(user, name, args):
pass
@staticmethod
def get(user, name):
pass
@staticmethod
def delete(user, name):
pass
|
class SavedRollManager:
"""
Class for managing saved rolls.
Attributes:
connection (sqlite3.Connection): Database connection used by manager
"""
def __init__(self, connection):
"""
Create a SavedRollManager instance.
Args:
connection (sqlite3.Connection): Database connection to use
"""
self.conn = connection
def save(self, user, chat, name, args):
"""
Save a roll to the database.
Args:
user (int): User ID to save roll for
chat (int): Chat ID to save roll for
name: Name of saved roll
args: Arguments to save for roll
"""
pass
def get(self, user, chat, name):
"""
Get a saved roll from the database.
Args:
user (int): User ID to get roll for
chat (int): Chat ID to get roll for
name: Name of saved roll
Returns:
list: List of arguments of saved roll
"""
pass
def delete(self, user, chat, name):
"""
Delete a saved roll from the database.
Args:
user (int): User ID to delete roll from
chat (int): Chat ID to delete roll from
name: Name of saved roll
"""
pass
|
Make SavedRollManager less static, also docstrings
|
Make SavedRollManager less static, also docstrings
|
Python
|
mit
|
foxscotch/foxrollbot
|
b54507e05475dfc11e04678ee358476f571323b2
|
plugins/Tools/PerObjectSettingsTool/__init__.py
|
plugins/Tools/PerObjectSettingsTool/__init__.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Settings Per Object Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Settings Per Object"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml"
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Per Object Settings"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml"
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
|
Normalize strings for per object settings
|
Normalize strings for per object settings
|
Python
|
agpl-3.0
|
onitake/Uranium,onitake/Uranium
|
ec61fec1ae60a565110876101dabad352e3ea46b
|
core/management/commands/delete_old_sessions.py
|
core/management/commands/delete_old_sessions.py
|
from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
class Command(BaseCommand):
args = '<count count ...>'
help = "Delete old sessions"
def handle(self, *args, **options):
old_sessions = Session.objects.filter(expire_date__lt=datetime.now())
self.stdout.write("Deleting {0} expired sessions".format(
old_sessions.count()
)
)
for index, session in enumerate(old_sessions):
session.delete()
if str(index).endswith('000'):
self.stdout.write("{0} records deleted".format(index))
self.stdout.write("{0} expired sessions remaining".format(
Session.objects.filter(expire_date__lt=datetime.now())
)
)
|
from datetime import datetime
from django.core.management.base import NoArgsCommand
from django.contrib.sessions.models import Session
class Command(NoArgsCommand):
help = "Delete old sessions"
def handle_noargs(self, **options):
old_sessions = Session.objects.filter(expire_date__lt=datetime.now())
self.stdout.write("Deleting {0} expired sessions".format(
old_sessions.count()
)
)
for index, session in enumerate(old_sessions)[:10000]:
session.delete()
if str(index).endswith('000'):
self.stdout.write("{0} records deleted".format(index))
self.stdout.write("{0} expired sessions remaining".format(
Session.objects.filter(expire_date__lt=datetime.now())
)
)
|
Add delete old sessions command
|
Add delete old sessions command
|
Python
|
mit
|
QLGu/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,pydanny/djangopackages
|
648c7fb94f92e8ef722af8c9462c9ff65bf643fc
|
intelmq/bots/collectors/mail/collector_mail_body.py
|
intelmq/bots/collectors/mail/collector_mail_body.py
|
# -*- coding: utf-8 -*-
"""
Uses the common mail iteration method from the lib file.
"""
from .lib import MailCollectorBot
class MailBodyCollectorBot(MailCollectorBot):
def init(self):
super().init()
self.content_types = getattr(self.parameters, 'content_types', ('plain', 'html'))
if isinstance(self.content_types, str):
self.content_types = [x.strip() for x in self.content_types.split(',')]
elif not self.content_types or self.content_types is True: # empty string, null, false, true
self.content_types = ('plain', 'html')
def process_message(self, uid, message):
seen = False
for content_type in self.content_types:
for body in message.body[content_type]:
if not body:
continue
report = self.new_report()
report["raw"] = body
report["extra.email_subject"] = message.subject
report["extra.email_from"] = ','.join(x['email'] for x in message.sent_from)
report["extra.email_message_id"] = message.message_id
self.send_message(report)
# at least one body has successfully been processed
seen = True
return seen
BOT = MailBodyCollectorBot
|
# -*- coding: utf-8 -*-
"""
Uses the common mail iteration method from the lib file.
"""
from .lib import MailCollectorBot
class MailBodyCollectorBot(MailCollectorBot):
def init(self):
super().init()
self.content_types = getattr(self.parameters, 'content_types', ('plain', 'html'))
if isinstance(self.content_types, str):
self.content_types = [x.strip() for x in self.content_types.split(',')]
elif not self.content_types or self.content_types is True: # empty string, null, false, true
self.content_types = ('plain', 'html')
def process_message(self, uid, message):
seen = False
for content_type in self.content_types:
for body in message.body[content_type]:
if not body:
continue
report = self.new_report()
report["raw"] = body
report["extra.email_subject"] = message.subject
report["extra.email_from"] = ','.join(x['email'] for x in message.sent_from)
report["extra.email_message_id"] = message.message_id
report["extra.email_received"] = message.date
self.send_message(report)
# at least one body has successfully been processed
seen = True
return seen
BOT = MailBodyCollectorBot
|
Insert date when email was received
|
Insert date when email was received
Sometimes we receive email reports like "this is happening right now" and there is no date/time included. So if we process emails once per hour - we don't have info about event time. Additional field `extra.email_received` in the mail body collector would help.
|
Python
|
agpl-3.0
|
aaronkaplan/intelmq,aaronkaplan/intelmq,certtools/intelmq,certtools/intelmq,certtools/intelmq,aaronkaplan/intelmq
|
8286aee8eca008e2e469d49e7a426828e4f6c2bf
|
bin/s3imageresize.py
|
bin/s3imageresize.py
|
#!/usr/bin/env python
import argparse
from s3imageresize import resize_image_folder
parser = argparse.ArgumentParser(description='Upload a file to Amazon S3 and rotate old backups.')
parser.add_argument('bucket', help="Name of the Amazon S3 bucket to save the backup file to.")
parser.add_argument('prefix', help="The prefix to add before the filename for the key.")
parser.add_argument('psize', help="Path to the file to upload.")
args = parser.parse_args()
resize_image_folder(args.bucket, args.prefix, args.psize)
|
#!/usr/bin/env python
import argparse
from s3imageresize import resize_image_folder
parser = argparse.ArgumentParser(description='Resize all images stored in a folder on Amazon S3.')
parser.add_argument('bucket', help="Name of the Amazon S3 bucket to save the backup file to.")
parser.add_argument('prefix', help="The prefix to add before the filename for the key.")
parser.add_argument('width', help="Maximum width of the image.")
parser.add_argument('height', help="Maximum height of the image.")
args = parser.parse_args()
resize_image_folder(args.bucket, args.prefix, (args.width,args.height))
|
Fix parameter descriptions and change size to individual width and height parameters
|
Fix parameter descriptions and change size to individual width and height parameters
|
Python
|
mit
|
dirkcuys/s3imageresize
|
945e2def0a106541583907101060a234e6846d27
|
sources/bioformats/large_image_source_bioformats/girder_source.py
|
sources/bioformats/large_image_source_bioformats/girder_source.py
|
# -*- coding: utf-8 -*-
##############################################################################
# Copyright Kitware 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.
##############################################################################
import cherrypy
from girder_large_image.girder_tilesource import GirderTileSource
from . import BioformatsFileTileSource, _stopJavabridge
cherrypy.engine.subscribe('stop', _stopJavabridge)
class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource):
"""
Provides tile access to Girder items that can be read with bioformats.
"""
cacheName = 'tilesource'
name = 'bioformats'
|
# -*- coding: utf-8 -*-
##############################################################################
# Copyright Kitware 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.
##############################################################################
import cherrypy
from girder_large_image.girder_tilesource import GirderTileSource
from . import BioformatsFileTileSource, _stopJavabridge
cherrypy.engine.subscribe('stop', _stopJavabridge)
class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource):
"""
Provides tile access to Girder items that can be read with bioformats.
"""
cacheName = 'tilesource'
name = 'bioformats'
def mayHaveAdjacentFiles(self, largeImageFile):
# bioformats uses extensions to determine how to open a file, so this
# needs to be set for all file formats.
return True
|
Fix reading from hashed file names.
|
Fix reading from hashed file names.
Bioformats expects file extensions to exist, so flag that we should
always appear as actual, fully-pathed files.
|
Python
|
apache-2.0
|
girder/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image,DigitalSlideArchive/large_image,DigitalSlideArchive/large_image
|
82f5a5cccb8a7a36adc6f880d3cc1e11b8e596ee
|
envelope/templatetags/envelope_tags.py
|
envelope/templatetags/envelope_tags.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Template tags related to the contact form.
"""
from django import template
try:
import honeypot
except ImportError: # pragma: no cover
honeypot = None
register = template.Library()
@register.inclusion_tag('envelope/contact_form.html', takes_context=True)
def render_contact_form(context):
"""
Renders the contact form which must be in the template context.
The most common use case for this template tag is to call it in the
template rendered by :class:`~envelope.views.ContactView`. The template
tag will then render a sub-template ``envelope/contact_form.html``.
.. versionadded:: 0.7.0
"""
form = context['form']
return {
'form': form,
}
@register.simple_tag
def antispam_fields():
"""
Returns the HTML for any spam filters available.
"""
content = ''
if honeypot:
t = template.Template('{% load honeypot %}{% render_honeypot_field %}')
content += t.render(template.Context({}))
return content
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Template tags related to the contact form.
"""
from django import template
try:
import honeypot
except ImportError: # pragma: no cover
honeypot = None
register = template.Library()
@register.inclusion_tag('envelope/contact_form.html', takes_context=True)
def render_contact_form(context):
"""
Renders the contact form which must be in the template context.
The most common use case for this template tag is to call it in the
template rendered by :class:`~envelope.views.ContactView`. The template
tag will then render a sub-template ``envelope/contact_form.html``.
.. versionadded:: 0.7.0
"""
try:
form = context['form']
except KeyError:
raise template.TemplateSyntaxError("There is no 'form' variable in the template context.")
return {
'form': form,
}
@register.simple_tag
def antispam_fields():
"""
Returns the HTML for any spam filters available.
"""
content = ''
if honeypot:
t = template.Template('{% load honeypot %}{% render_honeypot_field %}')
content += t.render(template.Context({}))
return content
|
Raise a more specific error when form is not passed to the template.
|
Raise a more specific error when form is not passed to the template.
|
Python
|
mit
|
r4ts0n/django-envelope,r4ts0n/django-envelope,affan2/django-envelope,affan2/django-envelope,zsiciarz/django-envelope,zsiciarz/django-envelope
|
f1e2859f5535d7eddb13c10e71f9c0074c94c719
|
axes_login_actions/signals.py
|
axes_login_actions/signals.py
|
# -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'AXES_LOGIN_ACTIONS', [DEFAULT_ACTION])
#----------------------------------------------------------------------
def import_dotted_path(path):
"""
Takes a dotted path to a member name in a module, and returns
the member after importing it.
"""
# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(module_path)
return getattr(module, member_name)
except (ValueError, ImportError, AttributeError), e:
raise ImportError("Could not import the name: %s: %s" % (path, e))
#----------------------------------------------------------------------
@receiver(post_save, sender=AccessAttempt)
def access_attempt_handler(sender, instance, **kwargs):
for action_path in ACTIONS:
action = import_dotted_path(action_path)
action(instance, **kwargs)
|
# -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'AXES_LOGIN_ACTIONS', [DEFAULT_ACTION])
#----------------------------------------------------------------------
def import_dotted_path(path):
"""
Takes a dotted path to a member name in a module, and returns
the member after importing it.
"""
# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(module_path)
return getattr(module, member_name)
except (ValueError, ImportError, AttributeError), e:
raise ImportError("Could not import the name: %s: %s" % (path, e))
#----------------------------------------------------------------------
@receiver(post_save, sender=AccessAttempt, dispatch_uid='axes_login_actions_post_save')
def access_attempt_handler(sender, instance, **kwargs):
for action_path in ACTIONS:
action = import_dotted_path(action_path)
action(instance, **kwargs)
|
Add "dispatch_uid" to ensure we connect the signal only once
|
Add "dispatch_uid" to ensure we connect the signal only once
|
Python
|
bsd-3-clause
|
eht16/django-axes-login-actions
|
ea324a30823fbf18c72dd639b9c43d3ecb57b034
|
txircd/modules/extra/services/account_extban.py
|
txircd/modules/extra/services/account_extban.py
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase
class AccountExtban(ModuleData):
implements(IPlugin, IModuleData)
name = "AccountExtban"
def actions(self):
return [ ("usermatchban-R", 1, self.matchBan),
("usermetadataupdate", 10, self.updateBansOnAccountChange) ]
def matchBan(self, user, matchNegated, mask):
if not user.metadataKeyExists("account"):
return matchNegated
userAccount = ircLower(user.metadataValue("account"))
if fnmatchcase(userAccount, mask):
return not matchNegated
return matchNegated
def updateBansOnAccountChange(self, user, key, oldValue, value, visibility, setByUser, fromServer = None):
if key != "account":
return
self.ircd.runActionStandard("updateuserbancache", user)
matchExtban = AccountExtban()
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase
class AccountExtban(ModuleData):
implements(IPlugin, IModuleData)
name = "AccountExtban"
def actions(self):
return [ ("usermatchban-R", 1, self.matchBan),
("usermetadataupdate", 10, self.updateBansOnAccountChange) ]
def matchBan(self, user, matchNegated, mask):
if not user.metadataKeyExists("account"):
return matchNegated
userAccount = ircLower(user.metadataValue("account"))
lowerMask = ircLower(mask)
if fnmatchcase(userAccount, lowerMask):
return not matchNegated
return matchNegated
def updateBansOnAccountChange(self, user, key, oldValue, value, visibility, setByUser, fromServer = None):
if key != "account":
return
self.ircd.runActionStandard("updateuserbancache", user)
matchExtban = AccountExtban()
|
Fix matching users against R: extbans
|
Fix matching users against R: extbans
|
Python
|
bsd-3-clause
|
Heufneutje/txircd
|
d649e0ff501604d9b8b24bd69a7545528332c05c
|
polling_stations/apps/pollingstations/models.py
|
polling_stations/apps/pollingstations/models.py
|
from django.contrib.gis.db import models
from councils.models import Council
class PollingStation(models.Model):
council = models.ForeignKey(Council, null=True)
internal_council_id = models.CharField(blank=True, max_length=100)
postcode = models.CharField(blank=True, null=True, max_length=100)
address = models.TextField(blank=True, null=True)
location = models.PointField(null=True, blank=True)
objects = models.GeoManager()
class PollingDistrict(models.Model):
name = models.CharField(blank=True, null=True, max_length=255)
council = models.ForeignKey(Council, null=True)
internal_council_id = models.CharField(blank=True, max_length=100)
extra_id = models.CharField(blank=True, null=True, max_length=100)
area = models.MultiPolygonField(null=True, blank=True, geography=True)
objects = models.GeoManager()
def __unicode__(self):
return self.name
|
from django.contrib.gis.db import models
from councils.models import Council
class PollingStation(models.Model):
council = models.ForeignKey(Council, null=True)
internal_council_id = models.CharField(blank=True, max_length=100)
postcode = models.CharField(blank=True, null=True, max_length=100)
address = models.TextField(blank=True, null=True)
location = models.PointField(null=True, blank=True)
objects = models.GeoManager()
class PollingDistrict(models.Model):
name = models.CharField(blank=True, null=True, max_length=255)
council = models.ForeignKey(Council, null=True)
internal_council_id = models.CharField(blank=True, max_length=100)
extra_id = models.CharField(blank=True, null=True, max_length=100)
area = models.MultiPolygonField(null=True, blank=True, geography=True)
objects = models.GeoManager()
def __unicode__(self):
name = self.name or "Unnamed"
return "%s (%s)" % (name, self.council)
|
Fix unicode for unknown names
|
Fix unicode for unknown names
|
Python
|
bsd-3-clause
|
andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
|
c5996b4a933f2d27251e8d85f3392b715e130759
|
mapentity/templatetags/convert_tags.py
|
mapentity/templatetags/convert_tags.py
|
import urllib
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def convert_url(request, sourceurl, format='pdf'):
fullurl = request.build_absolute_uri(sourceurl)
conversion_url = "%s?url=%s&to=%s" % (settings.CONVERSION_SERVER,
urllib.quote(fullurl),
format)
return conversion_url
|
import urllib
from mimetypes import types_map
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def convert_url(request, sourceurl, format='pdf'):
if '/' not in format:
extension = '.' + format if not format.startswith('.') else format
format = types_map[extension]
fullurl = request.build_absolute_uri(sourceurl)
conversion_url = "%s?url=%s&to=%s" % (settings.CONVERSION_SERVER,
urllib.quote(fullurl),
format)
return conversion_url
|
Support conversion format as extension, instead of mimetype
|
Support conversion format as extension, instead of mimetype
|
Python
|
bsd-3-clause
|
Anaethelion/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity,Anaethelion/django-mapentity,Anaethelion/django-mapentity
|
5885c053e9bf20c7b91ebc2c8aebd1dfb9c78a46
|
avalonstar/components/broadcasts/models.py
|
avalonstar/components/broadcasts/models.py
|
# -*- coding: utf-8 -*-
from django.db import models
from components.games.models import Game
class Broadcast(models.Model):
airdate = models.DateField()
status = models.CharField(max_length=200)
number = models.IntegerField(blank=True, null=True)
# ...
games = models.ManyToManyField(Game, related_name='appears_on')
def __unicode__(self):
return 'Episode %s' % self.number
|
# -*- coding: utf-8 -*-
from django.db import models
from components.games.models import Game
class Series(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return '%s' % self.name
class Broadcast(models.Model):
airdate = models.DateField()
status = models.CharField(max_length=200)
number = models.IntegerField(blank=True, null=True)
# ...
games = models.ManyToManyField(Game, related_name='appears_on')
series = models.ForeignKey(Series, related_name='broadcasts')
# ...
def __unicode__(self):
return 'Episode %s' % self.number
|
Add the concept of series (like Whatever Wednesday).
|
Add the concept of series (like Whatever Wednesday).
|
Python
|
apache-2.0
|
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
|
c7f6e0c2e9c5be112a7576c3d2a1fc8a79eb9f18
|
brasilcomvc/settings/staticfiles.py
|
brasilcomvc/settings/staticfiles.py
|
import os
import sys
# Disable django-pipeline when in test mode
PIPELINE_ENABLED = 'test' not in sys.argv
# Main project directory
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
STATIC_BASE_DIR = os.path.join(BASE_DIR, '../webroot')
# Static file dirs
STATIC_ROOT = os.path.join(STATIC_BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(STATIC_BASE_DIR, 'media')
# Static file URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# django-pipeline settings
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATICFILES_FINDERS = (
'pipeline.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
'pipeline.compilers.stylus.StylusCompiler',
)
# Stylus configuration
PIPELINE_STYLUS_ARGUMENTS = ' '.join([
'--include {path}/common/static/styl', # Expose common styl lib dir
'--use kouto-swiss',
]).format(path=BASE_DIR)
# Packaging specs for CSS
PIPELINE_CSS = {
'app': {
'source_filenames': [
# ...
],
'output_filename': 'css/app.css',
}
}
# Packaging specs for JavaScript
PIPELINE_JS = {
}
|
import os
import sys
# Main project directory
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
STATIC_BASE_DIR = os.path.join(BASE_DIR, '../webroot')
# Static file dirs
STATIC_ROOT = os.path.join(STATIC_BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(STATIC_BASE_DIR, 'media')
# Static file URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# django-pipeline settings
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
if 'test' in sys.argv:
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
STATICFILES_FINDERS = (
'pipeline.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
'pipeline.compilers.stylus.StylusCompiler',
)
# Stylus configuration
PIPELINE_STYLUS_ARGUMENTS = ' '.join([
'--include {path}/common/static/styl', # Expose common styl lib dir
'--use kouto-swiss',
]).format(path=BASE_DIR)
# Packaging specs for CSS
PIPELINE_CSS = {
'app': {
'source_filenames': [
# ...
],
'output_filename': 'css/app.css',
}
}
# Packaging specs for JavaScript
PIPELINE_JS = {
}
|
Fix django-pipeline configuration for development/test
|
fix(set): Fix django-pipeline configuration for development/test
|
Python
|
apache-2.0
|
brasilcomvc/brasilcomvc,brasilcomvc/brasilcomvc,brasilcomvc/brasilcomvc
|
a5274f0628bec7a77fc2722ced723c4f35f3fb4b
|
microcosm_flask/fields/query_string_list.py
|
microcosm_flask/fields/query_string_list.py
|
"""
A list field field that supports query string parameter parsing.
"""
from marshmallow.fields import List, ValidationError
class SelfSerializableList(list):
def __str__(self):
return ",".join(str(item) for item in self)
class QueryStringList(List):
def _deserialize(self, value, attr, obj):
"""
_deserialize handles multiple formats of query string parameter lists
including:
/foo?bars=1,2
/foo?bars[]=1&bars[]2
and returns a list of values
"""
if value is None:
return None
try:
attribute_elements = [attr_element.split(",") for attr_element in obj.getlist(attr)]
attribute_params = SelfSerializableList(param for attr_param in attribute_elements for param in attr_param)
return attribute_params
except ValueError:
raise ValidationError("Invalid query string list argument")
|
"""
A list field field that supports query string parameter parsing.
"""
from marshmallow.fields import List, ValidationError
class PrintableList(list):
def __str__(self):
return ",".join(str(item) for item in self)
class QueryStringList(List):
def _deserialize(self, value, attr, obj):
"""
_deserialize handles multiple formats of query string parameter lists
including:
/foo?bars=1,2
/foo?bars[]=1&bars[]2
and returns a list of values
"""
if value is None:
return None
try:
attribute_elements = [attr_element.split(",") for attr_element in obj.getlist(attr)]
attribute_params = PrintableList(param for attr_param in attribute_elements for param in attr_param)
return attribute_params
except ValueError:
raise ValidationError("Invalid query string list argument")
|
Change the name of SelfSerializableList to PrintableList
|
Change the name of SelfSerializableList to PrintableList
|
Python
|
apache-2.0
|
globality-corp/microcosm-flask,globality-corp/microcosm-flask
|
faa74af66ff0542c5a08d85caf2e2b897506b1d0
|
custom/ewsghana/handlers/help.py
|
custom/ewsghana/handlers/help.py
|
from corehq.apps.products.models import SQLProduct
from custom.ewsghana.handlers import HELP_TEXT
from custom.ilsgateway.tanzania.handlers.keyword import KeywordHandler
class HelpHandler(KeywordHandler):
def help(self):
self.respond(HELP_TEXT)
def handle(self):
topic = self.args[0].lower()
if topic == 'stock':
self.respond("Please send your receipts in the format "
"' <Commodity code> <stock on hand > . <quantity received>'")
elif topic == 'stop':
self.respond("Text 'stop' to stop receiving text message reminders.")
elif topic == 'start':
self.respond("Text 'start' to get text message reminders every week to submit your stock reports.")
elif 'code' in topic:
codes = [c.code for c in SQLProduct.by_domain(self.domain).order_by('code')]
self.respond("Available commodity codes: %(codes)s", codes=", ".join(codes))
else:
try:
sql_product = SQLProduct.objects.get(domain=self.domain, code=topic)
msg = "%s is the commodity code for %s" % (topic, sql_product.name)
if sql_product.units:
msg += " (%s)" % sql_product.units
if sql_product.description and sql_product.description not in sql_product.name:
msg += " %s" % sql_product.description
self.respond(msg)
except SQLProduct.DoesNotExist:
self.help()
|
from corehq.apps.products.models import SQLProduct
from custom.ewsghana.handlers import HELP_TEXT
from custom.ilsgateway.tanzania.handlers.keyword import KeywordHandler
class HelpHandler(KeywordHandler):
def help(self):
self.respond(HELP_TEXT)
def handle(self):
topic = self.args[0].lower()
if topic == 'stock':
self.respond("Please send your receipts in the format "
"' <Commodity code> <stock on hand > . <quantity received>'")
elif topic == 'stop':
self.respond("Text 'stop' to stop receiving text message reminders.")
elif topic == 'start':
self.respond("Text 'start' to get text message reminders every week to submit your stock reports.")
elif 'code' in topic:
codes = SQLProduct.by_domain(self.domain).order_by('code').values_list('code', flat=True)
self.respond("Available commodity codes: %(codes)s", codes=", ".join(codes))
else:
try:
sql_product = SQLProduct.objects.get(domain=self.domain, code=topic)
msg = "%s is the commodity code for %s" % (topic, sql_product.name)
if sql_product.units:
msg += " (%s)" % sql_product.units
if sql_product.description and sql_product.description not in sql_product.name:
msg += " %s" % sql_product.description
self.respond(msg)
except SQLProduct.DoesNotExist:
self.help()
|
Use values_list instead of iterating over
|
Use values_list instead of iterating over
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
|
0a0d5e0c833c82a26697f049444bb6e3c359c3c7
|
django_lti_tool_provider/urls.py
|
django_lti_tool_provider/urls.py
|
from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='lti')
]
|
from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
app_name = 'django_lti_tool_provider'
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='lti')
]
|
Adjust URL configuration based on changes introduced in Django 1.9:
|
Adjust URL configuration based on changes introduced in Django 1.9:
- URL application namespace required if setting an instance namespace:
https://docs.djangoproject.com/en/2.1/releases/1.9/#url-application-namespace-required-if-setting-an-instance-namespace
|
Python
|
agpl-3.0
|
open-craft/django-lti-tool-provider
|
b0bed22c3ccafe596cf715f2be56c3261b4a6853
|
reporting_scripts/course_completers.py
|
reporting_scripts/course_completers.py
|
'''
This module extracts the student IDs from the collection certificates_generatedcertificate
of the students who completed the course and achieved a certificate. The ids
are then used to extract the usernames of the course completers
Usage:
python course_completers.py
'''
from collections import defaultdict
from base_edx import EdXConnection
from generate_csv_report import CSV
connection = EdXConnection('certificates_generatedcertificate', 'auth_user')
collection = connection.get_access_to_collection()
completers = collection['certificates_generatedcertificate'].find({'status' : 'downloadable'})
result = []
for document in completers:
user_document = collection['auth_user'].find_one({"id" : document['user_id']})
result.append([user_document['username'], document['name'], document['grade']])
output = CSV(result, ['Username', 'Name', 'Grade'], output_file='course_completers.csv')
output.generate_csv()
|
'''
This module extracts the student IDs from the collection certificates_generatedcertificate
of the students who completed the course and achieved a certificate. The ids
are then used to extract the usernames of the course completers
Usage:
python course_completers.py
'''
from collections import defaultdict
from base_edx import EdXConnection
from generate_csv_report import CSV
connection = EdXConnection('certificates_generatedcertificate', 'auth_user')
collection = connection.get_access_to_collection()
completers = collection['certificates_generatedcertificate'].find({'status' : 'downloadable'})
result = []
for document in completers:
user_document = collection['auth_user'].find_one({"id" : document['user_id']})
result.append([user_document['id'],user_document['username'], document['name'], document['grade']])
output = CSV(result, ['User ID','Username', 'Name', 'Grade'], output_file='course_completers.csv')
output.generate_csv()
|
Update to include User ID in result
|
Update to include User ID in result
|
Python
|
mit
|
McGillX/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research
|
fd9c73fc65a7234732ed55a7ae89365aec6cf123
|
behave_django/runner.py
|
behave_django/runner.py
|
from django.test.runner import DiscoverRunner
from behave_django.environment import BehaveHooksMixin
from behave_django.testcase import (BehaviorDrivenTestCase,
ExistingDatabaseTestCase)
class BehaviorDrivenTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the BehaviorDrivenTestCase
"""
testcase_class = BehaviorDrivenTestCase
class ExistingDatabaseTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the ExistingDatabaseTestCase
This test runner nullifies Django's test database setup methods. Using this
test runner would make your tests run with the default configured database
in settings.py.
"""
testcase_class = ExistingDatabaseTestCase
def setup_databases(*args, **kwargs):
pass
def teardown_databases(*args, **kwargs):
pass
|
from django.test.runner import DiscoverRunner
from behave_django.environment import BehaveHooksMixin
from behave_django.testcase import (BehaviorDrivenTestCase,
ExistingDatabaseTestCase)
class BehaviorDrivenTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the BehaviorDrivenTestCase
"""
testcase_class = BehaviorDrivenTestCase
class ExistingDatabaseTestRunner(DiscoverRunner, BehaveHooksMixin):
"""
Test runner that uses the ExistingDatabaseTestCase
This test runner nullifies Django's test database setup methods. Using this
test runner would make your tests run with the default configured database
in settings.py.
"""
testcase_class = ExistingDatabaseTestCase
def setup_databases(self, **kwargs):
pass
def teardown_databases(self, old_config, **kwargs):
pass
|
Fix Landscape complaint "Method has no argument"
|
Fix Landscape complaint "Method has no argument"
|
Python
|
mit
|
bittner/behave-django,behave/behave-django,behave/behave-django,bittner/behave-django
|
dfc7c7ae72b91f3bc7724da6b0d8071b3e9253b7
|
altair/vegalite/v2/examples/us_state_capitals.py
|
altair/vegalite/v2/examples/us_state_capitals.py
|
"""
U.S. state capitals overlayed on a map of the U.S
================================================-
This is a geographic visualization that shows US capitals
overlayed on a map.
"""
import altair as alt
from vega_datasets import data
states = alt.UrlData(data.us_10m.url,
format=alt.TopoDataFormat(type='topojson',
feature='states'))
capitals = data.us_state_capitals.url
# US states background
background = alt.Chart(states).mark_geoshape(
fill='lightgray',
stroke='white'
).properties(
projection={'type': 'albersUsa'},
width=800,
height=500
)
# State capitals labeled on background
points = alt.Chart(capitals).mark_text().encode(
alt.Text('city', type='nominal'),
alt.X('lon', type='longitude'),
alt.Y('lat', type='latitude'),
)
chart = background + points
|
"""
U.S. state capitals overlayed on a map of the U.S
================================================
This is a layered geographic visualization that shows US capitals
overlayed on a map.
"""
import altair as alt
from vega_datasets import data
states = alt.UrlData(data.us_10m.url,
format=alt.TopoDataFormat(type='topojson',
feature='states'))
capitals = data.us_state_capitals.url
# US states background
background = alt.Chart(states).mark_geoshape(
fill='lightgray',
stroke='white'
).properties(
projection={'type': 'albersUsa'},
width=800,
height=500
)
# State capitals labeled on background
points = alt.Chart(capitals).mark_text(dy=-5, align='right').encode(
alt.Text('city', type='nominal'),
alt.X('lon', type='longitude'),
alt.Y('lat', type='latitude'),
)
chart = background + points + points.mark_point(color='black')
|
Add points for capital locations>
|
Add points for capital locations>
|
Python
|
bsd-3-clause
|
ellisonbg/altair,jakevdp/altair,altair-viz/altair
|
80a940305765a22f96b0c0af0b0b46f1e3f5c377
|
tests/unit/models/listing/test_generator.py
|
tests/unit/models/listing/test_generator.py
|
"""Test praw.models.front."""
from praw.models.listing.generator import ListingGenerator
from ... import UnitTest
class TestListingGenerator(UnitTest):
def test_params_are_not_modified(self):
params = {"prawtest": "yes"}
generator = ListingGenerator(None, None, params=params)
assert "limit" in generator.params
assert "limit" not in params
assert ("prawtest", "yes") in generator.params.items()
|
"""Test praw.models.listing.generator."""
from praw.models.listing.generator import ListingGenerator
from ... import UnitTest
class TestListingGenerator(UnitTest):
def test_params_are_not_modified(self):
params = {"prawtest": "yes"}
generator = ListingGenerator(None, None, params=params)
assert "limit" in generator.params
assert "limit" not in params
assert ("prawtest", "yes") in generator.params.items()
|
Fix docstring typo in ListingGenerator unit tests
|
Fix docstring typo in ListingGenerator unit tests
|
Python
|
bsd-2-clause
|
praw-dev/praw,praw-dev/praw
|
7416f2fc34bad2036024874ad6a0c9a5f57d0657
|
education/management/commands/fake_incoming_message.py
|
education/management/commands/fake_incoming_message.py
|
from django.core.management.base import BaseCommand
from optparse import make_option
from rapidsms_httprouter.router import get_router
from rapidsms.models import Connection
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option("-p", "--phone", dest="phone"),
make_option("-t", "--text", dest="text"),
)
def handle(self, **options):
if not options['phone']:
phone = raw_input('Phone number you wish the message to appear to come from: ')
else:
phone = options['phone']
if not options['text']:
text = raw_input('Text of the message: ')
else:
text = options['text']
connection = Connection.object.get(identity = phone)
router = get_router()
handled = router.handle_incoming(connection.backend.name, connection.identity, text)
self.stdout.write('Done!\n')
|
from django.core.management.base import BaseCommand
from optparse import make_option
from rapidsms_httprouter.router import get_router
from rapidsms.models import Connection
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option("-p", "--phone", dest="phone"),
make_option("-t", "--text", dest="text"),
)
def handle(self, **options):
phone = options['phone'] or raw_input('Phone number you wish the message to appear to come from: ')
text = options['text'] or raw_input('Text of the message: ')
connection = Connection.objects.get(identity = phone)
router = get_router()
handled = router.handle_incoming(connection.backend.name, connection.identity, text)
self.stdout.write('Done!\n')
|
Simplify the requesting of parameters.
|
Simplify the requesting of parameters.
|
Python
|
bsd-3-clause
|
unicefuganda/edtrac,unicefuganda/edtrac,unicefuganda/edtrac
|
e5a94d2902a66d55be62b92e35ac90ac7aed7991
|
javascript/navigator/__init__.py
|
javascript/navigator/__init__.py
|
__author__ = 'katharine'
import PyV8 as v8
from geolocation import Geolocation
class Navigator(v8.JSClass):
def __init__(self, runtime):
# W3C spec says that if geolocation is disabled, navigator.geolocation should not exist.
# if 'location' in runtime.manifest.get('capabilities', []):
if True:
self.geolocation = Geolocation(runtime)
|
__author__ = 'katharine'
import PyV8 as v8
from geolocation import Geolocation
from javascript.exceptions import JSRuntimeException
class Navigator(v8.JSClass):
def __init__(self, runtime):
self._runtime = runtime
# W3C spec says that if geolocation is disabled, navigator.geolocation should not exist.
if 'location' in runtime.manifest.get('capabilities', []):
self.geolocation = Geolocation(runtime)
def __getattr__(self, item):
# __getattr__ is only called if something does not exist. Therefore, if it's called, geolocation
# does not exist.
# This approach lets us report it doesn't exist if tested for (e.g. `'geolocation' in navigator`),
# but throw an informative exception if it's accessed.
if item == 'geolocation':
raise JSRuntimeException(
self._runtime,
"You must add 'location' to the appinfo.json capabilities array to access geolocation."
)
else:
raise AttributeError
|
Implement location restriction more thoroughly.
|
Implement location restriction more thoroughly.
|
Python
|
mit
|
youtux/pypkjs,pebble/pypkjs
|
70847e9d88f086d52e167629666aebe5137c7a2e
|
debileweb/blueprints/forms.py
|
debileweb/blueprints/forms.py
|
from wtforms import TextField, BooleanField, Form
from wtforms.validators import Required
class SearchPackageForm(Form):
package = TextField('package', validators = [Required()])
maintainer = TextField('maintainer', validators = [Required()])
|
# Copyright (c) 2013 Sylvestre Ledru <sylvestre@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from wtforms import TextField, Form
from wtforms.validators import Required
class SearchPackageForm(Form):
package = TextField('package', validators = [Required()])
maintainer = TextField('maintainer', validators = [Required()])
|
Add license + remove useless declaration
|
Add license + remove useless declaration
|
Python
|
mit
|
opencollab/debile-web,opencollab/debile-web,opencollab/debile-web
|
78ca15758018d52f1353b29410f97bba215e0be2
|
django_afip/views.py
|
django_afip/views.py
|
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
template_name = 'django_afip/invoice.html'
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
|
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
|
Remove unused (albeit confusing) variable
|
Remove unused (albeit confusing) variable
See #13
|
Python
|
isc
|
hobarrera/django-afip,hobarrera/django-afip
|
13a2ea421b761b9009fb7e1328e54cf0ae5cc54f
|
gapipy/resources/booking/agency.py
|
gapipy/resources/booking/agency.py
|
from __future__ import unicode_literals
from ...models import Address
from ...models import AgencyDocument
from .agency_chain import AgencyChain
from ..base import Resource
from ..tour import Promotion
class Agency(Resource):
_resource_name = 'agencies'
_is_listable = False
_is_parent_resource = True
_as_is_fields = ['id', 'href', 'name', 'booking_currencies', 'latitude', 'longitude']
_date_time_fields_local = ['date_created']
_model_fields = [('address', Address)]
_resource_fields = [('agency_chain', AgencyChain)]
_model_collection_fields = [('documents', AgencyDocument)]
_resource_collection_fields = [
('bookings', 'Booking'),
('agents', 'Agent'),
('promotions', Promotion),
]
|
from __future__ import unicode_literals
from ...models import Address
from ...models import AgencyDocument
from ...models.base import BaseModel
from .agency_chain import AgencyChain
from ..base import Resource
from ..tour import Promotion
class AgencyEmail(BaseModel):
_as_is_fields = ['type', 'address']
class Agency(Resource):
_resource_name = 'agencies'
_is_listable = False
_is_parent_resource = True
_as_is_fields = ['id', 'href', 'name', 'booking_currencies', 'latitude', 'longitude', 'transactional_email']
_date_time_fields_local = ['date_created']
_model_fields = [('address', Address)]
_resource_fields = [('agency_chain', AgencyChain)]
_model_collection_fields = [
('documents', AgencyDocument),
('emails', AgencyEmail),
]
_resource_collection_fields = [
('bookings', 'Booking'),
('agents', 'Agent'),
('promotions', Promotion),
]
|
Add new Agency resource fields
|
Add new Agency resource fields
|
Python
|
mit
|
gadventures/gapipy
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.