commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
fef12d2a5cce5c1db488a4bb11b9c21b83a66cab
avocado/export/_json.py
avocado/export/_json.py
import json import inspect from _base import BaseExporter class JSONGeneratorEncoder(json.JSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
import inspect from django.core.serializers.json import DjangoJSONEncoder from _base import BaseExporter class JSONGeneratorEncoder(DjangoJSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
Update JSONGeneratorEncoder to subclass DjangoJSONEncoder This handles Decimals and datetimes
Update JSONGeneratorEncoder to subclass DjangoJSONEncoder This handles Decimals and datetimes
Python
bsd-2-clause
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
- import json import inspect + from django.core.serializers.json import DjangoJSONEncoder from _base import BaseExporter - class JSONGeneratorEncoder(json.JSONEncoder): + class JSONGeneratorEncoder(DjangoJSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
Update JSONGeneratorEncoder to subclass DjangoJSONEncoder This handles Decimals and datetimes
## Code Before: import json import inspect from _base import BaseExporter class JSONGeneratorEncoder(json.JSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff ## Instruction: Update JSONGeneratorEncoder to subclass DjangoJSONEncoder This handles Decimals and datetimes ## Code After: import inspect from django.core.serializers.json import DjangoJSONEncoder from _base import BaseExporter class JSONGeneratorEncoder(DjangoJSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
- import json import inspect + from django.core.serializers.json import DjangoJSONEncoder from _base import BaseExporter - class JSONGeneratorEncoder(json.JSONEncoder): ? ^ -- + class JSONGeneratorEncoder(DjangoJSONEncoder): ? + ^^^ "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
677d2d4f422f9b05746fa80d63492de4ae9aced4
tests/test_examples.py
tests/test_examples.py
import pytest import examples.basic_usage import examples.basic_usage_manual import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage_manual.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
import importlib import importlib.util import sys import types import pytest def load_script(example: str) -> types.ModuleType: file_path = f"examples/{example}.py" module_name = "run" spec = importlib.util.spec_from_file_location(module_name, file_path) assert spec is not None module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module assert spec.loader is not None spec.loader.exec_module(module) return module def test_dataset(unihan_options): example = load_script("dataset") example.run() def test_variants(unihan_options): example = load_script("variants") example.run() def test_ts_difficulties(unihan_options): example = load_script("variant_ts_difficulties") example.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage_manual") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
Rework for handling of examples/
refactor(tests): Rework for handling of examples/
Python
mit
cihai/cihai,cihai/cihai
+ import importlib + import importlib.util + import sys + import types + import pytest - import examples.basic_usage - import examples.basic_usage_manual - import examples.dataset - import examples.variant_ts_difficulties - import examples.variants + + def load_script(example: str) -> types.ModuleType: + file_path = f"examples/{example}.py" + module_name = "run" + + spec = importlib.util.spec_from_file_location(module_name, file_path) + assert spec is not None + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + + assert spec.loader is not None + spec.loader.exec_module(module) + + return module def test_dataset(unihan_options): + example = load_script("dataset") - examples.dataset.run() + example.run() def test_variants(unihan_options): - examples.variants.run(unihan_options=unihan_options) + example = load_script("variants") + example.run() def test_ts_difficulties(unihan_options): + example = load_script("variant_ts_difficulties") - examples.variant_ts_difficulties.run(unihan_options=unihan_options) + example.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): + example = load_script("basic_usage") - examples.basic_usage.run(unihan_options=unihan_options) + example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): + example = load_script("basic_usage_manual") - examples.basic_usage_manual.run(unihan_options=unihan_options) + example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
Rework for handling of examples/
## Code Before: import pytest import examples.basic_usage import examples.basic_usage_manual import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage_manual.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out ## Instruction: Rework for handling of examples/ ## Code After: import importlib import importlib.util import sys import types import pytest def load_script(example: str) -> types.ModuleType: file_path = f"examples/{example}.py" module_name = "run" spec = importlib.util.spec_from_file_location(module_name, file_path) assert spec is not None module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module assert spec.loader is not None spec.loader.exec_module(module) return module def test_dataset(unihan_options): example = load_script("dataset") example.run() def test_variants(unihan_options): example = load_script("variants") example.run() def test_ts_difficulties(unihan_options): example = load_script("variant_ts_difficulties") example.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage_manual") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
+ import importlib + import importlib.util + import sys + import types + import pytest - import examples.basic_usage - import examples.basic_usage_manual - import examples.dataset - import examples.variant_ts_difficulties - import examples.variants + + def load_script(example: str) -> types.ModuleType: + file_path = f"examples/{example}.py" + module_name = "run" + + spec = importlib.util.spec_from_file_location(module_name, file_path) + assert spec is not None + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + + assert spec.loader is not None + spec.loader.exec_module(module) + + return module def test_dataset(unihan_options): + example = load_script("dataset") - examples.dataset.run() ? --------- + example.run() def test_variants(unihan_options): - examples.variants.run(unihan_options=unihan_options) + example = load_script("variants") + example.run() def test_ts_difficulties(unihan_options): + example = load_script("variant_ts_difficulties") - examples.variant_ts_difficulties.run(unihan_options=unihan_options) ? ------------------------- + example.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): + example = load_script("basic_usage") - examples.basic_usage.run(unihan_options=unihan_options) ? ------------- + example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): + example = load_script("basic_usage_manual") - examples.basic_usage_manual.run(unihan_options=unihan_options) ? -------------------- + example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
61e8b679c64c7c2155c1c3f5077cf058dd6610d3
forms.py
forms.py
from django.utils.translation import ugettext_lazy as _ from django.forms.fields import RegexField, Select class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): from jp_prefectures import JP_PREFECTURES super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
from __future__ import absolute_import from django.contrib.localflavor.jp.jp_prefectures import JP_PREFECTURES from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
Remove all relative imports. We have always been at war with relative imports.
Remove all relative imports. We have always been at war with relative imports. git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@17009 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Python
bsd-3-clause
luyikei/django-localflavor-jp
+ from __future__ import absolute_import + + from django.contrib.localflavor.jp.jp_prefectures import JP_PREFECTURES + from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ - from django.forms.fields import RegexField, Select + class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): - from jp_prefectures import JP_PREFECTURES super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
Remove all relative imports. We have always been at war with relative imports.
## Code Before: from django.utils.translation import ugettext_lazy as _ from django.forms.fields import RegexField, Select class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): from jp_prefectures import JP_PREFECTURES super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES) ## Instruction: Remove all relative imports. We have always been at war with relative imports. ## Code After: from __future__ import absolute_import from django.contrib.localflavor.jp.jp_prefectures import JP_PREFECTURES from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
+ from __future__ import absolute_import + + from django.contrib.localflavor.jp.jp_prefectures import JP_PREFECTURES + from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ - from django.forms.fields import RegexField, Select + class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): - from jp_prefectures import JP_PREFECTURES super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
1b40a51e371d10cc37f4d8f8c7557dbc741d690f
butterfly/ImageLayer/HDF5.py
butterfly/ImageLayer/HDF5.py
from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE (K0,J0,I0),(K1,J1,I1) = query.source_bounds with h5py.File(path) as fd: vol = fd[fd.keys()[0]] return vol[::Sk,::Sj,::Si]
from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE z0,y0,x0 = query.index_zyx*query.blocksize z1,y1,x1 = query.index_zyx*query.blocksize + query.blocksize with h5py.File(path) as fd: vol = fd[fd.keys()[0]] return vol[z0:z1:Sk,y0:y1:Sj,x0:x1:Si]
Fix loading a whole tile into memory.
Fix loading a whole tile into memory.
Python
mit
Rhoana/butterfly,Rhoana/butterfly,Rhoana/butterfly2,Rhoana/butterfly,Rhoana/butterfly
from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE - (K0,J0,I0),(K1,J1,I1) = query.source_bounds + z0,y0,x0 = query.index_zyx*query.blocksize + z1,y1,x1 = query.index_zyx*query.blocksize + query.blocksize with h5py.File(path) as fd: vol = fd[fd.keys()[0]] - return vol[::Sk,::Sj,::Si] + return vol[z0:z1:Sk,y0:y1:Sj,x0:x1:Si]
Fix loading a whole tile into memory.
## Code Before: from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE (K0,J0,I0),(K1,J1,I1) = query.source_bounds with h5py.File(path) as fd: vol = fd[fd.keys()[0]] return vol[::Sk,::Sj,::Si] ## Instruction: Fix loading a whole tile into memory. ## Code After: from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE z0,y0,x0 = query.index_zyx*query.blocksize z1,y1,x1 = query.index_zyx*query.blocksize + query.blocksize with h5py.File(path) as fd: vol = fd[fd.keys()[0]] return vol[z0:z1:Sk,y0:y1:Sj,x0:x1:Si]
from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE - (K0,J0,I0),(K1,J1,I1) = query.source_bounds + z0,y0,x0 = query.index_zyx*query.blocksize + z1,y1,x1 = query.index_zyx*query.blocksize + query.blocksize with h5py.File(path) as fd: vol = fd[fd.keys()[0]] - return vol[::Sk,::Sj,::Si] + return vol[z0:z1:Sk,y0:y1:Sj,x0:x1:Si] ? ++ ++ ++ ++ ++ ++
5363224395b26528465417ff550d6a2163cbe8e6
spacy/zh/__init__.py
spacy/zh/__init__.py
from ..language import Language from ..tokenizer import Tokenizer from ..tagger import Tagger class CharacterTokenizer(Tokenizer): def __call__(self, text): return self.tokens_from_list(list(text)) class Chinese(Language): lang = u'zh' def __call__(self, text): doc = self.tokenizer.tokens_from_list(list(text)) self.tagger(doc) self.merge_characters(doc) return doc def merge_characters(self, doc): start = 0 chunks = [] for token in doc: if token.tag_ != 'CHAR': chunk = doc[start : token.i + 1] chunks.append(chunk) start = token.i + 1 text = doc.text for chunk in chunks: chunk.merge(chunk[-1].tag_, chunk.text, u'')
import jieba from ..language import Language from ..tokens import Doc class Chinese(Language): lang = u'zh' def make_doc(self, text): words = list(jieba.cut(text, cut_all=True)) return Doc(self.vocab, words=words, spaces=[False]*len(words))
Add draft Jieba tokenizer for Chinese
Add draft Jieba tokenizer for Chinese
Python
mit
spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,honnibal/spaCy,banglakit/spaCy,explosion/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,recognai/spaCy,banglakit/spaCy,recognai/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,spacy-io/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,raphael0202/spaCy,spacy-io/spaCy,raphael0202/spaCy,honnibal/spaCy,raphael0202/spaCy,aikramer2/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,Gregory-Howard/spaCy,recognai/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,banglakit/spaCy,recognai/spaCy,explosion/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,banglakit/spaCy,spacy-io/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy
+ import jieba + from ..language import Language + from ..tokens import Doc - from ..tokenizer import Tokenizer - from ..tagger import Tagger - - - class CharacterTokenizer(Tokenizer): - def __call__(self, text): - return self.tokens_from_list(list(text)) class Chinese(Language): lang = u'zh' - def __call__(self, text): + def make_doc(self, text): + words = list(jieba.cut(text, cut_all=True)) + return Doc(self.vocab, words=words, spaces=[False]*len(words)) - doc = self.tokenizer.tokens_from_list(list(text)) - self.tagger(doc) - self.merge_characters(doc) - return doc - def merge_characters(self, doc): - start = 0 - chunks = [] - for token in doc: - if token.tag_ != 'CHAR': - chunk = doc[start : token.i + 1] - chunks.append(chunk) - start = token.i + 1 - text = doc.text - for chunk in chunks: - chunk.merge(chunk[-1].tag_, chunk.text, u'') -
Add draft Jieba tokenizer for Chinese
## Code Before: from ..language import Language from ..tokenizer import Tokenizer from ..tagger import Tagger class CharacterTokenizer(Tokenizer): def __call__(self, text): return self.tokens_from_list(list(text)) class Chinese(Language): lang = u'zh' def __call__(self, text): doc = self.tokenizer.tokens_from_list(list(text)) self.tagger(doc) self.merge_characters(doc) return doc def merge_characters(self, doc): start = 0 chunks = [] for token in doc: if token.tag_ != 'CHAR': chunk = doc[start : token.i + 1] chunks.append(chunk) start = token.i + 1 text = doc.text for chunk in chunks: chunk.merge(chunk[-1].tag_, chunk.text, u'') ## Instruction: Add draft Jieba tokenizer for Chinese ## Code After: import jieba from ..language import Language from ..tokens import Doc class Chinese(Language): lang = u'zh' def make_doc(self, text): words = list(jieba.cut(text, cut_all=True)) return Doc(self.vocab, words=words, spaces=[False]*len(words))
+ import jieba + from ..language import Language + from ..tokens import Doc - from ..tokenizer import Tokenizer - from ..tagger import Tagger - - - class CharacterTokenizer(Tokenizer): - def __call__(self, text): - return self.tokens_from_list(list(text)) class Chinese(Language): lang = u'zh' - def __call__(self, text): ? ^ ----- + def make_doc(self, text): ? ++++ ^^ + words = list(jieba.cut(text, cut_all=True)) + return Doc(self.vocab, words=words, spaces=[False]*len(words)) - doc = self.tokenizer.tokens_from_list(list(text)) - self.tagger(doc) - self.merge_characters(doc) - return doc - - def merge_characters(self, doc): - start = 0 - chunks = [] - for token in doc: - if token.tag_ != 'CHAR': - chunk = doc[start : token.i + 1] - chunks.append(chunk) - start = token.i + 1 - text = doc.text - for chunk in chunks: - chunk.merge(chunk[-1].tag_, chunk.text, u'')
c55a2b152cd2b6603ef358e0f764eeb0308ff332
Orange/__init__.py
Orange/__init__.py
from __future__ import absolute_import from importlib import import_module try: from .import version # Always use short_version here (see PEP 386) __version__ = version.short_version __git_revision__ = version.git_revision except ImportError: __version__ = "unknown" __git_revision__ = "unknown" ADDONS_ENTRY_POINT = 'orange.addons' import warnings import pkg_resources alreadyWarned = False disabledMsg = "Some features will be disabled due to failing modules\n" def _import(name): global alreadyWarned try: import_module(name, package='Orange') except ImportError as err: warnings.warn("%sImporting '%s' failed: %s" % (disabledMsg if not alreadyWarned else "", name, err), UserWarning, 2) alreadyWarned = True def import_all(): import Orange for name in ["classification", "clustering", "data", "distance", "evaluation", "feature", "misc", "regression", "statistics"]: Orange.__dict__[name] = import_module('Orange.' + name, package='Orange') # Alternatives: # global classification # import Orange.classification as classification # or # import Orange.classification as classification # globals()['clasification'] = classification _import(".data") _import(".distance") _import(".feature") _import(".feature.discretization") _import(".data.discretization") del _import del alreadyWarned del disabledMsg
from __future__ import absolute_import from importlib import import_module try: from .import version # Always use short_version here (see PEP 386) __version__ = version.short_version __git_revision__ = version.git_revision except ImportError: __version__ = "unknown" __git_revision__ = "unknown" ADDONS_ENTRY_POINT = 'orange.addons' import warnings import pkg_resources alreadyWarned = False disabledMsg = "Some features will be disabled due to failing modules\n" def _import(name): global alreadyWarned try: import_module(name, package='Orange') except ImportError as err: warnings.warn("%sImporting '%s' failed: %s" % (disabledMsg if not alreadyWarned else "", name, err), UserWarning, 2) alreadyWarned = True def import_all(): import Orange for name in ["classification", "clustering", "data", "distance", "evaluation", "feature", "misc", "regression", "statistics"]: Orange.__dict__[name] = import_module('Orange.' + name, package='Orange') # Alternatives: # global classification # import Orange.classification as classification # or # import Orange.classification as classification # globals()['clasification'] = classification _import(".data") del _import del alreadyWarned del disabledMsg
Remove imports in Orange, except data
Remove imports in Orange, except data
Python
bsd-2-clause
marinkaz/orange3,kwikadi/orange3,qusp/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,kwikadi/orange3,qPCR4vir/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,qusp/orange3,qPCR4vir/orange3,cheral/orange3,qusp/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,qusp/orange3,kwikadi/orange3,cheral/orange3,marinkaz/orange3,cheral/orange3
from __future__ import absolute_import from importlib import import_module try: from .import version # Always use short_version here (see PEP 386) __version__ = version.short_version __git_revision__ = version.git_revision except ImportError: __version__ = "unknown" __git_revision__ = "unknown" ADDONS_ENTRY_POINT = 'orange.addons' import warnings import pkg_resources alreadyWarned = False disabledMsg = "Some features will be disabled due to failing modules\n" def _import(name): global alreadyWarned try: import_module(name, package='Orange') except ImportError as err: warnings.warn("%sImporting '%s' failed: %s" % (disabledMsg if not alreadyWarned else "", name, err), UserWarning, 2) alreadyWarned = True def import_all(): import Orange for name in ["classification", "clustering", "data", "distance", "evaluation", "feature", "misc", "regression", "statistics"]: Orange.__dict__[name] = import_module('Orange.' + name, package='Orange') # Alternatives: # global classification # import Orange.classification as classification # or # import Orange.classification as classification # globals()['clasification'] = classification _import(".data") - _import(".distance") - _import(".feature") - _import(".feature.discretization") - _import(".data.discretization") del _import del alreadyWarned del disabledMsg
Remove imports in Orange, except data
## Code Before: from __future__ import absolute_import from importlib import import_module try: from .import version # Always use short_version here (see PEP 386) __version__ = version.short_version __git_revision__ = version.git_revision except ImportError: __version__ = "unknown" __git_revision__ = "unknown" ADDONS_ENTRY_POINT = 'orange.addons' import warnings import pkg_resources alreadyWarned = False disabledMsg = "Some features will be disabled due to failing modules\n" def _import(name): global alreadyWarned try: import_module(name, package='Orange') except ImportError as err: warnings.warn("%sImporting '%s' failed: %s" % (disabledMsg if not alreadyWarned else "", name, err), UserWarning, 2) alreadyWarned = True def import_all(): import Orange for name in ["classification", "clustering", "data", "distance", "evaluation", "feature", "misc", "regression", "statistics"]: Orange.__dict__[name] = import_module('Orange.' + name, package='Orange') # Alternatives: # global classification # import Orange.classification as classification # or # import Orange.classification as classification # globals()['clasification'] = classification _import(".data") _import(".distance") _import(".feature") _import(".feature.discretization") _import(".data.discretization") del _import del alreadyWarned del disabledMsg ## Instruction: Remove imports in Orange, except data ## Code After: from __future__ import absolute_import from importlib import import_module try: from .import version # Always use short_version here (see PEP 386) __version__ = version.short_version __git_revision__ = version.git_revision except ImportError: __version__ = "unknown" __git_revision__ = "unknown" ADDONS_ENTRY_POINT = 'orange.addons' import warnings import pkg_resources alreadyWarned = False disabledMsg = "Some features will be disabled due to failing modules\n" def _import(name): global alreadyWarned try: import_module(name, package='Orange') except ImportError as err: warnings.warn("%sImporting '%s' failed: %s" % (disabledMsg if not alreadyWarned else "", name, err), UserWarning, 2) alreadyWarned = True def import_all(): import Orange for name in ["classification", "clustering", "data", "distance", "evaluation", "feature", "misc", "regression", "statistics"]: Orange.__dict__[name] = import_module('Orange.' + name, package='Orange') # Alternatives: # global classification # import Orange.classification as classification # or # import Orange.classification as classification # globals()['clasification'] = classification _import(".data") del _import del alreadyWarned del disabledMsg
from __future__ import absolute_import from importlib import import_module try: from .import version # Always use short_version here (see PEP 386) __version__ = version.short_version __git_revision__ = version.git_revision except ImportError: __version__ = "unknown" __git_revision__ = "unknown" ADDONS_ENTRY_POINT = 'orange.addons' import warnings import pkg_resources alreadyWarned = False disabledMsg = "Some features will be disabled due to failing modules\n" def _import(name): global alreadyWarned try: import_module(name, package='Orange') except ImportError as err: warnings.warn("%sImporting '%s' failed: %s" % (disabledMsg if not alreadyWarned else "", name, err), UserWarning, 2) alreadyWarned = True def import_all(): import Orange for name in ["classification", "clustering", "data", "distance", "evaluation", "feature", "misc", "regression", "statistics"]: Orange.__dict__[name] = import_module('Orange.' + name, package='Orange') # Alternatives: # global classification # import Orange.classification as classification # or # import Orange.classification as classification # globals()['clasification'] = classification _import(".data") - _import(".distance") - _import(".feature") - _import(".feature.discretization") - _import(".data.discretization") del _import del alreadyWarned del disabledMsg
c30d9685239607883aeaee73618651f694f7d1b2
server/lib/slack/add_player.py
server/lib/slack/add_player.py
import re import lib.webutil as webutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_player(new_player_id) if player is not None: return webutil.respond_success('A player record for you already exists.') player_data.add_player(new_player_id) return webutil.respond_success('Alright, <@' + new_player_id + '>, you\'re ready to play!')
import re import lib.webutil as webutil import slack.util as slackutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_player(new_player_id) if player is not None: return webutil.respond_success('A player record for <@' + new_player_id + '> already exists.') player_data.add_player(new_player_id) return webutil.respond_success(slackutil.in_channel_response('Alright, <@' + new_player_id + '> is ready to play!'))
Update response for adding a player
Update response for adding a player
Python
mit
groppe/mario
import re import lib.webutil as webutil + import slack.util as slackutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_player(new_player_id) if player is not None: - return webutil.respond_success('A player record for you already exists.') + return webutil.respond_success('A player record for <@' + new_player_id + '> already exists.') player_data.add_player(new_player_id) - return webutil.respond_success('Alright, <@' + new_player_id + '>, you\'re ready to play!') + return webutil.respond_success(slackutil.in_channel_response('Alright, <@' + new_player_id + '> is ready to play!'))
Update response for adding a player
## Code Before: import re import lib.webutil as webutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_player(new_player_id) if player is not None: return webutil.respond_success('A player record for you already exists.') player_data.add_player(new_player_id) return webutil.respond_success('Alright, <@' + new_player_id + '>, you\'re ready to play!') ## Instruction: Update response for adding a player ## Code After: import re import lib.webutil as webutil import slack.util as slackutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_player(new_player_id) if player is not None: return webutil.respond_success('A player record for <@' + new_player_id + '> already exists.') player_data.add_player(new_player_id) return webutil.respond_success(slackutil.in_channel_response('Alright, <@' + new_player_id + '> is ready to play!'))
import re import lib.webutil as webutil + import slack.util as slackutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_player(new_player_id) if player is not None: - return webutil.respond_success('A player record for you already exists.') ? ^^ + return webutil.respond_success('A player record for <@' + new_player_id + '> already exists.') ? +++++++++++++ ^^^^^^^^^^ player_data.add_player(new_player_id) - return webutil.respond_success('Alright, <@' + new_player_id + '>, you\'re ready to play!') ? - ^^^^^^^ + return webutil.respond_success(slackutil.in_channel_response('Alright, <@' + new_player_id + '> is ready to play!')) ? ++++++++++++++++++++++++++++++ ^^ +
7c3c9e2ab7be0d91b4edc3d15d50cc1245941e47
logicaldelete/models.py
logicaldelete/models.py
from django.db import models try: from django.utils import timezone except ImportError: from datetime import datetime as timezonefrom logicaldelete import managers class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True
from django.db import models from logicaldelete import managers try: from django.utils import timezone except ImportError: from datetime import datetime as timezone class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True
Fix issue with manager (error w cut and paste)
Fix issue with manager (error w cut and paste)
Python
bsd-3-clause
angvp/django-logical-delete,angvp/django-logical-delete
from django.db import models + from logicaldelete import managers try: from django.utils import timezone except ImportError: - from datetime import datetime as timezonefrom logicaldelete import managers + from datetime import datetime as timezone + class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True
Fix issue with manager (error w cut and paste)
## Code Before: from django.db import models try: from django.utils import timezone except ImportError: from datetime import datetime as timezonefrom logicaldelete import managers class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True ## Instruction: Fix issue with manager (error w cut and paste) ## Code After: from django.db import models from logicaldelete import managers try: from django.utils import timezone except ImportError: from datetime import datetime as timezone class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True
from django.db import models + from logicaldelete import managers try: from django.utils import timezone except ImportError: - from datetime import datetime as timezonefrom logicaldelete import managers + from datetime import datetime as timezone + class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True
f20e7abc1672b3814062357add9f3adc1ca300f9
editorsnotes/main/migrations/0021_populate_display_name.py
editorsnotes/main/migrations/0021_populate_display_name.py
from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): user.display_name = user._get_display_name() user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): if user.first_name or user.last_name: display_name = user.first_name + ' ' + user.last_name display_name = display_name.strip().rstrip() else: display_name = user.username user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
Fix data migration for user display names
Fix data migration for user display names
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): + if user.first_name or user.last_name: + display_name = user.first_name + ' ' + user.last_name + display_name = display_name.strip().rstrip() + else: + display_name = user.username + - user.display_name = user._get_display_name() + user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
Fix data migration for user display names
## Code Before: from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): user.display_name = user._get_display_name() user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ] ## Instruction: Fix data migration for user display names ## Code After: from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): if user.first_name or user.last_name: display_name = user.first_name + ' ' + user.last_name display_name = display_name.strip().rstrip() else: display_name = user.username user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
from __future__ import unicode_literals from django.db import migrations, models def populate_usernames(apps, schema_editor): User = apps.get_model('main', 'User') for user in User.objects.all(): + if user.first_name or user.last_name: + display_name = user.first_name + ' ' + user.last_name + display_name = display_name.strip().rstrip() + else: + display_name = user.username + - user.display_name = user._get_display_name() ? ---------- -- + user.display_name = display_name user.save() class Migration(migrations.Migration): dependencies = [ ('main', '0020_user_display_name'), ] operations = [ migrations.RunPython(populate_usernames) ]
ff308a17c79fe2c27dcb2a1f888ee1332f6fdc11
events.py
events.py
import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): return None texts = util.text_preceding_points(view, points) if all([text.strip().endswith('perform') for text in texts]): subroutines = util.find_text_by_selector(view, 'entity.name.function.natural') if not subroutines: return None subroutines.sort() completions = [[sub, sub] for sub in subroutines] return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): return None texts = util.text_preceding_points(view, points) if all([text.strip().endswith('perform') for text in texts]): subroutines = util.find_text_by_selector(view, 'entity.name.function.natural') if not subroutines: return None subroutines.sort() completions = [[sub, sub] for sub in subroutines] return (completions, sublime.INHIBIT_WORD_COMPLETIONS) class AddRulerToColumn72Listener(sublime_plugin.EventListener): """Add a ruler to column 72 when a Natural file is opened. If the user has other rulers, they're not messed with.""" def on_load(self, view): if not util.is_natural_file(view): return rulers = view.settings().get('rulers') if 72 not in rulers: rulers.append(72) rulers.sort() view.settings().set('rulers', rulers)
Add a ruler to column 72
Add a ruler to column 72
Python
mit
andref/Unnatural-Sublime-Package
import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): return None texts = util.text_preceding_points(view, points) if all([text.strip().endswith('perform') for text in texts]): subroutines = util.find_text_by_selector(view, 'entity.name.function.natural') if not subroutines: return None subroutines.sort() completions = [[sub, sub] for sub in subroutines] return (completions, sublime.INHIBIT_WORD_COMPLETIONS) + + class AddRulerToColumn72Listener(sublime_plugin.EventListener): + """Add a ruler to column 72 when a Natural file is opened. If the user has + other rulers, they're not messed with.""" + + def on_load(self, view): + if not util.is_natural_file(view): + return + rulers = view.settings().get('rulers') + if 72 not in rulers: + rulers.append(72) + rulers.sort() + view.settings().set('rulers', rulers) +
Add a ruler to column 72
## Code Before: import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): return None texts = util.text_preceding_points(view, points) if all([text.strip().endswith('perform') for text in texts]): subroutines = util.find_text_by_selector(view, 'entity.name.function.natural') if not subroutines: return None subroutines.sort() completions = [[sub, sub] for sub in subroutines] return (completions, sublime.INHIBIT_WORD_COMPLETIONS) ## Instruction: Add a ruler to column 72 ## Code After: import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): return None texts = util.text_preceding_points(view, points) if all([text.strip().endswith('perform') for text in texts]): subroutines = util.find_text_by_selector(view, 'entity.name.function.natural') if not subroutines: return None subroutines.sort() completions = [[sub, sub] for sub in subroutines] return (completions, sublime.INHIBIT_WORD_COMPLETIONS) class AddRulerToColumn72Listener(sublime_plugin.EventListener): """Add a ruler to column 72 when a Natural file is opened. If the user has other rulers, they're not messed with.""" def on_load(self, view): if not util.is_natural_file(view): return rulers = view.settings().get('rulers') if 72 not in rulers: rulers.append(72) rulers.sort() view.settings().set('rulers', rulers)
import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): return None texts = util.text_preceding_points(view, points) if all([text.strip().endswith('perform') for text in texts]): subroutines = util.find_text_by_selector(view, 'entity.name.function.natural') if not subroutines: return None subroutines.sort() completions = [[sub, sub] for sub in subroutines] return (completions, sublime.INHIBIT_WORD_COMPLETIONS) + + + class AddRulerToColumn72Listener(sublime_plugin.EventListener): + """Add a ruler to column 72 when a Natural file is opened. If the user has + other rulers, they're not messed with.""" + + def on_load(self, view): + if not util.is_natural_file(view): + return + rulers = view.settings().get('rulers') + if 72 not in rulers: + rulers.append(72) + rulers.sort() + view.settings().set('rulers', rulers)
4c2c0e9da70459063c6f1f682a181e4d350e853c
do_the_tests.py
do_the_tests.py
import sys; sys.path.pop(0) from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:])
from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:])
Remove now not needed path munging
Remove now not needed path munging
Python
mit
sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra
- import sys; sys.path.pop(0) from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:])
Remove now not needed path munging
## Code Before: import sys; sys.path.pop(0) from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:]) ## Instruction: Remove now not needed path munging ## Code After: from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:])
- import sys; sys.path.pop(0) from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:])
47ea7ebce827727bef5ad49e5df84fa0e5f6e4b9
pycloudflare/services.py
pycloudflare/services.py
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def get_zones(self): zones = [] for page in count(): batch = self.get( 'zones?page=%s&per_page=50' % page).json()['result'] if batch: zones.extend(batch) else: break return zones def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def iter_zones(self): for page in count(): batch = self.get('zones?page=%i&per_page=50' % page).json()['result'] if not batch: return for result in batch: yield result def get_zones(self): return list(self.iter_zones()) def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
Use an iterator to get pages
Use an iterator to get pages
Python
mit
gnowxilef/pycloudflare,yola/pycloudflare
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) + def iter_zones(self): + for page in count(): + batch = self.get('zones?page=%i&per_page=50' % page).json()['result'] + if not batch: + return + for result in batch: + yield result + def get_zones(self): + return list(self.iter_zones()) - zones = [] - for page in count(): - batch = self.get( - 'zones?page=%s&per_page=50' % page).json()['result'] - if batch: - zones.extend(batch) - else: - break - return zones def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
Use an iterator to get pages
## Code Before: from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def get_zones(self): zones = [] for page in count(): batch = self.get( 'zones?page=%s&per_page=50' % page).json()['result'] if batch: zones.extend(batch) else: break return zones def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result'] ## Instruction: Use an iterator to get pages ## Code After: from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) def iter_zones(self): for page in count(): batch = self.get('zones?page=%i&per_page=50' % page).json()['result'] if not batch: return for result in batch: yield result def get_zones(self): return list(self.iter_zones()) def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': config['api_key'], 'X-Auth-Email': config['email'] } super(CloudFlareService, self).__init__(config['url'], headers=headers) + def iter_zones(self): + for page in count(): + batch = self.get('zones?page=%i&per_page=50' % page).json()['result'] + if not batch: + return + for result in batch: + yield result + def get_zones(self): + return list(self.iter_zones()) - zones = [] - for page in count(): - batch = self.get( - 'zones?page=%s&per_page=50' % page).json()['result'] - if batch: - zones.extend(batch) - else: - break - return zones def get_zone(self, zone_id): return self.get('zones/%s' % zone_id).json()['result']
fc27b35dd1ac34b19bdc2d71dd71704bd9321b9d
src/test/ed/db/pythonnumbers.py
src/test/ed/db/pythonnumbers.py
import types db = connect( "test" ); t = db.pythonnumbers t.drop() thing = { "a" : 5 , "b" : 5.5 } assert( type( thing["a"] ) == types.IntType ); assert( type( thing["b"] ) == types.FloatType ); t.save( thing ) thing = t.findOne() assert( type( thing["b"] ) == types.FloatType ); assert( type( thing["a"] ) == types.IntType ); t.drop(); t.save( { "a" : 1 , "b" : 1.0 } ); assert( t.findOne() ); assert( t.findOne( { "a" : 1 } ) ); assert( t.findOne( { "b" : 1.0 } ) ); assert( not t.findOne( { "b" : 2.0 } ) ); assert( t.findOne( { "a" : 1.0 } ) ); assert( t.findOne( { "b" : 1 } ) );
import _10gen import types db = _10gen.connect( "test" ); t = db.pythonnumbers t.drop() thing = { "a" : 5 , "b" : 5.5 } assert( type( thing["a"] ) == types.IntType ); assert( type( thing["b"] ) == types.FloatType ); t.save( thing ) thing = t.findOne() assert( type( thing["b"] ) == types.FloatType ); assert( type( thing["a"] ) == types.IntType ); t.drop(); t.save( { "a" : 1 , "b" : 1.0 } ); assert( t.findOne() ); assert( t.findOne( { "a" : 1 } ) ); assert( t.findOne( { "b" : 1.0 } ) ); assert( not t.findOne( { "b" : 2.0 } ) ); assert( t.findOne( { "a" : 1.0 } ) ); assert( t.findOne( { "b" : 1 } ) );
Fix test for unwelded scopes.
Fix test for unwelded scopes.
Python
apache-2.0
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
+ import _10gen import types - db = connect( "test" ); + db = _10gen.connect( "test" ); t = db.pythonnumbers t.drop() thing = { "a" : 5 , "b" : 5.5 } assert( type( thing["a"] ) == types.IntType ); assert( type( thing["b"] ) == types.FloatType ); t.save( thing ) thing = t.findOne() assert( type( thing["b"] ) == types.FloatType ); assert( type( thing["a"] ) == types.IntType ); t.drop(); t.save( { "a" : 1 , "b" : 1.0 } ); assert( t.findOne() ); assert( t.findOne( { "a" : 1 } ) ); assert( t.findOne( { "b" : 1.0 } ) ); assert( not t.findOne( { "b" : 2.0 } ) ); assert( t.findOne( { "a" : 1.0 } ) ); assert( t.findOne( { "b" : 1 } ) );
Fix test for unwelded scopes.
## Code Before: import types db = connect( "test" ); t = db.pythonnumbers t.drop() thing = { "a" : 5 , "b" : 5.5 } assert( type( thing["a"] ) == types.IntType ); assert( type( thing["b"] ) == types.FloatType ); t.save( thing ) thing = t.findOne() assert( type( thing["b"] ) == types.FloatType ); assert( type( thing["a"] ) == types.IntType ); t.drop(); t.save( { "a" : 1 , "b" : 1.0 } ); assert( t.findOne() ); assert( t.findOne( { "a" : 1 } ) ); assert( t.findOne( { "b" : 1.0 } ) ); assert( not t.findOne( { "b" : 2.0 } ) ); assert( t.findOne( { "a" : 1.0 } ) ); assert( t.findOne( { "b" : 1 } ) ); ## Instruction: Fix test for unwelded scopes. ## Code After: import _10gen import types db = _10gen.connect( "test" ); t = db.pythonnumbers t.drop() thing = { "a" : 5 , "b" : 5.5 } assert( type( thing["a"] ) == types.IntType ); assert( type( thing["b"] ) == types.FloatType ); t.save( thing ) thing = t.findOne() assert( type( thing["b"] ) == types.FloatType ); assert( type( thing["a"] ) == types.IntType ); t.drop(); t.save( { "a" : 1 , "b" : 1.0 } ); assert( t.findOne() ); assert( t.findOne( { "a" : 1 } ) ); assert( t.findOne( { "b" : 1.0 } ) ); assert( not t.findOne( { "b" : 2.0 } ) ); assert( t.findOne( { "a" : 1.0 } ) ); assert( t.findOne( { "b" : 1 } ) );
+ import _10gen import types - db = connect( "test" ); + db = _10gen.connect( "test" ); ? +++++++ t = db.pythonnumbers t.drop() thing = { "a" : 5 , "b" : 5.5 } assert( type( thing["a"] ) == types.IntType ); assert( type( thing["b"] ) == types.FloatType ); t.save( thing ) thing = t.findOne() assert( type( thing["b"] ) == types.FloatType ); assert( type( thing["a"] ) == types.IntType ); t.drop(); t.save( { "a" : 1 , "b" : 1.0 } ); assert( t.findOne() ); assert( t.findOne( { "a" : 1 } ) ); assert( t.findOne( { "b" : 1.0 } ) ); assert( not t.findOne( { "b" : 2.0 } ) ); assert( t.findOne( { "a" : 1.0 } ) ); assert( t.findOne( { "b" : 1 } ) );
1ec0f5267119874244474072dfb32f952ae4a8f1
setup.py
setup.py
from distutils.core import setup setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
from distutils.core import setup from sh import pandoc setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
Use pandoc to convert the markdown readme to rst.
Use pandoc to convert the markdown readme to rst.
Python
agpl-3.0
cnelsonsic/cardscript
from distutils.core import setup + from sh import pandoc setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', - long_description=open('README.md').read(), + long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
Use pandoc to convert the markdown readme to rst.
## Code Before: from distutils.core import setup setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], ) ## Instruction: Use pandoc to convert the markdown readme to rst. ## Code After: from distutils.core import setup from sh import pandoc setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
from distutils.core import setup + from sh import pandoc setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="cnelsonsic@gmail.com", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', - long_description=open('README.md').read(), + long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
16b2de5a1c4965b1e3a2cb96c6ea3bd847e85c95
hxl/commands/hxlvalidate.py
hxl/commands/hxlvalidate.py
import sys import argparse from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input, output=sys.stdout, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) schema.validate(parser) # end
import sys from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input=sys.stdin, output=sys.stderr, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) return schema.validate(parser) # end
Return result of validation from the command script.
Return result of validation from the command script.
Python
unlicense
HXLStandard/libhxl-python,HXLStandard/libhxl-python
import sys - import argparse from hxl.parser import HXLReader from hxl.schema import loadHXLSchema - def hxlvalidate(input, output=sys.stdout, schema_input=None): + def hxlvalidate(input=sys.stdin, output=sys.stderr, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) - schema.validate(parser) + return schema.validate(parser) # end
Return result of validation from the command script.
## Code Before: import sys import argparse from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input, output=sys.stdout, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) schema.validate(parser) # end ## Instruction: Return result of validation from the command script. ## Code After: import sys from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input=sys.stdin, output=sys.stderr, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) return schema.validate(parser) # end
import sys - import argparse from hxl.parser import HXLReader from hxl.schema import loadHXLSchema - def hxlvalidate(input, output=sys.stdout, schema_input=None): ? ^^^ + def hxlvalidate(input=sys.stdin, output=sys.stderr, schema_input=None): ? ++++++++++ ^^^ parser = HXLReader(input) schema = loadHXLSchema(schema_input) - schema.validate(parser) + return schema.validate(parser) ? +++++++ # end
72af62bdf9339c880b0cc0f1e1002cf1961e962b
rule.py
rule.py
class PriceRule: """PriceRule is a rule that triggers when a stock price satisfies a condition. The condition is usually greater, equal or lesser than a given value. """ def __init__(self, symbol, condition): self.symbol = symbol self.condition = condition def matches(self, exchange): try: stock = exchange[self.symbol] except KeyError: return False return self.condition(stock) if stock.price else False def depends_on(self): return {self.symbol} class AndRule: def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2
class PriceRule: """PriceRule is a rule that triggers when a stock price satisfies a condition. The condition is usually greater, equal or lesser than a given value. """ def __init__(self, symbol, condition): self.symbol = symbol self.condition = condition def matches(self, exchange): try: stock = exchange[self.symbol] except KeyError: return False return self.condition(stock) if stock.price else False def depends_on(self): return {self.symbol} class AndRule: def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 def matches(self, exchange): matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange) return matches_bool
Add matches method to AndRule class.
Add matches method to AndRule class.
Python
mit
bsmukasa/stock_alerter
class PriceRule: """PriceRule is a rule that triggers when a stock price satisfies a condition. The condition is usually greater, equal or lesser than a given value. """ def __init__(self, symbol, condition): self.symbol = symbol self.condition = condition def matches(self, exchange): try: stock = exchange[self.symbol] except KeyError: return False return self.condition(stock) if stock.price else False def depends_on(self): return {self.symbol} class AndRule: def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 + def matches(self, exchange): + matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange) + return matches_bool +
Add matches method to AndRule class.
## Code Before: class PriceRule: """PriceRule is a rule that triggers when a stock price satisfies a condition. The condition is usually greater, equal or lesser than a given value. """ def __init__(self, symbol, condition): self.symbol = symbol self.condition = condition def matches(self, exchange): try: stock = exchange[self.symbol] except KeyError: return False return self.condition(stock) if stock.price else False def depends_on(self): return {self.symbol} class AndRule: def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 ## Instruction: Add matches method to AndRule class. ## Code After: class PriceRule: """PriceRule is a rule that triggers when a stock price satisfies a condition. The condition is usually greater, equal or lesser than a given value. """ def __init__(self, symbol, condition): self.symbol = symbol self.condition = condition def matches(self, exchange): try: stock = exchange[self.symbol] except KeyError: return False return self.condition(stock) if stock.price else False def depends_on(self): return {self.symbol} class AndRule: def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 def matches(self, exchange): matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange) return matches_bool
class PriceRule: """PriceRule is a rule that triggers when a stock price satisfies a condition. The condition is usually greater, equal or lesser than a given value. """ def __init__(self, symbol, condition): self.symbol = symbol self.condition = condition def matches(self, exchange): try: stock = exchange[self.symbol] except KeyError: return False return self.condition(stock) if stock.price else False def depends_on(self): return {self.symbol} class AndRule: def __init__(self, rule1, rule2): self.rule1 = rule1 self.rule2 = rule2 + + def matches(self, exchange): + matches_bool = self.rule1.matches(exchange) and self.rule2.matches(exchange) + return matches_bool
edebe37458da391723e3206c63102cbb69606c5b
ideascube/conf/idb_irq_bardarash.py
ideascube/conf/idb_irq_bardarash.py
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = []
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] HOME_CARDS = STAFF_HOME_CARDS + [ { 'id': 'blog', }, { 'id': 'mediacenter', }, { 'id': 'library', } ]
Remove Kalite until Arabic language is available
Remove Kalite until Arabic language is available
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] + HOME_CARDS = STAFF_HOME_CARDS + [ + { + 'id': 'blog', + }, + { + 'id': 'mediacenter', + }, + { + 'id': 'library', + } + ] + +
Remove Kalite until Arabic language is available
## Code Before: """Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] ## Instruction: Remove Kalite until Arabic language is available ## Code After: """Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] HOME_CARDS = STAFF_HOME_CARDS + [ { 'id': 'blog', }, { 'id': 'mediacenter', }, { 'id': 'library', } ]
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_of_origin_occupation', 'school_level']), # noqa (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa (_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa (_('Language skills'), ['ar_level', 'ku_level', 'sdb_level', 'en_level']), ) MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'birth_year', 'gender'] ENTRY_ACTIVITY_CHOICES = [] + + HOME_CARDS = STAFF_HOME_CARDS + [ + { + 'id': 'blog', + }, + { + 'id': 'mediacenter', + }, + { + 'id': 'library', + } + ] +
21a7e7557b8e02ef448bcc46a63e983f48cafe38
tests/test_endpoint.py
tests/test_endpoint.py
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'} assert resources['/'].children == [resources['/foo']] assert resources['/foo'].parent == resources['/'] def test_endpoints_added(): from noopy.endpoint import Endpoint endpoints = Endpoint.endpoints assert set(endpoints.keys()) == {('/foo', methods.GET)}
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'} assert resources['/'].children == [resources['/foo']] assert resources['/foo'].parent == resources['/'] def test_endpoints_added(): from noopy.endpoint import Endpoint endpoints = Endpoint.endpoints foo_endpoint = Endpoint('/foo', methods.GET) assert set(endpoints.keys()) == {foo_endpoint} assert endpoints[foo_endpoint] == sample_view
Test Endpoint.endpoints has all endpoints
Test Endpoint.endpoints has all endpoints
Python
mit
acuros/noopy
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'} assert resources['/'].children == [resources['/foo']] assert resources['/foo'].parent == resources['/'] def test_endpoints_added(): from noopy.endpoint import Endpoint endpoints = Endpoint.endpoints + foo_endpoint = Endpoint('/foo', methods.GET) - assert set(endpoints.keys()) == {('/foo', methods.GET)} + assert set(endpoints.keys()) == {foo_endpoint} + assert endpoints[foo_endpoint] == sample_view
Test Endpoint.endpoints has all endpoints
## Code Before: from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'} assert resources['/'].children == [resources['/foo']] assert resources['/foo'].parent == resources['/'] def test_endpoints_added(): from noopy.endpoint import Endpoint endpoints = Endpoint.endpoints assert set(endpoints.keys()) == {('/foo', methods.GET)} ## Instruction: Test Endpoint.endpoints has all endpoints ## Code After: from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'} assert resources['/'].children == [resources['/foo']] assert resources['/foo'].parent == resources['/'] def test_endpoints_added(): from noopy.endpoint import Endpoint endpoints = Endpoint.endpoints foo_endpoint = Endpoint('/foo', methods.GET) assert set(endpoints.keys()) == {foo_endpoint} assert endpoints[foo_endpoint] == sample_view
from noopy.endpoint import methods from noopy.endpoint.decorators import endpoint @endpoint('/foo', methods.GET) def sample_view(event, context): pass def test_resources_added(): from noopy.endpoint.resource import Resource resources = Resource.resources assert set(resources.keys()) == {'/', '/foo'} assert resources['/'].children == [resources['/foo']] assert resources['/foo'].parent == resources['/'] def test_endpoints_added(): from noopy.endpoint import Endpoint endpoints = Endpoint.endpoints + foo_endpoint = Endpoint('/foo', methods.GET) - assert set(endpoints.keys()) == {('/foo', methods.GET)} ? --- ^^^^ --------- + assert set(endpoints.keys()) == {foo_endpoint} ? ^ ++++++ + assert endpoints[foo_endpoint] == sample_view
a6e7f053c151fc343f0dd86010b159e21c0948b5
accountsplus/forms.py
accountsplus/forms.py
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): return self.cleaned_data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): return self.cleaned_data['username'].lower()
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): return self.data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): return self.data['username'].lower()
Fix how we are reading user name
Fix how we are reading user name
Python
mit
foundertherapy/django-users-plus,foundertherapy/django-users-plus
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): - return self.cleaned_data['username'].lower() + return self.data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): - return self.cleaned_data['username'].lower() + return self.data['username'].lower()
Fix how we are reading user name
## Code Before: from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): return self.cleaned_data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): return self.cleaned_data['username'].lower() ## Instruction: Fix how we are reading user name ## Code After: from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): return self.data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): return self.data['username'].lower()
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.Form): captcha = ReCaptchaField() username = django.forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL')) if not User.objects.filter(email=username).exists(): raise django.forms.ValidationError("Username does not belong to a registered user") return username class EmailBasedAuthenticationForm(AuthenticationForm): def clean_username(self): - return self.cleaned_data['username'].lower() ? -------- + return self.data['username'].lower() class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm): def clean_username(self): - return self.cleaned_data['username'].lower() ? -------- + return self.data['username'].lower()
6811b04a0a2e311fc2d014cd601da61a2f17a451
sell/views.py
sell/views.py
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if request.session['personal_data']: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
Fix KeyError in Provide personal data form
Fix KeyError in Provide personal data form
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: - if request.session['personal_data']: + if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
Fix KeyError in Provide personal data form
## Code Before: from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if request.session['personal_data']: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!") ## Instruction: Fix KeyError in Provide personal data form ## Code After: from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
from django.core.urlresolvers import reverse from django.forms import model_to_dict from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render from common.models import Student from sell.forms import PersonalDataForm def index(request): return HttpResponseRedirect(reverse('sell.views.personal_data')) def personal_data(request): if request.method == 'POST': form = PersonalDataForm(request.POST) if form.is_valid(): request.session['personal_data'] = model_to_dict(form.save(commit=False)) return HttpResponseRedirect(reverse('sell.views.books')) else: - if request.session['personal_data']: + if 'personal_data' in request.session: form = PersonalDataForm(instance=Student(**request.session['personal_data'])) else: form = PersonalDataForm() return render(request, 'sell/personal_data.html', {'form': form}) def books(request): return HttpResponse("Hello, world!")
a1e18385c2c5df9db8390b2da4d5baa2465f150e
webcomix/tests/test_comic_availability.py
webcomix/tests/test_comic_availability.py
import pytest from webcomix.comic import Comic from webcomix.supported_comics import supported_comics from webcomix.util import check_first_pages @pytest.mark.slow def test_supported_comics(): for comic_name, comic_info in supported_comics.items(): comic = Comic(comic_name, *comic_info) first_pages = comic.verify_xpath() check_first_pages(first_pages)
import pytest from webcomix.comic import Comic from webcomix.supported_comics import supported_comics from webcomix.util import check_first_pages @pytest.mark.slow @pytest.mark.parametrize("comic_name", list(supported_comics.keys())) def test_supported_comics(comic_name): comic = Comic(comic_name, *supported_comics[comic_name]) first_pages = comic.verify_xpath() check_first_pages(first_pages)
Test comic availability of all supported comics independently through parametrization
Test comic availability of all supported comics independently through parametrization
Python
mit
J-CPelletier/webcomix,J-CPelletier/WebComicToCBZ,J-CPelletier/webcomix
import pytest from webcomix.comic import Comic from webcomix.supported_comics import supported_comics from webcomix.util import check_first_pages @pytest.mark.slow + @pytest.mark.parametrize("comic_name", list(supported_comics.keys())) - def test_supported_comics(): + def test_supported_comics(comic_name): + comic = Comic(comic_name, *supported_comics[comic_name]) - for comic_name, comic_info in supported_comics.items(): - comic = Comic(comic_name, *comic_info) - first_pages = comic.verify_xpath() + first_pages = comic.verify_xpath() - check_first_pages(first_pages) + check_first_pages(first_pages)
Test comic availability of all supported comics independently through parametrization
## Code Before: import pytest from webcomix.comic import Comic from webcomix.supported_comics import supported_comics from webcomix.util import check_first_pages @pytest.mark.slow def test_supported_comics(): for comic_name, comic_info in supported_comics.items(): comic = Comic(comic_name, *comic_info) first_pages = comic.verify_xpath() check_first_pages(first_pages) ## Instruction: Test comic availability of all supported comics independently through parametrization ## Code After: import pytest from webcomix.comic import Comic from webcomix.supported_comics import supported_comics from webcomix.util import check_first_pages @pytest.mark.slow @pytest.mark.parametrize("comic_name", list(supported_comics.keys())) def test_supported_comics(comic_name): comic = Comic(comic_name, *supported_comics[comic_name]) first_pages = comic.verify_xpath() check_first_pages(first_pages)
import pytest from webcomix.comic import Comic from webcomix.supported_comics import supported_comics from webcomix.util import check_first_pages @pytest.mark.slow + @pytest.mark.parametrize("comic_name", list(supported_comics.keys())) - def test_supported_comics(): + def test_supported_comics(comic_name): ? ++++++++++ + comic = Comic(comic_name, *supported_comics[comic_name]) - for comic_name, comic_info in supported_comics.items(): - comic = Comic(comic_name, *comic_info) - first_pages = comic.verify_xpath() ? ---- + first_pages = comic.verify_xpath() - check_first_pages(first_pages) ? ---- + check_first_pages(first_pages)
6e9159b66cd791561a24bd935aaaab2a4ea6a6af
sgapi/__init__.py
sgapi/__init__.py
from .core import Shotgun, ShotgunError # For API compatibility Fault = ShotgunError
from .core import Shotgun, ShotgunError, TransportError # For API compatibility Fault = ShotgunError
Add TransportError to top-level package
Add TransportError to top-level package
Python
bsd-3-clause
westernx/sgapi
- from .core import Shotgun, ShotgunError + from .core import Shotgun, ShotgunError, TransportError # For API compatibility Fault = ShotgunError
Add TransportError to top-level package
## Code Before: from .core import Shotgun, ShotgunError # For API compatibility Fault = ShotgunError ## Instruction: Add TransportError to top-level package ## Code After: from .core import Shotgun, ShotgunError, TransportError # For API compatibility Fault = ShotgunError
- from .core import Shotgun, ShotgunError + from .core import Shotgun, ShotgunError, TransportError ? ++++++++++++++++ # For API compatibility Fault = ShotgunError
b47821b4fce6ab969fab3c7c5a1ef1a8fb58764c
jacquard/storage/tests/test_dummy.py
jacquard/storage/tests/test_dummy.py
import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('')
import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
Cover this exception with a test
Cover this exception with a test
Python
mit
prophile/jacquard,prophile/jacquard
+ import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') + def test_transaction_raises_error_for_bad_commit(self): + store = self.open_storage() + transaction = store.transaction(read_only=True) + transaction_map = transaction.__enter__() + + transaction_map['new_key'] = 'new_value' + + with pytest.raises(RuntimeError): + transaction.__exit__(None, None, None) + + assert 'new_key' not in store.data +
Cover this exception with a test
## Code Before: import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') ## Instruction: Cover this exception with a test ## Code After: import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
+ import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') + + def test_transaction_raises_error_for_bad_commit(self): + store = self.open_storage() + transaction = store.transaction(read_only=True) + transaction_map = transaction.__enter__() + + transaction_map['new_key'] = 'new_value' + + with pytest.raises(RuntimeError): + transaction.__exit__(None, None, None) + + assert 'new_key' not in store.data
aa966c1a208f2c3f4b2a2a196c39b1df5a0b67c8
basics/candidate.py
basics/candidate.py
import numpy as np class Bubble2D(object): """ Class for candidate bubble portions from 2D planes. """ def __init__(self, props): super(Bubble2D, self).__init__() self._channel = props[0] self._y = props[1] self._x = props[2] self._major = props[3] self._minor = props[4] self._pa = props[5] @property def params(self): return [self._channel, self._y, self._x, self._major, self._minor, self._pa] @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profiles_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs)
import numpy as np class Bubble2D(object): """ Class for candidate bubble portions from 2D planes. """ def __init__(self, props): super(Bubble2D, self).__init__() self._channel = props[0] self._y = props[1] self._x = props[2] self._major = props[3] self._minor = props[4] self._pa = props[5] @property def params(self): return [self._channel, self._y, self._x, self._major, self._minor, self._pa] @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profiles_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs) def as_mask(self): ''' Return a boolean mask of the 2D region. ''' raise NotImplementedError() def find_shape(self): ''' Expand/contract to match the contours in the data. ''' raise NotImplementedError()
Add methods that need to be implemented
Add methods that need to be implemented
Python
mit
e-koch/BaSiCs
import numpy as np class Bubble2D(object): """ Class for candidate bubble portions from 2D planes. """ def __init__(self, props): super(Bubble2D, self).__init__() self._channel = props[0] self._y = props[1] self._x = props[2] self._major = props[3] self._minor = props[4] self._pa = props[5] @property def params(self): return [self._channel, self._y, self._x, self._major, self._minor, self._pa] @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profiles_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs) + def as_mask(self): + ''' + Return a boolean mask of the 2D region. + ''' + raise NotImplementedError() + + def find_shape(self): + ''' + Expand/contract to match the contours in the data. + ''' + raise NotImplementedError() +
Add methods that need to be implemented
## Code Before: import numpy as np class Bubble2D(object): """ Class for candidate bubble portions from 2D planes. """ def __init__(self, props): super(Bubble2D, self).__init__() self._channel = props[0] self._y = props[1] self._x = props[2] self._major = props[3] self._minor = props[4] self._pa = props[5] @property def params(self): return [self._channel, self._y, self._x, self._major, self._minor, self._pa] @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profiles_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs) ## Instruction: Add methods that need to be implemented ## Code After: import numpy as np class Bubble2D(object): """ Class for candidate bubble portions from 2D planes. """ def __init__(self, props): super(Bubble2D, self).__init__() self._channel = props[0] self._y = props[1] self._x = props[2] self._major = props[3] self._minor = props[4] self._pa = props[5] @property def params(self): return [self._channel, self._y, self._x, self._major, self._minor, self._pa] @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profiles_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs) def as_mask(self): ''' Return a boolean mask of the 2D region. ''' raise NotImplementedError() def find_shape(self): ''' Expand/contract to match the contours in the data. ''' raise NotImplementedError()
import numpy as np class Bubble2D(object): """ Class for candidate bubble portions from 2D planes. """ def __init__(self, props): super(Bubble2D, self).__init__() self._channel = props[0] self._y = props[1] self._x = props[2] self._major = props[3] self._minor = props[4] self._pa = props[5] @property def params(self): return [self._channel, self._y, self._x, self._major, self._minor, self._pa] @property def area(self): return np.pi * self.major * self.minor @property def pa(self): return self._pa @property def major(self): return self._major @property def minor(self): return self._minor def profiles_lines(self, array, **kwargs): ''' Calculate radial profile lines of the 2D bubbles. ''' from basics.profile import azimuthal_profiles return azimuthal_profiles(array, self.params, **kwargs) + + def as_mask(self): + ''' + Return a boolean mask of the 2D region. + ''' + raise NotImplementedError() + + def find_shape(self): + ''' + Expand/contract to match the contours in the data. + ''' + raise NotImplementedError()
3ca46f1407d8984ca5cbd1eb0581765386533d71
observatory/rcos/tests/test_rcos.py
observatory/rcos/tests/test_rcos.py
import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301]
import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( "/", "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301]
Add / to rcos tests
rcos: Add / to rcos tests
Python
isc
rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory
import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( + "/", "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301]
Add / to rcos tests
## Code Before: import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301] ## Instruction: Add / to rcos tests ## Code After: import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( "/", "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301]
import pytest from django.core.urlresolvers import reverse @pytest.mark.django_db def test_homepage(client): for url in ( + "/", "/donor", "/students", "/courses", "/talks", "/programming-competition", "/achievements", "/urp-application", "/links-and-contacts", "/talk-sign-up", "/irc", "/faq", "/calendar", "/howtojoin", "/past-projects", ): #Load Site response = client.get(url) #Check for normal processing assert response.status_code in [200, 301]
56c25218cb3c987201839917930fc1ae791b5601
reg/__init__.py
reg/__init__.py
from .dispatch import dispatch, Dispatch from .context import (dispatch_method, DispatchMethod, methodify, clean_dispatch_methods) from .arginfo import arginfo from .error import RegistrationError from .predicate import (Predicate, KeyIndex, ClassIndex, match_key, match_instance, match_class) from .cache import DictCachingKeyLookup, LruCachingKeyLookup
from .dispatch import dispatch, Dispatch, LookupEntry from .context import (dispatch_method, DispatchMethod, methodify, clean_dispatch_methods) from .arginfo import arginfo from .error import RegistrationError from .predicate import (Predicate, KeyIndex, ClassIndex, match_key, match_instance, match_class) from .cache import DictCachingKeyLookup, LruCachingKeyLookup
Add LookupEntry to the API.
Add LookupEntry to the API.
Python
bsd-3-clause
morepath/reg,taschini/reg
- from .dispatch import dispatch, Dispatch + from .dispatch import dispatch, Dispatch, LookupEntry from .context import (dispatch_method, DispatchMethod, methodify, clean_dispatch_methods) from .arginfo import arginfo from .error import RegistrationError from .predicate import (Predicate, KeyIndex, ClassIndex, match_key, match_instance, match_class) from .cache import DictCachingKeyLookup, LruCachingKeyLookup
Add LookupEntry to the API.
## Code Before: from .dispatch import dispatch, Dispatch from .context import (dispatch_method, DispatchMethod, methodify, clean_dispatch_methods) from .arginfo import arginfo from .error import RegistrationError from .predicate import (Predicate, KeyIndex, ClassIndex, match_key, match_instance, match_class) from .cache import DictCachingKeyLookup, LruCachingKeyLookup ## Instruction: Add LookupEntry to the API. ## Code After: from .dispatch import dispatch, Dispatch, LookupEntry from .context import (dispatch_method, DispatchMethod, methodify, clean_dispatch_methods) from .arginfo import arginfo from .error import RegistrationError from .predicate import (Predicate, KeyIndex, ClassIndex, match_key, match_instance, match_class) from .cache import DictCachingKeyLookup, LruCachingKeyLookup
- from .dispatch import dispatch, Dispatch + from .dispatch import dispatch, Dispatch, LookupEntry ? +++++++++++++ from .context import (dispatch_method, DispatchMethod, methodify, clean_dispatch_methods) from .arginfo import arginfo from .error import RegistrationError from .predicate import (Predicate, KeyIndex, ClassIndex, match_key, match_instance, match_class) from .cache import DictCachingKeyLookup, LruCachingKeyLookup
cb39c1edf395f7da1c241010fc833fe512fa74ac
bcbio/distributed/clargs.py
bcbio/distributed/clargs.py
def to_parallel(args, module="bcbio.distributed"): """Convert input arguments into a parallel dictionary for passing to processing. """ ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None), args.scheduler) parallel = {"type": ptype, "cores": cores, "scheduler": args.scheduler, "queue": args.queue, "tag": args.tag, "module": module, "resources": args.resources, "timeout": args.timeout, "retries": args.retries, "run_local": args.queue == "localrun", "local_controller": args.local_controller} return parallel def _get_cores_and_type(numcores, paralleltype, scheduler): """Return core and parallelization approach from command line providing sane defaults. """ if scheduler is not None: paralleltype = "ipython" if paralleltype is None: paralleltype = "local" if not numcores or int(numcores) < 1: numcores = 1 return paralleltype, int(numcores)
def to_parallel(args, module="bcbio.distributed"): """Convert input arguments into a parallel dictionary for passing to processing. """ ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None), args.scheduler) local_controller = getattr(args, "local_controller", False) parallel = {"type": ptype, "cores": cores, "scheduler": args.scheduler, "queue": args.queue, "tag": args.tag, "module": module, "resources": args.resources, "timeout": args.timeout, "retries": args.retries, "run_local": args.queue == "localrun", "local_controller": local_controller} return parallel def _get_cores_and_type(numcores, paralleltype, scheduler): """Return core and parallelization approach from command line providing sane defaults. """ if scheduler is not None: paralleltype = "ipython" if paralleltype is None: paralleltype = "local" if not numcores or int(numcores) < 1: numcores = 1 return paralleltype, int(numcores)
Fix for bcbio-nextgen-vm not passing the local_controller option.
Fix for bcbio-nextgen-vm not passing the local_controller option.
Python
mit
brainstorm/bcbio-nextgen,brainstorm/bcbio-nextgen,vladsaveliev/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,brainstorm/bcbio-nextgen,lbeltrame/bcbio-nextgen,a113n/bcbio-nextgen,biocyberman/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,chapmanb/bcbio-nextgen,a113n/bcbio-nextgen,chapmanb/bcbio-nextgen,chapmanb/bcbio-nextgen,a113n/bcbio-nextgen,biocyberman/bcbio-nextgen,biocyberman/bcbio-nextgen
def to_parallel(args, module="bcbio.distributed"): """Convert input arguments into a parallel dictionary for passing to processing. """ - ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None), + ptype, cores = _get_cores_and_type(args.numcores, + getattr(args, "paralleltype", None), args.scheduler) + local_controller = getattr(args, "local_controller", False) parallel = {"type": ptype, "cores": cores, "scheduler": args.scheduler, "queue": args.queue, "tag": args.tag, "module": module, "resources": args.resources, "timeout": args.timeout, "retries": args.retries, "run_local": args.queue == "localrun", - "local_controller": args.local_controller} + "local_controller": local_controller} return parallel def _get_cores_and_type(numcores, paralleltype, scheduler): """Return core and parallelization approach from command line providing sane defaults. """ if scheduler is not None: paralleltype = "ipython" if paralleltype is None: paralleltype = "local" if not numcores or int(numcores) < 1: numcores = 1 return paralleltype, int(numcores)
Fix for bcbio-nextgen-vm not passing the local_controller option.
## Code Before: def to_parallel(args, module="bcbio.distributed"): """Convert input arguments into a parallel dictionary for passing to processing. """ ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None), args.scheduler) parallel = {"type": ptype, "cores": cores, "scheduler": args.scheduler, "queue": args.queue, "tag": args.tag, "module": module, "resources": args.resources, "timeout": args.timeout, "retries": args.retries, "run_local": args.queue == "localrun", "local_controller": args.local_controller} return parallel def _get_cores_and_type(numcores, paralleltype, scheduler): """Return core and parallelization approach from command line providing sane defaults. """ if scheduler is not None: paralleltype = "ipython" if paralleltype is None: paralleltype = "local" if not numcores or int(numcores) < 1: numcores = 1 return paralleltype, int(numcores) ## Instruction: Fix for bcbio-nextgen-vm not passing the local_controller option. ## Code After: def to_parallel(args, module="bcbio.distributed"): """Convert input arguments into a parallel dictionary for passing to processing. """ ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None), args.scheduler) local_controller = getattr(args, "local_controller", False) parallel = {"type": ptype, "cores": cores, "scheduler": args.scheduler, "queue": args.queue, "tag": args.tag, "module": module, "resources": args.resources, "timeout": args.timeout, "retries": args.retries, "run_local": args.queue == "localrun", "local_controller": local_controller} return parallel def _get_cores_and_type(numcores, paralleltype, scheduler): """Return core and parallelization approach from command line providing sane defaults. """ if scheduler is not None: paralleltype = "ipython" if paralleltype is None: paralleltype = "local" if not numcores or int(numcores) < 1: numcores = 1 return paralleltype, int(numcores)
def to_parallel(args, module="bcbio.distributed"): """Convert input arguments into a parallel dictionary for passing to processing. """ - ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None), + ptype, cores = _get_cores_and_type(args.numcores, + getattr(args, "paralleltype", None), args.scheduler) + local_controller = getattr(args, "local_controller", False) parallel = {"type": ptype, "cores": cores, "scheduler": args.scheduler, "queue": args.queue, "tag": args.tag, "module": module, "resources": args.resources, "timeout": args.timeout, "retries": args.retries, "run_local": args.queue == "localrun", - "local_controller": args.local_controller} ? ----- + "local_controller": local_controller} return parallel def _get_cores_and_type(numcores, paralleltype, scheduler): """Return core and parallelization approach from command line providing sane defaults. """ if scheduler is not None: paralleltype = "ipython" if paralleltype is None: paralleltype = "local" if not numcores or int(numcores) < 1: numcores = 1 return paralleltype, int(numcores)
d60112e569e13333cfd6316d30683282ceff8bee
changes/jobs/cleanup_builds.py
changes/jobs/cleanup_builds.py
from datetime import datetime, timedelta from changes.config import db, queue from changes.constants import Status from changes.models.build import Build def cleanup_builds(): """ Look for any jobs which haven't checked in (but are listed in a pending state) and mark them as finished in an unknown state. """ now = datetime.utcnow() cutoff = now - timedelta(minutes=5) build_list = Build.query.filter( Build.status != Status.finished, Build.date_modified < cutoff, ) db.session.query(Build).filter( Build.id.in_(b.id for b in build_list), ).update({ Build.date_modified: now, }) for build in build_list: queue.delay('sync_build', kwargs={ 'build_id': build.id.hex, })
from datetime import datetime, timedelta from sqlalchemy.sql import func from changes.config import db, queue from changes.constants import Status from changes.models.build import Build def cleanup_builds(): """ Look for any jobs which haven't checked in (but are listed in a pending state) and mark them as finished in an unknown state. """ now = datetime.utcnow() cutoff = now - timedelta(minutes=5) build_list = Build.query.filter( Build.status != Status.finished, Build.date_modified < cutoff, ) db.session.query(Build).filter( Build.id.in_(b.id for b in build_list), ).update({ Build.date_modified: func.now(), }) for build in build_list: queue.delay('sync_build', kwargs={ 'build_id': build.id.hex, })
Use func.now for timestamp update
Use func.now for timestamp update
Python
apache-2.0
dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes
from datetime import datetime, timedelta + from sqlalchemy.sql import func from changes.config import db, queue from changes.constants import Status from changes.models.build import Build def cleanup_builds(): """ Look for any jobs which haven't checked in (but are listed in a pending state) and mark them as finished in an unknown state. """ now = datetime.utcnow() cutoff = now - timedelta(minutes=5) build_list = Build.query.filter( Build.status != Status.finished, Build.date_modified < cutoff, ) db.session.query(Build).filter( Build.id.in_(b.id for b in build_list), ).update({ - Build.date_modified: now, + Build.date_modified: func.now(), }) for build in build_list: queue.delay('sync_build', kwargs={ 'build_id': build.id.hex, })
Use func.now for timestamp update
## Code Before: from datetime import datetime, timedelta from changes.config import db, queue from changes.constants import Status from changes.models.build import Build def cleanup_builds(): """ Look for any jobs which haven't checked in (but are listed in a pending state) and mark them as finished in an unknown state. """ now = datetime.utcnow() cutoff = now - timedelta(minutes=5) build_list = Build.query.filter( Build.status != Status.finished, Build.date_modified < cutoff, ) db.session.query(Build).filter( Build.id.in_(b.id for b in build_list), ).update({ Build.date_modified: now, }) for build in build_list: queue.delay('sync_build', kwargs={ 'build_id': build.id.hex, }) ## Instruction: Use func.now for timestamp update ## Code After: from datetime import datetime, timedelta from sqlalchemy.sql import func from changes.config import db, queue from changes.constants import Status from changes.models.build import Build def cleanup_builds(): """ Look for any jobs which haven't checked in (but are listed in a pending state) and mark them as finished in an unknown state. """ now = datetime.utcnow() cutoff = now - timedelta(minutes=5) build_list = Build.query.filter( Build.status != Status.finished, Build.date_modified < cutoff, ) db.session.query(Build).filter( Build.id.in_(b.id for b in build_list), ).update({ Build.date_modified: func.now(), }) for build in build_list: queue.delay('sync_build', kwargs={ 'build_id': build.id.hex, })
from datetime import datetime, timedelta + from sqlalchemy.sql import func from changes.config import db, queue from changes.constants import Status from changes.models.build import Build def cleanup_builds(): """ Look for any jobs which haven't checked in (but are listed in a pending state) and mark them as finished in an unknown state. """ now = datetime.utcnow() cutoff = now - timedelta(minutes=5) build_list = Build.query.filter( Build.status != Status.finished, Build.date_modified < cutoff, ) db.session.query(Build).filter( Build.id.in_(b.id for b in build_list), ).update({ - Build.date_modified: now, + Build.date_modified: func.now(), ? +++++ ++ }) for build in build_list: queue.delay('sync_build', kwargs={ 'build_id': build.id.hex, })
0e0f61edd95bef03a470ae4717d5d4e390011ae3
chatterbot/ext/django_chatterbot/views.py
chatterbot/ext/django_chatterbot/views.py
from django.views.generic import View from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings class ChatterBotView(View): chatterbot = ChatBot(**settings.CHATTERBOT) def post(self, request, *args, **kwargs): input_statement = request.POST.get('text') response_data = self.chatterbot.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.', 'name': self.chatterbot.name } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405)
from django.views.generic import View from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings import json class ChatterBotView(View): chatterbot = ChatBot(**settings.CHATTERBOT) def _serialize_recent_statements(self): if self.chatterbot.recent_statements.empty(): return [] recent_statements = [] for statement, response in self.chatterbot.recent_statements: recent_statements.append([statement.serialize(), response.serialize()]) return recent_statements def post(self, request, *args, **kwargs): if request.is_ajax(): data = json.loads(request.body) input_statement = data.get('text') else: input_statement = request.POST.get('text') response_data = self.chatterbot.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.', 'name': self.chatterbot.name, 'recent_statements': self._serialize_recent_statements() } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405)
Return recent statement data in GET response.
Return recent statement data in GET response.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,Gustavo6046/ChatterBot,davizucon/ChatterBot,vkosuri/ChatterBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,gunthercox/ChatterBot
from django.views.generic import View from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings + import json class ChatterBotView(View): chatterbot = ChatBot(**settings.CHATTERBOT) + def _serialize_recent_statements(self): + if self.chatterbot.recent_statements.empty(): + return [] + + recent_statements = [] + + for statement, response in self.chatterbot.recent_statements: + recent_statements.append([statement.serialize(), response.serialize()]) + + return recent_statements + def post(self, request, *args, **kwargs): + if request.is_ajax(): + data = json.loads(request.body) + input_statement = data.get('text') + else: - input_statement = request.POST.get('text') + input_statement = request.POST.get('text') response_data = self.chatterbot.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.', - 'name': self.chatterbot.name + 'name': self.chatterbot.name, + 'recent_statements': self._serialize_recent_statements() } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405)
Return recent statement data in GET response.
## Code Before: from django.views.generic import View from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings class ChatterBotView(View): chatterbot = ChatBot(**settings.CHATTERBOT) def post(self, request, *args, **kwargs): input_statement = request.POST.get('text') response_data = self.chatterbot.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.', 'name': self.chatterbot.name } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) ## Instruction: Return recent statement data in GET response. ## Code After: from django.views.generic import View from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings import json class ChatterBotView(View): chatterbot = ChatBot(**settings.CHATTERBOT) def _serialize_recent_statements(self): if self.chatterbot.recent_statements.empty(): return [] recent_statements = [] for statement, response in self.chatterbot.recent_statements: recent_statements.append([statement.serialize(), response.serialize()]) return recent_statements def post(self, request, *args, **kwargs): if request.is_ajax(): data = json.loads(request.body) input_statement = data.get('text') else: input_statement = request.POST.get('text') response_data = self.chatterbot.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.', 'name': self.chatterbot.name, 'recent_statements': self._serialize_recent_statements() } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405)
from django.views.generic import View from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings + import json class ChatterBotView(View): chatterbot = ChatBot(**settings.CHATTERBOT) + def _serialize_recent_statements(self): + if self.chatterbot.recent_statements.empty(): + return [] + + recent_statements = [] + + for statement, response in self.chatterbot.recent_statements: + recent_statements.append([statement.serialize(), response.serialize()]) + + return recent_statements + def post(self, request, *args, **kwargs): + if request.is_ajax(): + data = json.loads(request.body) + input_statement = data.get('text') + else: - input_statement = request.POST.get('text') + input_statement = request.POST.get('text') ? ++++ response_data = self.chatterbot.get_response(input_statement) return JsonResponse(response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.', - 'name': self.chatterbot.name + 'name': self.chatterbot.name, ? + + 'recent_statements': self._serialize_recent_statements() } # Return a method not allowed response return JsonResponse(data, status=405) def patch(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405) def delete(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.' } # Return a method not allowed response return JsonResponse(data, status=405)
ea22192c9debe171db5d4b6b83d581fe079d6fa4
ipython/profile_bots/startup/05-import-company.py
ipython/profile_bots/startup/05-import-company.py
"""Set up access to important employer data for IPython""" from dataclasses import dataclass @dataclass class EmployerData: name: str wwts = EmployerData('wwts')
"""Set up access to important employer data for IPython""" from dataclasses import dataclass from tools.issues import issues @dataclass class EmployerData: name: str wwts = EmployerData('wwts') def issue_branch(issue): name = issues.one(issue).branch_name() print(name)
Add functuion to ibots to name a branch
Add functuion to ibots to name a branch
Python
mit
jalanb/jab,jalanb/dotjab,jalanb/jab,jalanb/dotjab
"""Set up access to important employer data for IPython""" from dataclasses import dataclass + + from tools.issues import issues @dataclass class EmployerData: name: str wwts = EmployerData('wwts') + + def issue_branch(issue): + name = issues.one(issue).branch_name() + print(name) +
Add functuion to ibots to name a branch
## Code Before: """Set up access to important employer data for IPython""" from dataclasses import dataclass @dataclass class EmployerData: name: str wwts = EmployerData('wwts') ## Instruction: Add functuion to ibots to name a branch ## Code After: """Set up access to important employer data for IPython""" from dataclasses import dataclass from tools.issues import issues @dataclass class EmployerData: name: str wwts = EmployerData('wwts') def issue_branch(issue): name = issues.one(issue).branch_name() print(name)
"""Set up access to important employer data for IPython""" from dataclasses import dataclass + + from tools.issues import issues @dataclass class EmployerData: name: str wwts = EmployerData('wwts') + + + def issue_branch(issue): + name = issues.one(issue).branch_name() + print(name)
de5fbf7d63245e9d14844e66fdf16f88dbfae2e5
rest_framework/authtoken/migrations/0001_initial.py
rest_framework/authtoken/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('key', models.CharField(max_length=40, serialize=False, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True)), ('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), ]
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('key', models.CharField(primary_key=True, serialize=False, max_length=40)), ('created', models.DateTimeField(auto_now_add=True)), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')), ], options={ }, bases=(models.Model,), ), ]
Update initial migration to work on Python 3
Update initial migration to work on Python 3
Python
bsd-2-clause
ajaali/django-rest-framework,mgaitan/django-rest-framework,xiaotangyuan/django-rest-framework,wedaly/django-rest-framework,edx/django-rest-framework,uploadcare/django-rest-framework,brandoncazander/django-rest-framework,mgaitan/django-rest-framework,werthen/django-rest-framework,akalipetis/django-rest-framework,YBJAY00000/django-rest-framework,douwevandermeij/django-rest-framework,elim/django-rest-framework,jpulec/django-rest-framework,abdulhaq-e/django-rest-framework,waytai/django-rest-framework,sbellem/django-rest-framework,justanr/django-rest-framework,akalipetis/django-rest-framework,antonyc/django-rest-framework,simudream/django-rest-framework,gregmuellegger/django-rest-framework,AlexandreProenca/django-rest-framework,aericson/django-rest-framework,jpadilla/django-rest-framework,johnraz/django-rest-framework,fishky/django-rest-framework,jerryhebert/django-rest-framework,sheppard/django-rest-framework,wwj718/django-rest-framework,raphaelmerx/django-rest-framework,cyberj/django-rest-framework,kgeorgy/django-rest-framework,justanr/django-rest-framework,cheif/django-rest-framework,leeahoward/django-rest-framework,alacritythief/django-rest-framework,cyberj/django-rest-framework,ebsaral/django-rest-framework,MJafarMashhadi/django-rest-framework,nryoung/django-rest-framework,rubendura/django-rest-framework,jness/django-rest-framework,James1345/django-rest-framework,jtiai/django-rest-framework,qsorix/django-rest-framework,raphaelmerx/django-rest-framework,kgeorgy/django-rest-framework,rhblind/django-rest-framework,hunter007/django-rest-framework,davesque/django-rest-framework,jtiai/django-rest-framework,bluedazzle/django-rest-framework,gregmuellegger/django-rest-framework,hnakamur/django-rest-framework,adambain-vokal/django-rest-framework,zeldalink0515/django-rest-framework,tomchristie/django-rest-framework,tigeraniya/django-rest-framework,cheif/django-rest-framework,lubomir/django-rest-framework,iheitlager/django-rest-framework,AlexandreProenca/django-rest-framework,andriy-s/django-rest-framework,VishvajitP/django-rest-framework,krinart/django-rest-framework,abdulhaq-e/django-rest-framework,zeldalink0515/django-rest-framework,ambivalentno/django-rest-framework,ashishfinoit/django-rest-framework,gregmuellegger/django-rest-framework,canassa/django-rest-framework,YBJAY00000/django-rest-framework,vstoykov/django-rest-framework,alacritythief/django-rest-framework,ajaali/django-rest-framework,hunter007/django-rest-framework,uruz/django-rest-framework,delinhabit/django-rest-framework,lubomir/django-rest-framework,pombredanne/django-rest-framework,leeahoward/django-rest-framework,mgaitan/django-rest-framework,tcroiset/django-rest-framework,adambain-vokal/django-rest-framework,d0ugal/django-rest-framework,nryoung/django-rest-framework,ossanna16/django-rest-framework,potpath/django-rest-framework,nryoung/django-rest-framework,nhorelik/django-rest-framework,jpadilla/django-rest-framework,ashishfinoit/django-rest-framework,qsorix/django-rest-framework,rafaelcaricio/django-rest-framework,uruz/django-rest-framework,arpheno/django-rest-framework,cheif/django-rest-framework,kylefox/django-rest-framework,brandoncazander/django-rest-framework,linovia/django-rest-framework,linovia/django-rest-framework,yiyocx/django-rest-framework,jpulec/django-rest-framework,ambivalentno/django-rest-framework,jerryhebert/django-rest-framework,damycra/django-rest-framework,pombredanne/django-rest-framework,andriy-s/django-rest-framework,abdulhaq-e/django-rest-framework,buptlsl/django-rest-framework,leeahoward/django-rest-framework,kylefox/django-rest-framework,delinhabit/django-rest-framework,tcroiset/django-rest-framework,MJafarMashhadi/django-rest-framework,ajaali/django-rest-framework,rhblind/django-rest-framework,agconti/django-rest-framework,ticosax/django-rest-framework,bluedazzle/django-rest-framework,wwj718/django-rest-framework,davesque/django-rest-framework,alacritythief/django-rest-framework,jpulec/django-rest-framework,ashishfinoit/django-rest-framework,tomchristie/django-rest-framework,potpath/django-rest-framework,ossanna16/django-rest-framework,aericson/django-rest-framework,ticosax/django-rest-framework,antonyc/django-rest-framework,iheitlager/django-rest-framework,ticosax/django-rest-framework,rubendura/django-rest-framework,HireAnEsquire/django-rest-framework,paolopaolopaolo/django-rest-framework,ezheidtmann/django-rest-framework,delinhabit/django-rest-framework,aericson/django-rest-framework,d0ugal/django-rest-framework,canassa/django-rest-framework,wangpanjun/django-rest-framework,rafaelang/django-rest-framework,kezabelle/django-rest-framework,paolopaolopaolo/django-rest-framework,wzbozon/django-rest-framework,wangpanjun/django-rest-framework,callorico/django-rest-framework,krinart/django-rest-framework,thedrow/django-rest-framework-1,linovia/django-rest-framework,jpadilla/django-rest-framework,bluedazzle/django-rest-framework,wangpanjun/django-rest-framework,thedrow/django-rest-framework-1,yiyocx/django-rest-framework,brandoncazander/django-rest-framework,potpath/django-rest-framework,canassa/django-rest-framework,dmwyatt/django-rest-framework,pombredanne/django-rest-framework,maryokhin/django-rest-framework,MJafarMashhadi/django-rest-framework,ambivalentno/django-rest-framework,qsorix/django-rest-framework,sheppard/django-rest-framework,hnarayanan/django-rest-framework,arpheno/django-rest-framework,wzbozon/django-rest-framework,lubomir/django-rest-framework,johnraz/django-rest-framework,damycra/django-rest-framework,werthen/django-rest-framework,atombrella/django-rest-framework,uruz/django-rest-framework,James1345/django-rest-framework,tigeraniya/django-rest-framework,waytai/django-rest-framework,sehmaschine/django-rest-framework,fishky/django-rest-framework,yiyocx/django-rest-framework,nhorelik/django-rest-framework,YBJAY00000/django-rest-framework,johnraz/django-rest-framework,kylefox/django-rest-framework,werthen/django-rest-framework,wwj718/django-rest-framework,dmwyatt/django-rest-framework,xiaotangyuan/django-rest-framework,atombrella/django-rest-framework,hnarayanan/django-rest-framework,James1345/django-rest-framework,tigeraniya/django-rest-framework,kgeorgy/django-rest-framework,maryokhin/django-rest-framework,sbellem/django-rest-framework,xiaotangyuan/django-rest-framework,AlexandreProenca/django-rest-framework,douwevandermeij/django-rest-framework,sehmaschine/django-rest-framework,hnakamur/django-rest-framework,edx/django-rest-framework,HireAnEsquire/django-rest-framework,vstoykov/django-rest-framework,rafaelcaricio/django-rest-framework,sbellem/django-rest-framework,vstoykov/django-rest-framework,kezabelle/django-rest-framework,HireAnEsquire/django-rest-framework,kezabelle/django-rest-framework,jness/django-rest-framework,elim/django-rest-framework,raphaelmerx/django-rest-framework,davesque/django-rest-framework,rubendura/django-rest-framework,simudream/django-rest-framework,kennydude/django-rest-framework,ossanna16/django-rest-framework,waytai/django-rest-framework,justanr/django-rest-framework,maryokhin/django-rest-framework,thedrow/django-rest-framework-1,cyberj/django-rest-framework,wedaly/django-rest-framework,rafaelang/django-rest-framework,rafaelcaricio/django-rest-framework,rafaelang/django-rest-framework,tcroiset/django-rest-framework,rhblind/django-rest-framework,jness/django-rest-framework,ebsaral/django-rest-framework,sehmaschine/django-rest-framework,kennydude/django-rest-framework,kennydude/django-rest-framework,ezheidtmann/django-rest-framework,sheppard/django-rest-framework,akalipetis/django-rest-framework,tomchristie/django-rest-framework,adambain-vokal/django-rest-framework,hunter007/django-rest-framework,damycra/django-rest-framework,edx/django-rest-framework,nhorelik/django-rest-framework,dmwyatt/django-rest-framework,jerryhebert/django-rest-framework,d0ugal/django-rest-framework,jtiai/django-rest-framework,callorico/django-rest-framework,callorico/django-rest-framework,agconti/django-rest-framework,uploadcare/django-rest-framework,andriy-s/django-rest-framework,iheitlager/django-rest-framework,krinart/django-rest-framework,agconti/django-rest-framework,zeldalink0515/django-rest-framework,wzbozon/django-rest-framework,fishky/django-rest-framework,arpheno/django-rest-framework,wedaly/django-rest-framework,paolopaolopaolo/django-rest-framework,VishvajitP/django-rest-framework,VishvajitP/django-rest-framework,simudream/django-rest-framework,ezheidtmann/django-rest-framework,ebsaral/django-rest-framework,antonyc/django-rest-framework,elim/django-rest-framework,atombrella/django-rest-framework,hnarayanan/django-rest-framework,buptlsl/django-rest-framework,buptlsl/django-rest-framework,hnakamur/django-rest-framework,douwevandermeij/django-rest-framework,uploadcare/django-rest-framework
- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Token', fields=[ - ('key', models.CharField(max_length=40, serialize=False, primary_key=True)), + ('key', models.CharField(primary_key=True, serialize=False, max_length=40)), ('created', models.DateTimeField(auto_now_add=True)), - ('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)), + ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')), ], options={ }, bases=(models.Model,), ), ]
Update initial migration to work on Python 3
## Code Before: from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('key', models.CharField(max_length=40, serialize=False, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True)), ('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), ] ## Instruction: Update initial migration to work on Python 3 ## Code After: from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('key', models.CharField(primary_key=True, serialize=False, max_length=40)), ('created', models.DateTimeField(auto_now_add=True)), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')), ], options={ }, bases=(models.Model,), ), ]
- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Token', fields=[ - ('key', models.CharField(max_length=40, serialize=False, primary_key=True)), ? ^ ^ ^^^^ ^^ --- ^^ ^ ^ ^^^^ + ('key', models.CharField(primary_key=True, serialize=False, max_length=40)), ? +++ ^^ ^ ^ ^^^^ ^ ^ ^^^^ ^^ ('created', models.DateTimeField(auto_now_add=True)), - ('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)), + ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')), ], options={ }, bases=(models.Model,), ), ]
f2399e49e657848a58022b63915fad7969841b62
setup.py
setup.py
import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), packages = ['portfolio'], package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], )
import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), packages = ['portfolio', 'portfolio.tests'], package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], )
Add tests to package list.
Add tests to package list. Missed this earlier. Oops.
Python
bsd-3-clause
blturner/django-portfolio,blturner/django-portfolio,benspaulding/django-portfolio
import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), - packages = ['portfolio'], + packages = ['portfolio', 'portfolio.tests'], package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], )
Add tests to package list.
## Code Before: import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), packages = ['portfolio'], package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], ) ## Instruction: Add tests to package list. ## Code After: import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), packages = ['portfolio', 'portfolio.tests'], package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], )
import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), - packages = ['portfolio'], + packages = ['portfolio', 'portfolio.tests'], ? +++++++++++++++++++ package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], )
0147e9a6c9d61028781b55f4f8e068e576b653a0
manage.py
manage.py
import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from api import create_app, db application = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(application, db) manager = Manager(application) manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a local database. Drops and creates a new database """ db.drop_all() db.create_all() db.session.commit() if __name__ == "__main__": manager.run()
import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from api import create_app, db application = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(application, db) manager = Manager(application) manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a local database. Drops and creates a new database """ db.drop_all() db.create_all() db.session.commit() @manager.command def create_db(): db.create_all() db.session.commit() @manager.command def drop_db(): db.drop_all() db.session.commit() if __name__ == "__main__": manager.run()
Add create and drop db tasks
Add create and drop db tasks
Python
mit
EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list
import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from api import create_app, db application = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(application, db) manager = Manager(application) manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a local database. Drops and creates a new database """ db.drop_all() db.create_all() db.session.commit() + @manager.command + def create_db(): + db.create_all() + db.session.commit() + + @manager.command + def drop_db(): + db.drop_all() + db.session.commit() + + if __name__ == "__main__": manager.run()
Add create and drop db tasks
## Code Before: import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from api import create_app, db application = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(application, db) manager = Manager(application) manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a local database. Drops and creates a new database """ db.drop_all() db.create_all() db.session.commit() if __name__ == "__main__": manager.run() ## Instruction: Add create and drop db tasks ## Code After: import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from api import create_app, db application = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(application, db) manager = Manager(application) manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a local database. Drops and creates a new database """ db.drop_all() db.create_all() db.session.commit() @manager.command def create_db(): db.create_all() db.session.commit() @manager.command def drop_db(): db.drop_all() db.session.commit() if __name__ == "__main__": manager.run()
import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from api import create_app, db application = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(application, db) manager = Manager(application) manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) @manager.command def recreate_db(): """ Recreates a local database. Drops and creates a new database """ db.drop_all() db.create_all() db.session.commit() + @manager.command + def create_db(): + db.create_all() + db.session.commit() + + @manager.command + def drop_db(): + db.drop_all() + db.session.commit() + + if __name__ == "__main__": manager.run()
12555db92719be1aa96111ac788bc2fba784b5de
mapclientplugins/plainmodelviewerstep/view/plainmodelviewerwidget.py
mapclientplugins/plainmodelviewerstep/view/plainmodelviewerwidget.py
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._zinc.defineStandardMaterials() self._zinc.defineStangardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _visualise(self): ''' Read model data '''
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._defineStandardMaterials() self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _defineStandardGlyphs(self): ''' Helper method to define the standard glyphs ''' glyph_module = self._context.getGlyphmodule() glyph_module.defineStandardGlyphs() def _defineStandardMaterials(self): ''' Helper method to define the standard materials. ''' material_module = self._context.getMaterialmodule() material_module.defineStandardMaterials() def _visualise(self): ''' Read model data '''
Add functions defineStandardMaterials and defineStandardGlyphs.
Add functions defineStandardMaterials and defineStandardGlyphs.
Python
apache-2.0
mapclient-plugins/plainmodelviewer
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) - self._zinc.defineStandardMaterials() + self._defineStandardMaterials() - self._zinc.defineStangardGlyphs() + self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() + def _defineStandardGlyphs(self): + ''' + Helper method to define the standard glyphs + ''' + glyph_module = self._context.getGlyphmodule() + glyph_module.defineStandardGlyphs() + + def _defineStandardMaterials(self): + ''' + Helper method to define the standard materials. + ''' + material_module = self._context.getMaterialmodule() + material_module.defineStandardMaterials() + def _visualise(self): ''' Read model data '''
Add functions defineStandardMaterials and defineStandardGlyphs.
## Code Before: __author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._zinc.defineStandardMaterials() self._zinc.defineStangardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _visualise(self): ''' Read model data ''' ## Instruction: Add functions defineStandardMaterials and defineStandardGlyphs. ## Code After: __author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._defineStandardMaterials() self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _defineStandardGlyphs(self): ''' Helper method to define the standard glyphs ''' glyph_module = self._context.getGlyphmodule() glyph_module.defineStandardGlyphs() def _defineStandardMaterials(self): ''' Helper method to define the standard materials. ''' material_module = self._context.getMaterialmodule() material_module.defineStandardMaterials() def _visualise(self): ''' Read model data '''
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) - self._zinc.defineStandardMaterials() ? ----- + self._defineStandardMaterials() - self._zinc.defineStangardGlyphs() ? ----- ^ + self._defineStandardGlyphs() ? ^ def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() + def _defineStandardGlyphs(self): + ''' + Helper method to define the standard glyphs + ''' + glyph_module = self._context.getGlyphmodule() + glyph_module.defineStandardGlyphs() + + def _defineStandardMaterials(self): + ''' + Helper method to define the standard materials. + ''' + material_module = self._context.getMaterialmodule() + material_module.defineStandardMaterials() + def _visualise(self): ''' Read model data '''
0b1f38b8354a0ad6a021f247a7bc1336ae5d50fb
arcade/__init__.py
arcade/__init__.py
import arcade.key import arcade.color from .version import * from .window_commands import * from .draw_commands import * from .sprite import * from .physics_engines import * from .physics_engine_2d import * from .application import * from .sound import * from .shape_objects import *
import arcade.key import arcade.color from arcade.version import * from arcade.window_commands import * from arcade.draw_commands import * from arcade.sprite import * from arcade.physics_engines import * from arcade.physics_engine_2d import * from arcade.application import * from arcade.sound import * from arcade.shape_objects import *
Change some of the relative imports, which fail in doctests, to absolute imports.
Change some of the relative imports, which fail in doctests, to absolute imports.
Python
mit
mikemhenry/arcade,mikemhenry/arcade
import arcade.key import arcade.color - from .version import * + from arcade.version import * - from .window_commands import * + from arcade.window_commands import * - from .draw_commands import * + from arcade.draw_commands import * - from .sprite import * + from arcade.sprite import * - from .physics_engines import * + from arcade.physics_engines import * - from .physics_engine_2d import * + from arcade.physics_engine_2d import * - from .application import * + from arcade.application import * - from .sound import * + from arcade.sound import * - from .shape_objects import * + from arcade.shape_objects import *
Change some of the relative imports, which fail in doctests, to absolute imports.
## Code Before: import arcade.key import arcade.color from .version import * from .window_commands import * from .draw_commands import * from .sprite import * from .physics_engines import * from .physics_engine_2d import * from .application import * from .sound import * from .shape_objects import * ## Instruction: Change some of the relative imports, which fail in doctests, to absolute imports. ## Code After: import arcade.key import arcade.color from arcade.version import * from arcade.window_commands import * from arcade.draw_commands import * from arcade.sprite import * from arcade.physics_engines import * from arcade.physics_engine_2d import * from arcade.application import * from arcade.sound import * from arcade.shape_objects import *
import arcade.key import arcade.color - from .version import * + from arcade.version import * ? ++++++ - from .window_commands import * + from arcade.window_commands import * ? ++++++ - from .draw_commands import * + from arcade.draw_commands import * ? ++++++ - from .sprite import * + from arcade.sprite import * ? ++++++ - from .physics_engines import * + from arcade.physics_engines import * ? ++++++ - from .physics_engine_2d import * + from arcade.physics_engine_2d import * ? ++++++ - from .application import * + from arcade.application import * ? ++++++ - from .sound import * + from arcade.sound import * ? ++++++ - from .shape_objects import * + from arcade.shape_objects import * ? ++++++
b528b2cf4379369da8277a0a1c904267b5c7cf6f
Lib/test/test_atexit.py
Lib/test/test_atexit.py
from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
Use sys.executable to run Python, as suggested by Neal Norwitz.
Use sys.executable to run Python, as suggested by Neal Norwitz.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
from test_support import TESTFN, vereq import atexit import os + import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() - p = os.popen("python " + fname) + p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() - p = os.popen("python " + fname) + p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
Use sys.executable to run Python, as suggested by Neal Norwitz.
## Code Before: from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname) ## Instruction: Use sys.executable to run Python, as suggested by Neal Norwitz. ## Code After: from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
from test_support import TESTFN, vereq import atexit import os + import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() - p = os.popen("python " + fname) + p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() - p = os.popen("python " + fname) + p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
32388a96b848629bf8f4b7d7ea832fca8c3dccd9
fabfile/templates/collector_haproxy.py
fabfile/templates/collector_haproxy.py
import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger balance roundrobin option tcp-check tcp-check connect port 6379 default-server error-limit 1 on-error mark-down $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """)
import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger timeout server 3m balance roundrobin $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """)
Remove tcp-check connect option for redis on haproxy
Remove tcp-check connect option for redis on haproxy tcp-check connect option for redis on haproxy.cfg causes the client connections in the redis-server to grow continuously and reaches the max limit resulting in connection failure/response error for requests from collector and other analytics services to redis. Change-Id: If088ba40e7f0bc420a753ec11bca9dd081ffb160 Partial-Bug: #1648601
Python
apache-2.0
Juniper/contrail-fabric-utils,Juniper/contrail-fabric-utils
import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger + timeout server 3m balance roundrobin - option tcp-check - tcp-check connect port 6379 - default-server error-limit 1 on-error mark-down $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """)
Remove tcp-check connect option for redis on haproxy
## Code Before: import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger balance roundrobin option tcp-check tcp-check connect port 6379 default-server error-limit 1 on-error mark-down $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """) ## Instruction: Remove tcp-check connect option for redis on haproxy ## Code After: import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger timeout server 3m balance roundrobin $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """)
import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger + timeout server 3m balance roundrobin - option tcp-check - tcp-check connect port 6379 - default-server error-limit 1 on-error mark-down $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """)
74ec59b48b8a0bd7bac9d0eada4caa463a897d08
playground/settings.py
playground/settings.py
DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, # Example of a scoped resource "projects": { "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", "schema": { "name": { "type": "string", }, "owner": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
Add example of a scoped resource
Add example of a scoped resource Add the Project resource and set the `url` setting in the domain to allow it to sit as a sub resource under accounts. See: http://python-eve.org/features.html#sub-resources
Python
mit
proxama/eve-playground
DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, + + # Example of a scoped resource + "projects": { + "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", + "schema": { + "name": { + "type": "string", + }, + "owner": { + "type": "objectid", + "data_relation": { + "resource": "accounts", + "field": "_id", + "embeddable": True, + }, + }, + }, + }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
Add example of a scoped resource
## Code Before: DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground" ## Instruction: Add example of a scoped resource ## Code After: DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, # Example of a scoped resource "projects": { "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", "schema": { "name": { "type": "string", }, "owner": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, + + # Example of a scoped resource + "projects": { + "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", + "schema": { + "name": { + "type": "string", + }, + "owner": { + "type": "objectid", + "data_relation": { + "resource": "accounts", + "field": "_id", + "embeddable": True, + }, + }, + }, + }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
e8030cfb3daee6b7e467f50a215fbffc5ef90223
api/preprint_providers/serializers.py
api/preprint_providers/serializers.py
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'description', 'id' ]) name = ser.CharField(required=True) description = ser.CharField(required=False) id = ser.CharField(max_length=200, source='_id') class Meta: type_ = 'preprint_providers'
from rest_framework import serializers as ser from website.settings import API_DOMAIN from api.base.settings.defaults import API_BASE from api.base.serializers import JSONAPISerializer, LinksField class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'description', 'id' ]) name = ser.CharField(required=True) description = ser.CharField(required=False) id = ser.CharField(max_length=200, source='_id') links = LinksField({ 'self': 'get_absolute_url', 'preprints': 'preprint_links' }) class Meta: type_ = 'preprint_providers' def get_absolute_url(self, obj): return obj.absolute_api_v2_url def preprint_links(self, obj): return '{}{}preprint_providers/{}/preprints/'.format(API_DOMAIN, API_BASE, obj._id)
Add links field and related methods to link to a given provider's preprints from the preprint provider serializer
Add links field and related methods to link to a given provider's preprints from the preprint provider serializer
Python
apache-2.0
CenterForOpenScience/osf.io,icereval/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,binoculars/osf.io,acshi/osf.io,chrisseto/osf.io,adlius/osf.io,cwisecarver/osf.io,cslzchen/osf.io,erinspace/osf.io,mluo613/osf.io,mluo613/osf.io,mluo613/osf.io,caseyrollins/osf.io,rdhyee/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,alexschiller/osf.io,acshi/osf.io,adlius/osf.io,monikagrabowska/osf.io,crcresearch/osf.io,binoculars/osf.io,felliott/osf.io,alexschiller/osf.io,mattclark/osf.io,TomBaxter/osf.io,mfraezz/osf.io,Nesiehr/osf.io,emetsger/osf.io,caseyrollins/osf.io,TomBaxter/osf.io,adlius/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,brianjgeiger/osf.io,emetsger/osf.io,emetsger/osf.io,crcresearch/osf.io,hmoco/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,emetsger/osf.io,crcresearch/osf.io,pattisdr/osf.io,mattclark/osf.io,monikagrabowska/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,laurenrevere/osf.io,acshi/osf.io,caneruguz/osf.io,icereval/osf.io,pattisdr/osf.io,Nesiehr/osf.io,chrisseto/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,rdhyee/osf.io,leb2dg/osf.io,binoculars/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,felliott/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,laurenrevere/osf.io,caneruguz/osf.io,mfraezz/osf.io,mluo613/osf.io,acshi/osf.io,chennan47/osf.io,sloria/osf.io,hmoco/osf.io,sloria/osf.io,mfraezz/osf.io,cwisecarver/osf.io,mluo613/osf.io,felliott/osf.io,leb2dg/osf.io,felliott/osf.io,brianjgeiger/osf.io,pattisdr/osf.io,adlius/osf.io,saradbowman/osf.io,chennan47/osf.io,rdhyee/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,baylee-d/osf.io,baylee-d/osf.io,caneruguz/osf.io,samchrisinger/osf.io,rdhyee/osf.io,aaxelb/osf.io,erinspace/osf.io,samchrisinger/osf.io,TomBaxter/osf.io,acshi/osf.io,mfraezz/osf.io,icereval/osf.io,hmoco/osf.io,chrisseto/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,alexschiller/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,samchrisinger/osf.io,Johnetordoff/osf.io,mattclark/osf.io,alexschiller/osf.io,leb2dg/osf.io,brianjgeiger/osf.io
from rest_framework import serializers as ser + from website.settings import API_DOMAIN + from api.base.settings.defaults import API_BASE - from api.base.serializers import JSONAPISerializer + from api.base.serializers import JSONAPISerializer, LinksField - class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'description', 'id' ]) name = ser.CharField(required=True) description = ser.CharField(required=False) id = ser.CharField(max_length=200, source='_id') + links = LinksField({ + 'self': 'get_absolute_url', + 'preprints': 'preprint_links' + }) + class Meta: type_ = 'preprint_providers' + def get_absolute_url(self, obj): + return obj.absolute_api_v2_url + + def preprint_links(self, obj): + return '{}{}preprint_providers/{}/preprints/'.format(API_DOMAIN, API_BASE, obj._id) +
Add links field and related methods to link to a given provider's preprints from the preprint provider serializer
## Code Before: from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'description', 'id' ]) name = ser.CharField(required=True) description = ser.CharField(required=False) id = ser.CharField(max_length=200, source='_id') class Meta: type_ = 'preprint_providers' ## Instruction: Add links field and related methods to link to a given provider's preprints from the preprint provider serializer ## Code After: from rest_framework import serializers as ser from website.settings import API_DOMAIN from api.base.settings.defaults import API_BASE from api.base.serializers import JSONAPISerializer, LinksField class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'description', 'id' ]) name = ser.CharField(required=True) description = ser.CharField(required=False) id = ser.CharField(max_length=200, source='_id') links = LinksField({ 'self': 'get_absolute_url', 'preprints': 'preprint_links' }) class Meta: type_ = 'preprint_providers' def get_absolute_url(self, obj): return obj.absolute_api_v2_url def preprint_links(self, obj): return '{}{}preprint_providers/{}/preprints/'.format(API_DOMAIN, API_BASE, obj._id)
from rest_framework import serializers as ser + from website.settings import API_DOMAIN + from api.base.settings.defaults import API_BASE - from api.base.serializers import JSONAPISerializer + from api.base.serializers import JSONAPISerializer, LinksField ? ++++++++++++ - class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'description', 'id' ]) name = ser.CharField(required=True) description = ser.CharField(required=False) id = ser.CharField(max_length=200, source='_id') + links = LinksField({ + 'self': 'get_absolute_url', + 'preprints': 'preprint_links' + }) + class Meta: type_ = 'preprint_providers' + + def get_absolute_url(self, obj): + return obj.absolute_api_v2_url + + def preprint_links(self, obj): + return '{}{}preprint_providers/{}/preprints/'.format(API_DOMAIN, API_BASE, obj._id)
025bc069e231b58977e7d8ea7c526849f227b9ff
pytest_pipeline/utils.py
pytest_pipeline/utils.py
import gzip import hashlib def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener = gzip.open else: opener = open hasher = hashlib.md5() with opener(fname, mode) as src: buf = src.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = src.read(blocksize) return hasher.hexdigest()
import gzip import hashlib import os def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener = gzip.open else: opener = open hasher = hashlib.md5() with opener(fname, mode) as src: buf = src.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = src.read(blocksize) return hasher.hexdigest() def isexecfile(fname): return os.path.isfile(fname) and os.access(fname, os.X_OK) def which(program): # can not do anything meaningful without PATH if "PATH" not in os.environ: return for possible in os.environ["PATH"].split(":"): qualname = os.path.join(possible, program) if isexecfile(qualname): return qualname return
Add utility function for executable checking
Add utility function for executable checking
Python
bsd-3-clause
bow/pytest-pipeline
import gzip import hashlib + import os def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener = gzip.open else: opener = open hasher = hashlib.md5() with opener(fname, mode) as src: buf = src.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = src.read(blocksize) return hasher.hexdigest() + + def isexecfile(fname): + return os.path.isfile(fname) and os.access(fname, os.X_OK) + + + def which(program): + # can not do anything meaningful without PATH + if "PATH" not in os.environ: + return + for possible in os.environ["PATH"].split(":"): + qualname = os.path.join(possible, program) + if isexecfile(qualname): + return qualname + return +
Add utility function for executable checking
## Code Before: import gzip import hashlib def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener = gzip.open else: opener = open hasher = hashlib.md5() with opener(fname, mode) as src: buf = src.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = src.read(blocksize) return hasher.hexdigest() ## Instruction: Add utility function for executable checking ## Code After: import gzip import hashlib import os def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener = gzip.open else: opener = open hasher = hashlib.md5() with opener(fname, mode) as src: buf = src.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = src.read(blocksize) return hasher.hexdigest() def isexecfile(fname): return os.path.isfile(fname) and os.access(fname, os.X_OK) def which(program): # can not do anything meaningful without PATH if "PATH" not in os.environ: return for possible in os.environ["PATH"].split(":"): qualname = os.path.join(possible, program) if isexecfile(qualname): return qualname return
import gzip import hashlib + import os def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener = gzip.open else: opener = open hasher = hashlib.md5() with opener(fname, mode) as src: buf = src.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = src.read(blocksize) return hasher.hexdigest() + + + def isexecfile(fname): + return os.path.isfile(fname) and os.access(fname, os.X_OK) + + + def which(program): + # can not do anything meaningful without PATH + if "PATH" not in os.environ: + return + for possible in os.environ["PATH"].split(":"): + qualname = os.path.join(possible, program) + if isexecfile(qualname): + return qualname + return
eace27e618187860564de9501aabcb360112025a
matchmaker/skill.py
matchmaker/skill.py
import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( MatchResult.bot, func.sum(MatchResult.delta_chips), func.sum(MatchResult.hands) ) \ .group_by(MatchResult.bot) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( [BotSkill(s[0], today, s[1] / s[2], yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit()
import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank, BotIdentity class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( BotIdentity.id, func.coalesce(func.sum(MatchResult.delta_chips), 0), func.coalesce(func.sum(MatchResult.hands), 0), ) \ .outerjoin(MatchResult) \ .group_by(BotIdentity.id) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( [BotSkill(s[0], today, self.calc_winnings_per_hand(s[1], s[2]), yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() def calc_winnings_per_hand(self, chips, hand): try: return chips / hand except ZeroDivisionError: return 0 class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit()
Add bots with no games to the leaderboard
Add bots with no games to the leaderboard
Python
mit
gnmerritt/casino,gnmerritt/casino,gnmerritt/casino,gnmerritt/casino
import datetime from sqlalchemy.sql import func - from models import MatchResult, BotSkill, BotRank + from models import MatchResult, BotSkill, BotRank, BotIdentity class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( - MatchResult.bot, + BotIdentity.id, - func.sum(MatchResult.delta_chips), + func.coalesce(func.sum(MatchResult.delta_chips), 0), - func.sum(MatchResult.hands) + func.coalesce(func.sum(MatchResult.hands), 0), ) \ - .group_by(MatchResult.bot) \ + .outerjoin(MatchResult) \ + .group_by(BotIdentity.id) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( - [BotSkill(s[0], today, s[1] / s[2], yesterdays_skills.get(s[0], 0)) + [BotSkill(s[0], today, + self.calc_winnings_per_hand(s[1], s[2]), + yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() + + def calc_winnings_per_hand(self, chips, hand): + try: + return chips / hand + except ZeroDivisionError: + return 0 class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit()
Add bots with no games to the leaderboard
## Code Before: import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( MatchResult.bot, func.sum(MatchResult.delta_chips), func.sum(MatchResult.hands) ) \ .group_by(MatchResult.bot) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( [BotSkill(s[0], today, s[1] / s[2], yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit() ## Instruction: Add bots with no games to the leaderboard ## Code After: import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank, BotIdentity class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( BotIdentity.id, func.coalesce(func.sum(MatchResult.delta_chips), 0), func.coalesce(func.sum(MatchResult.hands), 0), ) \ .outerjoin(MatchResult) \ .group_by(BotIdentity.id) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( [BotSkill(s[0], today, self.calc_winnings_per_hand(s[1], s[2]), yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() def calc_winnings_per_hand(self, chips, hand): try: return chips / hand except ZeroDivisionError: return 0 class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit()
import datetime from sqlalchemy.sql import func - from models import MatchResult, BotSkill, BotRank + from models import MatchResult, BotSkill, BotRank, BotIdentity ? +++++++++++++ class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( - MatchResult.bot, + BotIdentity.id, - func.sum(MatchResult.delta_chips), + func.coalesce(func.sum(MatchResult.delta_chips), 0), ? ++++++++++++++ ++++ - func.sum(MatchResult.hands) + func.coalesce(func.sum(MatchResult.hands), 0), ? ++++++++++++++ +++++ ) \ - .group_by(MatchResult.bot) \ ? -- ^^^^ ---- + .outerjoin(MatchResult) \ ? ^^^^^^^ + .group_by(BotIdentity.id) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( - [BotSkill(s[0], today, s[1] / s[2], yesterdays_skills.get(s[0], 0)) + [BotSkill(s[0], today, + self.calc_winnings_per_hand(s[1], s[2]), + yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() + + def calc_winnings_per_hand(self, chips, hand): + try: + return chips / hand + except ZeroDivisionError: + return 0 class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit()
45325a43cf4525ef39afec86c03451525f907e92
hiro/utils.py
hiro/utils.py
import datetime import functools import time from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): return time.mktime(value.timetuple()) else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper
import calendar import datetime import functools from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): return calendar.timegm(value.timetuple()) else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper
Fix TZ-dependent return values from time_in_seconds()
Fix TZ-dependent return values from time_in_seconds() time.mktime assumes that the time tuple is in local time, rather than UTC. Use calendar.timegm instead for consistency.
Python
mit
alisaifee/hiro,alisaifee/hiro
+ import calendar import datetime import functools - import time from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): - return time.mktime(value.timetuple()) + return calendar.timegm(value.timetuple()) else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper
Fix TZ-dependent return values from time_in_seconds()
## Code Before: import datetime import functools import time from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): return time.mktime(value.timetuple()) else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper ## Instruction: Fix TZ-dependent return values from time_in_seconds() ## Code After: import calendar import datetime import functools from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): return calendar.timegm(value.timetuple()) else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper
+ import calendar import datetime import functools - import time from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): - return time.mktime(value.timetuple()) ? ^ ----- + return calendar.timegm(value.timetuple()) ? +++++++++ ^ else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper
e8ab72d069633aca71ae60d62ece3c0146289b18
xc7/utils/vivado_output_timing.py
xc7/utils/vivado_output_timing.py
import argparse def create_runme(f_out, args): print( """ report_timing_summary source {util_tcl} write_timing_info timing_{name}.json5 """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: create_runme(f, args) if __name__ == "__main__": main()
import argparse def create_output_timing(f_out, args): print( """ source {util_tcl} write_timing_info timing_{name}.json5 report_timing_summary """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: create_output_timing(f, args) if __name__ == "__main__": main()
Correct function name and put report_timing_summary at end of script.
Correct function name and put report_timing_summary at end of script. Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
Python
isc
SymbiFlow/symbiflow-arch-defs,SymbiFlow/symbiflow-arch-defs
import argparse - def create_runme(f_out, args): + def create_output_timing(f_out, args): print( """ - report_timing_summary - source {util_tcl} write_timing_info timing_{name}.json5 + + report_timing_summary """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: - create_runme(f, args) + create_output_timing(f, args) if __name__ == "__main__": main()
Correct function name and put report_timing_summary at end of script.
## Code Before: import argparse def create_runme(f_out, args): print( """ report_timing_summary source {util_tcl} write_timing_info timing_{name}.json5 """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: create_runme(f, args) if __name__ == "__main__": main() ## Instruction: Correct function name and put report_timing_summary at end of script. ## Code After: import argparse def create_output_timing(f_out, args): print( """ source {util_tcl} write_timing_info timing_{name}.json5 report_timing_summary """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: create_output_timing(f, args) if __name__ == "__main__": main()
import argparse - def create_runme(f_out, args): ? ^ ^^ + def create_output_timing(f_out, args): ? ^ +++++++++ ^ print( """ - report_timing_summary - source {util_tcl} write_timing_info timing_{name}.json5 + + report_timing_summary """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: - create_runme(f, args) ? ^ ^^ + create_output_timing(f, args) ? ^ +++++++++ ^ if __name__ == "__main__": main()
5cd6ed09511fdd40714ebe647577cb77fd366f7f
linter.py
linter.py
"""This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint ${temp_file} ${args}' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False tempfile_suffix = 'pug' error_stream = util.STREAM_BOTH defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = WARNING
"""This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint ${temp_file} ${args}' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False on_stderr = None tempfile_suffix = 'pug' defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = WARNING
Remove `error_stream`; Add `on_stderr` to make it works
Remove `error_stream`; Add `on_stderr` to make it works
Python
mit
benedfit/SublimeLinter-contrib-pug-lint,benedfit/SublimeLinter-contrib-jade-lint
"""This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint ${temp_file} ${args}' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False + on_stderr = None tempfile_suffix = 'pug' - error_stream = util.STREAM_BOTH defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = WARNING
Remove `error_stream`; Add `on_stderr` to make it works
## Code Before: """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint ${temp_file} ${args}' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False tempfile_suffix = 'pug' error_stream = util.STREAM_BOTH defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = WARNING ## Instruction: Remove `error_stream`; Add `on_stderr` to make it works ## Code After: """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint ${temp_file} ${args}' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False on_stderr = None tempfile_suffix = 'pug' defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = WARNING
"""This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an interface to pug-lint.""" cmd = 'pug-lint ${temp_file} ${args}' regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)' multiline = False + on_stderr = None tempfile_suffix = 'pug' - error_stream = util.STREAM_BOTH defaults = { 'selector': 'text.pug, source.pypug, text.jade', '--reporter=': 'inline' } default_type = WARNING
6477768e3040ed43fb10072730b84c29bef1e949
continuate/__init__.py
continuate/__init__.py
import importlib __all__ = ["linalg", "single_parameter"] for m in __all__: importlib.import_module("continuate." + m)
import importlib import os.path as op from glob import glob __all__ = [op.basename(f)[:-3] for f in glob(op.join(op.dirname(__file__), "*.py")) if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
Change manual listing of submodules to automatic
Change manual listing of submodules to automatic
Python
mit
termoshtt/continuate
import importlib + import os.path as op + from glob import glob - __all__ = ["linalg", "single_parameter"] + __all__ = [op.basename(f)[:-3] + for f in glob(op.join(op.dirname(__file__), "*.py")) + if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
Change manual listing of submodules to automatic
## Code Before: import importlib __all__ = ["linalg", "single_parameter"] for m in __all__: importlib.import_module("continuate." + m) ## Instruction: Change manual listing of submodules to automatic ## Code After: import importlib import os.path as op from glob import glob __all__ = [op.basename(f)[:-3] for f in glob(op.join(op.dirname(__file__), "*.py")) if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
import importlib + import os.path as op + from glob import glob - __all__ = ["linalg", "single_parameter"] + __all__ = [op.basename(f)[:-3] + for f in glob(op.join(op.dirname(__file__), "*.py")) + if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
432bbebbfa6376779bc605a45857ccdf5fef4b59
soundgen.py
soundgen.py
from wavebender import * import sys start = 10 final = 200 end_time= 10 def val(i): time = float(i) / 44100 k = (final - start) / end_time return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2))) def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
from wavebender import * import sys from common import * def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
Make sound generator use common
Make sound generator use common Signed-off-by: Ian Macalinao <57a33a5496950fec8433e4dd83347673459dcdfc@giza.us>
Python
isc
simplyianm/resonance-finder
from wavebender import * import sys + from common import * - - start = 10 - final = 200 - - end_time= 10 - - def val(i): - time = float(i) / 44100 - k = (final - start) / end_time - return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2))) def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
Make sound generator use common
## Code Before: from wavebender import * import sys start = 10 final = 200 end_time= 10 def val(i): time = float(i) / 44100 k = (final - start) / end_time return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2))) def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1) ## Instruction: Make sound generator use common ## Code After: from wavebender import * import sys from common import * def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
from wavebender import * import sys + from common import * - - start = 10 - final = 200 - - end_time= 10 - - def val(i): - time = float(i) / 44100 - k = (final - start) / end_time - return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2))) def sweep(): return (val(i) for i in count(0)) channels = ((sweep(),),) samples = compute_samples(channels, 44100 * 60 * 1) write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
a490a85e5842bd31a99a94f2530dbbea2d1c2584
bot/game/launch.py
bot/game/launch.py
import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id bot.answerCallbackQuery(callback_query_id, url="https://alvarogzp.github.io/telegram-games/rock-paper-scissors.html")
import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id bot.answerCallbackQuery(callback_query_id, url="https://rawgit.com/alvarogzp/telegram-games/develop/games/rock-paper-scissors/game.html")
Update url to point to return develop branch html page
Update url to point to return develop branch html page
Python
apache-2.0
alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games
import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id - bot.answerCallbackQuery(callback_query_id, url="https://alvarogzp.github.io/telegram-games/rock-paper-scissors.html") + bot.answerCallbackQuery(callback_query_id, url="https://rawgit.com/alvarogzp/telegram-games/develop/games/rock-paper-scissors/game.html")
Update url to point to return develop branch html page
## Code Before: import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id bot.answerCallbackQuery(callback_query_id, url="https://alvarogzp.github.io/telegram-games/rock-paper-scissors.html") ## Instruction: Update url to point to return develop branch html page ## Code After: import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id bot.answerCallbackQuery(callback_query_id, url="https://rawgit.com/alvarogzp/telegram-games/develop/games/rock-paper-scissors/game.html")
import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id - bot.answerCallbackQuery(callback_query_id, url="https://alvarogzp.github.io/telegram-games/rock-paper-scissors.html") ? ---------- + bot.answerCallbackQuery(callback_query_id, url="https://rawgit.com/alvarogzp/telegram-games/develop/games/rock-paper-scissors/game.html") ? +++++++++++ ++++++++++++++ +++++
95fa71c4439343764cac95a1667e08dc21cb6ebe
plugins.py
plugins.py
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) run("ln -sf %s %s" % (source_path, target_folder))
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) with settings(user=env.deploy_user): run("ln -sf %s %s" % (source_path, target_folder))
Fix plugin test by running scripts as user deploy
Fix plugin test by running scripts as user deploy
Python
bsd-3-clause
ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment,ctsit/redcap_deployment
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) + with settings(user=env.deploy_user): - run("ln -sf %s %s" % (source_path, target_folder)) + run("ln -sf %s %s" % (source_path, target_folder))
Fix plugin test by running scripts as user deploy
## Code Before: from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) run("ln -sf %s %s" % (source_path, target_folder)) ## Instruction: Fix plugin test by running scripts as user deploy ## Code After: from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) with settings(user=env.deploy_user): run("ln -sf %s %s" % (source_path, target_folder))
from fabric.api import * import os import re __all__ = [] @task def test(plugin_path): """ Symbolically link a host file that contains a redcap plugin into the ./redcap/plugins folder :param plugin_path: path to plugin folder relative to VagrantFile :return: """ if not os.path.exists(plugin_path): abort("The folder %s does not exist. Please provide a relative path to a plugin folder you would like to test in the local vm" % plugin_path) redcap_root = env.live_project_full_path source_path = "/vagrant/" + plugin_path target_folder = "/".join([redcap_root, env.plugins_path]) + with settings(user=env.deploy_user): - run("ln -sf %s %s" % (source_path, target_folder)) + run("ln -sf %s %s" % (source_path, target_folder)) ? ++++++++
817976878b584086bedc296e5fd6d264006c8dcd
tests/conftest.py
tests/conftest.py
from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import mock import pytest @pytest.yield_fixture def in_tmpdir(tmpdir): pwd = os.getcwd() os.chdir(tmpdir.strpath) try: yield finally: os.chdir(pwd) @pytest.yield_fixture def check_call_mock(): with mock.patch.object(subprocess, 'check_call') as mocked: yield mocked
from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import mock import pytest @pytest.fixture def in_tmpdir(tmpdir): pwd = os.getcwd() os.chdir(tmpdir.strpath) try: yield finally: os.chdir(pwd) @pytest.fixture def check_call_mock(): with mock.patch.object(subprocess, 'check_call') as mocked: yield mocked
Replace deprecated yield_fixture with fixture
Replace deprecated yield_fixture with fixture Committed via https://github.com/asottile/all-repos
Python
mit
asottile/css-explore
from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import mock import pytest - @pytest.yield_fixture + @pytest.fixture def in_tmpdir(tmpdir): pwd = os.getcwd() os.chdir(tmpdir.strpath) try: yield finally: os.chdir(pwd) - @pytest.yield_fixture + @pytest.fixture def check_call_mock(): with mock.patch.object(subprocess, 'check_call') as mocked: yield mocked
Replace deprecated yield_fixture with fixture
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import mock import pytest @pytest.yield_fixture def in_tmpdir(tmpdir): pwd = os.getcwd() os.chdir(tmpdir.strpath) try: yield finally: os.chdir(pwd) @pytest.yield_fixture def check_call_mock(): with mock.patch.object(subprocess, 'check_call') as mocked: yield mocked ## Instruction: Replace deprecated yield_fixture with fixture ## Code After: from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import mock import pytest @pytest.fixture def in_tmpdir(tmpdir): pwd = os.getcwd() os.chdir(tmpdir.strpath) try: yield finally: os.chdir(pwd) @pytest.fixture def check_call_mock(): with mock.patch.object(subprocess, 'check_call') as mocked: yield mocked
from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import mock import pytest - @pytest.yield_fixture ? ------ + @pytest.fixture def in_tmpdir(tmpdir): pwd = os.getcwd() os.chdir(tmpdir.strpath) try: yield finally: os.chdir(pwd) - @pytest.yield_fixture ? ------ + @pytest.fixture def check_call_mock(): with mock.patch.object(subprocess, 'check_call') as mocked: yield mocked
b48e39aafd9ef413216444a6bfb97e867aa40e1c
tests/auto/keras/test_constraints.py
tests/auto/keras/test_constraints.py
import unittest import numpy as np from theano import tensor as T class TestConstraints(unittest.TestCase): def setUp(self): self.some_values = [0.1,0.5,3,8,1e-7] self.example_array = np.random.random((100,100))*100. - 50. self.example_array[0,0] = 0. # 0 could possibly cause trouble def test_maxnorm(self): from keras.constraints import maxnorm for m in self.some_values: norm_instance = maxnorm(m) normed = norm_instance(self.example_array) assert(np.all(normed.eval() < m)) if __name__ == '__main__': unittest.main()
import unittest import numpy as np from theano import tensor as T class TestConstraints(unittest.TestCase): def setUp(self): self.some_values = [0.1,0.5,3,8,1e-7] self.example_array = np.random.random((100,100))*100. - 50. self.example_array[0,0] = 0. # 0 could possibly cause trouble def test_maxnorm(self): from keras.constraints import maxnorm for m in self.some_values: norm_instance = maxnorm(m) normed = norm_instance(self.example_array) assert(np.all(normed.eval() < m)) def test_nonneg(self): from keras.constraints import nonneg normed = nonneg(self.example_array) assert(np.all(np.min(normed.eval(),axis=1) == 0.)) def test_identity(self): from keras.constraints import identity normed = identity(self.example_array) assert(np.all(normed == self.example_array)) def test_unitnorm(self): from keras.constraints import unitnorm normed = unitnorm(self.example_array) self.assertAlmostEqual( np.max(np.abs(np.sqrt(np.sum(normed.eval()**2,axis=1))-1.)) ,0.) if __name__ == '__main__': unittest.main()
Add a test for the identity, non-negative, and unit-norm constraints
Add a test for the identity, non-negative, and unit-norm constraints
Python
mit
saurav111/keras,kfoss/keras,Aureliu/keras,stephenbalaban/keras,chenych11/keras,jiumem/keras,cvfish/keras,xiaoda99/keras,rodrigob/keras,iamtrask/keras,wubr2000/keras,navyjeff/keras,keskarnitish/keras,eulerreich/keras,zxytim/keras,tencrance/keras,printedheart/keras,rudaoshi/keras,dribnet/keras,pthaike/keras,cheng6076/keras,nebw/keras,johmathe/keras,harshhemani/keras,llcao/keras,jayhetee/keras,wxs/keras,JasonTam/keras,mikekestemont/keras,DLlearn/keras,zhangxujinsh/keras,fmacias64/keras,jonberliner/keras,ledbetdr/keras,zhmz90/keras,Cadene/keras,pjadzinsky/keras,OlafLee/keras,kod3r/keras,jalexvig/keras,yingzha/keras,abayowbo/keras,vseledkin/keras,ashhher3/keras,ml-lab/keras,kuza55/keras,gamer13/keras,bboalimoe/keras,keras-team/keras,jasonyaw/keras,relh/keras,jbolinge/keras,marchick209/keras,florentchandelier/keras,ogrisel/keras,zxsted/keras,MagicSen/keras,nt/keras,amy12xx/keras,nzer0/keras,why11002526/keras,iScienceLuvr/keras,danielforsyth/keras,dhruvparamhans/keras,bottler/keras,Yingmin-Li/keras,asampat3090/keras,xurantju/keras,3dconv/keras,untom/keras,gavinmh/keras,dolaameng/keras,LIBOTAO/keras,jimgoo/keras,hhaoyan/keras,imcomking/Convolutional-GRU-keras-extension-,dxj19831029/keras,sjuvekar/keras,happyboy310/keras,jhauswald/keras,ekamioka/keras,brainwater/keras,Smerity/keras,rlkelly/keras,kemaswill/keras,ypkang/keras,nehz/keras,meanmee/keras,EderSantana/keras,DeepGnosis/keras,keras-team/keras,daviddiazvico/keras
import unittest import numpy as np from theano import tensor as T class TestConstraints(unittest.TestCase): def setUp(self): self.some_values = [0.1,0.5,3,8,1e-7] self.example_array = np.random.random((100,100))*100. - 50. self.example_array[0,0] = 0. # 0 could possibly cause trouble def test_maxnorm(self): from keras.constraints import maxnorm for m in self.some_values: norm_instance = maxnorm(m) normed = norm_instance(self.example_array) assert(np.all(normed.eval() < m)) + def test_nonneg(self): + from keras.constraints import nonneg + + normed = nonneg(self.example_array) + assert(np.all(np.min(normed.eval(),axis=1) == 0.)) + + def test_identity(self): + from keras.constraints import identity + + normed = identity(self.example_array) + assert(np.all(normed == self.example_array)) + + def test_unitnorm(self): + from keras.constraints import unitnorm + + normed = unitnorm(self.example_array) + self.assertAlmostEqual( + np.max(np.abs(np.sqrt(np.sum(normed.eval()**2,axis=1))-1.)) + ,0.) + if __name__ == '__main__': unittest.main()
Add a test for the identity, non-negative, and unit-norm constraints
## Code Before: import unittest import numpy as np from theano import tensor as T class TestConstraints(unittest.TestCase): def setUp(self): self.some_values = [0.1,0.5,3,8,1e-7] self.example_array = np.random.random((100,100))*100. - 50. self.example_array[0,0] = 0. # 0 could possibly cause trouble def test_maxnorm(self): from keras.constraints import maxnorm for m in self.some_values: norm_instance = maxnorm(m) normed = norm_instance(self.example_array) assert(np.all(normed.eval() < m)) if __name__ == '__main__': unittest.main() ## Instruction: Add a test for the identity, non-negative, and unit-norm constraints ## Code After: import unittest import numpy as np from theano import tensor as T class TestConstraints(unittest.TestCase): def setUp(self): self.some_values = [0.1,0.5,3,8,1e-7] self.example_array = np.random.random((100,100))*100. - 50. self.example_array[0,0] = 0. # 0 could possibly cause trouble def test_maxnorm(self): from keras.constraints import maxnorm for m in self.some_values: norm_instance = maxnorm(m) normed = norm_instance(self.example_array) assert(np.all(normed.eval() < m)) def test_nonneg(self): from keras.constraints import nonneg normed = nonneg(self.example_array) assert(np.all(np.min(normed.eval(),axis=1) == 0.)) def test_identity(self): from keras.constraints import identity normed = identity(self.example_array) assert(np.all(normed == self.example_array)) def test_unitnorm(self): from keras.constraints import unitnorm normed = unitnorm(self.example_array) self.assertAlmostEqual( np.max(np.abs(np.sqrt(np.sum(normed.eval()**2,axis=1))-1.)) ,0.) if __name__ == '__main__': unittest.main()
import unittest import numpy as np from theano import tensor as T class TestConstraints(unittest.TestCase): def setUp(self): self.some_values = [0.1,0.5,3,8,1e-7] self.example_array = np.random.random((100,100))*100. - 50. self.example_array[0,0] = 0. # 0 could possibly cause trouble def test_maxnorm(self): from keras.constraints import maxnorm for m in self.some_values: norm_instance = maxnorm(m) normed = norm_instance(self.example_array) assert(np.all(normed.eval() < m)) + def test_nonneg(self): + from keras.constraints import nonneg + + normed = nonneg(self.example_array) + assert(np.all(np.min(normed.eval(),axis=1) == 0.)) + + def test_identity(self): + from keras.constraints import identity + + normed = identity(self.example_array) + assert(np.all(normed == self.example_array)) + + def test_unitnorm(self): + from keras.constraints import unitnorm + + normed = unitnorm(self.example_array) + self.assertAlmostEqual( + np.max(np.abs(np.sqrt(np.sum(normed.eval()**2,axis=1))-1.)) + ,0.) + if __name__ == '__main__': unittest.main()
a7b92bdbb4c71a33896105022e70c69c3bc33861
patterns/gradient.py
patterns/gradient.py
from blinkytape import color class Gradient(object): def __init__(self, pixel_count, start_color, end_color): self._pixels = self._rgb_gradient(pixel_count, start_color, end_color) @property def pixels(self): return list(self._pixels) def _rgb_gradient(self, pixel_count, start_color, end_color): red_gradient = self._gradient(start_color.red, end_color.red, pixel_count) green_gradient = self._gradient(start_color.green, end_color.green, pixel_count) blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count) rgb_gradient = zip(red_gradient, green_gradient, blue_gradient) return [color.Color(*rgb) for rgb in rgb_gradient] def _gradient(self, start, end, count): delta = (end - start) / float(count - 1) return [start + (delta * index) for index in range(0, count)]
from blinkytape import color class Gradient(object): # TBD: If this had a length it would also work as a streak; consider def __init__(self, pixel_count, start_color, end_color): self._pixels = self._rgb_gradient(pixel_count, start_color, end_color) @property def pixels(self): return list(self._pixels) def _rgb_gradient(self, pixel_count, start_color, end_color): red_gradient = self._gradient(start_color.red, end_color.red, pixel_count) green_gradient = self._gradient(start_color.green, end_color.green, pixel_count) blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count) rgb_gradient = zip(red_gradient, green_gradient, blue_gradient) return [color.Color(*rgb) for rgb in rgb_gradient] def _gradient(self, start, end, count): delta = (end - start) / float(count - 1) return [start + (delta * index) for index in range(0, count)]
Add another TBD for future reference
Add another TBD for future reference
Python
mit
jonspeicher/blinkyfun
from blinkytape import color class Gradient(object): + # TBD: If this had a length it would also work as a streak; consider def __init__(self, pixel_count, start_color, end_color): self._pixels = self._rgb_gradient(pixel_count, start_color, end_color) @property def pixels(self): return list(self._pixels) def _rgb_gradient(self, pixel_count, start_color, end_color): red_gradient = self._gradient(start_color.red, end_color.red, pixel_count) green_gradient = self._gradient(start_color.green, end_color.green, pixel_count) blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count) rgb_gradient = zip(red_gradient, green_gradient, blue_gradient) return [color.Color(*rgb) for rgb in rgb_gradient] def _gradient(self, start, end, count): delta = (end - start) / float(count - 1) return [start + (delta * index) for index in range(0, count)]
Add another TBD for future reference
## Code Before: from blinkytape import color class Gradient(object): def __init__(self, pixel_count, start_color, end_color): self._pixels = self._rgb_gradient(pixel_count, start_color, end_color) @property def pixels(self): return list(self._pixels) def _rgb_gradient(self, pixel_count, start_color, end_color): red_gradient = self._gradient(start_color.red, end_color.red, pixel_count) green_gradient = self._gradient(start_color.green, end_color.green, pixel_count) blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count) rgb_gradient = zip(red_gradient, green_gradient, blue_gradient) return [color.Color(*rgb) for rgb in rgb_gradient] def _gradient(self, start, end, count): delta = (end - start) / float(count - 1) return [start + (delta * index) for index in range(0, count)] ## Instruction: Add another TBD for future reference ## Code After: from blinkytape import color class Gradient(object): # TBD: If this had a length it would also work as a streak; consider def __init__(self, pixel_count, start_color, end_color): self._pixels = self._rgb_gradient(pixel_count, start_color, end_color) @property def pixels(self): return list(self._pixels) def _rgb_gradient(self, pixel_count, start_color, end_color): red_gradient = self._gradient(start_color.red, end_color.red, pixel_count) green_gradient = self._gradient(start_color.green, end_color.green, pixel_count) blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count) rgb_gradient = zip(red_gradient, green_gradient, blue_gradient) return [color.Color(*rgb) for rgb in rgb_gradient] def _gradient(self, start, end, count): delta = (end - start) / float(count - 1) return [start + (delta * index) for index in range(0, count)]
from blinkytape import color class Gradient(object): + # TBD: If this had a length it would also work as a streak; consider def __init__(self, pixel_count, start_color, end_color): self._pixels = self._rgb_gradient(pixel_count, start_color, end_color) @property def pixels(self): return list(self._pixels) def _rgb_gradient(self, pixel_count, start_color, end_color): red_gradient = self._gradient(start_color.red, end_color.red, pixel_count) green_gradient = self._gradient(start_color.green, end_color.green, pixel_count) blue_gradient = self._gradient(start_color.blue, end_color.blue, pixel_count) rgb_gradient = zip(red_gradient, green_gradient, blue_gradient) return [color.Color(*rgb) for rgb in rgb_gradient] def _gradient(self, start, end, count): delta = (end - start) / float(count - 1) return [start + (delta * index) for index in range(0, count)]
186a72b91798b11d13ea7f2538141f620b0787a8
tests/test_metrics.py
tests/test_metrics.py
import json from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.data.decode('utf-8')), {'results': []})
from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, {'results': []}) def test_noop(self): url = '/dashboard/find' response = self.app.get(url) self.assertJSON(response, {'dashboards': []}) url = '/dashboard/load/foo' response = self.app.get(url) self.assertJSON(response, {'error': "Dashboard 'foo' does not exist."}, status_code=404) url = '/events/get_data' response = self.app.get(url) self.assertJSON(response, [])
Add test for noop routes
Add test for noop routes
Python
apache-2.0
vladimir-smirnov-sociomantic/graphite-api,michaelrice/graphite-api,GeorgeJahad/graphite-api,vladimir-smirnov-sociomantic/graphite-api,michaelrice/graphite-api,alphapigger/graphite-api,raintank/graphite-api,hubrick/graphite-api,rackerlabs/graphite-api,Knewton/graphite-api,raintank/graphite-api,Knewton/graphite-api,bogus-py/graphite-api,cybem/graphite-api-iow,DaveBlooman/graphite-api,rackerlabs/graphite-api,brutasse/graphite-api,DaveBlooman/graphite-api,hubrick/graphite-api,raintank/graphite-api,tpeng/graphite-api,winguru/graphite-api,winguru/graphite-api,bogus-py/graphite-api,tpeng/graphite-api,cybem/graphite-api-iow,absalon-james/graphite-api,alphapigger/graphite-api,absalon-james/graphite-api,brutasse/graphite-api,GeorgeJahad/graphite-api
- import json - from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) + self.assertJSON(response, {'results': []}) - self.assertEqual(response.status_code, 200) - self.assertEqual(json.loads(response.data.decode('utf-8')), - {'results': []}) + def test_noop(self): + url = '/dashboard/find' + response = self.app.get(url) + self.assertJSON(response, {'dashboards': []}) + + url = '/dashboard/load/foo' + response = self.app.get(url) + self.assertJSON(response, {'error': "Dashboard 'foo' does not exist."}, + status_code=404) + + url = '/events/get_data' + response = self.app.get(url) + self.assertJSON(response, []) +
Add test for noop routes
## Code Before: import json from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.data.decode('utf-8')), {'results': []}) ## Instruction: Add test for noop routes ## Code After: from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, {'results': []}) def test_noop(self): url = '/dashboard/find' response = self.app.get(url) self.assertJSON(response, {'dashboards': []}) url = '/dashboard/load/foo' response = self.app.get(url) self.assertJSON(response, {'error': "Dashboard 'foo' does not exist."}, status_code=404) url = '/events/get_data' response = self.app.get(url) self.assertJSON(response, [])
- import json - from . import TestCase class MetricsTests(TestCase): def test_find(self): url = '/metrics/find' response = self.app.get(url) self.assertEqual(response.status_code, 400) response = self.app.get(url, query_string={'query': 'test'}) self.assertJSON(response, []) def test_expand(self): url = '/metrics/expand' response = self.app.get(url) self.assertJSON(response, {'errors': {'query': 'this parameter is required.'}}, status_code=400) response = self.app.get(url, query_string={'query': 'test'}) - self.assertEqual(response.status_code, 200) - self.assertEqual(json.loads(response.data.decode('utf-8')), - {'results': []}) + self.assertJSON(response, {'results': []}) + + def test_noop(self): + url = '/dashboard/find' + response = self.app.get(url) + self.assertJSON(response, {'dashboards': []}) + + url = '/dashboard/load/foo' + response = self.app.get(url) + self.assertJSON(response, {'error': "Dashboard 'foo' does not exist."}, + status_code=404) + + url = '/events/get_data' + response = self.app.get(url) + self.assertJSON(response, [])
02548b44a3b5de203e4a82693288ebae4037d90e
jug/__init__.py
jug/__init__.py
from __future__ import division from .task import TaskGenerator, Task from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.0'
from __future__ import division from .task import TaskGenerator, Task, value from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.9-git'
Add value() to jug namespace
Add value() to jug namespace The jug namespace might need some attention.
Python
mit
unode/jug,luispedro/jug,luispedro/jug,unode/jug
from __future__ import division - from .task import TaskGenerator, Task + from .task import TaskGenerator, Task, value from .jug import init from .backends import file_store, dict_store, redis_store - __version__ = '0.5.0' + __version__ = '0.5.9-git'
Add value() to jug namespace
## Code Before: from __future__ import division from .task import TaskGenerator, Task from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.0' ## Instruction: Add value() to jug namespace ## Code After: from __future__ import division from .task import TaskGenerator, Task, value from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.9-git'
from __future__ import division - from .task import TaskGenerator, Task + from .task import TaskGenerator, Task, value ? +++++++ from .jug import init from .backends import file_store, dict_store, redis_store - __version__ = '0.5.0' ? ^ + __version__ = '0.5.9-git' ? ^^^^^
c0df1342b6625cdc2a205f2ba13ee201e8d0b02a
tests/conftest.py
tests/conftest.py
from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" mock_services_mapping_getter_patch = mock.patch('app.mapping.get_services_mapping') mock_services_mapping_getter = mock_services_mapping_getter_patch.start() mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value mock_services_mapping_getter_patch.stop()
from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" with mock.patch('app.mapping.get_services_mapping') as mock_services_mapping_getter: mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value
Use with block to start/stop the patch context manager.
Use with block to start/stop the patch context manager. - this is less code, hopefully is just as clear why we need to 'yield' rather than just 'return'. https://trello.com/c/OpWI068M/380-after-g9-go-live-removal-of-old-filters-from-search-api-mapping
Python
mit
alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api
from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" + with mock.patch('app.mapping.get_services_mapping') as mock_services_mapping_getter: - mock_services_mapping_getter_patch = mock.patch('app.mapping.get_services_mapping') - mock_services_mapping_getter = mock_services_mapping_getter_patch.start() - mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') + mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') + yield mock_services_mapping_getter.return_value - yield mock_services_mapping_getter.return_value - - mock_services_mapping_getter_patch.stop() -
Use with block to start/stop the patch context manager.
## Code Before: from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" mock_services_mapping_getter_patch = mock.patch('app.mapping.get_services_mapping') mock_services_mapping_getter = mock_services_mapping_getter_patch.start() mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value mock_services_mapping_getter_patch.stop() ## Instruction: Use with block to start/stop the patch context manager. ## Code After: from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" with mock.patch('app.mapping.get_services_mapping') as mock_services_mapping_getter: mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value
from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" + with mock.patch('app.mapping.get_services_mapping') as mock_services_mapping_getter: - mock_services_mapping_getter_patch = mock.patch('app.mapping.get_services_mapping') - mock_services_mapping_getter = mock_services_mapping_getter_patch.start() - mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') + mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') ? ++++ - - yield mock_services_mapping_getter.return_value + yield mock_services_mapping_getter.return_value ? ++++ - - mock_services_mapping_getter_patch.stop()
018f8e7c7c69eefeb121c8552eb319b4b550f251
backslash/error_container.py
backslash/error_container.py
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'exception': exception, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'message': message, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
Unify errors and failures in API
Unify errors and failures in API
Python
bsd-3-clause
vmalloc/backslash-python,slash-testing/backslash-python
from sentinels import NOTHING class ErrorContainer(object): - def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): + def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, - 'exception': exception, + 'message': message, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
Unify errors and failures in API
## Code Before: from sentinels import NOTHING class ErrorContainer(object): def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'exception': exception, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id' ## Instruction: Unify errors and failures in API ## Code After: from sentinels import NOTHING class ErrorContainer(object): def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'message': message, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
from sentinels import NOTHING class ErrorContainer(object): - def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): ? ^^ ----- + def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): ? + ^^^^ ++++++++ ++++++++ return self.client.api.call_function('add_error', {self._get_id_key(): self.id, - 'exception': exception, ? ^^ ----- ^^ ----- + 'message': message, ? + ^^^^ + ^^^^ 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
ca09f3e4286be605e179f0b6ac742305d165b431
monasca_setup/detection/plugins/http_check.py
monasca_setup/detection/plugins/http_check.py
import logging import monasca_setup.agent_config import monasca_setup.detection log = logging.getLogger(__name__) class HttpCheck(monasca_setup.detection.ArgsPlugin): """ Setup an http_check according to the passed in args. Despite being a detection plugin this plugin does no detection and will be a noop without arguments. Expects space seperated arguments, the required argument is url. Optional parameters include: disable_ssl_validation and match_pattern. """ def _detect(self): """Run detection, set self.available True if the service is detected. """ self.available = self._check_required_args(['url']) def build_config(self): """Build the config as a Plugins object and return. """ config = monasca_setup.agent_config.Plugins() log.info("\tEnabling the http_check plugin for {url}".format(**self.args)) # No support for setting headers at this time instance = self._build_instance(['url', 'timeout', 'username', 'password', 'match_pattern', 'disable_ssl_validation']) instance['name'] = self.args['url'] instance['collect_response_time'] = True config['http_check'] = {'init_config': None, 'instances': [instance]} return config
import ast import logging import monasca_setup.agent_config import monasca_setup.detection log = logging.getLogger(__name__) class HttpCheck(monasca_setup.detection.ArgsPlugin): """ Setup an http_check according to the passed in args. Despite being a detection plugin this plugin does no detection and will be a noop without arguments. Expects space seperated arguments, the required argument is url. Optional parameters include: disable_ssl_validation and match_pattern. """ def _detect(self): """Run detection, set self.available True if the service is detected. """ self.available = self._check_required_args(['url']) def build_config(self): """Build the config as a Plugins object and return. """ config = monasca_setup.agent_config.Plugins() log.info("\tEnabling the http_check plugin for {url}".format(**self.args)) # No support for setting headers at this time instance = self._build_instance(['url', 'timeout', 'username', 'password', 'match_pattern', 'disable_ssl_validation', 'name', 'use_keystone', 'collect_response_time']) # Normalize any boolean parameters for param in ['use_keystone', 'collect_response_time']: if param in self.args: instance[param] = ast.literal_eval(self.args[param].capitalize()) # Set some defaults if 'collect_response_time' not in instance: instance['collect_response_time'] = True if 'name' not in instance: instance['name'] = self.args['url'] config['http_check'] = {'init_config': None, 'instances': [instance]} return config
Allow additional customization of HttpCheck
Allow additional customization of HttpCheck Documentation on HttpCheck detection plugin refers to things that do not currently work in the plugin, like activating use_keystone. This change fixes that, and adds the ability to customize other http_check parameters which were missing. Change-Id: I2309b25f83f395dcd56914ba7cdfeac9b42c7481
Python
bsd-3-clause
sapcc/monasca-agent,sapcc/monasca-agent,sapcc/monasca-agent
+ import ast import logging import monasca_setup.agent_config import monasca_setup.detection log = logging.getLogger(__name__) class HttpCheck(monasca_setup.detection.ArgsPlugin): """ Setup an http_check according to the passed in args. Despite being a detection plugin this plugin does no detection and will be a noop without arguments. Expects space seperated arguments, the required argument is url. Optional parameters include: disable_ssl_validation and match_pattern. """ def _detect(self): """Run detection, set self.available True if the service is detected. """ self.available = self._check_required_args(['url']) def build_config(self): """Build the config as a Plugins object and return. """ config = monasca_setup.agent_config.Plugins() log.info("\tEnabling the http_check plugin for {url}".format(**self.args)) # No support for setting headers at this time - instance = self._build_instance(['url', 'timeout', 'username', 'password', 'match_pattern', + instance = self._build_instance(['url', 'timeout', 'username', 'password', - 'disable_ssl_validation']) + 'match_pattern', 'disable_ssl_validation', - instance['name'] = self.args['url'] + 'name', 'use_keystone', 'collect_response_time']) + + # Normalize any boolean parameters + for param in ['use_keystone', 'collect_response_time']: + if param in self.args: + instance[param] = ast.literal_eval(self.args[param].capitalize()) + # Set some defaults + if 'collect_response_time' not in instance: - instance['collect_response_time'] = True + instance['collect_response_time'] = True + if 'name' not in instance: + instance['name'] = self.args['url'] config['http_check'] = {'init_config': None, 'instances': [instance]} return config -
Allow additional customization of HttpCheck
## Code Before: import logging import monasca_setup.agent_config import monasca_setup.detection log = logging.getLogger(__name__) class HttpCheck(monasca_setup.detection.ArgsPlugin): """ Setup an http_check according to the passed in args. Despite being a detection plugin this plugin does no detection and will be a noop without arguments. Expects space seperated arguments, the required argument is url. Optional parameters include: disable_ssl_validation and match_pattern. """ def _detect(self): """Run detection, set self.available True if the service is detected. """ self.available = self._check_required_args(['url']) def build_config(self): """Build the config as a Plugins object and return. """ config = monasca_setup.agent_config.Plugins() log.info("\tEnabling the http_check plugin for {url}".format(**self.args)) # No support for setting headers at this time instance = self._build_instance(['url', 'timeout', 'username', 'password', 'match_pattern', 'disable_ssl_validation']) instance['name'] = self.args['url'] instance['collect_response_time'] = True config['http_check'] = {'init_config': None, 'instances': [instance]} return config ## Instruction: Allow additional customization of HttpCheck ## Code After: import ast import logging import monasca_setup.agent_config import monasca_setup.detection log = logging.getLogger(__name__) class HttpCheck(monasca_setup.detection.ArgsPlugin): """ Setup an http_check according to the passed in args. Despite being a detection plugin this plugin does no detection and will be a noop without arguments. Expects space seperated arguments, the required argument is url. Optional parameters include: disable_ssl_validation and match_pattern. """ def _detect(self): """Run detection, set self.available True if the service is detected. """ self.available = self._check_required_args(['url']) def build_config(self): """Build the config as a Plugins object and return. """ config = monasca_setup.agent_config.Plugins() log.info("\tEnabling the http_check plugin for {url}".format(**self.args)) # No support for setting headers at this time instance = self._build_instance(['url', 'timeout', 'username', 'password', 'match_pattern', 'disable_ssl_validation', 'name', 'use_keystone', 'collect_response_time']) # Normalize any boolean parameters for param in ['use_keystone', 'collect_response_time']: if param in self.args: instance[param] = ast.literal_eval(self.args[param].capitalize()) # Set some defaults if 'collect_response_time' not in instance: instance['collect_response_time'] = True if 'name' not in instance: instance['name'] = self.args['url'] config['http_check'] = {'init_config': None, 'instances': [instance]} return config
+ import ast import logging import monasca_setup.agent_config import monasca_setup.detection log = logging.getLogger(__name__) class HttpCheck(monasca_setup.detection.ArgsPlugin): """ Setup an http_check according to the passed in args. Despite being a detection plugin this plugin does no detection and will be a noop without arguments. Expects space seperated arguments, the required argument is url. Optional parameters include: disable_ssl_validation and match_pattern. """ def _detect(self): """Run detection, set self.available True if the service is detected. """ self.available = self._check_required_args(['url']) def build_config(self): """Build the config as a Plugins object and return. """ config = monasca_setup.agent_config.Plugins() log.info("\tEnabling the http_check plugin for {url}".format(**self.args)) # No support for setting headers at this time - instance = self._build_instance(['url', 'timeout', 'username', 'password', 'match_pattern', ? ----------------- + instance = self._build_instance(['url', 'timeout', 'username', 'password', - 'disable_ssl_validation']) ? ^^ + 'match_pattern', 'disable_ssl_validation', ? +++++++++++++++++ ^ - instance['name'] = self.args['url'] + 'name', 'use_keystone', 'collect_response_time']) + + # Normalize any boolean parameters + for param in ['use_keystone', 'collect_response_time']: + if param in self.args: + instance[param] = ast.literal_eval(self.args[param].capitalize()) + # Set some defaults + if 'collect_response_time' not in instance: - instance['collect_response_time'] = True + instance['collect_response_time'] = True ? ++++ + if 'name' not in instance: + instance['name'] = self.args['url'] config['http_check'] = {'init_config': None, 'instances': [instance]} return config -
667a3d2803529c5b14fd17c6877961646615f2fd
python2/raygun4py/middleware/wsgi.py
python2/raygun4py/middleware/wsgi.py
import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") try: chunk = self.app(environ, start_response) except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise try: for event in chunk: yield event except Exception as e: request = build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if chunk and hasattr(chunk, 'close') and callable(chunk.close): try: chunk.close() except Exception as e: request = build_request(environ) self.send_exception(exception=e, request=request) def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request
import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") iterable = None try: iterable = self.app(environ, start_response) for event in iterable: yield event except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if hasattr(iterable, 'close'): try: iterable.close() except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request
Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly
Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly
Python
mit
MindscapeHQ/raygun4py
import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") + iterable = None + try: - chunk = self.app(environ, start_response) + iterable = self.app(environ, start_response) + for event in iterable: + yield event + except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) - raise - try: - for event in chunk: - yield event - except Exception as e: - request = build_request(environ) - self.sender.send_exception(exception=e, request=request) - - raise finally: - if chunk and hasattr(chunk, 'close') and callable(chunk.close): + if hasattr(iterable, 'close'): try: - chunk.close() + iterable.close() except Exception as e: - request = build_request(environ) + request = self.build_request(environ) - self.send_exception(exception=e, request=request) + self.sender.send_exception(exception=e, request=request) + raise def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request
Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly
## Code Before: import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") try: chunk = self.app(environ, start_response) except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise try: for event in chunk: yield event except Exception as e: request = build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if chunk and hasattr(chunk, 'close') and callable(chunk.close): try: chunk.close() except Exception as e: request = build_request(environ) self.send_exception(exception=e, request=request) def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request ## Instruction: Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly ## Code After: import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") iterable = None try: iterable = self.app(environ, start_response) for event in iterable: yield event except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if hasattr(iterable, 'close'): try: iterable.close() except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request
import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") + iterable = None + try: - chunk = self.app(environ, start_response) ? ^^^^^ + iterable = self.app(environ, start_response) ? ^^^^^^^^ + for event in iterable: + yield event + except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) - raise - try: - for event in chunk: - yield event - except Exception as e: - request = build_request(environ) - self.sender.send_exception(exception=e, request=request) - - raise finally: - if chunk and hasattr(chunk, 'close') and callable(chunk.close): + if hasattr(iterable, 'close'): try: - chunk.close() ? ^^^^^ + iterable.close() ? ^^^^^^^^ except Exception as e: - request = build_request(environ) + request = self.build_request(environ) ? +++++ - self.send_exception(exception=e, request=request) + self.sender.send_exception(exception=e, request=request) ? +++++++ + raise def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request
b7b0724b7f663a8a0d0e5c46d66f42726d700f45
djng/router.py
djng/router.py
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) self.resolver = urlresolvers.RegexURLResolver(r'^/', self) def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) # for 1.0 compatibility we pass in None for urlconf_name and then # modify the _urlconf_module to make self hack as if its the module. self.resolver = urlresolvers.RegexURLResolver(r'^/', None) self.resolver._urlconf_module = self def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
Add back 1.0.X compatibility for Router URL resolution.
Add back 1.0.X compatibility for Router URL resolution. Signed-off-by: Simon Willison <088e16a1019277b15d58faf0541e11910eb756f6@simonwillison.net>
Python
bsd-2-clause
simonw/djng
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) + # for 1.0 compatibility we pass in None for urlconf_name and then + # modify the _urlconf_module to make self hack as if its the module. - self.resolver = urlresolvers.RegexURLResolver(r'^/', self) + self.resolver = urlresolvers.RegexURLResolver(r'^/', None) + self.resolver._urlconf_module = self def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
Add back 1.0.X compatibility for Router URL resolution.
## Code Before: from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) self.resolver = urlresolvers.RegexURLResolver(r'^/', self) def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request) ## Instruction: Add back 1.0.X compatibility for Router URL resolution. ## Code After: from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) # for 1.0 compatibility we pass in None for urlconf_name and then # modify the _urlconf_module to make self hack as if its the module. self.resolver = urlresolvers.RegexURLResolver(r'^/', None) self.resolver._urlconf_module = self def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
from django.conf.urls.defaults import patterns from django.core import urlresolvers class Router(object): """ Convenient wrapper around Django's urlresolvers, allowing them to be used from normal application code. from django.http import HttpResponse from django_openid.request_factory import RequestFactory from django.conf.urls.defaults import url router = Router( url('^foo/$', lambda r: HttpResponse('foo'), name='foo'), url('^bar/$', lambda r: HttpResponse('bar'), name='bar') ) rf = RequestFactory() print router(rf.get('/bar/')) """ def __init__(self, *urlpairs): self.urlpatterns = patterns('', *urlpairs) + # for 1.0 compatibility we pass in None for urlconf_name and then + # modify the _urlconf_module to make self hack as if its the module. - self.resolver = urlresolvers.RegexURLResolver(r'^/', self) ? ^ -- + self.resolver = urlresolvers.RegexURLResolver(r'^/', None) ? ^^^ + self.resolver._urlconf_module = self def handle(self, request): path = request.path_info callback, callback_args, callback_kwargs = self.resolver.resolve(path) return callback(request, *callback_args, **callback_kwargs) def __call__(self, request): return self.handle(request)
88fcd9e1ae2a8fe21023816304023526eb7b7e35
fb_import.py
fb_import.py
import MySQLdb # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" data = open(filename, 'r'); guests = []; db_host = "" # Add your host db_user = "" # Add your user db_password = "" # Add your password db_name = "" # Add your database name db_table = "" # Add your table name for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) db = MySQLdb.connect(db_host, db_user, db_password, db_name) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close()
import MySQLdb import json # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" data = open(filename, 'r') guests = [] # Config Setup config_file = open('config.json', 'r') config = json.load(config_file) for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) db = MySQLdb.connect(config['db_host'], config['db_user'], config['db_password'], config['db_name']) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close()
Use config file in import script
Use config file in import script
Python
mit
copperwall/Attendance-Checker,copperwall/Attendance-Checker,copperwall/Attendance-Checker
import MySQLdb + import json # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" - data = open(filename, 'r'); + data = open(filename, 'r') - guests = []; + guests = [] + # Config Setup + config_file = open('config.json', 'r') + config = json.load(config_file) - db_host = "" # Add your host - db_user = "" # Add your user - db_password = "" # Add your password - db_name = "" # Add your database name - db_table = "" # Add your table name for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) - db = MySQLdb.connect(db_host, db_user, db_password, db_name) + db = MySQLdb.connect(config['db_host'], config['db_user'], config['db_password'], + config['db_name']) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close()
Use config file in import script
## Code Before: import MySQLdb # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" data = open(filename, 'r'); guests = []; db_host = "" # Add your host db_user = "" # Add your user db_password = "" # Add your password db_name = "" # Add your database name db_table = "" # Add your table name for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) db = MySQLdb.connect(db_host, db_user, db_password, db_name) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close() ## Instruction: Use config file in import script ## Code After: import MySQLdb import json # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" data = open(filename, 'r') guests = [] # Config Setup config_file = open('config.json', 'r') config = json.load(config_file) for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) db = MySQLdb.connect(config['db_host'], config['db_user'], config['db_password'], config['db_name']) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close()
import MySQLdb + import json # Download Guest List.csv from Facebook event page and copy it to a file named # 'list.csv'. Remove the first line (column title) and the '"'s around each # name (they cause trouble with MySQL) filename = "list.csv" - data = open(filename, 'r'); ? - + data = open(filename, 'r') - guests = []; ? - + guests = [] + # Config Setup + config_file = open('config.json', 'r') + config = json.load(config_file) - db_host = "" # Add your host - db_user = "" # Add your user - db_password = "" # Add your password - db_name = "" # Add your database name - db_table = "" # Add your table name for line in data: person = line.split(',') guests.append([person[0].strip(), person[1].strip()]) print("Number of guests {}\n".format(str(len(guests)))) - db = MySQLdb.connect(db_host, db_user, db_password, db_name) + db = MySQLdb.connect(config['db_host'], config['db_user'], config['db_password'], + config['db_name']) cursor = db.cursor() for person, status in guests: print("Adding " + person + " status: " + status) cursor.execute("INSERT INTO {} (name, status)\ VALUES (\"{}\", \"{}\")".format(db_table, person, status)) # Clean up cursor.close() db.commit() db.close()
f19b66d42f67a6a45bec6fdaffe6c73366788b48
rules/RoleRelativePath.py
rules/RoleRelativePath.py
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False if "../copys" in play['copy']['src']: return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return []
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False if 'src' in play['copy']: if "../copys" in play['copy']['src']: return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return []
Add check for src field
Add check for src field Src field can be absent in copy task, and content field can be used instead, so we should check if src is present to avoid Keyerror exception.
Python
mit
tsukinowasha/ansible-lint-rules
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False + if 'src' in play['copy']: - if "../copys" in play['copy']['src']: + if "../copys" in play['copy']['src']: - return ({'sudo': play['copy']}, + return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return []
Add check for src field
## Code Before: from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False if "../copys" in play['copy']['src']: return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return [] ## Instruction: Add check for src field ## Code After: from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False if 'src' in play['copy']: if "../copys" in play['copy']['src']: return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return []
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False + if 'src' in play['copy']: - if "../copys" in play['copy']['src']: + if "../copys" in play['copy']['src']: ? ++++ - return ({'sudo': play['copy']}, + return ({'sudo': play['copy']}, ? ++++ self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return []
c9cc5585e030951a09687c6a61a489ec51f83446
cr2/plotter/__init__.py
cr2/plotter/__init__.py
"""Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot
"""Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot import AttrConf def register_forwarding_arg(arg_name): """Allows the user to register args to be forwarded to matplotlib """ if arg_name not in AttrConf.ARGS_TO_FORWARD: AttrConf.ARGS_TO_FORWARD.append(arg_name) def unregister_forwarding_arg(arg_name): """Unregisters arg_name from being passed to plotter matplotlib calls """ try: AttrConf.ARGS_TO_FORWARD.remove(arg_name) except ValueError: pass
Enable user specified arg forwarding to matplotlib
plotter: Enable user specified arg forwarding to matplotlib This change allows the user to register args for forwarding to matplotlib and also unregister the same. Change-Id: If53dab43dd4a2f530b3d1faf35582206ac925740 Signed-off-by: Kapileshwar Singh <d373e2b6407ea84be359ce4a11e8631121819e79@arm.com>
Python
apache-2.0
JaviMerino/trappy,joelagnel/trappy,bjackman/trappy,derkling/trappy,ARM-software/trappy,sinkap/trappy,JaviMerino/trappy,joelagnel/trappy,ARM-software/trappy,derkling/trappy,bjackman/trappy,sinkap/trappy,ARM-software/trappy,ARM-software/trappy,bjackman/trappy,sinkap/trappy,joelagnel/trappy,sinkap/trappy,JaviMerino/trappy,bjackman/trappy,derkling/trappy,joelagnel/trappy
"""Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot + import AttrConf + + def register_forwarding_arg(arg_name): + """Allows the user to register args to + be forwarded to matplotlib + """ + if arg_name not in AttrConf.ARGS_TO_FORWARD: + AttrConf.ARGS_TO_FORWARD.append(arg_name) + + def unregister_forwarding_arg(arg_name): + """Unregisters arg_name from being passed to + plotter matplotlib calls + """ + try: + AttrConf.ARGS_TO_FORWARD.remove(arg_name) + except ValueError: + pass +
Enable user specified arg forwarding to matplotlib
## Code Before: """Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot ## Instruction: Enable user specified arg forwarding to matplotlib ## Code After: """Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot import AttrConf def register_forwarding_arg(arg_name): """Allows the user to register args to be forwarded to matplotlib """ if arg_name not in AttrConf.ARGS_TO_FORWARD: AttrConf.ARGS_TO_FORWARD.append(arg_name) def unregister_forwarding_arg(arg_name): """Unregisters arg_name from being passed to plotter matplotlib calls """ try: AttrConf.ARGS_TO_FORWARD.remove(arg_name) except ValueError: pass
"""Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot + import AttrConf + + + def register_forwarding_arg(arg_name): + """Allows the user to register args to + be forwarded to matplotlib + """ + if arg_name not in AttrConf.ARGS_TO_FORWARD: + AttrConf.ARGS_TO_FORWARD.append(arg_name) + + def unregister_forwarding_arg(arg_name): + """Unregisters arg_name from being passed to + plotter matplotlib calls + """ + try: + AttrConf.ARGS_TO_FORWARD.remove(arg_name) + except ValueError: + pass
21651120925cc3e51aeada4eac4dbfaa5bf98fae
src/header_filter/__init__.py
src/header_filter/__init__.py
from header_filter.matchers import Header # noqa: F401 from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401
from header_filter.matchers import Header, HeaderRegexp # noqa: F401 from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401
Allow HeaderRegexp to be imported directly from header_filter package.
Allow HeaderRegexp to be imported directly from header_filter package.
Python
mit
sanjioh/django-header-filter
- from header_filter.matchers import Header # noqa: F401 + from header_filter.matchers import Header, HeaderRegexp # noqa: F401 from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401
Allow HeaderRegexp to be imported directly from header_filter package.
## Code Before: from header_filter.matchers import Header # noqa: F401 from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401 ## Instruction: Allow HeaderRegexp to be imported directly from header_filter package. ## Code After: from header_filter.matchers import Header, HeaderRegexp # noqa: F401 from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401
- from header_filter.matchers import Header # noqa: F401 + from header_filter.matchers import Header, HeaderRegexp # noqa: F401 ? ++++++++++++++ from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401
8e3beda427e2edc2bc7b8f7f96f8ef1c7dd571c7
downloads/urls.py
downloads/urls.py
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(_(r'solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='solutions/', model_class=UserSolution), name='download_solution'), )
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(_(r'solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='solutions/', model_class=UserSolution), name='download_solution'), url(_(r'corrected_solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='corrected_solutions/', model_class=UserSolution), name='download_corrected_solution'), )
Add view for displaying corrected solutions
downloads: Add view for displaying corrected solutions
Python
mit
matus-stehlik/roots,tbabej/roots,tbabej/roots,matus-stehlik/roots,rtrembecky/roots,matus-stehlik/roots,rtrembecky/roots,tbabej/roots,rtrembecky/roots
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(_(r'solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='solutions/', model_class=UserSolution), name='download_solution'), + url(_(r'corrected_solutions/(?P<path>.*)$'), download_protected_file, + dict(path_prefix='corrected_solutions/', model_class=UserSolution), + name='download_corrected_solution'), )
Add view for displaying corrected solutions
## Code Before: from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(_(r'solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='solutions/', model_class=UserSolution), name='download_solution'), ) ## Instruction: Add view for displaying corrected solutions ## Code After: from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(_(r'solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='solutions/', model_class=UserSolution), name='download_solution'), url(_(r'corrected_solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='corrected_solutions/', model_class=UserSolution), name='download_corrected_solution'), )
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(_(r'solutions/(?P<path>.*)$'), download_protected_file, dict(path_prefix='solutions/', model_class=UserSolution), name='download_solution'), + url(_(r'corrected_solutions/(?P<path>.*)$'), download_protected_file, + dict(path_prefix='corrected_solutions/', model_class=UserSolution), + name='download_corrected_solution'), )
e5a397033c5720cd7d0ab321c05a8f1d12f4dc99
tm/tmux_wrapper.py
tm/tmux_wrapper.py
import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): p = subprocess.Popen("tmux kill-session -t {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): p = subprocess.Popen("tmux ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): p = subprocess.Popen("tmux new -s {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "duplicate session" in err: raise SessionExists(session) def attach(session): p = subprocess.Popen("tmux attach-session -t {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): create(session) except SessionExists: attach(session)
import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): out, err = command("kill-session -t {}".format(session)) if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): out, err = command("ls") if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): out, err = command("new -s {}".format(session)) if "duplicate session" in err: raise SessionExists(session) def attach(session): out, err = command("attach-session -t {}".format(session)) if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): try: create(session) except SessionExists: attach(session)
Use raw command method to run all commands in wrapper
Use raw command method to run all commands in wrapper
Python
mit
ethanal/tm
import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): + out, err = command("kill-session -t {}".format(session)) - p = subprocess.Popen("tmux kill-session -t {}".format(session), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): - p = subprocess.Popen("tmux ls", - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() + out, err = command("ls") if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): + out, err = command("new -s {}".format(session)) - p = subprocess.Popen("tmux new -s {}".format(session), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() if "duplicate session" in err: raise SessionExists(session) def attach(session): + out, err = command("attach-session -t {}".format(session)) - p = subprocess.Popen("tmux attach-session -t {}".format(session), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): - + try: create(session) except SessionExists: attach(session)
Use raw command method to run all commands in wrapper
## Code Before: import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): p = subprocess.Popen("tmux kill-session -t {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): p = subprocess.Popen("tmux ls", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): p = subprocess.Popen("tmux new -s {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "duplicate session" in err: raise SessionExists(session) def attach(session): p = subprocess.Popen("tmux attach-session -t {}".format(session), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): create(session) except SessionExists: attach(session) ## Instruction: Use raw command method to run all commands in wrapper ## Code After: import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): out, err = command("kill-session -t {}".format(session)) if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): out, err = command("ls") if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): out, err = command("new -s {}".format(session)) if "duplicate session" in err: raise SessionExists(session) def attach(session): out, err = command("attach-session -t {}".format(session)) if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): try: create(session) except SessionExists: attach(session)
import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist." pass def command(command): p = subprocess.Popen("tmux " + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return p.communicate() def kill(session): + out, err = command("kill-session -t {}".format(session)) - p = subprocess.Popen("tmux kill-session -t {}".format(session), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() if "session not found" in err: raise SessionDoesNotExist(session) if "failed to connect to server" in err: raise ServerConnectionError() def list(): - p = subprocess.Popen("tmux ls", - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() ? -- ^ ^^^^^ + out, err = command("ls") ? ^ ^ ++++ if "failed to connect to server" in err: raise ServerConnectionError() return out def create(session): + out, err = command("new -s {}".format(session)) - p = subprocess.Popen("tmux new -s {}".format(session), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() if "duplicate session" in err: raise SessionExists(session) def attach(session): + out, err = command("attach-session -t {}".format(session)) - p = subprocess.Popen("tmux attach-session -t {}".format(session), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=True) - out, err = p.communicate() if "no sessions" in err: raise SessionDoesNotExist(session) def create_or_attach(session): - + try: create(session) except SessionExists: attach(session)
e79c90db5dcda56ff9b2b154659984db9c6f7663
src/main.py
src/main.py
import pygame from scenes import director from scenes import intro_scene pygame.init() def main(): game_director = director.Director() scene = intro_scene.IntroScene(game_director) game_director.change_scene(scene) game_director.loop() if __name__ == '__main__': pygame.init() main()
import pygame from scenes import director from scenes import intro_scene from game_logic import settings pygame.init() def main(): initial_settings = settings.Settings( trials=1000, player='O', oponent='Computer') game_director = director.Director() scene = intro_scene.IntroScene(game_director) game_director.change_scene(scene, initial_settings) game_director.loop() if __name__ == '__main__': pygame.init() main()
Create initial config when starting game
Create initial config when starting game
Python
mit
juangallostra/TicTacToe
import pygame from scenes import director from scenes import intro_scene + from game_logic import settings pygame.init() def main(): + initial_settings = settings.Settings( + trials=1000, player='O', oponent='Computer') game_director = director.Director() scene = intro_scene.IntroScene(game_director) - game_director.change_scene(scene) + game_director.change_scene(scene, initial_settings) game_director.loop() if __name__ == '__main__': pygame.init() main()
Create initial config when starting game
## Code Before: import pygame from scenes import director from scenes import intro_scene pygame.init() def main(): game_director = director.Director() scene = intro_scene.IntroScene(game_director) game_director.change_scene(scene) game_director.loop() if __name__ == '__main__': pygame.init() main() ## Instruction: Create initial config when starting game ## Code After: import pygame from scenes import director from scenes import intro_scene from game_logic import settings pygame.init() def main(): initial_settings = settings.Settings( trials=1000, player='O', oponent='Computer') game_director = director.Director() scene = intro_scene.IntroScene(game_director) game_director.change_scene(scene, initial_settings) game_director.loop() if __name__ == '__main__': pygame.init() main()
import pygame from scenes import director from scenes import intro_scene + from game_logic import settings pygame.init() def main(): + initial_settings = settings.Settings( + trials=1000, player='O', oponent='Computer') game_director = director.Director() scene = intro_scene.IntroScene(game_director) - game_director.change_scene(scene) + game_director.change_scene(scene, initial_settings) ? ++++++++++++++++++ game_director.loop() if __name__ == '__main__': pygame.init() main()
b44345efada2a89423c89ec88a24f1dbe97ef562
viewer.py
viewer.py
if __name__ == '__main__': import wx from controller import ViewerController app = wx.App(0) ViewerController() app.MainLoop()
if __name__ == '__main__': import sys try: import wx except ImportError: print("""\ You need to install WXPython to use the viewer http://wxpython.org/download.php """) sys.exit() from controller import ViewerController app = wx.App(0) ViewerController() app.MainLoop()
Add simple test for whether WX is installed. Display download link if not.
Add simple test for whether WX is installed. Display download link if not.
Python
agpl-3.0
nccgroup/lapith
if __name__ == '__main__': + import sys + try: - import wx + import wx + except ImportError: + print("""\ + You need to install WXPython to use the viewer + + http://wxpython.org/download.php + """) + sys.exit() from controller import ViewerController app = wx.App(0) ViewerController() app.MainLoop()
Add simple test for whether WX is installed. Display download link if not.
## Code Before: if __name__ == '__main__': import wx from controller import ViewerController app = wx.App(0) ViewerController() app.MainLoop() ## Instruction: Add simple test for whether WX is installed. Display download link if not. ## Code After: if __name__ == '__main__': import sys try: import wx except ImportError: print("""\ You need to install WXPython to use the viewer http://wxpython.org/download.php """) sys.exit() from controller import ViewerController app = wx.App(0) ViewerController() app.MainLoop()
if __name__ == '__main__': + import sys + try: - import wx + import wx ? ++++ + except ImportError: + print("""\ + You need to install WXPython to use the viewer + + http://wxpython.org/download.php + """) + sys.exit() from controller import ViewerController app = wx.App(0) ViewerController() app.MainLoop()
4f20f940102d353b6200f44ae5aaa51a85b89aba
pxe_manager/tests/test_pxemanager.py
pxe_manager/tests/test_pxemanager.py
from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): client = ResourceManagerClient() cobbler_url = "http://cobbler.example.com/cobbler_api" cobbler_user = "user" cobbler_password = "password" response_body = '''<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>Some Value</string></value> </param> </params> </methodResponse> ''' distro_map = {'esxi51': 'qa-vmwareesxi51u0-x86_64', 'esxi50': 'qa-vmwareesxi50u1-x86_64', 'centos': 'qa-centos6-x86_64-striped-drives', 'rhel': 'qa-rhel6u5-x86_64-striped-drives'} httpretty.register_uri(httpretty.POST, cobbler_url, body=response_body) pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, client) for key, value in distro_map.iteritems(): assert pxe_manager.distro[key] == value
from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): host_client = ResourceManagerClient() pub_ip_client = ResourceManagerClient(resource_type='public-addresses') priv_ip_client = ResourceManagerClient(resource_type='private-addresses') cobbler_url = "http://cobbler.example.com/cobbler_api" cobbler_user = "user" cobbler_password = "password" response_body = '''<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>Some Value</string></value> </param> </params> </methodResponse> ''' distro_map = {'esxi51': 'qa-vmwareesxi51u0-x86_64', 'esxi50': 'qa-vmwareesxi50u1-x86_64', 'centos': 'qa-centos6-x86_64-striped-drives', 'rhel': 'qa-rhel6u5-x86_64-striped-drives'} httpretty.register_uri(httpretty.POST, cobbler_url, body=response_body) pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, host_client, pub_ip_client, priv_ip_client) for key, value in distro_map.iteritems(): assert pxe_manager.distro[key] == value
Update unit test with new pxemanager signature
Update unit test with new pxemanager signature
Python
apache-2.0
tbeckham/DeploymentManager,tbeckham/DeploymentManager,ccassler/DeploymentManager,tbeckham/DeploymentManager,ccassler/DeploymentManager,ccassler/DeploymentManager
from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): - client = ResourceManagerClient() + host_client = ResourceManagerClient() + pub_ip_client = ResourceManagerClient(resource_type='public-addresses') + priv_ip_client = ResourceManagerClient(resource_type='private-addresses') cobbler_url = "http://cobbler.example.com/cobbler_api" cobbler_user = "user" cobbler_password = "password" response_body = '''<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>Some Value</string></value> </param> </params> </methodResponse> ''' distro_map = {'esxi51': 'qa-vmwareesxi51u0-x86_64', 'esxi50': 'qa-vmwareesxi50u1-x86_64', 'centos': 'qa-centos6-x86_64-striped-drives', 'rhel': 'qa-rhel6u5-x86_64-striped-drives'} httpretty.register_uri(httpretty.POST, cobbler_url, body=response_body) - pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, client) + pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, host_client, pub_ip_client, priv_ip_client) for key, value in distro_map.iteritems(): assert pxe_manager.distro[key] == value
Update unit test with new pxemanager signature
## Code Before: from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): client = ResourceManagerClient() cobbler_url = "http://cobbler.example.com/cobbler_api" cobbler_user = "user" cobbler_password = "password" response_body = '''<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>Some Value</string></value> </param> </params> </methodResponse> ''' distro_map = {'esxi51': 'qa-vmwareesxi51u0-x86_64', 'esxi50': 'qa-vmwareesxi50u1-x86_64', 'centos': 'qa-centos6-x86_64-striped-drives', 'rhel': 'qa-rhel6u5-x86_64-striped-drives'} httpretty.register_uri(httpretty.POST, cobbler_url, body=response_body) pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, client) for key, value in distro_map.iteritems(): assert pxe_manager.distro[key] == value ## Instruction: Update unit test with new pxemanager signature ## Code After: from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): host_client = ResourceManagerClient() pub_ip_client = ResourceManagerClient(resource_type='public-addresses') priv_ip_client = ResourceManagerClient(resource_type='private-addresses') cobbler_url = "http://cobbler.example.com/cobbler_api" cobbler_user = "user" cobbler_password = "password" response_body = '''<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>Some Value</string></value> </param> </params> </methodResponse> ''' distro_map = {'esxi51': 'qa-vmwareesxi51u0-x86_64', 'esxi50': 'qa-vmwareesxi50u1-x86_64', 'centos': 'qa-centos6-x86_64-striped-drives', 'rhel': 'qa-rhel6u5-x86_64-striped-drives'} httpretty.register_uri(httpretty.POST, cobbler_url, body=response_body) pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, host_client, pub_ip_client, priv_ip_client) for key, value in distro_map.iteritems(): assert pxe_manager.distro[key] == value
from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): - client = ResourceManagerClient() + host_client = ResourceManagerClient() ? +++++ + pub_ip_client = ResourceManagerClient(resource_type='public-addresses') + priv_ip_client = ResourceManagerClient(resource_type='private-addresses') cobbler_url = "http://cobbler.example.com/cobbler_api" cobbler_user = "user" cobbler_password = "password" response_body = '''<?xml version="1.0"?> <methodResponse> <params> <param> <value><string>Some Value</string></value> </param> </params> </methodResponse> ''' distro_map = {'esxi51': 'qa-vmwareesxi51u0-x86_64', 'esxi50': 'qa-vmwareesxi50u1-x86_64', 'centos': 'qa-centos6-x86_64-striped-drives', 'rhel': 'qa-rhel6u5-x86_64-striped-drives'} httpretty.register_uri(httpretty.POST, cobbler_url, body=response_body) - pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, client) + pxe_manager = PxeManager(cobbler_url, cobbler_user, cobbler_password, host_client, pub_ip_client, priv_ip_client) ? ++++++++++++++++++++++++++++++++++++ for key, value in distro_map.iteritems(): assert pxe_manager.distro[key] == value
019f259ae42a95802dce644511399332506ad1cc
tracing/tracing/metrics/metric_runner.py
tracing/tracing/metrics/metric_runner.py
import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): th = file_handle.URLFileHandle(filename, 'file://' + filename) result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result
import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): url = 'file://' + os.path.abspath(filename) th = file_handle.URLFileHandle(filename, url) result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result
Support relative paths in bin/run_metric
Support relative paths in bin/run_metric As a result of this patch, it will be possible to run: bin/run_metric MemoryMetric test_data/memory_dumps.json ^^^^^^^^^^^^^^^^^^^^^^^^^^^ instead of: bin/run_metric MemoryMetric $PWD/test_data/memory_dumps.json ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Review URL: https://codereview.chromium.org/1836283008
Python
bsd-3-clause
catapult-project/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult,benschmaus/catapult
import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): + url = 'file://' + os.path.abspath(filename) - th = file_handle.URLFileHandle(filename, 'file://' + filename) + th = file_handle.URLFileHandle(filename, url) result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result
Support relative paths in bin/run_metric
## Code Before: import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): th = file_handle.URLFileHandle(filename, 'file://' + filename) result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result ## Instruction: Support relative paths in bin/run_metric ## Code After: import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): url = 'file://' + os.path.abspath(filename) th = file_handle.URLFileHandle(filename, url) result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result
import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): + url = 'file://' + os.path.abspath(filename) - th = file_handle.URLFileHandle(filename, 'file://' + filename) ? ^^^ ---------------- + th = file_handle.URLFileHandle(filename, url) ? ^^ result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result
4c4fd3021931e2203088a2ec578eb479a622e2c5
blogsite/models.py
blogsite/models.py
"""Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % (self.id, self.title)
"""Collection of Models used in blogsite.""" from . import db from datetime import datetime class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column pub_date : SQLAlchemy.Column Date and Time of Post creation category_id : SQLAlchemy.Column Foreign Key ID to Category category : SQLAlchemy.relationship Category object that relates to this Post """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) pub_date = db.Column(db.DateTime) category_id = db.Column(db.Integer, db.ForeignKey('category.id')) category = db.relationship('Category', backref=db.backref('posts', lazy='dynamic')) def __init__(self, title, body, category, pub_date=None): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents category : Category Category object blog post is related to pub_date : DateTime Optional """ self.title = title self.body = body self.category = category if pub_date is None: pub_date = datetime.utcnow() self.pub_date = pub_date def __repr__(self): """Representation.""" return '<Post %r:%r>' % (self.id, self.title) class Category(db.Model): """Model to represent a overall category. Attributes ---------- id : SQLAlchemy.Column name : SQLAlchemy.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(128)) def __init__(self, name): """Constructor for Category. Parameters ---------- name : String Name of new category """ self.name = name def __repr__(self): """Representation.""" return '<Category %r>' % self.name
Add Category model and expanding Post model.
Add Category model and expanding Post model. Post model now contains a publish date and a foreign key reference to the Category model.
Python
mit
paulaylingdev/blogsite,paulaylingdev/blogsite
"""Collection of Models used in blogsite.""" from . import db + from datetime import datetime class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column + pub_date : SQLAlchemy.Column + Date and Time of Post creation + category_id : SQLAlchemy.Column + Foreign Key ID to Category + category : SQLAlchemy.relationship + Category object that relates to this Post """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) + pub_date = db.Column(db.DateTime) + category_id = db.Column(db.Integer, db.ForeignKey('category.id')) + category = db.relationship('Category', + backref=db.backref('posts', lazy='dynamic')) - def __init__(self, title, body): + def __init__(self, title, body, category, pub_date=None): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents + category : Category + Category object blog post is related to + pub_date : DateTime + Optional """ self.title = title self.body = body + self.category = category + if pub_date is None: + pub_date = datetime.utcnow() + self.pub_date = pub_date def __repr__(self): """Representation.""" return '<Post %r:%r>' % (self.id, self.title) + + class Category(db.Model): + """Model to represent a overall category. + + Attributes + ---------- + id : SQLAlchemy.Column + name : SQLAlchemy.Column + """ + + # Columns + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String(128)) + + def __init__(self, name): + """Constructor for Category. + + Parameters + ---------- + name : String + Name of new category + """ + self.name = name + + def __repr__(self): + """Representation.""" + return '<Category %r>' % self.name +
Add Category model and expanding Post model.
## Code Before: """Collection of Models used in blogsite.""" from . import db class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) def __init__(self, title, body): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents """ self.title = title self.body = body def __repr__(self): """Representation.""" return '<Post %r:%r>' % (self.id, self.title) ## Instruction: Add Category model and expanding Post model. ## Code After: """Collection of Models used in blogsite.""" from . import db from datetime import datetime class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column pub_date : SQLAlchemy.Column Date and Time of Post creation category_id : SQLAlchemy.Column Foreign Key ID to Category category : SQLAlchemy.relationship Category object that relates to this Post """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) pub_date = db.Column(db.DateTime) category_id = db.Column(db.Integer, db.ForeignKey('category.id')) category = db.relationship('Category', backref=db.backref('posts', lazy='dynamic')) def __init__(self, title, body, category, pub_date=None): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents category : Category Category object blog post is related to pub_date : DateTime Optional """ self.title = title self.body = body self.category = category if pub_date is None: pub_date = datetime.utcnow() self.pub_date = pub_date def __repr__(self): """Representation.""" return '<Post %r:%r>' % (self.id, self.title) class Category(db.Model): """Model to represent a overall category. Attributes ---------- id : SQLAlchemy.Column name : SQLAlchemy.Column """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(128)) def __init__(self, name): """Constructor for Category. Parameters ---------- name : String Name of new category """ self.name = name def __repr__(self): """Representation.""" return '<Category %r>' % self.name
"""Collection of Models used in blogsite.""" from . import db + from datetime import datetime class Post(db.Model): """Model representing a blog post. Attributes ---------- id : SQLAlchemy.Column Autogenerated primary key title : SQLAlchemy.Column body : SQLAlchemy.Column + pub_date : SQLAlchemy.Column + Date and Time of Post creation + category_id : SQLAlchemy.Column + Foreign Key ID to Category + category : SQLAlchemy.relationship + Category object that relates to this Post """ # Columns id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) body = db.Column(db.String(4096)) + pub_date = db.Column(db.DateTime) + category_id = db.Column(db.Integer, db.ForeignKey('category.id')) + category = db.relationship('Category', + backref=db.backref('posts', lazy='dynamic')) - def __init__(self, title, body): + def __init__(self, title, body, category, pub_date=None): """Constructor for Post. Parameters ---------- title : String Title/Summary of post body : String Contents + category : Category + Category object blog post is related to + pub_date : DateTime + Optional """ self.title = title self.body = body + self.category = category + if pub_date is None: + pub_date = datetime.utcnow() + self.pub_date = pub_date def __repr__(self): """Representation.""" return '<Post %r:%r>' % (self.id, self.title) + + + class Category(db.Model): + """Model to represent a overall category. + + Attributes + ---------- + id : SQLAlchemy.Column + name : SQLAlchemy.Column + """ + + # Columns + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String(128)) + + def __init__(self, name): + """Constructor for Category. + + Parameters + ---------- + name : String + Name of new category + """ + self.name = name + + def __repr__(self): + """Representation.""" + return '<Category %r>' % self.name
f5e8bfaf5c4f7a2131fbe0ffd0f8d14a316b907e
camoco/Exceptions.py
camoco/Exceptions.py
class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) )
class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) class CamocoInteractive(CamocoError): def __init__(self,expr=None,message='',*args): self.expr = expr self.message = 'Camoco interactive ipython session.'
Add exception for cli command line to run interactively.
Add exception for cli command line to run interactively.
Python
mit
schae234/Camoco,schae234/Camoco
class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) + class CamocoInteractive(CamocoError): + def __init__(self,expr=None,message='',*args): + self.expr = expr + self.message = 'Camoco interactive ipython session.' +
Add exception for cli command line to run interactively.
## Code Before: class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) ## Instruction: Add exception for cli command line to run interactively. ## Code After: class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) class CamocoInteractive(CamocoError): def __init__(self,expr=None,message='',*args): self.expr = expr self.message = 'Camoco interactive ipython session.'
class CamocoError(Exception): pass class CamocoExistsError(CamocoError): ''' You tried to create a camoco object which already exists under the same name,type combination. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'You are trying to create a Camoco based object' 'That already exists' + message.format(*args) ) class CamocoGeneNameError(CamocoError): ''' Gene names must be beautiful snowflakes. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = 'Gene names must be unique:' + message.format(args) class CamocoAccessionNameError(CamocoError): ''' Accession names must be Unique. ''' def __init__(self,expr,message='',*args): self.expr = expr self.message = ( 'Accession names must be unique:' + message.format(args) ) class CamocoZeroWindowError(CamocoError): def __init__(self,expr,message,*args): self.expr = expr self.message = ( 'Operation requiring window, but window is 0:' + \ message.format(args) ) + + class CamocoInteractive(CamocoError): + def __init__(self,expr=None,message='',*args): + self.expr = expr + self.message = 'Camoco interactive ipython session.'
95ccab69cfff30c24932c4cd156983a29639435d
nginxauthdaemon/crowdauth.py
nginxauthdaemon/crowdauth.py
import crowd from auth import Authenticator class CrowdAuthenticator(Authenticator): """Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD""" def __init__(self, config): super(CrowdAuthenticator, self).__init__(config) app_url = config['CROWD_URL'] app_user = config['CROWD_APP_NAME'] app_pass = config['CROWD_APP_PASSWORD'] self._cs = crowd.CrowdServer(app_url, app_user, app_pass) def authenticate(self, username, password): result = self._cs.auth_user(username, password) return result.get('name') == username
import crowd from auth import Authenticator class CrowdAuthenticator(Authenticator): """Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD""" def __init__(self, config): super(CrowdAuthenticator, self).__init__(config) app_url = config['CROWD_URL'] app_user = config['CROWD_APP_NAME'] app_pass = config['CROWD_APP_PASSWORD'] self._cs = crowd.CrowdServer(app_url, app_user, app_pass) def authenticate(self, username, password): result = self._cs.auth_user(username, password) if result == None: # auth failed return False # auth succeeded return result.get('name') == username
Fix 500 error when Crowd auth is failed
Fix 500 error when Crowd auth is failed
Python
mit
akurdyukov/nginxauthdaemon,akurdyukov/nginxauthdaemon
import crowd from auth import Authenticator class CrowdAuthenticator(Authenticator): """Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD""" def __init__(self, config): super(CrowdAuthenticator, self).__init__(config) app_url = config['CROWD_URL'] app_user = config['CROWD_APP_NAME'] app_pass = config['CROWD_APP_PASSWORD'] self._cs = crowd.CrowdServer(app_url, app_user, app_pass) def authenticate(self, username, password): result = self._cs.auth_user(username, password) + if result == None: + # auth failed + return False + # auth succeeded return result.get('name') == username
Fix 500 error when Crowd auth is failed
## Code Before: import crowd from auth import Authenticator class CrowdAuthenticator(Authenticator): """Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD""" def __init__(self, config): super(CrowdAuthenticator, self).__init__(config) app_url = config['CROWD_URL'] app_user = config['CROWD_APP_NAME'] app_pass = config['CROWD_APP_PASSWORD'] self._cs = crowd.CrowdServer(app_url, app_user, app_pass) def authenticate(self, username, password): result = self._cs.auth_user(username, password) return result.get('name') == username ## Instruction: Fix 500 error when Crowd auth is failed ## Code After: import crowd from auth import Authenticator class CrowdAuthenticator(Authenticator): """Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD""" def __init__(self, config): super(CrowdAuthenticator, self).__init__(config) app_url = config['CROWD_URL'] app_user = config['CROWD_APP_NAME'] app_pass = config['CROWD_APP_PASSWORD'] self._cs = crowd.CrowdServer(app_url, app_user, app_pass) def authenticate(self, username, password): result = self._cs.auth_user(username, password) if result == None: # auth failed return False # auth succeeded return result.get('name') == username
import crowd from auth import Authenticator class CrowdAuthenticator(Authenticator): """Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD""" def __init__(self, config): super(CrowdAuthenticator, self).__init__(config) app_url = config['CROWD_URL'] app_user = config['CROWD_APP_NAME'] app_pass = config['CROWD_APP_PASSWORD'] self._cs = crowd.CrowdServer(app_url, app_user, app_pass) def authenticate(self, username, password): result = self._cs.auth_user(username, password) + if result == None: + # auth failed + return False + # auth succeeded return result.get('name') == username
55745f668715c294cd5662712b2d1ccb7726f125
setup.py
setup.py
from distutils.core import setup import multi_schema setup( name = "django-multi-schema", version = multi_schema.__version__, description = "Postgres schema support in django.", url = "http://hg.schinckel.net/django-multi-schema", author = "Matthew Schinckel", author_email = "matt@schinckel.net", packages = [ "multi_schema", ], classifiers = [ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Framework :: Django', ], )
from distutils.core import setup import multi_schema setup( name = "django-multi-schema", version = multi_schema.__version__, description = "Postgres schema support in django.", url = "http://hg.schinckel.net/django-multi-schema", author = "Matthew Schinckel", author_email = "matt@schinckel.net", packages = [ "multi_schema", ], install_requires = [ 'south==0.7.4', ], classifiers = [ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Framework :: Django', ], )
Add south as a dependency, so we can apply a version. Does not need to be installed in INSTALLED_APPS.
Add south as a dependency, so we can apply a version. Does not need to be installed in INSTALLED_APPS.
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
from distutils.core import setup import multi_schema setup( name = "django-multi-schema", version = multi_schema.__version__, description = "Postgres schema support in django.", url = "http://hg.schinckel.net/django-multi-schema", author = "Matthew Schinckel", author_email = "matt@schinckel.net", packages = [ "multi_schema", ], + install_requires = [ + 'south==0.7.4', + ], classifiers = [ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Framework :: Django', ], )
Add south as a dependency, so we can apply a version. Does not need to be installed in INSTALLED_APPS.
## Code Before: from distutils.core import setup import multi_schema setup( name = "django-multi-schema", version = multi_schema.__version__, description = "Postgres schema support in django.", url = "http://hg.schinckel.net/django-multi-schema", author = "Matthew Schinckel", author_email = "matt@schinckel.net", packages = [ "multi_schema", ], classifiers = [ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Framework :: Django', ], ) ## Instruction: Add south as a dependency, so we can apply a version. Does not need to be installed in INSTALLED_APPS. ## Code After: from distutils.core import setup import multi_schema setup( name = "django-multi-schema", version = multi_schema.__version__, description = "Postgres schema support in django.", url = "http://hg.schinckel.net/django-multi-schema", author = "Matthew Schinckel", author_email = "matt@schinckel.net", packages = [ "multi_schema", ], install_requires = [ 'south==0.7.4', ], classifiers = [ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Framework :: Django', ], )
from distutils.core import setup import multi_schema setup( name = "django-multi-schema", version = multi_schema.__version__, description = "Postgres schema support in django.", url = "http://hg.schinckel.net/django-multi-schema", author = "Matthew Schinckel", author_email = "matt@schinckel.net", packages = [ "multi_schema", ], + install_requires = [ + 'south==0.7.4', + ], classifiers = [ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Framework :: Django', ], )
55c60d059a4f6a6ae6633318420a7c0cd22c2513
product/models.py
product/models.py
from django.db import models from amadaa.models import AmadaaModel from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class ProductCategory(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-category-detail', kwargs={'pk': self.pk}) def __str__(self): return "{}".format(self.name) class ProductType(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-type-list') def __str__(self): return "{}".format(self.name) class UnitOfMeasurement(AmadaaModel): unit = models.CharField(max_length=30, unique=True) def get_absolute_url(self): return reverse('uom-list') def __str__(self): return "%(self.unit)s" class Product(AmadaaModel): name = models.CharField(max_length=100) internal_ref = models.CharField(max_length=100, default='') product_type = models.ForeignKey(ProductType, default=0) category = models.ForeignKey(ProductCategory) description = RichTextField(blank=True, default='') def get_absolute_url(self): return reverse('product-list') def __str__(self): return "%(self.name)s"
from django.db import models from amadaa.models import AmadaaModel from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class ProductCategory(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-category-detail', kwargs={'pk': self.pk}) def __str__(self): return "{}".format(self.name) class ProductType(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-type-list') def __str__(self): return "{}".format(self.name) class UnitOfMeasurement(AmadaaModel): unit = models.CharField(max_length=30, unique=True) def get_absolute_url(self): return reverse('uom-list') def __str__(self): return "%(self.unit)s" class Product(AmadaaModel): name = models.CharField(max_length=100) internal_ref = models.CharField(max_length=100, default='') product_type = models.ForeignKey(ProductType, default=0) category = models.ForeignKey(ProductCategory) description = RichTextField(blank=True, default='') def get_absolute_url(self): return reverse('product-list') def __str__(self): return "{}".format(self.name)
Fix in string representation of product model.
Fix in string representation of product model.
Python
mit
borderitsolutions/amadaa,borderitsolutions/amadaa,borderitsolutions/amadaa
from django.db import models from amadaa.models import AmadaaModel from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class ProductCategory(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-category-detail', kwargs={'pk': self.pk}) def __str__(self): return "{}".format(self.name) class ProductType(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-type-list') def __str__(self): return "{}".format(self.name) class UnitOfMeasurement(AmadaaModel): unit = models.CharField(max_length=30, unique=True) def get_absolute_url(self): return reverse('uom-list') def __str__(self): return "%(self.unit)s" class Product(AmadaaModel): name = models.CharField(max_length=100) internal_ref = models.CharField(max_length=100, default='') product_type = models.ForeignKey(ProductType, default=0) category = models.ForeignKey(ProductCategory) description = RichTextField(blank=True, default='') def get_absolute_url(self): return reverse('product-list') def __str__(self): - return "%(self.name)s" + return "{}".format(self.name)
Fix in string representation of product model.
## Code Before: from django.db import models from amadaa.models import AmadaaModel from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class ProductCategory(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-category-detail', kwargs={'pk': self.pk}) def __str__(self): return "{}".format(self.name) class ProductType(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-type-list') def __str__(self): return "{}".format(self.name) class UnitOfMeasurement(AmadaaModel): unit = models.CharField(max_length=30, unique=True) def get_absolute_url(self): return reverse('uom-list') def __str__(self): return "%(self.unit)s" class Product(AmadaaModel): name = models.CharField(max_length=100) internal_ref = models.CharField(max_length=100, default='') product_type = models.ForeignKey(ProductType, default=0) category = models.ForeignKey(ProductCategory) description = RichTextField(blank=True, default='') def get_absolute_url(self): return reverse('product-list') def __str__(self): return "%(self.name)s" ## Instruction: Fix in string representation of product model. ## Code After: from django.db import models from amadaa.models import AmadaaModel from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class ProductCategory(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-category-detail', kwargs={'pk': self.pk}) def __str__(self): return "{}".format(self.name) class ProductType(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-type-list') def __str__(self): return "{}".format(self.name) class UnitOfMeasurement(AmadaaModel): unit = models.CharField(max_length=30, unique=True) def get_absolute_url(self): return reverse('uom-list') def __str__(self): return "%(self.unit)s" class Product(AmadaaModel): name = models.CharField(max_length=100) internal_ref = models.CharField(max_length=100, default='') product_type = models.ForeignKey(ProductType, default=0) category = models.ForeignKey(ProductCategory) description = RichTextField(blank=True, default='') def get_absolute_url(self): return reverse('product-list') def __str__(self): return "{}".format(self.name)
from django.db import models from amadaa.models import AmadaaModel from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class ProductCategory(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-category-detail', kwargs={'pk': self.pk}) def __str__(self): return "{}".format(self.name) class ProductType(AmadaaModel): name = models.CharField(max_length=100, unique=True) def get_absolute_url(self): return reverse('product-type-list') def __str__(self): return "{}".format(self.name) class UnitOfMeasurement(AmadaaModel): unit = models.CharField(max_length=30, unique=True) def get_absolute_url(self): return reverse('uom-list') def __str__(self): return "%(self.unit)s" class Product(AmadaaModel): name = models.CharField(max_length=100) internal_ref = models.CharField(max_length=100, default='') product_type = models.ForeignKey(ProductType, default=0) category = models.ForeignKey(ProductCategory) description = RichTextField(blank=True, default='') def get_absolute_url(self): return reverse('product-list') def __str__(self): - return "%(self.name)s" ? ^ -- + return "{}".format(self.name) ? ^^^^^^^^^^
28f59d245d4695de5dbcfc0302f34c46234fd116
blackgate/executor_pools.py
blackgate/executor_pools.py
from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} def register_pool(self, group_key, max_size=1): executor = QueueExecutor(pool_key=group_key, max_size=max_size) IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key]
from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} def register_pool(self, group_key, max_size=10, max_workers=10): executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers) IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key]
Set max_workers the same as max_size.
Set max_workers the same as max_size.
Python
mit
soasme/blackgate
from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} - def register_pool(self, group_key, max_size=1): + def register_pool(self, group_key, max_size=10, max_workers=10): - executor = QueueExecutor(pool_key=group_key, max_size=max_size) + executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers) IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key]
Set max_workers the same as max_size.
## Code Before: from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} def register_pool(self, group_key, max_size=1): executor = QueueExecutor(pool_key=group_key, max_size=max_size) IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key] ## Instruction: Set max_workers the same as max_size. ## Code After: from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} def register_pool(self, group_key, max_size=10, max_workers=10): executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers) IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key]
from blackgate.executor import QueueExecutor from tornado.ioloop import IOLoop class ExecutorPools(object): class PoolFull(Exception): pass class ExecutionTimeout(Exception): pass class ExecutionFailure(Exception): pass def __init__(self): self.pools = {} - def register_pool(self, group_key, max_size=1): + def register_pool(self, group_key, max_size=10, max_workers=10): ? +++++++++++++++++ - executor = QueueExecutor(pool_key=group_key, max_size=max_size) + executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers) ? +++++++++++++++++++++++++ IOLoop.current().spawn_callback(executor.consume) self.pools[group_key] = executor def get_executor(self, group_key): if group_key not in self.pools: raise Exception("Pool not registerd") return self.pools[group_key]
451a435ca051305517c79216d7ab9441939f4004
src/amr.py
src/amr.py
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = df.grad(u) costheta = df.dot(m, E) sigma = 1/(1 + costheta**2) F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive()
import dolfin as df def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = -df.grad(u) costheta = df.dot(m, E) sigma = s0/(1 + alpha*costheta**2) F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive()
Add sigma0 and alpha AMR parameters to the function.
Add sigma0 and alpha AMR parameters to the function.
Python
bsd-2-clause
fangohr/fenics-anisotropic-magneto-resistance
import dolfin as df - def amr(mesh, m, DirichletBoundary, g, d): + def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) - E = df.grad(u) + E = -df.grad(u) costheta = df.dot(m, E) - sigma = 1/(1 + costheta**2) + sigma = s0/(1 + alpha*costheta**2) F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive()
Add sigma0 and alpha AMR parameters to the function.
## Code Before: import dolfin as df def amr(mesh, m, DirichletBoundary, g, d): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = df.grad(u) costheta = df.dot(m, E) sigma = 1/(1 + costheta**2) F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive() ## Instruction: Add sigma0 and alpha AMR parameters to the function. ## Code After: import dolfin as df def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) E = -df.grad(u) costheta = df.dot(m, E) sigma = s0/(1 + alpha*costheta**2) F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive()
import dolfin as df - def amr(mesh, m, DirichletBoundary, g, d): + def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1): ? +++++++++++++++ V = df.FunctionSpace(mesh, "CG", 1) # Define boundary condition bc = df.DirichletBC(V, g, DirichletBoundary()) # Define variational problem u = df.Function(V) v = df.TestFunction(V) - E = df.grad(u) + E = -df.grad(u) ? + costheta = df.dot(m, E) - sigma = 1/(1 + costheta**2) ? ^ + sigma = s0/(1 + alpha*costheta**2) ? ^^ ++++++ F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx # Compute solution df.solve(F == 0, u, bc, solver_parameters={"newton_solver": {"relative_tolerance": 1e-6}}) # Plot solution and solution gradient df.plot(u, title="Solution") df.plot(sigma*df.grad(u), title="Solution gradient") df.interactive()
698677a623722b63ec4cceb7690b62fa7e4ede37
django_prices_openexchangerates/templatetags/prices_multicurrency_i18n.py
django_prices_openexchangerates/templatetags/prices_multicurrency_i18n.py
from django.template import Library from django_prices.templatetags import prices_i18n from .. import exchange_currency register = Library() @register.simple_tag # noqa def gross_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.gross(converted_price) @register.simple_tag # noqa def net_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.net(converted_price) @register.simple_tag # noqa def tax_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.tax(converted_price)
from django.template import Library from django_prices.templatetags import prices_i18n from .. import exchange_currency register = Library() @register.simple_tag # noqa def gross_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.gross(converted_price) @register.simple_tag # noqa def net_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.net(converted_price) @register.simple_tag # noqa def tax_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.tax(converted_price) @register.simple_tag def discount_amount_in_currency(discount, price, currency): price = exchange_currency(price, to_currency=currency) discount_amount = exchange_currency(discount.amount, to_currency=currency) discount.amount = discount_amount return (price | discount) - price
Add templatetag for converting discounts between currencies
Add templatetag for converting discounts between currencies
Python
bsd-3-clause
mirumee/django-prices-openexchangerates,artursmet/django-prices-openexchangerates
from django.template import Library from django_prices.templatetags import prices_i18n from .. import exchange_currency register = Library() @register.simple_tag # noqa def gross_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.gross(converted_price) @register.simple_tag # noqa def net_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.net(converted_price) @register.simple_tag # noqa def tax_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.tax(converted_price) + @register.simple_tag + def discount_amount_in_currency(discount, price, currency): + price = exchange_currency(price, to_currency=currency) + discount_amount = exchange_currency(discount.amount, to_currency=currency) + discount.amount = discount_amount + return (price | discount) - price +
Add templatetag for converting discounts between currencies
## Code Before: from django.template import Library from django_prices.templatetags import prices_i18n from .. import exchange_currency register = Library() @register.simple_tag # noqa def gross_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.gross(converted_price) @register.simple_tag # noqa def net_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.net(converted_price) @register.simple_tag # noqa def tax_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.tax(converted_price) ## Instruction: Add templatetag for converting discounts between currencies ## Code After: from django.template import Library from django_prices.templatetags import prices_i18n from .. import exchange_currency register = Library() @register.simple_tag # noqa def gross_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.gross(converted_price) @register.simple_tag # noqa def net_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.net(converted_price) @register.simple_tag # noqa def tax_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.tax(converted_price) @register.simple_tag def discount_amount_in_currency(discount, price, currency): price = exchange_currency(price, to_currency=currency) discount_amount = exchange_currency(discount.amount, to_currency=currency) discount.amount = discount_amount return (price | discount) - price
from django.template import Library from django_prices.templatetags import prices_i18n from .. import exchange_currency register = Library() @register.simple_tag # noqa def gross_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.gross(converted_price) @register.simple_tag # noqa def net_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.net(converted_price) @register.simple_tag # noqa def tax_in_currency(price, currency): # noqa converted_price = exchange_currency(price, currency) return prices_i18n.tax(converted_price) + + @register.simple_tag + def discount_amount_in_currency(discount, price, currency): + price = exchange_currency(price, to_currency=currency) + discount_amount = exchange_currency(discount.amount, to_currency=currency) + discount.amount = discount_amount + return (price | discount) - price
44be93c5efb334297fc1bb10eaafec197018b241
python/render/render_tracks.py
python/render/render_tracks.py
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number']) d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number']) d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
Update formatting on track labels
Update formatting on track labels
Python
mit
Duke-GCB/TrackHubGenerator,Duke-GCB/TrackHubGenerator
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] - d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number']) + d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number']) - d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier']) + d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
Update formatting on track labels
## Code Before: __author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number']) d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main() ## Instruction: Update formatting on track labels ## Code After: __author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number']) d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] - d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number']) ? ------ + d['short_label'] = '{}_{} binding'.format(metadata['protein'], metadata['serial_number']) - d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier']) + d['long_label'] = 'Predicted {} binding sites (site width = {})'.format(metadata['protein'], metadata['width']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
b9e3485030ef7acf5b3d312b8e9d9fc54367eded
tests/ext/argcomplete_tests.py
tests/ext/argcomplete_tests.py
"""Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run()
"""Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, argv=['default'], base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run()
Fix Argcomplete Tests on Python <3.2
Fix Argcomplete Tests on Python <3.2
Python
bsd-3-clause
akhilman/cement,fxstein/cement,datafolklabs/cement,akhilman/cement,akhilman/cement,fxstein/cement,fxstein/cement,datafolklabs/cement,datafolklabs/cement
"""Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, + argv=['default'], base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run()
Fix Argcomplete Tests on Python <3.2
## Code Before: """Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run() ## Instruction: Fix Argcomplete Tests on Python <3.2 ## Code After: """Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, argv=['default'], base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run()
"""Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, + argv=['default'], base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run()
394e3ffd4221a749bcc8df7d11da2f3bc3ace5f9
getalltext.py
getalltext.py
import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if args.usernames: print(event['from']['username'],end=': ') #do i need the "from" here? print(event["text"]) if __name__ == "__main__": main()
import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') parser.add_argument('-u','--usernames', help='Show usernames before messages. ' 'If someone doesn\'t have a username, the line will start with "@: ".' 'Useful when output will be read back as a chatlog.', action='store_true') parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when ' 'output will be piped into analysis expecting newline separated messages. ', action='store_true') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if args.usernames: if 'username' in event['from']: print('@' + event['from']['username'],end=': ') else: print('@',end=': ') if args.no_newlines: print(event['text'].replace('\n','')) else: print(event["text"]) if __name__ == "__main__": main()
Add option to remove newlines; remove bug on messages sent by someone without a username
Add option to remove newlines; remove bug on messages sent by someone without a username
Python
mit
expectocode/telegram-analysis,expectocode/telegramAnalysis
import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') - parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true') + parser.add_argument('-u','--usernames', help='Show usernames before messages. ' + 'If someone doesn\'t have a username, the line will start with "@: ".' + 'Useful when output will be read back as a chatlog.', + action='store_true') + parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when ' + 'output will be piped into analysis expecting newline separated messages. ', + action='store_true') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if args.usernames: + if 'username' in event['from']: - print(event['from']['username'],end=': ') + print('@' + event['from']['username'],end=': ') - #do i need the "from" here? + else: + print('@',end=': ') + if args.no_newlines: + print(event['text'].replace('\n','')) + else: - print(event["text"]) + print(event["text"]) if __name__ == "__main__": main()
Add option to remove newlines; remove bug on messages sent by someone without a username
## Code Before: import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if args.usernames: print(event['from']['username'],end=': ') #do i need the "from" here? print(event["text"]) if __name__ == "__main__": main() ## Instruction: Add option to remove newlines; remove bug on messages sent by someone without a username ## Code After: import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') parser.add_argument('-u','--usernames', help='Show usernames before messages. ' 'If someone doesn\'t have a username, the line will start with "@: ".' 'Useful when output will be read back as a chatlog.', action='store_true') parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when ' 'output will be piped into analysis expecting newline separated messages. ', action='store_true') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if args.usernames: if 'username' in event['from']: print('@' + event['from']['username'],end=': ') else: print('@',end=': ') if args.no_newlines: print(event['text'].replace('\n','')) else: print(event["text"]) if __name__ == "__main__": main()
import argparse from json import loads def main(): parser = argparse.ArgumentParser( description="Extract all raw text from a specific Telegram chat") parser.add_argument('filepath', help='the json chatlog file to analyse') - parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true') ? --------------------- + parser.add_argument('-u','--usernames', help='Show usernames before messages. ' ? ++ + 'If someone doesn\'t have a username, the line will start with "@: ".' + 'Useful when output will be read back as a chatlog.', + action='store_true') + parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when ' + 'output will be piped into analysis expecting newline separated messages. ', + action='store_true') args=parser.parse_args() filepath = args.filepath with open(filepath, 'r') as jsonfile: events = (loads(line) for line in jsonfile) for event in events: #check the event is the sort we're looking for if "from" in event and "text" in event: if args.usernames: + if 'username' in event['from']: - print(event['from']['username'],end=': ') + print('@' + event['from']['username'],end=': ') ? ++++ ++++++ - #do i need the "from" here? + else: + print('@',end=': ') + if args.no_newlines: + print(event['text'].replace('\n','')) + else: - print(event["text"]) + print(event["text"]) ? ++++ if __name__ == "__main__": main()
52cbbadd3cf56ebc6783313058dbe129a4852a1d
call_server/extensions.py
call_server/extensions.py
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], 'media-src': ['\'self\'', 'media.twiliocdn.com'], 'connect-src': ['\'self\'', 'wss://*.twilio.com', ] } # unsafe-inline needed to render <script> tags without nonce # unsafe-eval needed to run bootstrap templates talisman = Talisman()
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com', 'js-agent.newrelic.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], 'media-src': ['\'self\'', 'media.twiliocdn.com'], 'connect-src': ['\'self\'', 'wss://*.twilio.com', ] } # unsafe-inline needed to render <script> tags without nonce # unsafe-eval needed to run bootstrap templates talisman = Talisman()
Update script-src to include newrelic
Update script-src to include newrelic
Python
agpl-3.0
OpenSourceActivismTech/call-power,18mr/call-congress,spacedogXYZ/call-power,18mr/call-congress,spacedogXYZ/call-power,18mr/call-congress,OpenSourceActivismTech/call-power,OpenSourceActivismTech/call-power,spacedogXYZ/call-power,spacedogXYZ/call-power,18mr/call-congress,OpenSourceActivismTech/call-power
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', - 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'], + 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', + 'cdnjs.cloudflare.com', 'media.twiliocdn.com', 'js-agent.newrelic.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], 'media-src': ['\'self\'', 'media.twiliocdn.com'], 'connect-src': ['\'self\'', 'wss://*.twilio.com', ] } # unsafe-inline needed to render <script> tags without nonce # unsafe-eval needed to run bootstrap templates talisman = Talisman()
Update script-src to include newrelic
## Code Before: from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], 'media-src': ['\'self\'', 'media.twiliocdn.com'], 'connect-src': ['\'self\'', 'wss://*.twilio.com', ] } # unsafe-inline needed to render <script> tags without nonce # unsafe-eval needed to run bootstrap templates talisman = Talisman() ## Instruction: Update script-src to include newrelic ## Code After: from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com', 'js-agent.newrelic.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], 'media-src': ['\'self\'', 'media.twiliocdn.com'], 'connect-src': ['\'self\'', 'wss://*.twilio.com', ] } # unsafe-inline needed to render <script> tags without nonce # unsafe-eval needed to run bootstrap templates talisman = Talisman()
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', - 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'], + 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', + 'cdnjs.cloudflare.com', 'media.twiliocdn.com', 'js-agent.newrelic.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], 'media-src': ['\'self\'', 'media.twiliocdn.com'], 'connect-src': ['\'self\'', 'wss://*.twilio.com', ] } # unsafe-inline needed to render <script> tags without nonce # unsafe-eval needed to run bootstrap templates talisman = Talisman()
3cb07a7f547b4187c918e7340d15c172cb9a7231
fabfile.py
fabfile.py
import sys from fabric import api as fab_api from fabric import exceptions as fab_ex try: import settings except ImportError: print('No settings file') sys.exit() fab_api.env.use_ssh_config = True fab_api.env.hosts = settings.ENV_HOSTS fab_api.env.warn_only = True def update_remotes(): try: fab_api.run('~/bin/src-git-pull') except fab_ex.NetworkError as ex: print(ex)
import sys from fabric import api as fab_api from fabric import exceptions as fab_ex try: import settings except ImportError: print('No settings file') sys.exit() fab_api.env.use_ssh_config = True fab_api.env.hosts = settings.ENV_HOSTS fab_api.env.warn_only = True def update_remotes(): if not fab_api.env.hosts: print('Empty tuple of remote hosts. Exiting...') return try: fab_api.run('~/bin/src-git-pull') except fab_ex.NetworkError as ex: print(ex)
Exit if tuple of remote hosts is empty.
Exit if tuple of remote hosts is empty.
Python
apache-2.0
gasull/src-git-pull
import sys from fabric import api as fab_api from fabric import exceptions as fab_ex try: import settings except ImportError: print('No settings file') sys.exit() fab_api.env.use_ssh_config = True fab_api.env.hosts = settings.ENV_HOSTS fab_api.env.warn_only = True def update_remotes(): + if not fab_api.env.hosts: + print('Empty tuple of remote hosts. Exiting...') + return try: fab_api.run('~/bin/src-git-pull') except fab_ex.NetworkError as ex: print(ex)
Exit if tuple of remote hosts is empty.
## Code Before: import sys from fabric import api as fab_api from fabric import exceptions as fab_ex try: import settings except ImportError: print('No settings file') sys.exit() fab_api.env.use_ssh_config = True fab_api.env.hosts = settings.ENV_HOSTS fab_api.env.warn_only = True def update_remotes(): try: fab_api.run('~/bin/src-git-pull') except fab_ex.NetworkError as ex: print(ex) ## Instruction: Exit if tuple of remote hosts is empty. ## Code After: import sys from fabric import api as fab_api from fabric import exceptions as fab_ex try: import settings except ImportError: print('No settings file') sys.exit() fab_api.env.use_ssh_config = True fab_api.env.hosts = settings.ENV_HOSTS fab_api.env.warn_only = True def update_remotes(): if not fab_api.env.hosts: print('Empty tuple of remote hosts. Exiting...') return try: fab_api.run('~/bin/src-git-pull') except fab_ex.NetworkError as ex: print(ex)
import sys from fabric import api as fab_api from fabric import exceptions as fab_ex try: import settings except ImportError: print('No settings file') sys.exit() fab_api.env.use_ssh_config = True fab_api.env.hosts = settings.ENV_HOSTS fab_api.env.warn_only = True def update_remotes(): + if not fab_api.env.hosts: + print('Empty tuple of remote hosts. Exiting...') + return try: fab_api.run('~/bin/src-git-pull') except fab_ex.NetworkError as ex: print(ex)
c7785ff4367de929392b85f73a396e987cfe4606
apps/chats/models.py
apps/chats/models.py
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def as_html(self, tag='div'): """ Return an HTML representation of this chat, including tags marking the author and text selection accordingly. Use the tag argument to customize the tag that wraps each line in a chat. """ html = u'' for line in self.text.splitlines(): line_sections = line.split(': ', 1) if len(line_sections) > 1: html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( author=line_sections[0], tag=tag, text=line_sections[1], ) else: html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( tag=tag, text=line_sections[0], ) return html def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
Add HTML representation of chat
Add HTML representation of chat
Python
mit
tofumatt/quotes,tofumatt/quotes
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() + def as_html(self, tag='div'): + """ + Return an HTML representation of this chat, including tags marking + the author and text selection accordingly. + + Use the tag argument to customize the tag that wraps each line in a chat. + """ + + html = u'' + for line in self.text.splitlines(): + line_sections = line.split(': ', 1) + if len(line_sections) > 1: + html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( + author=line_sections[0], + tag=tag, + text=line_sections[1], + ) + else: + html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( + tag=tag, + text=line_sections[0], + ) + + return html + def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
Add HTML representation of chat
## Code Before: from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6) ## Instruction: Add HTML representation of chat ## Code After: from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def as_html(self, tag='div'): """ Return an HTML representation of this chat, including tags marking the author and text selection accordingly. Use the tag argument to customize the tag that wraps each line in a chat. """ html = u'' for line in self.text.splitlines(): line_sections = line.split(': ', 1) if len(line_sections) > 1: html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( author=line_sections[0], tag=tag, text=line_sections[1], ) else: html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( tag=tag, text=line_sections[0], ) return html def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() + def as_html(self, tag='div'): + """ + Return an HTML representation of this chat, including tags marking + the author and text selection accordingly. + + Use the tag argument to customize the tag that wraps each line in a chat. + """ + + html = u'' + for line in self.text.splitlines(): + line_sections = line.split(': ', 1) + if len(line_sections) > 1: + html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( + author=line_sections[0], + tag=tag, + text=line_sections[1], + ) + else: + html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( + tag=tag, + text=line_sections[0], + ) + + return html + def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
451951b311ef6e2bb76348a116dc0465f735348e
pytest_watch/config.py
pytest_watch/config.py
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): if config.inifile: self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
Fix running when pytest.ini is not present.
Fix running when pytest.ini is not present.
Python
mit
joeyespo/pytest-watch
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): + if config.inifile: - self.path = str(config.inifile) + self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
Fix running when pytest.ini is not present.
## Code Before: try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name) ## Instruction: Fix running when pytest.ini is not present. ## Code After: try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): if config.inifile: self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): + if config.inifile: - self.path = str(config.inifile) + self.path = str(config.inifile) ? ++++ def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
43905a102092bdd50de1f8997cd19cb617b348b3
tests/cart_tests.py
tests/cart_tests.py
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) if __name__ == '__main__': unittest.main()
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) startAddr = cpu.ReadMemWord(cpu.reset) firstByte = cpu.ReadMemory(startAddr) self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
Use the reset adder from the banks properly
Use the reset adder from the banks properly
Python
bsd-2-clause
pusscat/refNes
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) + startAddr = cpu.ReadMemWord(cpu.reset) + firstByte = cpu.ReadMemory(startAddr) + self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
Use the reset adder from the banks properly
## Code Before: import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) if __name__ == '__main__': unittest.main() ## Instruction: Use the reset adder from the banks properly ## Code After: import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) startAddr = cpu.ReadMemWord(cpu.reset) firstByte = cpu.ReadMemory(startAddr) self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) + startAddr = cpu.ReadMemWord(cpu.reset) + firstByte = cpu.ReadMemory(startAddr) + self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
5f01b9da3cfa899037ac9f7c3262a08c074b5bf9
bedrock/stories/urls.py
bedrock/stories/urls.py
from bedrock.mozorg.util import page urlpatterns = ( page("", "stories/landing.html"), page("art-of-engagement/", "stories/articles/art-of-engagement.html"), page("build-together/", "stories/articles/build-together.html"), page("community-champion/", "stories/articles/community-champion.html"), )
from bedrock.mozorg.util import page from bedrock.redirects.util import redirect urlpatterns = ( page("", "stories/landing.html"), page("art-of-engagement/", "stories/articles/art-of-engagement.html"), page("build-together/", "stories/articles/build-together.html"), page("community-champion/", "stories/articles/community-champion.html"), # REMOVE WHEN REAL PAGE GOES LIVE redirect(r"^joy-of-color/?$", "https://blog.mozilla.org/en/products/firefox/firefox-news/independent-voices/", permanent=False), )
Add temporary redirect for stories URL
Add temporary redirect for stories URL
Python
mpl-2.0
mozilla/bedrock,mozilla/bedrock,alexgibson/bedrock,craigcook/bedrock,craigcook/bedrock,alexgibson/bedrock,craigcook/bedrock,alexgibson/bedrock,craigcook/bedrock,alexgibson/bedrock,mozilla/bedrock,mozilla/bedrock
from bedrock.mozorg.util import page + from bedrock.redirects.util import redirect urlpatterns = ( page("", "stories/landing.html"), page("art-of-engagement/", "stories/articles/art-of-engagement.html"), page("build-together/", "stories/articles/build-together.html"), page("community-champion/", "stories/articles/community-champion.html"), + # REMOVE WHEN REAL PAGE GOES LIVE + redirect(r"^joy-of-color/?$", "https://blog.mozilla.org/en/products/firefox/firefox-news/independent-voices/", permanent=False), )
Add temporary redirect for stories URL
## Code Before: from bedrock.mozorg.util import page urlpatterns = ( page("", "stories/landing.html"), page("art-of-engagement/", "stories/articles/art-of-engagement.html"), page("build-together/", "stories/articles/build-together.html"), page("community-champion/", "stories/articles/community-champion.html"), ) ## Instruction: Add temporary redirect for stories URL ## Code After: from bedrock.mozorg.util import page from bedrock.redirects.util import redirect urlpatterns = ( page("", "stories/landing.html"), page("art-of-engagement/", "stories/articles/art-of-engagement.html"), page("build-together/", "stories/articles/build-together.html"), page("community-champion/", "stories/articles/community-champion.html"), # REMOVE WHEN REAL PAGE GOES LIVE redirect(r"^joy-of-color/?$", "https://blog.mozilla.org/en/products/firefox/firefox-news/independent-voices/", permanent=False), )
from bedrock.mozorg.util import page + from bedrock.redirects.util import redirect urlpatterns = ( page("", "stories/landing.html"), page("art-of-engagement/", "stories/articles/art-of-engagement.html"), page("build-together/", "stories/articles/build-together.html"), page("community-champion/", "stories/articles/community-champion.html"), + # REMOVE WHEN REAL PAGE GOES LIVE + redirect(r"^joy-of-color/?$", "https://blog.mozilla.org/en/products/firefox/firefox-news/independent-voices/", permanent=False), )
92c024c2112573e4c4b2d1288b1ec3c7a40bc670
test/test_uploader.py
test/test_uploader.py
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile')) # fetch the contents back out, be sure we truly uploaded the dummyfile retrieved_bucket = conn.Object( mock_bucket, conf.s3_package_name() ).get()['Body'] found_contents = str(retrieved_bucket.read()).rstrip() assert found_contents == 'dummy data'
Add additional assertion that the file we uploaded is correct
Add additional assertion that the file we uploaded is correct We should pull back down the S3 bucket file and be sure it's the same, proving we used the boto3 API correctly. We should probably, at some point, also upload a _real_ zip file and not just a plaintext file.
Python
apache-2.0
rackerlabs/lambda-uploader,dsouzajude/lambda-uploader
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile')) + # fetch the contents back out, be sure we truly uploaded the dummyfile + retrieved_bucket = conn.Object( + mock_bucket, + conf.s3_package_name() + ).get()['Body'] + found_contents = str(retrieved_bucket.read()).rstrip() + assert found_contents == 'dummy data' +
Add additional assertion that the file we uploaded is correct
## Code Before: import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile')) ## Instruction: Add additional assertion that the file we uploaded is correct ## Code After: import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile')) # fetch the contents back out, be sure we truly uploaded the dummyfile retrieved_bucket = conn.Object( mock_bucket, conf.s3_package_name() ).get()['Body'] found_contents = str(retrieved_bucket.read()).rstrip() assert found_contents == 'dummy data'
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile')) + + # fetch the contents back out, be sure we truly uploaded the dummyfile + retrieved_bucket = conn.Object( + mock_bucket, + conf.s3_package_name() + ).get()['Body'] + found_contents = str(retrieved_bucket.read()).rstrip() + assert found_contents == 'dummy data'
b6cfa50e127d3f74247ab148219ef6336e445cca
InvenTree/InvenTree/ready.py
InvenTree/InvenTree/ready.py
import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent custom "on load" code from running! excluded_commands = [ 'flush', 'loaddata', 'dumpdata', 'makemirations', 'migrate', 'check', 'dbbackup', 'mediabackup', 'dbrestore', 'mediarestore', 'shell', 'createsuperuser', 'wait_for_db', 'prerender', 'collectstatic', 'makemessages', 'compilemessages', 'test', ] for cmd in excluded_commands: if cmd in sys.argv: return False return True
import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent custom "on load" code from running! excluded_commands = [ 'flush', 'loaddata', 'dumpdata', 'makemirations', 'migrate', 'check', 'dbbackup', 'mediabackup', 'dbrestore', 'mediarestore', 'shell', 'createsuperuser', 'wait_for_db', 'prerender', 'collectstatic', 'makemessages', 'compilemessages', ] for cmd in excluded_commands: if cmd in sys.argv: return False return True
Allow data operations to run for 'test'
Allow data operations to run for 'test'
Python
mit
inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent custom "on load" code from running! excluded_commands = [ 'flush', 'loaddata', 'dumpdata', 'makemirations', 'migrate', 'check', 'dbbackup', 'mediabackup', 'dbrestore', 'mediarestore', 'shell', 'createsuperuser', 'wait_for_db', 'prerender', 'collectstatic', 'makemessages', 'compilemessages', - 'test', ] for cmd in excluded_commands: if cmd in sys.argv: return False return True
Allow data operations to run for 'test'
## Code Before: import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent custom "on load" code from running! excluded_commands = [ 'flush', 'loaddata', 'dumpdata', 'makemirations', 'migrate', 'check', 'dbbackup', 'mediabackup', 'dbrestore', 'mediarestore', 'shell', 'createsuperuser', 'wait_for_db', 'prerender', 'collectstatic', 'makemessages', 'compilemessages', 'test', ] for cmd in excluded_commands: if cmd in sys.argv: return False return True ## Instruction: Allow data operations to run for 'test' ## Code After: import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent custom "on load" code from running! excluded_commands = [ 'flush', 'loaddata', 'dumpdata', 'makemirations', 'migrate', 'check', 'dbbackup', 'mediabackup', 'dbrestore', 'mediarestore', 'shell', 'createsuperuser', 'wait_for_db', 'prerender', 'collectstatic', 'makemessages', 'compilemessages', ] for cmd in excluded_commands: if cmd in sys.argv: return False return True
import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent custom "on load" code from running! excluded_commands = [ 'flush', 'loaddata', 'dumpdata', 'makemirations', 'migrate', 'check', 'dbbackup', 'mediabackup', 'dbrestore', 'mediarestore', 'shell', 'createsuperuser', 'wait_for_db', 'prerender', 'collectstatic', 'makemessages', 'compilemessages', - 'test', ] for cmd in excluded_commands: if cmd in sys.argv: return False return True
90ee1f19ad1b99c3960f5b4917d6801cd4d4d607
paypal_registration/models.py
paypal_registration/models.py
from django.db import models # Create your models here.
from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
Make a bit more sensible model.
Make a bit more sensible model.
Python
bsd-3-clause
buchuki/django-registration-paypal
from django.db import models + from registration.models import RegistrationProfile - # Create your models here. + class PaypalRegistrationProfile(RegistrationProfile): + paid = models.BooleanField(default=False) +
Make a bit more sensible model.
## Code Before: from django.db import models # Create your models here. ## Instruction: Make a bit more sensible model. ## Code After: from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
from django.db import models + from registration.models import RegistrationProfile - # Create your models here. + + class PaypalRegistrationProfile(RegistrationProfile): + paid = models.BooleanField(default=False)
0e740b5fd924b113173b546f2dd2b8fa1e55d074
indra/sparser/sparser_api.py
indra/sparser/sparser_api.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB from indra.sparser.processor import SparserProcessor logger = logging.getLogger('sparser') def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) except ET.ParseError: logger.error('Could not parse XML string') return None sp = _process_elementtree(tree) return sp def _process_elementtree(tree): sp = SparserProcessor(tree) sp.get_modifications() sp.get_activations() return sp
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB from indra.sparser.processor import SparserProcessor logger = logging.getLogger('sparser') def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) except ET.ParseError as e: logger.error('Could not parse XML string') logger.error(e) return None sp = _process_elementtree(tree) return sp def _process_elementtree(tree): sp = SparserProcessor(tree) sp.get_modifications() sp.get_activations() return sp
Print XML parse errors in Sparser API
Print XML parse errors in Sparser API
Python
bsd-2-clause
sorgerlab/belpy,bgyori/indra,johnbachman/belpy,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB from indra.sparser.processor import SparserProcessor logger = logging.getLogger('sparser') def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) - except ET.ParseError: + except ET.ParseError as e: logger.error('Could not parse XML string') + logger.error(e) return None sp = _process_elementtree(tree) return sp def _process_elementtree(tree): sp = SparserProcessor(tree) sp.get_modifications() sp.get_activations() return sp
Print XML parse errors in Sparser API
## Code Before: from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB from indra.sparser.processor import SparserProcessor logger = logging.getLogger('sparser') def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) except ET.ParseError: logger.error('Could not parse XML string') return None sp = _process_elementtree(tree) return sp def _process_elementtree(tree): sp = SparserProcessor(tree) sp.get_modifications() sp.get_activations() return sp ## Instruction: Print XML parse errors in Sparser API ## Code After: from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB from indra.sparser.processor import SparserProcessor logger = logging.getLogger('sparser') def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) except ET.ParseError as e: logger.error('Could not parse XML string') logger.error(e) return None sp = _process_elementtree(tree) return sp def _process_elementtree(tree): sp = SparserProcessor(tree) sp.get_modifications() sp.get_activations() return sp
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB from indra.sparser.processor import SparserProcessor logger = logging.getLogger('sparser') def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) - except ET.ParseError: + except ET.ParseError as e: ? +++++ logger.error('Could not parse XML string') + logger.error(e) return None sp = _process_elementtree(tree) return sp def _process_elementtree(tree): sp = SparserProcessor(tree) sp.get_modifications() sp.get_activations() return sp
a23641edf1fd941768eebb1938340d2173ac2e11
iputil/parser.py
iputil/parser.py
import json import os import re IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})') def find_ips(filename): """Returns all the unique IPs found within a file.""" matches = [] with open(filename) as f: for line in f: match = IP_REGEX.findall(line) if match: matches += match return set(sorted(matches)) if matches else set() def store_ips(cache_path, ips): """Stores the IPs into a cache for later retrieval.""" cache = [] if os.path.exists(cache_path): with open(cache_path, 'rb') as f: cache = json.loads(f.read()) new_ips = 0 existing_ips = [i['ip'] for i in cache] for ip in ips: if ip not in existing_ips: cache.append({'ip': ip}) new_ips += 1 with open(cache_path, 'wb') as f: f.write(json.dumps(cache)) return new_ips
import json import os import re IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})') def find_ips(filename): """Returns all the unique IPs found within a file.""" matches = [] with open(filename) as f: for line in f: matches += IP_REGEX.findall(line) return set(sorted(matches)) if matches else set() def store_ips(cache_path, ips): """Stores the IPs into a cache for later retrieval.""" cache = [] if os.path.exists(cache_path): with open(cache_path, 'rb') as f: cache = json.loads(f.read()) new_ips = 0 existing_ips = [i['ip'] for i in cache] for ip in ips: if ip not in existing_ips: cache.append({'ip': ip}) new_ips += 1 with open(cache_path, 'wb') as f: f.write(json.dumps(cache)) return new_ips
Remove unnecessary check, used to re functions returning different types
Remove unnecessary check, used to re functions returning different types
Python
mit
kolanos/iputil
import json import os import re IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})') def find_ips(filename): """Returns all the unique IPs found within a file.""" matches = [] with open(filename) as f: for line in f: - match = IP_REGEX.findall(line) + matches += IP_REGEX.findall(line) - if match: - matches += match return set(sorted(matches)) if matches else set() def store_ips(cache_path, ips): """Stores the IPs into a cache for later retrieval.""" cache = [] if os.path.exists(cache_path): with open(cache_path, 'rb') as f: cache = json.loads(f.read()) new_ips = 0 existing_ips = [i['ip'] for i in cache] for ip in ips: if ip not in existing_ips: cache.append({'ip': ip}) new_ips += 1 with open(cache_path, 'wb') as f: f.write(json.dumps(cache)) return new_ips
Remove unnecessary check, used to re functions returning different types
## Code Before: import json import os import re IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})') def find_ips(filename): """Returns all the unique IPs found within a file.""" matches = [] with open(filename) as f: for line in f: match = IP_REGEX.findall(line) if match: matches += match return set(sorted(matches)) if matches else set() def store_ips(cache_path, ips): """Stores the IPs into a cache for later retrieval.""" cache = [] if os.path.exists(cache_path): with open(cache_path, 'rb') as f: cache = json.loads(f.read()) new_ips = 0 existing_ips = [i['ip'] for i in cache] for ip in ips: if ip not in existing_ips: cache.append({'ip': ip}) new_ips += 1 with open(cache_path, 'wb') as f: f.write(json.dumps(cache)) return new_ips ## Instruction: Remove unnecessary check, used to re functions returning different types ## Code After: import json import os import re IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})') def find_ips(filename): """Returns all the unique IPs found within a file.""" matches = [] with open(filename) as f: for line in f: matches += IP_REGEX.findall(line) return set(sorted(matches)) if matches else set() def store_ips(cache_path, ips): """Stores the IPs into a cache for later retrieval.""" cache = [] if os.path.exists(cache_path): with open(cache_path, 'rb') as f: cache = json.loads(f.read()) new_ips = 0 existing_ips = [i['ip'] for i in cache] for ip in ips: if ip not in existing_ips: cache.append({'ip': ip}) new_ips += 1 with open(cache_path, 'wb') as f: f.write(json.dumps(cache)) return new_ips
import json import os import re IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})') def find_ips(filename): """Returns all the unique IPs found within a file.""" matches = [] with open(filename) as f: for line in f: - match = IP_REGEX.findall(line) + matches += IP_REGEX.findall(line) ? ++ + - if match: - matches += match return set(sorted(matches)) if matches else set() def store_ips(cache_path, ips): """Stores the IPs into a cache for later retrieval.""" cache = [] if os.path.exists(cache_path): with open(cache_path, 'rb') as f: cache = json.loads(f.read()) new_ips = 0 existing_ips = [i['ip'] for i in cache] for ip in ips: if ip not in existing_ips: cache.append({'ip': ip}) new_ips += 1 with open(cache_path, 'wb') as f: f.write(json.dumps(cache)) return new_ips
8dcf5b2c85430a09502649bb3bb95c7b56312c03
pysearch/urls.py
pysearch/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^search/', include('search.urls')), )
Connect search route to app
Connect search route to app
Python
mit
nh0815/PySearch,nh0815/PySearch
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), + url(r'^search/', include('search.urls')), )
Connect search route to app
## Code Before: from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), ) ## Instruction: Connect search route to app ## Code After: from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^search/', include('search.urls')), )
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), + url(r'^search/', include('search.urls')), )
0749c47bb280230ae5b1e2cda23773d3b10b2491
redis_check.py
redis_check.py
import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz)) except redis.exceptions.ResponseError as e: print('[+] {0}:{1} - {2}'.format(host, port, e)) except redis.exceptions.ConnectionError: print('[-] {0}:{1} - Connection Error'.format(host, port)) except redis.exceptions.TimeoutError: print('[-] {0}:{1} - Timeout'.format(host, port)) except redis.exceptions.InvalidResponse: print('[-] {0}:{1} - Invalid Response'.format(host, port))
import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1}:{2}'.format(host, ver, siz)) except redis.exceptions.ResponseError as e: print('[+] {0}::{1}'.format(host, e)) except redis.exceptions.ConnectionError: print('[-] {0}::Connection Error'.format(host)) except redis.exceptions.TimeoutError: print('[-] {0}::Timeout'.format(host)) except redis.exceptions.InvalidResponse: print('[-] {0}::Invalid Response'.format(host))
Make output easier to parse with cli tools.
Make output easier to parse with cli tools.
Python
bsd-3-clause
averagesecurityguy/research
import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() - print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz)) + print('[+] {0}:{1}:{2}'.format(host, ver, siz)) except redis.exceptions.ResponseError as e: - print('[+] {0}:{1} - {2}'.format(host, port, e)) + print('[+] {0}::{1}'.format(host, e)) except redis.exceptions.ConnectionError: - print('[-] {0}:{1} - Connection Error'.format(host, port)) + print('[-] {0}::Connection Error'.format(host)) except redis.exceptions.TimeoutError: - print('[-] {0}:{1} - Timeout'.format(host, port)) + print('[-] {0}::Timeout'.format(host)) except redis.exceptions.InvalidResponse: - print('[-] {0}:{1} - Invalid Response'.format(host, port)) + print('[-] {0}::Invalid Response'.format(host))
Make output easier to parse with cli tools.
## Code Before: import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz)) except redis.exceptions.ResponseError as e: print('[+] {0}:{1} - {2}'.format(host, port, e)) except redis.exceptions.ConnectionError: print('[-] {0}:{1} - Connection Error'.format(host, port)) except redis.exceptions.TimeoutError: print('[-] {0}:{1} - Timeout'.format(host, port)) except redis.exceptions.InvalidResponse: print('[-] {0}:{1} - Invalid Response'.format(host, port)) ## Instruction: Make output easier to parse with cli tools. ## Code After: import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1}:{2}'.format(host, ver, siz)) except redis.exceptions.ResponseError as e: print('[+] {0}::{1}'.format(host, e)) except redis.exceptions.ConnectionError: print('[-] {0}::Connection Error'.format(host)) except redis.exceptions.TimeoutError: print('[-] {0}::Timeout'.format(host)) except redis.exceptions.InvalidResponse: print('[-] {0}::Invalid Response'.format(host))
import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() - print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz)) ? ^^^ ----- ------ + print('[+] {0}:{1}:{2}'.format(host, ver, siz)) ? ^ except redis.exceptions.ResponseError as e: - print('[+] {0}:{1} - {2}'.format(host, port, e)) ? ------ ------ + print('[+] {0}::{1}'.format(host, e)) ? + except redis.exceptions.ConnectionError: - print('[-] {0}:{1} - Connection Error'.format(host, port)) ? ^^^^^^ ------ + print('[-] {0}::Connection Error'.format(host)) ? ^ except redis.exceptions.TimeoutError: - print('[-] {0}:{1} - Timeout'.format(host, port)) ? ^^^^^^ ------ + print('[-] {0}::Timeout'.format(host)) ? ^ except redis.exceptions.InvalidResponse: - print('[-] {0}:{1} - Invalid Response'.format(host, port)) ? ^^^^^^ ------ + print('[-] {0}::Invalid Response'.format(host)) ? ^
1e8ecd09ce6dc44c4955f8bb2f81aa65232ad9a0
multi_schema/management/commands/loaddata.py
multi_schema/management/commands/loaddata.py
from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named "%s"' % schema_name) schema.activate() super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate()
from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named "%s"' % schema_name) schema.activate() super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate() for schema in Schema.objects.all(): schema.create_schema()
Fix indenting. Create any schemas that were just loaded.
Fix indenting. Create any schemas that were just loaded.
Python
bsd-3-clause
luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse
from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named "%s"' % schema_name) schema.activate() - super(Command, self).handle(*app_labels, **options) + super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate() + + + for schema in Schema.objects.all(): + schema.create_schema()
Fix indenting. Create any schemas that were just loaded.
## Code Before: from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named "%s"' % schema_name) schema.activate() super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate() ## Instruction: Fix indenting. Create any schemas that were just loaded. ## Code After: from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named "%s"' % schema_name) schema.activate() super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate() for schema in Schema.objects.all(): schema.create_schema()
from django.core.management.commands import loaddata from django.core.management.base import CommandError from django.db import DatabaseError from optparse import make_option from ...models import Schema, template_schema class Command(loaddata.Command): option_list = loaddata.Command.option_list + ( make_option('--schema', action='store', dest='schema', help='Specify which schema to load schema-aware models to', default='__template__', ), ) def handle(self, *app_labels, **options): schema_name = options.get('schema') if schema_name == '__template__': # Hmm, we don't want to accidentally write data to this, so # we should raise an exception if we are going to be # writing any schema-aware objects. schema = None else: try: schema = Schema.objects.get(schema=options.get('schema')) except Schema.DoesNotExist: raise CommandError('No Schema found named "%s"' % schema_name) schema.activate() - super(Command, self).handle(*app_labels, **options) ? ----- + super(Command, self).handle(*app_labels, **options) if schema: schema.deactivate() + + + for schema in Schema.objects.all(): + schema.create_schema()
3245d884845748ef641ae1b39a14a040cf9a97a9
debexpo/tests/functional/test_register.py
debexpo/tests/functional/test_register.py
from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it meta.session.delete(user)
from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self, actually_delete_it=True): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it if actually_delete_it: meta.session.delete(user) else: return user def test_maintainer_signup_with_duplicate_name(self): self.test_maintainer_signup(actually_delete_it=False) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me_again@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me_again@example.com').count() self.assertEquals(count, 1)
Add a test that reproduces the crash if you sign up a second time with the same name
Add a test that reproduces the crash if you sign up a second time with the same name
Python
mit
jonnylamb/debexpo,swvist/Debexpo,jonnylamb/debexpo,swvist/Debexpo,jonnylamb/debexpo,swvist/Debexpo,jadonk/debexpo,jadonk/debexpo,jadonk/debexpo
from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): - def test_maintainer_signup(self): + def test_maintainer_signup(self, actually_delete_it=True): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it + if actually_delete_it: - meta.session.delete(user) + meta.session.delete(user) + else: + return user + + def test_maintainer_signup_with_duplicate_name(self): + self.test_maintainer_signup(actually_delete_it=False) + + self.app.post(url(controller='register', action='maintainer'), + {'name': 'Mr. Me', + 'password': 'password', + 'password_confirm': 'password', + 'commit': 'yes', + 'email': 'mr_me_again@example.com'}) + + count = meta.session.query(User).filter(User.email=='mr_me_again@example.com').count() + self.assertEquals(count, 1)
Add a test that reproduces the crash if you sign up a second time with the same name
## Code Before: from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it meta.session.delete(user) ## Instruction: Add a test that reproduces the crash if you sign up a second time with the same name ## Code After: from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self, actually_delete_it=True): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it if actually_delete_it: meta.session.delete(user) else: return user def test_maintainer_signup_with_duplicate_name(self): self.test_maintainer_signup(actually_delete_it=False) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me_again@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me_again@example.com').count() self.assertEquals(count, 1)
from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): - def test_maintainer_signup(self): + def test_maintainer_signup(self, actually_delete_it=True): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 0) self.app.post(url(controller='register', action='maintainer'), {'name': 'Mr. Me', 'password': 'password', 'password_confirm': 'password', 'commit': 'yes', 'email': 'mr_me@example.com'}) count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count, 1) user = meta.session.query(User).filter(User.email=='mr_me@example.com').one() # delete it + if actually_delete_it: - meta.session.delete(user) + meta.session.delete(user) ? ++++ + else: + return user + def test_maintainer_signup_with_duplicate_name(self): + self.test_maintainer_signup(actually_delete_it=False) + + self.app.post(url(controller='register', action='maintainer'), + {'name': 'Mr. Me', + 'password': 'password', + 'password_confirm': 'password', + 'commit': 'yes', + 'email': 'mr_me_again@example.com'}) + + count = meta.session.query(User).filter(User.email=='mr_me_again@example.com').count() + self.assertEquals(count, 1) +
ba983dea1e20409d403a86d62c300ea3d257b58a
parserscripts/phage.py
parserscripts/phage.py
import re class Phage: supported_databases = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): for db, regex in Phage.supported_databases.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db
import re class Phage: SUPPORTED_DATABASES = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): for db, regex in Phage.SUPPORTED_DATABASES.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db
Rename to follow constant naming conventions
Rename to follow constant naming conventions
Python
mit
mbonsma/phageParser,mbonsma/phageParser,phageParser/phageParser,mbonsma/phageParser,phageParser/phageParser,goyalsid/phageParser,goyalsid/phageParser,phageParser/phageParser,phageParser/phageParser,mbonsma/phageParser,goyalsid/phageParser
import re class Phage: - supported_databases = { + SUPPORTED_DATABASES = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): - for db, regex in Phage.supported_databases.items(): + for db, regex in Phage.SUPPORTED_DATABASES.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db
Rename to follow constant naming conventions
## Code Before: import re class Phage: supported_databases = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): for db, regex in Phage.supported_databases.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db ## Instruction: Rename to follow constant naming conventions ## Code After: import re class Phage: SUPPORTED_DATABASES = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): for db, regex in Phage.SUPPORTED_DATABASES.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db
import re class Phage: - supported_databases = { + SUPPORTED_DATABASES = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): - for db, regex in Phage.supported_databases.items(): + for db, regex in Phage.SUPPORTED_DATABASES.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db
fd48211548c8c2d5daec0994155ddb7e8d226882
tests/test_anki_sync.py
tests/test_anki_sync.py
import pytest import os import rememberberry from rememberscript import RememberMachine, FileStorage from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story @pytest.mark.asyncio @tmp_data_path('/tmp/data/', delete=True) async def test_anki_account(): storage = FileStorage() m, storage = get_isolated_story('login_anki', storage) await assert_replies(m.reply(''), 'What is your Anki username?') await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password') await assert_replies(m.reply('jkdhskjhgdksjhg'), 'Authentication with ankiweb failed, try again?', 'What is your Anki username?') await assert_replies(m.reply('ankitest8080@gmail.com'), 'And now the password') await assert_replies(m.reply('ankitest'), 'Authentication worked, now I\'ll try to sync your account', 'Syncing anki database', 'Syncing media files (this may take a while)', 'Syncing done', 'Great, you\'re all synced up!', 'enter init')
import pytest import os import rememberberry from rememberscript import RememberMachine, FileStorage from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story @pytest.mark.asyncio @tmp_data_path('/tmp/data/', delete=True) async def test_anki_account(): storage = FileStorage() storage['username'] = 'alice' m, storage = get_isolated_story('login_anki', storage) await assert_replies(m.reply(''), 'What is your Anki username?') await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password') await assert_replies(m.reply('jkdhskjhgdksjhg'), 'Authentication with ankiweb failed, try again?', 'What is your Anki username?') await assert_replies(m.reply('ankitest8080@gmail.com'), 'And now the password') await assert_replies(m.reply('ankitest'), 'Authentication worked, now I\'ll try to sync your account', 'Syncing anki database', 'Syncing media files (this may take a while)', 'Syncing done', 'Great, you\'re all synced up!', 'enter init')
Fix missing username in test
Fix missing username in test
Python
agpl-3.0
rememberberry/rememberberry-server,rememberberry/rememberberry-server
import pytest import os import rememberberry from rememberscript import RememberMachine, FileStorage from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story @pytest.mark.asyncio @tmp_data_path('/tmp/data/', delete=True) async def test_anki_account(): storage = FileStorage() + storage['username'] = 'alice' m, storage = get_isolated_story('login_anki', storage) await assert_replies(m.reply(''), 'What is your Anki username?') await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password') await assert_replies(m.reply('jkdhskjhgdksjhg'), 'Authentication with ankiweb failed, try again?', 'What is your Anki username?') await assert_replies(m.reply('ankitest8080@gmail.com'), 'And now the password') await assert_replies(m.reply('ankitest'), 'Authentication worked, now I\'ll try to sync your account', 'Syncing anki database', 'Syncing media files (this may take a while)', 'Syncing done', 'Great, you\'re all synced up!', 'enter init')
Fix missing username in test
## Code Before: import pytest import os import rememberberry from rememberscript import RememberMachine, FileStorage from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story @pytest.mark.asyncio @tmp_data_path('/tmp/data/', delete=True) async def test_anki_account(): storage = FileStorage() m, storage = get_isolated_story('login_anki', storage) await assert_replies(m.reply(''), 'What is your Anki username?') await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password') await assert_replies(m.reply('jkdhskjhgdksjhg'), 'Authentication with ankiweb failed, try again?', 'What is your Anki username?') await assert_replies(m.reply('ankitest8080@gmail.com'), 'And now the password') await assert_replies(m.reply('ankitest'), 'Authentication worked, now I\'ll try to sync your account', 'Syncing anki database', 'Syncing media files (this may take a while)', 'Syncing done', 'Great, you\'re all synced up!', 'enter init') ## Instruction: Fix missing username in test ## Code After: import pytest import os import rememberberry from rememberscript import RememberMachine, FileStorage from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story @pytest.mark.asyncio @tmp_data_path('/tmp/data/', delete=True) async def test_anki_account(): storage = FileStorage() storage['username'] = 'alice' m, storage = get_isolated_story('login_anki', storage) await assert_replies(m.reply(''), 'What is your Anki username?') await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password') await assert_replies(m.reply('jkdhskjhgdksjhg'), 'Authentication with ankiweb failed, try again?', 'What is your Anki username?') await assert_replies(m.reply('ankitest8080@gmail.com'), 'And now the password') await assert_replies(m.reply('ankitest'), 'Authentication worked, now I\'ll try to sync your account', 'Syncing anki database', 'Syncing media files (this may take a while)', 'Syncing done', 'Great, you\'re all synced up!', 'enter init')
import pytest import os import rememberberry from rememberscript import RememberMachine, FileStorage from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story @pytest.mark.asyncio @tmp_data_path('/tmp/data/', delete=True) async def test_anki_account(): storage = FileStorage() + storage['username'] = 'alice' m, storage = get_isolated_story('login_anki', storage) await assert_replies(m.reply(''), 'What is your Anki username?') await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password') await assert_replies(m.reply('jkdhskjhgdksjhg'), 'Authentication with ankiweb failed, try again?', 'What is your Anki username?') await assert_replies(m.reply('ankitest8080@gmail.com'), 'And now the password') await assert_replies(m.reply('ankitest'), 'Authentication worked, now I\'ll try to sync your account', 'Syncing anki database', 'Syncing media files (this may take a while)', 'Syncing done', 'Great, you\'re all synced up!', 'enter init')
b6ab579fa65f816704142716fbd68645ac5f2ff8
zenaida/contrib/feedback/models.py
zenaida/contrib/feedback/models.py
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path )
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path ) class Meta: ordering = ["-timestamp"]
Order feedback items by their timestamp.
Order feedback items by their timestamp.
Python
bsd-3-clause
littleweaver/django-zenaida,littleweaver/django-zenaida,littleweaver/django-zenaida,littleweaver/django-zenaida
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path ) + class Meta: + ordering = ["-timestamp"] +
Order feedback items by their timestamp.
## Code Before: from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path ) ## Instruction: Order feedback items by their timestamp. ## Code After: from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path ) class Meta: ordering = ["-timestamp"]
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots") # Request Data view = models.CharField(max_length=255) request_path = models.CharField(max_length=255) # The longest methods should be 7 chars, but we'll allow custom methods up # to 20 chars just in case. request_method = models.CharField(max_length=20, blank=True, null=True) # How long is the longest encoding name? request_encoding = models.CharField(max_length=20, blank=True, null=True) request_meta = models.TextField(blank=True, null=True) request_get = models.TextField(blank=True, null=True) request_post = models.TextField(blank=True, null=True) request_files = models.TextField(blank=True, null=True) def __unicode__(self): return "{username} at {path}".format( username=self.user.get_full_name(), path = self.request_path ) + + class Meta: + ordering = ["-timestamp"]
f1bdcde329b5b03e453f193720066914c908d46d
api/schemas.py
api/schemas.py
import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) location = marshmallow.fields.Str() section = marshmallow.fields.Str() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data}
import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) location = marshmallow.fields.Str(allow_none=True) section = marshmallow.fields.Str(allow_none=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data}
Allow story location and section to be null
Allow story location and section to be null
Python
mit
thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline
import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) - location = marshmallow.fields.Str() + location = marshmallow.fields.Str(allow_none=True) - section = marshmallow.fields.Str() + section = marshmallow.fields.Str(allow_none=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data}
Allow story location and section to be null
## Code Before: import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) location = marshmallow.fields.Str() section = marshmallow.fields.Str() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data} ## Instruction: Allow story location and section to be null ## Code After: import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) location = marshmallow.fields.Str(allow_none=True) section = marshmallow.fields.Str(allow_none=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data}
import marshmallow class StorySchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) title = marshmallow.fields.Str(required=True) created = marshmallow.fields.DateTime(dump_only=True) event_time = marshmallow.fields.DateTime(allow_none=True) - location = marshmallow.fields.Str() + location = marshmallow.fields.Str(allow_none=True) ? +++++++++++++++ - section = marshmallow.fields.Str() + section = marshmallow.fields.Str(allow_none=True) ? +++++++++++++++ @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'stories' if many else 'story' return {key: data} class PersonSchema(marshmallow.Schema): id = marshmallow.fields.Int(dump_only=True) name = marshmallow.fields.Str(required=True) @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'people' if many else 'person' return {key: data} class AddStoryPersonSchema(marshmallow.Schema): id = marshmallow.fields.Int() @marshmallow.post_dump(pass_many=True) def wrap(self, data, many): key = 'story_people' if many else 'story_person' return {key: data}
e3833d0c8352fa33e6b77200310edfdb96b2cd5a
chipy_org/libs/social_auth_pipelines.py
chipy_org/libs/social_auth_pipelines.py
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user=None, is_new=False, *args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" if not user: try: user = User.objects.filter(email=details.get('email')) except User.DoesNotExist: return social_auth_create_user(backend, details, response, uid, username, user=None, *args, **kwargs) else: if backend.name == 'google-oauth2': # We provide and exception here for users upgrading. return {'user': user} msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
Return the user in the pipeline if the backend is google oauth2
Return the user in the pipeline if the backend is google oauth2
Python
mit
bharathelangovan/chipy.org,brianray/chipy.org,chicagopython/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,brianray/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,agfor/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated + - def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, + def create_user(backend, details, response, uid, username, user=None, is_new=False, *args, **kwargs): - ''' - Check if a user with this email already exists. If they do, don't create an account. + """Check if a user with this email already exists. If they do, don't create an account.""" - ''' if not user: + try: - if User.objects.filter(email = details.get('email')).exists(): + user = User.objects.filter(email=details.get('email')) + except User.DoesNotExist: + return social_auth_create_user(backend, details, response, uid, username, user=None, + *args, **kwargs) + else: + if backend.name == 'google-oauth2': + # We provide and exception here for users upgrading. + return {'user': user} + - msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') + msg = ugettext('This email is already in use. First login with your other account and ' + 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) - else: - return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) - else: - return {}
Return the user in the pipeline if the backend is google oauth2
## Code Before: from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {} ## Instruction: Return the user in the pipeline if the backend is google oauth2 ## Code After: from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user=None, is_new=False, *args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" if not user: try: user = User.objects.filter(email=details.get('email')) except User.DoesNotExist: return social_auth_create_user(backend, details, response, uid, username, user=None, *args, **kwargs) else: if backend.name == 'google-oauth2': # We provide and exception here for users upgrading. return {'user': user} msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated + - def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, ? - - - - + def create_user(backend, details, response, uid, username, user=None, is_new=False, *args, **kwargs): - ''' - Check if a user with this email already exists. If they do, don't create an account. + """Check if a user with this email already exists. If they do, don't create an account.""" ? +++ +++ - ''' if not user: + try: - if User.objects.filter(email = details.get('email')).exists(): ? ^^ - - ---------- + user = User.objects.filter(email=details.get('email')) ? ^^^^^^^^^^ + except User.DoesNotExist: + return social_auth_create_user(backend, details, response, uid, username, user=None, + *args, **kwargs) + else: + if backend.name == 'google-oauth2': + # We provide and exception here for users upgrading. + return {'user': user} + - msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') ? ------------------------------------------- - + msg = ugettext('This email is already in use. First login with your other account and ' + 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) - else: - return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) - else: - return {}
a253eac5e4d7319a7a31dc33c90ce60fe77dfe60
bin/commands/upstream.py
bin/commands/upstream.py
"""Get the current upstream branch.""" import re from subprocess import check_output def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_info = check_output(['git', 'status', '--porcelain', '--branch']).splitlines()[0] regex = '^##\s[-_a-zA-Z0-9]+\.{3}([-_a-zA-Z0-9]+/([-_a-zA-Z0-9]+))(?:\s\[.*\])?$' match = re.match(regex, branch_info) upstream_info = '' if match is not None: upstream_info = match.group(1) if include_remote else match.group(2) return upstream_info
"""Get the current upstream branch.""" import re from subprocess import check_output, PIPE, Popen _MERGE_CONFIG = 'git config --local branch.{}.merge' _REMOTE_CONFIG = 'git config --local branch.{}.remote' def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_name = check_output('git rev-parse --abbrev-ref HEAD'.split()).splitlines()[0] # get remote branch name proc = Popen(_MERGE_CONFIG.format(branch_name).split(), stdout=PIPE) upstream_info = proc.communicate()[0].strip() upstream_info = upstream_info.rsplit('/', 1)[-1] # optionally, get remote name if upstream_info and include_remote: remote_name = check_output(_REMOTE_CONFIG.format(branch_name).split()).strip() upstream_info = remote_name + '/' + upstream_info return upstream_info
Refactor how remote info is retrieved
Refactor how remote info is retrieved The old way of retrieving remote information was to parse `git status`. This was brittle and lazy. Now the config values storing the remote information are used.
Python
mit
Brickstertwo/git-commands
"""Get the current upstream branch.""" import re - from subprocess import check_output + from subprocess import check_output, PIPE, Popen + _MERGE_CONFIG = 'git config --local branch.{}.merge' + _REMOTE_CONFIG = 'git config --local branch.{}.remote' def upstream(include_remote=False): """Get the upstream branch of the current branch.""" + branch_name = check_output('git rev-parse --abbrev-ref HEAD'.split()).splitlines()[0] - branch_info = check_output(['git', 'status', '--porcelain', '--branch']).splitlines()[0] - regex = '^##\s[-_a-zA-Z0-9]+\.{3}([-_a-zA-Z0-9]+/([-_a-zA-Z0-9]+))(?:\s\[.*\])?$' - match = re.match(regex, branch_info) - upstream_info = '' - if match is not None: - upstream_info = match.group(1) if include_remote else match.group(2) + # get remote branch name + proc = Popen(_MERGE_CONFIG.format(branch_name).split(), stdout=PIPE) + upstream_info = proc.communicate()[0].strip() + upstream_info = upstream_info.rsplit('/', 1)[-1] + + # optionally, get remote name + if upstream_info and include_remote: + remote_name = check_output(_REMOTE_CONFIG.format(branch_name).split()).strip() + upstream_info = remote_name + '/' + upstream_info return upstream_info
Refactor how remote info is retrieved
## Code Before: """Get the current upstream branch.""" import re from subprocess import check_output def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_info = check_output(['git', 'status', '--porcelain', '--branch']).splitlines()[0] regex = '^##\s[-_a-zA-Z0-9]+\.{3}([-_a-zA-Z0-9]+/([-_a-zA-Z0-9]+))(?:\s\[.*\])?$' match = re.match(regex, branch_info) upstream_info = '' if match is not None: upstream_info = match.group(1) if include_remote else match.group(2) return upstream_info ## Instruction: Refactor how remote info is retrieved ## Code After: """Get the current upstream branch.""" import re from subprocess import check_output, PIPE, Popen _MERGE_CONFIG = 'git config --local branch.{}.merge' _REMOTE_CONFIG = 'git config --local branch.{}.remote' def upstream(include_remote=False): """Get the upstream branch of the current branch.""" branch_name = check_output('git rev-parse --abbrev-ref HEAD'.split()).splitlines()[0] # get remote branch name proc = Popen(_MERGE_CONFIG.format(branch_name).split(), stdout=PIPE) upstream_info = proc.communicate()[0].strip() upstream_info = upstream_info.rsplit('/', 1)[-1] # optionally, get remote name if upstream_info and include_remote: remote_name = check_output(_REMOTE_CONFIG.format(branch_name).split()).strip() upstream_info = remote_name + '/' + upstream_info return upstream_info
"""Get the current upstream branch.""" import re - from subprocess import check_output + from subprocess import check_output, PIPE, Popen ? +++++++++++++ + _MERGE_CONFIG = 'git config --local branch.{}.merge' + _REMOTE_CONFIG = 'git config --local branch.{}.remote' def upstream(include_remote=False): """Get the upstream branch of the current branch.""" + branch_name = check_output('git rev-parse --abbrev-ref HEAD'.split()).splitlines()[0] - branch_info = check_output(['git', 'status', '--porcelain', '--branch']).splitlines()[0] - regex = '^##\s[-_a-zA-Z0-9]+\.{3}([-_a-zA-Z0-9]+/([-_a-zA-Z0-9]+))(?:\s\[.*\])?$' - match = re.match(regex, branch_info) - upstream_info = '' - if match is not None: - upstream_info = match.group(1) if include_remote else match.group(2) + # get remote branch name + proc = Popen(_MERGE_CONFIG.format(branch_name).split(), stdout=PIPE) + upstream_info = proc.communicate()[0].strip() + upstream_info = upstream_info.rsplit('/', 1)[-1] + + # optionally, get remote name + if upstream_info and include_remote: + remote_name = check_output(_REMOTE_CONFIG.format(branch_name).split()).strip() + upstream_info = remote_name + '/' + upstream_info return upstream_info