hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
13fab967f49271f788e255566aba622930033758
diff --git a/bundle/bundle.go b/bundle/bundle.go index <HASH>..<HASH> 100644 --- a/bundle/bundle.go +++ b/bundle/bundle.go @@ -387,7 +387,9 @@ func insertValue(b *Bundle, path string, value interface{}) error { // Remove leading / and . characters from the directory path. If the bundle // was written with OPA then the paths will contain a leading slash. On the // other hand, if the path is empty, filepath.Dir will return '.'. - dirpath := strings.TrimLeft(filepath.Dir(path), "/.") + // Note: filepath.Dir can return paths with '\' separators, always use + // filepath.ToSlash to keep them normalized. + dirpath := strings.TrimLeft(filepath.ToSlash(filepath.Dir(path)), "/.") var key []string if dirpath != "" { key = strings.Split(dirpath, "/")
bundle: Ensure data paths use `/` separators for key Turns out on windows the filepath.Dir() call will give back paths that are using `\` separators. This is problematic when we then go to split the path with `/` to get the key. We need to make sure they are always normalized to `/` separators. Fixes: #<I>
open-policy-agent_opa
train
3f6cbd95606771ac9f7b1c9247d2ca186cb72cb9
diff --git a/api/prometheus/v1/api.go b/api/prometheus/v1/api.go index <HASH>..<HASH> 100644 --- a/api/prometheus/v1/api.go +++ b/api/prometheus/v1/api.go @@ -538,8 +538,6 @@ func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time) (model. q.Set("time", ts.Format(time.RFC3339Nano)) } - u.RawQuery = q.Encode() - _, body, err := api.DoGetFallback(h.client, ctx, u, q) if err != nil { return nil, err
Remove encode of params in query before DoGetFallback (#<I>)
prometheus_client_golang
train
babf0afc14a08c8de8df5f172ca9eeacd63e1f0f
diff --git a/marshmallow_jsonschema/base.py b/marshmallow_jsonschema/base.py index <HASH>..<HASH> 100644 --- a/marshmallow_jsonschema/base.py +++ b/marshmallow_jsonschema/base.py @@ -85,6 +85,7 @@ MARSHMALLOW_TO_PY_TYPES_PAIRS = [ (fields.Url, str), (fields.List, list), (fields.Number, decimal.Decimal), + (fields.IP, str), # This one is here just for completeness sake and to check for # unknown marshmallow fields more cleanly. (fields.Nested, dict),
Added fields.IP marshmallow field type to python types mapping
fuhrysteve_marshmallow-jsonschema
train
1ec0abc61c6d022c6ab4b34cc527d330042d473b
diff --git a/captcha/audio.py b/captcha/audio.py index <HASH>..<HASH> 100644 --- a/captcha/audio.py +++ b/captcha/audio.py @@ -14,6 +14,12 @@ import wave import struct import random +import sys +if sys.version_info[0] != 2: + import functools + reduce = functools.reduce + + __all__ = ['AudioCaptcha'] WAVE_SAMPLE_RATE = 8000 # HZ @@ -216,7 +222,7 @@ class AudioCaptcha(object): return voice def _noise_pick(self): - key = random.choice(self._cache.keys()) + key = random.choice(self.choices) voice = random.choice(self._cache[key]) voice = copy.copy(voice) voice.reverse() diff --git a/tests/test_audio.py b/tests/test_audio.py index <HASH>..<HASH> 100644 --- a/tests/test_audio.py +++ b/tests/test_audio.py @@ -6,4 +6,4 @@ from captcha.audio import AudioCaptcha def test_audio_generate(): captcha = AudioCaptcha() data = captcha.generate('1234') - assert bytearray('RIFF') in data + assert bytearray(b'RIFF') in data
AudioCaptcha works on Python 3 now
lepture_captcha
train
0dcd39a0421621d18d3174ca986b04a07ccd2a7c
diff --git a/servers/src/main/java/tachyon/worker/DataServer.java b/servers/src/main/java/tachyon/worker/DataServer.java index <HASH>..<HASH> 100644 --- a/servers/src/main/java/tachyon/worker/DataServer.java +++ b/servers/src/main/java/tachyon/worker/DataServer.java @@ -24,6 +24,7 @@ import tachyon.Constants; import tachyon.ServerConstants; import tachyon.conf.TachyonConf; import tachyon.util.CommonUtils; +import tachyon.util.NetworkUtils; /** * Defines how to interact with a server running the data protocol. @@ -32,12 +33,12 @@ public interface DataServer extends Closeable { class Factory { public static DataServer createDataServer(final InetSocketAddress dataAddress, - final BlocksLocker blockLocker, TachyonConf conf) { + final CoreWorker coreWorker, TachyonConf conf) { try { return CommonUtils.createNewClassInstance( conf.getClass(Constants.WORKER_DATA_SERVER, ServerConstants.WORKER_DATA_SERVER_CLASS), new Class[] { InetSocketAddress.class, BlocksLocker.class, TachyonConf.class }, - new Object[] { dataAddress, blockLocker, conf }); + new Object[] { dataAddress, coreWorker, conf }); } catch (Exception e) { throw Throwables.propagate(e); } diff --git a/servers/src/main/java/tachyon/worker/TachyonWorker.java b/servers/src/main/java/tachyon/worker/TachyonWorker.java index <HASH>..<HASH> 100644 --- a/servers/src/main/java/tachyon/worker/TachyonWorker.java +++ b/servers/src/main/java/tachyon/worker/TachyonWorker.java @@ -57,8 +57,14 @@ public class TachyonWorker { public TachyonWorker(TachyonConf tachyonConf) { mTachyonConf = tachyonConf; - mCoreWorker = new CoreWorker(); - mDataServer = DataServer.Factory.createDataServer(mTachyonConf, mCoreWorker); + mCoreWorker = new CoreWorker(tachyonConf); + + int dataServerPort = + tachyonConf.getInt(Constants.WORKER_DATA_PORT, Constants.DEFAULT_WORKER_DATA_SERVER_PORT); + InetSocketAddress dataServerAddress = + new InetSocketAddress(NetworkUtils.getLocalHostName(tachyonConf), dataServerPort); + mDataServer = DataServer.Factory.createDataServer(dataServerAddress, mCoreWorker, mTachyonConf); + mServiceHandler = new BlockWorkerServiceHandler(mCoreWorker); mThriftServerSocket = createThriftServerSocket(); mThriftPort = NetworkUtils.getPort(mThriftServerSocket);
Create data server with core worker instead of block locker.
Alluxio_alluxio
train
2093755a9e9e5f557787c965edefc092fa38095c
diff --git a/src/Validation/Validation.php b/src/Validation/Validation.php index <HASH>..<HASH> 100644 --- a/src/Validation/Validation.php +++ b/src/Validation/Validation.php @@ -1098,6 +1098,26 @@ class Validation } /** + * Check that the input value is an integer + * + * This method will accept strings that contain only integer data + * as well. + * + * @param string $value The value to check + * @return bool + */ + public static function isInteger($value) + { + if (!is_scalar($value) || is_float($value)) { + return false; + } + if (is_int($value)) { + return true; + } + return (bool)preg_match('/^-?[0-9]+$/', $value); + } + + /** * Converts an array representing a date or datetime into a ISO string. * The arrays are typically sent for validation from a form generated by * the CakePHP FormHelper. diff --git a/tests/TestCase/Validation/ValidationTest.php b/tests/TestCase/Validation/ValidationTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/Validation/ValidationTest.php +++ b/tests/TestCase/Validation/ValidationTest.php @@ -2564,4 +2564,24 @@ class ValidationTest extends TestCase $this->assertTrue(Validation::longitude('10.451526')); $this->assertFalse(Validation::longitude('-190.52236')); } + + /** + * Test is_integer + * + * @return void + */ + public function testIsInteger() + { + $this->assertTrue(Validation::isInteger(-10)); + $this->assertTrue(Validation::isInteger(0)); + $this->assertTrue(Validation::isInteger(10)); + $this->assertTrue(Validation::isInteger('-10')); + $this->assertTrue(Validation::isInteger('0')); + $this->assertTrue(Validation::isInteger('10')); + + $this->assertFalse(Validation::isInteger('2.5')); + $this->assertFalse(Validation::isInteger([])); + $this->assertFalse(Validation::isInteger(new \StdClass)); + $this->assertFalse(Validation::isInteger('2 bears')); + } }
Add validator for integers. Add more strict validation method for checking integers. Sometimes you need to be more specific than isNumeric. This method lets you only accept integers.
cakephp_cakephp
train
c695a8371a8cc55e6b1c93faf7bbf4205d8673f3
diff --git a/tests/vagrant/vagrant_boxes.py b/tests/vagrant/vagrant_boxes.py index <HASH>..<HASH> 100644 --- a/tests/vagrant/vagrant_boxes.py +++ b/tests/vagrant/vagrant_boxes.py @@ -47,8 +47,9 @@ def run_box(options, vagrantfile, cmds, guiproc): with fabric.Connection( v.user_hostname_port(), connect_kwargs={"key_filename": v.keyfile(),}, ) as conn: - with conn.cd("/vagrant"): - cmds = ["env | sort"] + cmds + with conn.cd("c:/vagrant" if options.win else "/vagrant"): + if not options.win: + cmds = ["env | sort"] + cmds if guiproc: pid = None while not pid: @@ -128,6 +129,7 @@ def main(boxes="all", fast=False, destroy=False): boxes = boxes.split(",") for k, v in config.items(): if k in boxes: + options.win = k == "win" print("-----> %s %s %s" % (k, v[0], v[1])) run_box(options, v[0], v[1], v[2])
test: set directory and commands for win
ponty_pyscreenshot
train
3107102b4dcc2e0feae84fc97c336b4d1775ddab
diff --git a/resources.py b/resources.py index <HASH>..<HASH> 100644 --- a/resources.py +++ b/resources.py @@ -17,6 +17,12 @@ class _RI(object): (self._scheme, self._auth, self._hostname, self._port, self._path, self._querystr, self._fragment) = wkz_urls._uri_split(ri) + def __copy__(self): + return type(self)(ri, self.encoding, self.query_cls) + + def __repr__(self): + return "%s(%r, encoding='idna')" % (self.__class__.__name__, str(self)) + def replace(self, attribute, value): attributes = ('auth', 'scheme', 'hostname', 'port', 'path', 'fragment') return type(self)(ri, self.encoding, self.query_cls) @@ -88,15 +94,9 @@ class _RI(object): ':' + self.port if self.port else '' ) - def __copy__(self): - return type(self)(ri, self.encoding, self.query_cls) - - def __repr__(self): - return "%s(%r, encoding='idna')" % (self.__class__.__name__, str(self)) - def _unsplit(self): return urlparse.urlunsplit(( - self.scheme, self.hostname, + self.scheme, self.netloc, self.path, self.querystr, self.fragment )) diff --git a/tests/test_iri.py b/tests/test_iri.py index <HASH>..<HASH> 100644 --- a/tests/test_iri.py +++ b/tests/test_iri.py @@ -11,7 +11,7 @@ class TestIRISnowman(unittest.TestCase): iri = IRI("http://u:p@www.\N{SNOWMAN}:80/path") def test_repr(self): - expect = "IRI(u'http://u:p@www.\\u2603:80/path')" + expect = "IRI('http://u:p@www.xn--n3h:80/path', encoding='idna')" expect = expect.encode('ascii') self.assertEquals(repr(self.iri), expect) diff --git a/tests/test_uri.py b/tests/test_uri.py index <HASH>..<HASH> 100644 --- a/tests/test_uri.py +++ b/tests/test_uri.py @@ -10,7 +10,7 @@ class TestURISnowman(unittest.TestCase): u"\N{SNOWMAN}".encode('idna')) def test_repr(self): - expect = "URI('http://u:p@www.xn--n3h/path', encoding='idna')".encode('ascii') + expect = "URI('http://u:p@www.xn--n3h:80/path', encoding='idna')".encode('ascii') self.assertEquals(repr(self.uri), expect) def test_netloc(self):
add netloc to _unsplit. fix tests.
core_uricore
train
82cef1a0c6324d6f5f5485e1de152db1be93f32f
diff --git a/clients/ts/FunctionalTests/scripts/karma.local.conf.js b/clients/ts/FunctionalTests/scripts/karma.local.conf.js index <HASH>..<HASH> 100644 --- a/clients/ts/FunctionalTests/scripts/karma.local.conf.js +++ b/clients/ts/FunctionalTests/scripts/karma.local.conf.js @@ -40,7 +40,7 @@ try { } // We use the launchers themselves to figure out if the browser exists. It's a bit sneaky, but it works. - tryAddBrowser("ChromeHeadless", new ChromeHeadlessBrowser(() => { }, {})); + tryAddBrowser("ChromeHeadlessNoSandbox", new ChromeHeadlessBrowser(() => { }, {})); tryAddBrowser("ChromiumHeadless", new ChromiumHeadlessBrowser(() => { }, {})); tryAddBrowser("FirefoxHeadless", new FirefoxHeadlessBrowser(0, () => { }, {})); @@ -53,6 +53,12 @@ try { module.exports = createKarmaConfig({ browsers, + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: ['--no-sandbox'] + } + } }); } catch (e) { console.error(e);
fix chrome headless when root by adding --no-sandbox (#<I>)
aspnet_SignalR
train
bc633899170990ac20b390bcab59e88a571d8d7f
diff --git a/__init__.py b/__init__.py index <HASH>..<HASH> 100644 --- a/__init__.py +++ b/__init__.py @@ -219,7 +219,7 @@ class Firefox: glob.glob(os.path.join(os.environ.get('PROGRAMFILES(X86)', ''), 'Mozilla Firefox/profile/cookies.sqlite')) or \ glob.glob(os.path.join(os.environ.get('APPDATA', ''), - 'Mozilla/Firefox/Profiles/*.default/cookies.sqlite')) + 'Mozilla/Firefox/Profiles/*.default*/cookies.sqlite')) else: raise BrowserCookieError('Unsupported operating system: ' + sys.platform) if cookie_files:
Fix Firefox win<I> folder naming conventions .default may be followed by additional characters. This correctly locates profile folder.
borisbabic_browser_cookie3
train
5372b44d3543358b2090b6911a4f1c790aa68c94
diff --git a/clustergrammer/initialize_net.py b/clustergrammer/initialize_net.py index <HASH>..<HASH> 100644 --- a/clustergrammer/initialize_net.py +++ b/clustergrammer/initialize_net.py @@ -19,6 +19,7 @@ def main(self): self.viz['row_nodes'] = [] self.viz['col_nodes'] = [] self.viz['links'] = [] + self.viz['mat'] = [] self.sim = {} @@ -27,4 +28,5 @@ def viz(self): self.viz = {} self.viz['row_nodes'] = [] self.viz['col_nodes'] = [] - self.viz['links'] = [] \ No newline at end of file + self.viz['links'] = [] + self.viz['mat'] = [] \ No newline at end of file
added mat initialization to self.viz
MaayanLab_clustergrammer-py
train
53ae390f442e745503745e5fa8ed7b06b72fd102
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index <HASH>..<HASH> 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -175,7 +175,7 @@ Groupby/Resample/Rolling - Bug in ``DataFrame.resample(...).size()`` where an empty ``DataFrame`` did not return a ``Series`` (:issue:`14962`) - Bug in :func:`infer_freq` causing indices with 2-day gaps during the working week to be wrongly inferred as business daily (:issue:`16624`) - Bug in ``.rolling(...).quantile()`` which incorrectly used different defaults than :func:`Series.quantile()` and :func:`DataFrame.quantile()` (:issue:`9413`, :issue:`16211`) - +- Bug in ``groupby.transform()`` that would coerce boolean dtypes back to float (:issue:`16875`) Sparse ^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index <HASH>..<HASH> 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -110,9 +110,7 @@ def maybe_downcast_to_dtype(result, dtype): np.prod(result.shape)): return result - if issubclass(dtype.type, np.floating): - return result.astype(dtype) - elif is_bool_dtype(dtype) or is_integer_dtype(dtype): + if is_bool_dtype(dtype) or is_integer_dtype(dtype): # if we don't have any elements, just astype it if not np.prod(result.shape): @@ -144,6 +142,9 @@ def maybe_downcast_to_dtype(result, dtype): # hit here if (new_result == result).all(): return new_result + elif (issubclass(dtype.type, np.floating) and + not is_bool_dtype(result.dtype)): + return result.astype(dtype) # a datetimelike # GH12821, iNaT is casted to float diff --git a/pandas/tests/dtypes/test_cast.py b/pandas/tests/dtypes/test_cast.py index <HASH>..<HASH> 100644 --- a/pandas/tests/dtypes/test_cast.py +++ b/pandas/tests/dtypes/test_cast.py @@ -9,7 +9,7 @@ import pytest from datetime import datetime, timedelta, date import numpy as np -from pandas import Timedelta, Timestamp, DatetimeIndex, DataFrame, NaT +from pandas import Timedelta, Timestamp, DatetimeIndex, DataFrame, NaT, Series from pandas.core.dtypes.cast import ( maybe_downcast_to_dtype, @@ -45,6 +45,12 @@ class TestMaybeDowncast(object): expected = np.array([8, 8, 8, 8, 9]) assert (np.array_equal(result, expected)) + # GH16875 coercing of bools + ser = Series([True, True, False]) + result = maybe_downcast_to_dtype(ser, np.dtype(np.float64)) + expected = ser + tm.assert_series_equal(result, expected) + # conversions expected = np.array([1, 2]) diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index <HASH>..<HASH> 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -195,6 +195,19 @@ class TestGroupBy(MixIn): expected = Series(np.arange(5, 0, step=-1), name='B') assert_series_equal(result, expected) + def test_transform_numeric_to_boolean(self): + # GH 16875 + # inconsistency in transforming boolean values + expected = pd.Series([True, True], name='A') + + df = pd.DataFrame({'A': [1.1, 2.2], 'B': [1, 2]}) + result = df.groupby('B').A.transform(lambda x: True) + assert_series_equal(result, expected) + + df = pd.DataFrame({'A': [1, 2], 'B': [1, 2]}) + result = df.groupby('B').A.transform(lambda x: True) + assert_series_equal(result, expected) + def test_transform_datetime_to_timedelta(self): # GH 15429 # transforming a datetime to timedelta
BUG: coercing of bools in groupby transform (#<I>)
pandas-dev_pandas
train
177833c81cf0422891e3f928febf759e01c993f8
diff --git a/src/DocumentBinder.php b/src/DocumentBinder.php index <HASH>..<HASH> 100644 --- a/src/DocumentBinder.php +++ b/src/DocumentBinder.php @@ -1,8 +1,10 @@ <?php namespace Gt\DomTemplate; +use Gt\Dom\Attr; use Gt\Dom\Document; use Gt\Dom\Element; +use Gt\Dom\XPathResult; use Iterator; use ReflectionObject; @@ -126,6 +128,16 @@ class DocumentBinder { ); } + public function cleanBindAttributes():void { + $xpathResult = $this->document->evaluate( + "//*/@*[starts-with(name(), 'data-bind')] | //*/@*[starts-with(name(), 'data-template')]" + ); + foreach($xpathResult as $item) { + /** @var Attr $item */ + $item->ownerElement->removeAttribute($item->name); + } + } + private function bind( ?string $key, mixed $value, diff --git a/test/phpunit/DocumentBinderTest.php b/test/phpunit/DocumentBinderTest.php index <HASH>..<HASH> 100644 --- a/test/phpunit/DocumentBinderTest.php +++ b/test/phpunit/DocumentBinderTest.php @@ -706,4 +706,44 @@ class DocumentBinderTest extends TestCase { self::assertEquals($profitValue, $li->querySelector(".profit span")->textContent); } } + + public function testCleanBindAttributes_dataBind():void { + $document = DocumentTestFactory::createHTML(DocumentTestFactory::HTML_USER_PROFILE); + $sut = new DocumentBinder($document); + $sut->bindData([ + "username" => "codyboy123", + "email" => "codyboy@g105b.com", + "category" => "cat", + ]); + $sut->cleanBindAttributes(); + + foreach($document->querySelectorAll("dd") as $dd) { + self::assertCount(1, $dd->attributes); + } + + self::assertStringNotContainsString( + "data-bind:text", + $document->documentElement->innerHTML + ); + } + + public function testCleanBindAttributes_dataTemplate():void { + $document = DocumentTestFactory::createHTML(DocumentTestFactory::HTML_LIST_TEMPLATE); + $sut = new DocumentBinder($document); + $sut->bindList(["One", "Two", "Three", "Four"]); + $sut->cleanBindAttributes(); + + foreach($document->querySelectorAll("ul>li") as $li) { + self::assertCount(0, $li->attributes); + } + + self::assertStringNotContainsString( + "data-bind:text", + $document->documentElement->innerHTML + ); + self::assertStringNotContainsString( + "data-template", + $document->documentElement->innerHTML + ); + } } diff --git a/test/phpunit/TestFactory/DocumentTestFactory.php b/test/phpunit/TestFactory/DocumentTestFactory.php index <HASH>..<HASH> 100644 --- a/test/phpunit/TestFactory/DocumentTestFactory.php +++ b/test/phpunit/TestFactory/DocumentTestFactory.php @@ -183,7 +183,7 @@ HTML; <li data-template data-bind:text>Template item!</li> </ul> <ol> - <li>This doesn't have a data-template attribute</li> + <li>This doesn't have a data template attribute</li> </ol> HTML;
Clean data attributes (#<I>) * build: upgrade to stable dom release * test: bind objects in arrays with bindList * wip: complex test for #<I> * feature: bindListCallback allows callback to be called for each list item closes #<I> * feature: expose and test callback functions closes #<I> * feature: clean data-bind attributes closes #<I>
PhpGt_DomTemplate
train
c9d2cbbc0a3fc06b5b37c14b37d5a9047f82317a
diff --git a/syntax/lexer.go b/syntax/lexer.go index <HASH>..<HASH> 100644 --- a/syntax/lexer.go +++ b/syntax/lexer.go @@ -627,18 +627,10 @@ loop: if p.quote&allArithmExpr != 0 { break loop } - if byteAt(p.src, p.npos+1) == '(' { - tok = _Lit - break loop - } case ':', '=', '%', '?', '^', ',': if p.quote&allArithmExpr != 0 || p.quote&allParamReg != 0 { break loop } - if r == '?' && byteAt(p.src, p.npos+1) == '(' { - tok = _Lit - break loop - } case '#', '[': if p.quote&allParamReg != 0 { break loop @@ -650,15 +642,6 @@ loop: default: break loop } - if r == '+' && byteAt(p.src, p.npos+1) == '(' { - tok = _Lit - break loop - } - case '@': - if byteAt(p.src, p.npos+1) == '(' { - tok = _Lit - break loop - } case ' ', '\t', ';', '&', '>', '<', '|', '(', ')', '\r': switch p.quote { case paramExpExp, paramExpRepl, sglQuotes: diff --git a/syntax/parser.go b/syntax/parser.go index <HASH>..<HASH> 100644 --- a/syntax/parser.go +++ b/syntax/parser.go @@ -622,7 +622,11 @@ func (p *parser) wordPart() WordPart { p.rune() p.tok, p.val = _Lit, string(r) default: - p.advanceLitOther(r) + if p.quote&allRegTokens != 0 { + p.advanceLitNone(r) + } else { + p.advanceLitOther(r) + } } pe.Param = p.getLit() return pe diff --git a/syntax/parser_test.go b/syntax/parser_test.go index <HASH>..<HASH> 100644 --- a/syntax/parser_test.go +++ b/syntax/parser_test.go @@ -904,6 +904,10 @@ var bashTests = []errorCase{ `1:6: reached EOF without matching @( with )`, }, { + "((@(", + `1:1: reached EOF without matching (( with ))`, + }, + { "coproc", `1:1: coproc clause requires a command`, },
syntax: don't allow extglob inside extensions This gets messy, such as the added test case which used to hang. Also means we don't have to scatter the logic across p.advanceLitOther.
mvdan_sh
train
cef2baa3bcac931ec6911a687395a2c25ade81c7
diff --git a/bin/coderunner.json b/bin/coderunner.json index <HASH>..<HASH> 100644 --- a/bin/coderunner.json +++ b/bin/coderunner.json @@ -1,5 +1,5 @@ { - "managementHttpPort": 2992, + "managementHttpPort": null, "workers": { "cache": { "limit": 20 @@ -33,4 +33,4 @@ }, "sandbox": true, "verbose": false -} \ No newline at end of file +} diff --git a/lib/cli/consul.json b/lib/cli/consul.json index <HASH>..<HASH> 100644 --- a/lib/cli/consul.json +++ b/lib/cli/consul.json @@ -3,7 +3,16 @@ "msgBroker": { "host": "config/redis/bl/production/host", "port": "config/redis/bl/production/port", - "password": "config/redis/bl/production/password" + "password": "config/redis/bl/production/password", + "tls": { + "ca": "config/redis/bl/production/tls/ca", + "cert": "config/redis/bl/production/tls/cert", + "key": "config/redis/bl/production/tls/key", + "caFile": "config/redis/bl/production/tls/caFile", + "certFile": "config/redis/bl/production/tls/certFile", + "keyFile": "config/redis/bl/production/tls/keyFile", + "passphrase": "config/redis/bl/production/tls/passphrase" + } } } -} \ No newline at end of file +} diff --git a/lib/cli/options.js b/lib/cli/options.js index <HASH>..<HASH> 100644 --- a/lib/cli/options.js +++ b/lib/cli/options.js @@ -18,6 +18,8 @@ module.exports = async function getRunOptions(appRequired, repoPathRequired) { ensureApiUrl(options) + ensureRedisTLS(options) + return options } @@ -59,6 +61,27 @@ function ensureApiUrl(options) { } } +function ensureRedisTLS(options) { + const redisTls = options.backendless.msgBroker && options.backendless.msgBroker.tls + + if (!redisTls) { + return + } + + const fs = require('fs') + + if (redisTls.certFile) { + redisTls.cert = fs.readFileSync(redisTls.certFile, 'utf8') + } + + if (redisTls.keyFile) { + redisTls.key = fs.readFileSync(redisTls.keyFile, 'utf8') + } + + if (redisTls.caFile) { + redisTls.ca = fs.readFileSync(redisTls.caFile, 'utf8') + } +} diff --git a/lib/server-code/runners/cloud-master.js b/lib/server-code/runners/cloud-master.js index <HASH>..<HASH> 100644 --- a/lib/server-code/runners/cloud-master.js +++ b/lib/server-code/runners/cloud-master.js @@ -13,7 +13,7 @@ const SERVICE_QUEUE_P_CR_EVENT = 'SERVICE_QUEUE_P_CR' const CLEANUP_CODE_ALL_COMMAND = 'cleanup_code_all' module.exports = async function runMaster(opts) { - logger.info('Starting Backendless Cloud Code Runner for JS') + logger.info(`Starting Backendless ${opts.label || 'Cloud'} Code Runner for JS`) logger.info(`Backendless Repository Path is set to [${opts.backendless.repoPath}]`) const lowPriorityThreshold = opts.workers.lowPriorityThreshold @@ -96,4 +96,4 @@ module.exports = async function runMaster(opts) { process.exit(1) } -} \ No newline at end of file +} diff --git a/lib/server-code/runners/pro.js b/lib/server-code/runners/pro.js index <HASH>..<HASH> 100644 --- a/lib/server-code/runners/pro.js +++ b/lib/server-code/runners/pro.js @@ -2,4 +2,4 @@ const cloud = require('./cloud') -module.exports = opts => cloud(Object.assign(opts, { sandbox: false })) \ No newline at end of file +module.exports = opts => cloud(Object.assign(opts, { sandbox: false, label: 'Pro' })) diff --git a/lib/server-code/services/management-server.js b/lib/server-code/services/management-server.js index <HASH>..<HASH> 100644 --- a/lib/server-code/services/management-server.js +++ b/lib/server-code/services/management-server.js @@ -40,6 +40,8 @@ exports.start = function startManagementServer(port, workersBroker) { server.on('error', onError) + logger.info(`Starting Management Server on port:${port}....`) + server.listen(port, error => { if (error) { onError(error) diff --git a/lib/server-code/services/messages-broker.js b/lib/server-code/services/messages-broker.js index <HASH>..<HASH> 100644 --- a/lib/server-code/services/messages-broker.js +++ b/lib/server-code/services/messages-broker.js @@ -24,6 +24,10 @@ class MessagesBroker extends EventEmitter { createClient(name, isMainClient) { return new Promise(resolve => { + if (isMainClient) { + logger.info('Connection to Redis...') + } + const client = this[name] = new Redis(Object.assign({}, this.connectionInfo, { retryStrategy: times => { const nextReconnectionDelay = Math.min(times * 500, 5000)
- add an ability to use TLS options for Redis - disable Management Server by default
Backendless_JS-Code-Runner
train
a7c8cb52f39cda8e8cd12e65b2d6848515f768d2
diff --git a/src/Model/Common/AbstractJsonDeserializeObject.php b/src/Model/Common/AbstractJsonDeserializeObject.php index <HASH>..<HASH> 100644 --- a/src/Model/Common/AbstractJsonDeserializeObject.php +++ b/src/Model/Common/AbstractJsonDeserializeObject.php @@ -66,6 +66,17 @@ abstract class AbstractJsonDeserializeObject implements JsonDeserializeInterface return static::$primitives[$type]; } + protected function isValidType($type, $value) + { + if (!is_string($type)) { + return true; + } + if (is_null($value)) { + return true; + } + return $this->isType($type, $value); + } + /** * @param string $type * @param mixed $value @@ -144,6 +155,16 @@ abstract class AbstractJsonDeserializeObject implements JsonDeserializeInterface } /** + * @param array $data + * @param Context|callable $context + * @return static + */ + public static function fromArray(array $data, $context = null) + { + return new static($data, $context); + } + + /** * @return static */ public static function of() diff --git a/src/Model/Common/Collection.php b/src/Model/Common/Collection.php index <HASH>..<HASH> 100644 --- a/src/Model/Common/Collection.php +++ b/src/Model/Common/Collection.php @@ -39,16 +39,6 @@ class Collection extends AbstractJsonDeserializeObject implements \Iterator, \Js } /** - * @param array $data - * @param Context|callable $context - * @return static - */ - public static function fromArray(array $data, $context = null) - { - return new static($data, $context); - } - - /** * @return string */ public function getType() @@ -156,7 +146,7 @@ class Collection extends AbstractJsonDeserializeObject implements \Iterator, \Js public function setAt($offset, $object) { $type = $this->getType(); - if (!is_null($type) && !is_null($object) && !$this->isType($type, $object)) { + if (!$this->isValidType($type, $object)) { throw new \InvalidArgumentException(sprintf(Message::WRONG_TYPE, $offset, $type)); } if ($this->hasInterface(get_class($object))) { diff --git a/src/Model/Common/JsonObject.php b/src/Model/Common/JsonObject.php index <HASH>..<HASH> 100644 --- a/src/Model/Common/JsonObject.php +++ b/src/Model/Common/JsonObject.php @@ -31,17 +31,6 @@ class JsonObject extends AbstractJsonDeserializeObject implements \JsonSerializa } /** - * @param array $data - * @param Context|callable $context - * @return static - */ - public static function fromArray(array $data, $context = null) - { - return new static($data, $context); - } - - - /** * @return array * @internal */ @@ -147,17 +136,6 @@ class JsonObject extends AbstractJsonDeserializeObject implements \JsonSerializa $this->initialized[$field] = true; } - protected function isValidType($type, $value) - { - if (!is_string($type)) { - return true; - } - if (is_null($value)) { - return true; - } - return $this->isType($type, $value); - } - protected function isOptional($field, $value) { return ($value === null && $this->getFieldKey($field, static::OPTIONAL) === false);
decompose collection type check and fromArray
commercetools_commercetools-php-sdk
train
f4ebf5a6c59f2f4960d3589a685c99cba3886a0a
diff --git a/decode_response.go b/decode_response.go index <HASH>..<HASH> 100644 --- a/decode_response.go +++ b/decode_response.go @@ -84,10 +84,6 @@ func (sp *SAMLServiceProvider) ValidateEncodedResponse(encodedResponse string) ( } response := doc.Root() - err = sp.validateResponseAttributes(response) - if err != nil { - return nil, err - } if !sp.SkipSignatureValidation { response, err = sp.validationContext().Validate(response) @@ -98,35 +94,36 @@ func (sp *SAMLServiceProvider) ValidateEncodedResponse(encodedResponse string) ( // Unfortunately we just blew away our Response response = doc.Root() - unverifiedAssertion, err := etreeutils.NSSelectOne(response, SAMLAssertionNamespace, AssertionTag) - if err != nil { - return nil, err - } - - if unverifiedAssertion == nil { - return nil, ErrMissingAssertion - } - - assertion, err := sp.validationContext().Validate(unverifiedAssertion) - if err != nil { - return nil, err - } - - // Because the top level response wasn't signed, we don't trust it - // or any of its children - except the signed assertions as returned - // by the signature validation. Make a copy of the response (to avoid mutating - // the original document) and strip all of its children, then re-add only - // the validated assertion. - // - // Note that we're leaving attributes of the Response in place. Since we're - // processing an unsigned Response they can't be trusted, but we'll validate - // them anyway. - response = response.Copy() - for _, el := range response.ChildElements() { - response.RemoveChild(el) - } - - response.AddChild(assertion) + etreeutils.NSFindIterate(response, SAMLAssertionNamespace, AssertionTag, + func(ctx etreeutils.NSContext, unverifiedAssertion *etree.Element) error { + // Skip any Assertion which isn't a child of the Response + if unverifiedAssertion.Parent() != response { + return nil + } + + detatched, err := etreeutils.NSDetatch(ctx, unverifiedAssertion) + if err != nil { + return err + } + + assertion, err := sp.validationContext().Validate(detatched) + if err != nil { + return err + } + + // Replace the original unverified Assertion with the verified one. Note that + // at this point only the Assertion (and not the parent Response) can be trusted + // as having been signed by the IdP. + if response.RemoveChild(unverifiedAssertion) == nil { + // Out of an abundance of caution, check to make sure an Assertion was actually + // removed. If it wasn't a programming error has occurred. + panic("unable to remove assertion") + } + + response.AddChild(assertion) + + return nil + }) } else if err != nil || response == nil { return nil, err } diff --git a/validate.go b/validate.go index <HASH>..<HASH> 100644 --- a/validate.go +++ b/validate.go @@ -125,7 +125,10 @@ func (sp *SAMLServiceProvider) VerifyAssertionConditions(assertionElement, condi //Validate ensures that the assertion passed is valid for the current Service //Provider. func (sp *SAMLServiceProvider) Validate(el *etree.Element) error { - el = el.Copy() + err := sp.validateResponseAttributes(el) + if err != nil { + return err + } assertionElement := el.FindElement(AssertionTag) if assertionElement == nil {
Add support for verifying the signature of multiple Assertions
russellhaering_gosaml2
train
6ceea921854a16a4f4d3d5c7f60ed6967dc2034e
diff --git a/lib/3scale/client.rb b/lib/3scale/client.rb index <HASH>..<HASH> 100644 --- a/lib/3scale/client.rb +++ b/lib/3scale/client.rb @@ -159,6 +159,9 @@ module ThreeScale # app_key:: secret key assigned to the application. Required only if application has # a key defined. # service_id:: id of the service (required if you have more than one service) + # usage:: predicted usage. It is optional. It is a hash where the keys are metrics + # and the values their predicted usage. + # Example: {'hits' => 1, 'my_metric' => 100} # # == Return # @@ -202,6 +205,9 @@ module ThreeScale # # app_id:: id of the application to authorize. This is required. # service_id:: id of the service (required if you have more than one service) + # usage:: predicted usage. It is optional. It is a hash where the keys are metrics + # and the values their predicted usage. + # Example: {'hits' => 1, 'my_metric' => 100} # # == Return #
client: add missing documentation for usage param in auth calls
3scale_3scale_ws_api_for_ruby
train
8f452ef8ef7cfd33f2abf0110e849b8bc2b49e4c
diff --git a/panflute/containers.py b/panflute/containers.py index <HASH>..<HASH> 100644 --- a/panflute/containers.py +++ b/panflute/containers.py @@ -152,9 +152,9 @@ def attach(element, parent, location): def to_json_wrapper(e): - if type(e) == str: + if isinstance(e, str): return e - elif type(e) == bool: + elif isinstance(e, bool): return encode_dict('MetaBool', e) else: return e.to_json() diff --git a/panflute/tools.py b/panflute/tools.py index <HASH>..<HASH> 100644 --- a/panflute/tools.py +++ b/panflute/tools.py @@ -435,5 +435,5 @@ def _replace_keyword(self, keyword, replacement, count=0): else: raise NotImplementedError(type(replacement)) -# Bound the method +# Bind the method Element.replace_keyword = _replace_keyword
Replace type() with isinstance()
sergiocorreia_panflute
train
4e2ee18e29ab885a58404f5a1fc4bf466a9b08b9
diff --git a/app/controllers/concerns/sms.rb b/app/controllers/concerns/sms.rb index <HASH>..<HASH> 100644 --- a/app/controllers/concerns/sms.rb +++ b/app/controllers/concerns/sms.rb @@ -10,6 +10,8 @@ module Sms # off recipient defaults the value to the current participant) # rubocop:disable Metrics/AbcSize def send_sms(recipient = current_user, message_body) + return if recipient.phone_number.blank? + logger.info("INFO BEFORE: SMS notification sent \ to:" + recipient.phone_number) if recipient.is_a?(Participant) diff --git a/app/controllers/social_networking/comments_controller.rb b/app/controllers/social_networking/comments_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/social_networking/comments_controller.rb +++ b/app/controllers/social_networking/comments_controller.rb @@ -31,22 +31,22 @@ module SocialNetworking # rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/CyclomaticComplexity def notify(recipient) - unless current_participant == recipient - case recipient.contact_preference - when "email" - send_notify_email(recipient, message_body) - when "sms" - if recipient.phone_number && !recipient.phone_number.blank? - send_sms(recipient, message_body) - end - when "phone" - if recipient.phone_number && !recipient.phone_number.blank? - send_sms(recipient, message_body) - end - else - logger.error "ERROR: contact preference is not set for \ - participant with ID: " + recipient.id.to_s + return if current_participant == recipient + + case recipient.contact_preference + when "email" + send_notify_email(recipient, message_body) + when "sms" + if recipient.phone_number && !recipient.phone_number.blank? + send_sms(recipient, message_body) end + when "phone" + if recipient.phone_number && !recipient.phone_number.blank? + send_sms(recipient, message_body) + end + else + logger.error "ERROR: contact preference is not set for \ +participant with ID: " + recipient.id.to_s end end # rubocop:enable Metrics/AbcSize diff --git a/app/controllers/social_networking/likes_controller.rb b/app/controllers/social_networking/likes_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/social_networking/likes_controller.rb +++ b/app/controllers/social_networking/likes_controller.rb @@ -52,23 +52,20 @@ module SocialNetworking # Determine the body of the notification and then send the notification # based on the contact preferences. def notify(recipient) - unless current_participant == recipient - message_body = [ - "Someone liked your post! \ - Log in (#{main_app.root_url}) to see who.", - "People like what you're doing! \ - Log in (#{main_app.root_url}) \ - to see what's happening!" - ].sample + return if current_participant == recipient - if "email" == recipient.contact_preference - send_notify_email(recipient, message_body) - elsif ("sms" == recipient.contact_preference || - "phone" == recipient.contact_preference) && - recipient.phone_number && - !recipient.phone_number.blank? - send_sms(recipient, message_body) - end + message_body = [ + "Someone liked your post! " \ + "Log in (#{main_app.root_url}) to see who.", + "People like what you're doing! " \ + "Log in (#{main_app.root_url}) " \ + "to see what's happening!" + ].sample + + if recipient.contact_preference == "email" + send_notify_email(recipient, message_body) + else + send_sms(recipient, message_body) end end diff --git a/spec/controllers/social_networking/comments_controller_spec.rb b/spec/controllers/social_networking/comments_controller_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/social_networking/comments_controller_spec.rb +++ b/spec/controllers/social_networking/comments_controller_spec.rb @@ -28,7 +28,8 @@ module SocialNetworking context "when the participant is authenticated" do before do allow(controller).to receive(:authenticate_participant!) - allow(controller).to receive(:current_participant) { participant_email } + allow(controller).to receive(:current_participant) + .and_return(participant_email) allow(Comment).to receive(:new).with( participant_id: participant.id, text: "I like cheeses",
refactored notification message logic
NU-CBITS_social_networking
train
025f7297fac62d7d4ad465fec983484a153ec78d
diff --git a/lib/capybara/rspec/matchers.rb b/lib/capybara/rspec/matchers.rb index <HASH>..<HASH> 100644 --- a/lib/capybara/rspec/matchers.rb +++ b/lib/capybara/rspec/matchers.rb @@ -27,7 +27,7 @@ module Capybara end def description - "has #{query.description}" + "have #{query.description}" end def wrap(actual) @@ -82,7 +82,7 @@ module Capybara end def description - "has #{selector_name}" + "have #{selector_name}" end def selector_name diff --git a/spec/rspec/matchers_spec.rb b/spec/rspec/matchers_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rspec/matchers_spec.rb +++ b/spec/rspec/matchers_spec.rb @@ -8,7 +8,7 @@ describe Capybara::RSpecMatchers do describe "have_css matcher" do it "gives proper description" do - have_css('h1').description.should == "has css \"h1\"" + have_css('h1').description.should == "have css \"h1\"" end context "on a string" do @@ -90,7 +90,7 @@ describe Capybara::RSpecMatchers do describe "have_xpath matcher" do it "gives proper description" do - have_xpath('//h1').description.should == "has xpath \"\/\/h1\"" + have_xpath('//h1').description.should == "have xpath \"\/\/h1\"" end context "on a string" do @@ -154,7 +154,7 @@ describe Capybara::RSpecMatchers do it "gives proper description" do matcher = have_selector('//h1') "<h1>Text</h1>".should matcher - matcher.description.should == "has xpath \"//h1\"" + matcher.description.should == "have xpath \"//h1\"" end context "on a string" do @@ -242,7 +242,7 @@ describe Capybara::RSpecMatchers do describe "have_content matcher" do it "gives proper description" do - have_content('Text').description.should == "has content \"Text\"" + have_content('Text').description.should == "have content \"Text\"" end context "on a string" do @@ -314,7 +314,7 @@ describe Capybara::RSpecMatchers do describe "have_text matcher" do it "gives proper description" do - have_text('Text').description.should == "has text \"Text\"" + have_text('Text').description.should == "have text \"Text\"" end context "on a string" do @@ -388,7 +388,7 @@ describe Capybara::RSpecMatchers do let(:html) { '<a href="#">Just a link</a>' } it "gives proper description" do - have_link('Just a link').description.should == "has link \"Just a link\"" + have_link('Just a link').description.should == "have link \"Just a link\"" end it "passes if there is such a button" do @@ -406,7 +406,7 @@ describe Capybara::RSpecMatchers do let(:html) { '<button>A button</button><input type="submit" value="Another button"/>' } it "gives proper description" do - have_button('A button').description.should == "has button \"A button\"" + have_button('A button').description.should == "have button \"A button\"" end it "passes if there is such a button" do @@ -424,7 +424,7 @@ describe Capybara::RSpecMatchers do let(:html) { '<p><label>Text field<input type="text"/></label></p>' } it "gives proper description" do - have_field('Text field').description.should == "has field \"Text field\"" + have_field('Text field').description.should == "have field \"Text field\"" end it "passes if there is such a field" do @@ -445,7 +445,7 @@ describe Capybara::RSpecMatchers do end it "gives proper description" do - have_checked_field('it is checked').description.should == "has checked_field \"it is checked\"" + have_checked_field('it is checked').description.should == "have checked_field \"it is checked\"" end context "with should" do @@ -490,7 +490,7 @@ describe Capybara::RSpecMatchers do end it "gives proper description" do - have_unchecked_field('unchecked field').description.should == "has unchecked_field \"unchecked field\"" + have_unchecked_field('unchecked field').description.should == "have unchecked_field \"unchecked field\"" end context "with should" do @@ -532,7 +532,7 @@ describe Capybara::RSpecMatchers do let(:html) { '<label>Select Box<select></select></label>' } it "gives proper description" do - have_select('Select Box').description.should == "has select \"Select Box\"" + have_select('Select Box').description.should == "have select \"Select Box\"" end it "passes if there is such a select" do @@ -550,7 +550,7 @@ describe Capybara::RSpecMatchers do let(:html) { '<table><caption>Lovely table</caption></table>' } it "gives proper description" do - have_table('Lovely table').description.should == "has table \"Lovely table\"" + have_table('Lovely table').description.should == "have table \"Lovely table\"" end it "passes if there is such a select" do
Change RSpec descriptions from should has to should have
teamcapybara_capybara
train
6a190b39a179d1d7578ea17c02ea17dc2281906b
diff --git a/src/test/java/org/joda/beans/gen/ImmPerson.java b/src/test/java/org/joda/beans/gen/ImmPerson.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/joda/beans/gen/ImmPerson.java +++ b/src/test/java/org/joda/beans/gen/ImmPerson.java @@ -70,9 +70,6 @@ public final class ImmPerson implements ImmutableBean { private final List<List<Address>> addressesList; @PropertyDefinition private final ImmAddress mainAddress; -// @PropertyDefinition -// @XmlID -// private final FlexiBean extensions; @DerivedProperty public int getAge() {
Add support for immutable beans - no FlexiBean support See #<I>
JodaOrg_joda-beans
train
fbe9c75be2fe5d5f8322391c8393983db721bd71
diff --git a/lib/middlewares/favicon.js b/lib/middlewares/favicon.js index <HASH>..<HASH> 100644 --- a/lib/middlewares/favicon.js +++ b/lib/middlewares/favicon.js @@ -6,7 +6,7 @@ var swintHelper = require('swint-helper'), defaultize = swintHelper.defaultize; module.exports = function(options) { - defaultize({ + options = defaultize({ iconPath: path.join(__dirname, 'favicon.png') }, options); diff --git a/lib/middlewares/session.js b/lib/middlewares/session.js index <HASH>..<HASH> 100644 --- a/lib/middlewares/session.js +++ b/lib/middlewares/session.js @@ -6,7 +6,7 @@ var swintHelper = require('swint-helper'), defaultize = swintHelper.defaultize; module.exports = function(options) { - defaultize({ + options = defaultize({ mode: 'cookie', secret: 'SwintIsForTwins', cookie: {
Favicon doesn't need mandatory options
Knowre-Dev_swint-middleware
train
86e7c18c07d7e37613e2b5b56a52a32d0540321f
diff --git a/src/ScnSocialAuth/Authentication/Adapter/HybridAuth.php b/src/ScnSocialAuth/Authentication/Adapter/HybridAuth.php index <HASH>..<HASH> 100644 --- a/src/ScnSocialAuth/Authentication/Adapter/HybridAuth.php +++ b/src/ScnSocialAuth/Authentication/Adapter/HybridAuth.php @@ -124,6 +124,20 @@ class HybridAuth extends AbstractAdapter implements ServiceManagerAwareInterface $this->getMapper()->insert($localUserProvider); } + $zfcUserOptions = $this->getZfcUserOptions(); + + if ($zfcUserOptions->getEnableUserState()) { + // Don't allow user to login if state is not in allowed list + $mapper = $this->getZfcUserMapper(); + $user = $mapper->findById($localUserProvider->getUserId()); + if (!in_array($user->getState(), $zfcUserOptions->getAllowedLoginStates())) { + $authEvent->setCode(Result::FAILURE_UNCATEGORIZED) + ->setMessages(array('A record with the supplied identity is not active.')); + $this->setSatisfied(false); + return false; + } + } + $authEvent->setIdentity($localUserProvider->getUserId()); $this->setSatisfied(true);
Check for allowed user state if enabled.
SocalNick_ScnSocialAuth
train
a91f89790144d700dde8f8ddcbd08ab79cac71af
diff --git a/app/app.js b/app/app.js index <HASH>..<HASH> 100644 --- a/app/app.js +++ b/app/app.js @@ -24,7 +24,7 @@ window.onerror = function(errorMsg, url, lineNumber, colno, error) { if (error && error.stack) { errorMessage += "; stack:"+error.stack; } - console.log("Error: "+errorMessage); + console.log("UNCAUGHT ERROR IN APPLICATION: "+errorMessage); }; export default App;
Updated logging on uncaught errors
HospitalRun_hospitalrun-frontend
train
b06c026a7208a14fe6dfe1e15af24cbab134b341
diff --git a/log.go b/log.go index <HASH>..<HASH> 100644 --- a/log.go +++ b/log.go @@ -57,7 +57,7 @@ var ( INFO: "[INFO] ", DEBUG: "[DEBUG] ", } - escapeNewlines bool = true + escapeNewlines bool = false postFix = "" //\033[0m LogLevelWords map[string]int = map[string]int{"fatal": 0, "error": 1, "warn": 2, "info": 3, "debug": 4, "none": -1} logThrottles = make(map[string]*Throttler) @@ -93,6 +93,11 @@ func SetColorOutput() { postFix = "\033[0m" } +//Set whether to escape newline characters in log messages +func EscapeNewlines(en bool) { + escapeNewlines = en +} + // Setup default log output to go to a dev/null // // log.SetOutput(new(DevNull))
Defaulting to not escaping newlines to not change standard behavior Escaping newlines is necessary for keeping log messages consolidated via the Docker stdout logging system. EscapeNewlines(bool) can be called to set the variable.
araddon_gou
train
1bd146ed82f771395f991851f7d896d9ae778f3c
diff --git a/integration/exec_test.go b/integration/exec_test.go index <HASH>..<HASH> 100644 --- a/integration/exec_test.go +++ b/integration/exec_test.go @@ -67,7 +67,7 @@ func TestIPCPrivate(t *testing.T) { } if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual == l { - t.Fatalf("ipc link should be private to the conatiner but equals host %q %q", actual, l) + t.Fatalf("ipc link should be private to the container but equals host %q %q", actual, l) } } @@ -152,7 +152,7 @@ func TestIPCBadPath(t *testing.T) { _, _, err = runContainer(config, "", "true") if err == nil { - t.Fatal("container succeded with bad ipc path") + t.Fatal("container succeeded with bad ipc path") } } @@ -176,3 +176,34 @@ func TestRlimit(t *testing.T) { t.Fatalf("expected rlimit to be 1024, got %s", limit) } } + +func TestPIDNSPrivate(t *testing.T) { + if testing.Short() { + return + } + + rootfs, err := newRootFs() + if err != nil { + t.Fatal(err) + } + defer remove(rootfs) + + l, err := os.Readlink("/proc/1/ns/pid") + if err != nil { + t.Fatal(err) + } + + config := newTemplateConfig(rootfs) + buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/pid") + if err != nil { + t.Fatal(err) + } + + if exitCode != 0 { + t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) + } + + if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual == l { + t.Fatalf("pid link should be private to the container but equals host %q %q", actual, l) + } +} diff --git a/namespaces/exec.go b/namespaces/exec.go index <HASH>..<HASH> 100644 --- a/namespaces/exec.go +++ b/namespaces/exec.go @@ -110,9 +110,40 @@ func Exec(container *libcontainer.Config, stdin io.Reader, stdout, stderr io.Wri return -1, err } } + if !container.Namespaces.Contains(libcontainer.NEWPID) { + killAllPids(container) + } return command.ProcessState.Sys().(syscall.WaitStatus).ExitStatus(), nil } +func killAllPids(container *libcontainer.Config) { + var ( + pids []int + err error + ) + freeze := fs.Freeze + getPids := fs.GetPids + if systemd.UseSystemd() { + freeze = systemd.Freeze + getPids = systemd.GetPids + } + + freeze(container.Cgroups, cgroups.Frozen) + if pids, err = getPids(container.Cgroups); err == nil { + for _, pid := range pids { + if p, err := os.FindProcess(pid); err == nil { + p.Kill() + } + } + } + freeze(container.Cgroups, cgroups.Thawed) + for _, pid := range pids { + if p, err := os.FindProcess(pid); err == nil { + p.Wait() + } + } +} + // DefaultCreateCommand will return an exec.Cmd with the Cloneflags set to the proper namespaces // defined on the container's configuration and use the current binary as the init with the // args provided
This patch adds a test for the shared HOST Pid namespace It also kills all processes in a cgroup if you are not using the pid namespace If we stop using the PID namespace, and more then one process is running when the pid 1 exits, docker will hang since the cgroups do not disappear. This code will kill all remaining processes Add Tests for handing of Pid Namespaces Docker-DCO-<I>-
opencontainers_runc
train
2d0355b3b94351c96fb40ba6f3230a8ff75f19a8
diff --git a/src/babel/traversal/scope/binding.js b/src/babel/traversal/scope/binding.js index <HASH>..<HASH> 100644 --- a/src/babel/traversal/scope/binding.js +++ b/src/babel/traversal/scope/binding.js @@ -1,5 +1,5 @@ export default class Binding { - constructor({ identifier, scope, path, kind }) { + constructor({ existing, identifier, scope, path, kind }) { this.constantViolations = []; this.constant = true; @@ -12,6 +12,13 @@ export default class Binding { this.kind = kind; this.clearValue(); + + if (existing) { + this.constantViolations = this.constantViolations.concat( + existing.path, + existing.constantViolations + ); + } } /** diff --git a/src/babel/traversal/scope/index.js b/src/babel/traversal/scope/index.js index <HASH>..<HASH> 100644 --- a/src/babel/traversal/scope/index.js +++ b/src/babel/traversal/scope/index.js @@ -508,6 +508,7 @@ export default class Scope { this.bindings[name] = new Binding({ identifier: id, + existing: local, scope: this, path: path, kind: kind
merge previous bindings constantViolations and path onto new bindings constantViolations
babel_babel
train
9fb426b33dc3148ea52422f8ecae77e4f823c6e2
diff --git a/gflags/flagvalues.py b/gflags/flagvalues.py index <HASH>..<HASH> 100644 --- a/gflags/flagvalues.py +++ b/gflags/flagvalues.py @@ -123,8 +123,7 @@ class FlagValues(object): # None or Method(name, value) to call from __setattr__ for an unknown flag. self.__dict__['__set_unknown'] = None - # Set if we should use new style gnu_getopt rather than getopt when parsing - # the args. Only possible with Python 2.3+ + # By default don't use the GNU-style scanning when parsing the args. self.UseGnuGetOpt(False) def UseGnuGetOpt(self, use_gnu_getopt=True):
Cleanup nits around UseGnuGetOpt, we won't be able to flip the default to True.
google_python-gflags
train
dfc23edda483bb9c516ccfd00af1f214d0619920
diff --git a/lib/pulsar/index.js b/lib/pulsar/index.js index <HASH>..<HASH> 100644 --- a/lib/pulsar/index.js +++ b/lib/pulsar/index.js @@ -100,7 +100,13 @@ module.exports = (function() { process.stdout.on('data', collectResult); process.stderr.on('data', collectResult); process.on('close', function() { - callback(result) + var regex = /(.+[^\s])\s+#\s+([^\s].+)\n/g; + var match; + var tasks = {}; + while ((match = regex.exec(result)) !== null) { + tasks[match[1]] = match[2]; + } + callback(tasks); }); }; diff --git a/test/pulsar.js b/test/pulsar.js index <HASH>..<HASH> 100644 --- a/test/pulsar.js +++ b/test/pulsar.js @@ -74,8 +74,8 @@ exports.testTaskEvents = function(test) { }; exports.testAvailableTasks = function(test) { - this.pulsar.getAvailableTasks('example', 'production', function(data) { - if (data.indexOf('cap shell') === -1) { + this.pulsar.getAvailableTasks('example', 'production', function(tasks) { + if (!tasks['cap shell']) { test.ok(false, 'There is no shell task in available tasks'); } test.done();
JSON response for getAvailableTasks
cargomedia_pulsar-rest-api
train
f0d25af317b4643d80958c89721639062c8deb73
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -46,6 +46,7 @@ setup( 'sphinxcontrib-bibtex', 'GitPython', 'astropy-helpers>=0.2.0', + 'breathe==4.4.0', 'lsst-dd-rtd-theme==0.1.0', 'lsst-sphinx-bootstrap-theme>=0.1.0'], tests_require=['pytest',
Add breathe==<I> dependency Breathe is being used as the doxygen XML bridge to Sphinx-based documentation.
lsst-sqre_documenteer
train
34ff9f2a470306b856f261f35384650e42aa33c8
diff --git a/src/unity/python/turicreate/visualization/_plot.py b/src/unity/python/turicreate/visualization/_plot.py index <HASH>..<HASH> 100644 --- a/src/unity/python/turicreate/visualization/_plot.py +++ b/src/unity/python/turicreate/visualization/_plot.py @@ -34,7 +34,7 @@ def _focus_client_app(): delay .5 tell application \"Turi Create Visualization\" to activate ''' - focus = __subprocess._Popen(['osascript', '-'], stdout=_PIPE, stdin=_PIPE) + focus = _Popen(['osascript', '-'], stdout=_PIPE, stdin=_PIPE) focus.communicate(scpt) def _run_cmdline(command):
Removed the extra subprocess call in the focus_client_app function (#<I>)
apple_turicreate
train
cc27c87b8be9abd2595e40dc68223f314d1cb909
diff --git a/inc/class-media-meta.php b/inc/class-media-meta.php index <HASH>..<HASH> 100644 --- a/inc/class-media-meta.php +++ b/inc/class-media-meta.php @@ -286,6 +286,11 @@ class Hybrid_Media_Meta { */ public function audio_meta() { + /* Filters for the audio transcript. */ + add_filter( 'hybrid_audio_transcript', 'wptexturize', 10 ); + add_filter( 'hybrid_audio_transcript', 'convert_chars', 20 ); + add_filter( 'hybrid_audio_transcript', 'wpautop', 25 ); + $this->length_formatted(); $this->lyrics(); $this->artist(); @@ -433,7 +438,7 @@ class Hybrid_Media_Meta { $this->lyrics = $this->meta['unsychronised_lyric']; /* Apply filters for the transcript. */ - return apply_filters( 'hybrid_audio_transcript', $this->lyrics ); + $this->lyrics = apply_filters( 'hybrid_audio_transcript', $this->lyrics ); } /** diff --git a/inc/template-media.php b/inc/template-media.php index <HASH>..<HASH> 100644 --- a/inc/template-media.php +++ b/inc/template-media.php @@ -11,11 +11,6 @@ * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html */ -/* Filters for the audio transcript. */ -add_filter( 'hybrid_audio_transcript', 'wptexturize', 10 ); -add_filter( 'hybrid_audio_transcript', 'convert_chars', 20 ); -add_filter( 'hybrid_audio_transcript', 'wpautop', 25 ); - /** * Prints media meta directly to the screen. The `$property` parameter can be any of the public * properties in the `Hybrid_Media_Meta` object. @@ -161,24 +156,7 @@ function hybrid_get_image_size_links() { * @return string */ function hybrid_get_audio_transcript( $post_id = 0 ) { - - if ( empty( $post_id ) ) - $post_id = get_the_ID(); - - /* Set up some default variables and get the image metadata. */ - $lyrics = ''; - $meta = wp_get_attachment_metadata( $post_id ); - - /* Look for the 'unsynchronised_lyric' tag. */ - if ( isset( $meta['unsynchronised_lyric'] ) ) - $lyrics = $meta['unsynchronised_lyric']; - - /* Seen this misspelling of the id3 tag. */ - elseif ( isset( $meta['unsychronised_lyric'] ) ) - $lyrics = $meta['unsychronised_lyric']; - - /* Apply filters for the transcript. */ - return apply_filters( 'hybrid_audio_transcript', $lyrics ); + return hybrid_get_media_meta( 'lyrics', array( 'wrap' => '', 'post_id' => $post_id ? $post_id : get_the_ID() ) ); } /**
Use hybrid_get_media_meta() for audio lyrics.
justintadlock_hybrid-core
train
937d9c6e567257b9a0c111999905350cd772a4b2
diff --git a/clients/ptranslator/src/test/java/org/hawkular/metrics/clients/ptrans/data/ServerDataHelper.java b/clients/ptranslator/src/test/java/org/hawkular/metrics/clients/ptrans/data/ServerDataHelper.java index <HASH>..<HASH> 100644 --- a/clients/ptranslator/src/test/java/org/hawkular/metrics/clients/ptrans/data/ServerDataHelper.java +++ b/clients/ptranslator/src/test/java/org/hawkular/metrics/clients/ptrans/data/ServerDataHelper.java @@ -25,6 +25,7 @@ import static org.junit.Assert.fail; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; +import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.stream.Stream; @@ -64,6 +65,9 @@ public class ServerDataHelper { urlConnection.setRequestProperty(String.valueOf(TENANT_HEADER_NAME), tenant); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); + if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { + return Collections.emptyList(); + } if (responseCode != HttpURLConnection.HTTP_OK) { String msg = "Could not get metrics list from server: %s, %d"; fail(String.format(Locale.ROOT, msg, findGaugeMetricsUrl, responseCode));
HWKMETRICS-<I> ServerDataHelper should return empty list if no metrics are found yet
hawkular_hawkular-metrics
train
7bbcf06f4d615ac8f9c571af7d511d807ad940b2
diff --git a/pymatgen/analysis/structure_analyzer.py b/pymatgen/analysis/structure_analyzer.py index <HASH>..<HASH> 100644 --- a/pymatgen/analysis/structure_analyzer.py +++ b/pymatgen/analysis/structure_analyzer.py @@ -605,7 +605,7 @@ def get_max_bond_lengths(structure, el_radius_updates=None): def get_dimensionality(structure, max_hkl=2, el_radius_updates=None, min_slab_size=5, min_vacuum_size=5, - standardize=True): + standardize=True, bonds=None): """ This method returns whether a structure is 3D, 2D (layered), or 1D (linear @@ -626,6 +626,11 @@ def get_dimensionality(structure, max_hkl=2, el_radius_updates=None, standardize (bool): whether to standardize the structure before analysis. Set to False only if you already have the structure in a convention where layers / chains will be along low <hkl> indexes. + bonds ({(specie1, specie2): max_bond_dist}: bonds are + specified as a dict of tuples: float of specie1, specie2 + and the max bonding distance. For example, PO4 groups may be + defined as {("P", "O"): 3}. Otherwise, JMolCoordFinder is + used. Returns: (int) the dimensionality of the structure - 1 (molecules/chains), 2 (layered), or 3 (3D) @@ -635,7 +640,8 @@ def get_dimensionality(structure, max_hkl=2, el_radius_updates=None, structure = SpacegroupAnalyzer(structure).\ get_conventional_standard_structure() - bonds = get_max_bond_lengths(structure) + if not bonds: + bonds = get_max_bond_lengths(structure) num_surfaces = 0 for h in range(max_hkl): diff --git a/pymatgen/analysis/tests/test_structure_analyzer.py b/pymatgen/analysis/tests/test_structure_analyzer.py index <HASH>..<HASH> 100644 --- a/pymatgen/analysis/tests/test_structure_analyzer.py +++ b/pymatgen/analysis/tests/test_structure_analyzer.py @@ -96,6 +96,10 @@ class GetDimensionalityTest(PymatgenTest): s = self.get_structure('Graphite') self.assertEqual(get_dimensionality(s), 2) + def test_get_dimensionality_with_bonds(self): + s = self.get_structure('CsCl') + self.assertEqual(get_dimensionality(s), 1) + self.assertEqual(get_dimensionality(s, bonds={("Cs", "Cl"): 3.7}), 3) class RelaxationAnalyzerTest(unittest.TestCase): def setUp(self): @@ -362,7 +366,7 @@ class OrderParametersTest(PymatgenTest): [[15, 15, 15.707], [14.75, 14.75, 15], [14.75, 15.25, 15], \ [15.25, 14.75, 15], [15.25, 15.25, 15]], validate_proximity=False, to_unit_cell=False, - coords_are_cartesian=True, site_properties=None) + coords_are_cartesian=True, site_properties=None) self.square_pyramid = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H", "H"],
You can supply max bond distances to recognize dimensionality of NaCl As the comment of get_dimensionality says, bonding algorithm fails for ionic crystals. You can pass the max bond distances to avoid the issue.
materialsproject_pymatgen
train
711304123b36a5a9bf81e018f57bb0ea8464ef49
diff --git a/Test/AbstractElasticsearchTestCase.php b/Test/AbstractElasticsearchTestCase.php index <HASH>..<HASH> 100644 --- a/Test/AbstractElasticsearchTestCase.php +++ b/Test/AbstractElasticsearchTestCase.php @@ -62,7 +62,6 @@ abstract class AbstractElasticsearchTestCase extends WebTestCase protected function setUp() { $this->getContainer(); - $this->getManager(); } /**
fixing performance leak to not create index twice on func. tests
ongr-io_ElasticsearchBundle
train
640325b590c64e0c9bc52b95aa2cedec9955eafc
diff --git a/lib/fly/-parallel.js b/lib/fly/-parallel.js index <HASH>..<HASH> 100644 --- a/lib/fly/-parallel.js +++ b/lib/fly/-parallel.js @@ -4,13 +4,20 @@ const Promise = require('bluebird'); const co = Promise.coroutine; const READY = '_ready'; -module.exports = co(function * (tasks) { +const defs = { + src: null, + val: null +}; + +module.exports = co(function * (tasks, opts) { // ensure is intialized first if (!this[READY]) { yield this.init(); } - // wrap each task as new coroutine + // ensure base task options. (all receive the same) + opts = Object.assign({}, defs, opts); + yield Promise.all(tasks.map(t => co(this.start).apply(this, [t]))); // @todo: emit event console.log('parallel chain complete!'); diff --git a/lib/fly/-start.js b/lib/fly/-start.js index <HASH>..<HASH> 100644 --- a/lib/fly/-start.js +++ b/lib/fly/-start.js @@ -44,7 +44,6 @@ module.exports = co(function * (name, opts) { this.emit('task_error', obj); throw e; } - console.log('finished?'); return val; });
allow fly.parallel to accept options - all tasks will receive same obj
lukeed_taskr
train
7317c05df2eafd682e692f5b8a7b685bb884b3b6
diff --git a/gremlin-core/src/main/java/com/tinkerpop/gremlin/process/graph/step/branch/RepeatStep.java b/gremlin-core/src/main/java/com/tinkerpop/gremlin/process/graph/step/branch/RepeatStep.java index <HASH>..<HASH> 100644 --- a/gremlin-core/src/main/java/com/tinkerpop/gremlin/process/graph/step/branch/RepeatStep.java +++ b/gremlin-core/src/main/java/com/tinkerpop/gremlin/process/graph/step/branch/RepeatStep.java @@ -118,15 +118,22 @@ public final class RepeatStep<S> extends AbstractStep<S, S> implements Traversal @Override public String toString() { if (this.emitFirst && this.untilFirst) { - return TraversalHelper.makeStepString(this, "until(" + this.untilPredicate + ")", "emit(" + this.emitPredicate + ")", this.repeatTraversal); + return TraversalHelper.makeStepString(this, untilString(), emitString(), this.repeatTraversal); } else if (this.emitFirst && !this.untilFirst) { - return TraversalHelper.makeStepString(this, "emit(" + this.emitPredicate + ")", this.repeatTraversal, "until(" + this.untilPredicate + ")"); + return TraversalHelper.makeStepString(this, emitString(), this.repeatTraversal, untilString()); } else if (!this.emitFirst && this.untilFirst) { - return TraversalHelper.makeStepString(this, "until(" + this.untilPredicate + ")", this.repeatTraversal, "emit(" + this.emitPredicate + ")"); + return TraversalHelper.makeStepString(this, untilString(), this.repeatTraversal, emitString()); } else { - return TraversalHelper.makeStepString(this, this.repeatTraversal, "until(" + this.untilPredicate + ")", "emit(" + this.emitPredicate + ")"); + return TraversalHelper.makeStepString(this, this.repeatTraversal, untilString(), emitString()); } + } + + private final String untilString() { + return null == this.untilPredicate ? "until(true)" : "until(" + this.untilPredicate + ")"; + } + private final String emitString() { + return null == this.emitPredicate ? "emit(false)" : "emit(" + this.emitFirst + ")"; } @Override
added a non-null bearing toString() for RepeatStep.
apache_tinkerpop
train
5a9987bc1a9482429ce953561d7d3bb764bb2b25
diff --git a/cmd/juju/commands/upgradejuju_test.go b/cmd/juju/commands/upgradejuju_test.go index <HASH>..<HASH> 100644 --- a/cmd/juju/commands/upgradejuju_test.go +++ b/cmd/juju/commands/upgradejuju_test.go @@ -371,7 +371,7 @@ func (s *UpgradeJujuSuite) checkToolsUploaded(c *gc.C, vers version.Binary, agen storage, err := s.State.ToolsStorage() c.Assert(err, jc.ErrorIsNil) defer storage.Close() - _, r, err := storage.Tools(vers) + _, r, err := storage.Open(vers.String()) if !c.Check(err, jc.ErrorIsNil) { return } diff --git a/featuretests/api_model_test.go b/featuretests/api_model_test.go index <HASH>..<HASH> 100644 --- a/featuretests/api_model_test.go +++ b/featuretests/api_model_test.go @@ -124,10 +124,11 @@ func (s *apiEnvironmentSuite) TestUploadToolsOtherEnvironment(c *gc.C) { defer otherClient.ClientFacade.Close() newVersion := version.MustParseBinary("5.4.3-quantal-amd64") + vers := newVersion.String() // build fake tools tgz, checksum := coretesting.TarGz( - coretesting.NewTarFile(jujunames.Jujud, 0777, "jujud contents "+newVersion.String())) + coretesting.NewTarFile(jujunames.Jujud, 0777, "jujud contents "+vers)) tool, err := otherClient.UploadTools(bytes.NewReader(tgz), newVersion) c.Assert(err, jc.ErrorIsNil) @@ -136,9 +137,9 @@ func (s *apiEnvironmentSuite) TestUploadToolsOtherEnvironment(c *gc.C) { toolStrg, err := otherState.ToolsStorage() defer toolStrg.Close() c.Assert(err, jc.ErrorIsNil) - meta, closer, err := toolStrg.Tools(newVersion) + meta, closer, err := toolStrg.Open(vers) defer closer.Close() c.Assert(err, jc.ErrorIsNil) c.Assert(meta.SHA256, gc.Equals, checksum) - c.Assert(meta.Version, gc.Equals, newVersion) + c.Assert(meta.Version, gc.Equals, vers) }
Fix some remaining tests using old storage interface.
juju_juju
train
eb4f1f0333c5c046e30cdd1695f8fa3821c9e085
diff --git a/src/main/java/com/github/sebhoss/reguloj/AbstractRuleEngine.java b/src/main/java/com/github/sebhoss/reguloj/AbstractRuleEngine.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/sebhoss/reguloj/AbstractRuleEngine.java +++ b/src/main/java/com/github/sebhoss/reguloj/AbstractRuleEngine.java @@ -24,4 +24,8 @@ public abstract class AbstractRuleEngine<CONTEXT extends Context<?>> implements return FluentIterable.from(rules).anyMatch(Rules.ruleFires(context)); } + protected final boolean performSinglePass(final CONTEXT context, final Set<Rule<CONTEXT>> rules) { + return FluentIterable.from(rules).filter(Rules.ruleRuns(context)).size() > 0; + } + } diff --git a/src/main/java/com/github/sebhoss/reguloj/ChainedRuleEngine.java b/src/main/java/com/github/sebhoss/reguloj/ChainedRuleEngine.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/sebhoss/reguloj/ChainedRuleEngine.java +++ b/src/main/java/com/github/sebhoss/reguloj/ChainedRuleEngine.java @@ -8,15 +8,13 @@ package com.github.sebhoss.reguloj; import java.util.Set; -import com.google.common.collect.FluentIterable; - final class ChainedRuleEngine<CONTEXT extends Context<?>> extends AbstractRuleEngine<CONTEXT> { @Override public boolean infer(final CONTEXT context, final Set<Rule<CONTEXT>> rules) { boolean changeOccured = false; - while (FluentIterable.from(rules).filter(Rules.ruleRuns(context)).size() > 0) { + while (performSinglePass(context, rules)) { changeOccured = true; } diff --git a/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java b/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java +++ b/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java @@ -9,7 +9,6 @@ package com.github.sebhoss.reguloj; import java.util.Set; import com.google.common.base.Preconditions; -import com.google.common.collect.FluentIterable; final class LimitedRuleEngine<CONTEXT extends Context<?>> extends AbstractRuleEngine<CONTEXT> { @@ -26,7 +25,7 @@ final class LimitedRuleEngine<CONTEXT extends Context<?>> extends AbstractRuleEn boolean changeOccured = false; int currentRuns = 0; - while (FluentIterable.from(rules).filter(Rules.ruleRuns(context)).size() > 0) { + while (performSinglePass(context, rules)) { changeOccured = true; if (++currentRuns > maximumNumberOfRuns) {
performSinglePass(context, rules) runs all given rules in the given context and returns whether any rule returned true.
sebhoss_reguloj
train
aabf1c13f7c221d25364930fe3e7ce36b6c0cf36
diff --git a/vendors.php b/vendors.php index <HASH>..<HASH> 100755 --- a/vendors.php +++ b/vendors.php @@ -75,6 +75,26 @@ if (0 !== $code) { } } +// Remove previous assets +$assetDir = __DIR__. '/www/assets'; +$code = 0; +if (is_dir($assetDir)) { + system('rm -rf ' . escapeshellarg($assetDir), $code); +} + +if (0 !== $code) { + echo sprintf('Attention, failed to remove previous %s dependencies in %s', $bower, $assetDir); + echo "\n"; +} + +// Clean bower cache +system(sprintf('%s cache-clean', $bower), $code); + +if (0 !== $code) { + echo sprintf('Attention, failed to clean %s cache', $bower); + echo "\n"; +} + // Install asset dependencies with bower system(sprintf('%s install', $bower), $code);
Reset assets directory and bower cache
alchemy-fr_Phraseanet
train
93cab5b94a6c508dc206f92e09af8cb3319b065c
diff --git a/src/tree/builder/TreeAdapter.js b/src/tree/builder/TreeAdapter.js index <HASH>..<HASH> 100644 --- a/src/tree/builder/TreeAdapter.js +++ b/src/tree/builder/TreeAdapter.js @@ -135,26 +135,35 @@ class TreeAdapter { * @returns {void} */ appendChild( parent, child ) { - // Do not do anything with irrelevant content. + /* + Do not do anything with irrelevant content. + (We get the raw string contents later on from the source code). + */ if ( parent instanceof StructuredIrrelevant ) { return; } + /* + Ignored content can also be contained within headings, paragraphs + and other formatting elements, so we need to transform the Ignored + to a FormattingElement and add it to the respective heading or paragraph. + */ if ( child instanceof StructuredIrrelevant && ( TreeAdapter._isLeafNode( child ) || parent instanceof FormattingElement ) ) { - // Add StructuredIrrelevant element as formatting to the parent node. + // Add StructuredIrrelevant element as formatting to the first header or paragraph ancestor. const element = new FormattingElement( child.tagName, {} ); element.location = child.location; TreeAdapter._appendFormattingElement( parent, element ); return; } + // Add formatting element to its first ancestor that is either a heading or paragraph. if ( child instanceof FormattingElement ) { TreeAdapter._appendFormattingElement( parent, child ); return; } - // Just add nodes to parent's children if not formatting. + // Just add nodes to parent's children in any other case. child.parent = parent; parent.children.push( child ); }
Added comments to appendChild method of TreeAdapter.
Yoast_YoastSEO.js
train
5fded72481753c377c01468dbea8d54beab216ae
diff --git a/pyarlo/media.py b/pyarlo/media.py index <HASH>..<HASH> 100644 --- a/pyarlo/media.py +++ b/pyarlo/media.py @@ -62,11 +62,14 @@ class ArloMediaLibrary(object): for video in data: # pylint: disable=cell-var-from-loop - srccam = \ - list(filter( - lambda cam: cam.device_id == video.get('deviceId'), - all_cameras) - )[0] + try: + srccam = \ + list(filter( + lambda cam: cam.device_id == video.get('deviceId'), + all_cameras) + )[0] + except IndexError: + continue # make sure only_cameras is a list if only_cameras and \
Currently we don't support Arlo DoorBells and this code is a temporary workaround to get the media library loaded when a doorbell is present.
tchellomello_python-arlo
train
43696ec4b39cd463a7a706c5d2440aa6b15dd25f
diff --git a/src/Rules/UnusedFunctionParametersCheck.php b/src/Rules/UnusedFunctionParametersCheck.php index <HASH>..<HASH> 100644 --- a/src/Rules/UnusedFunctionParametersCheck.php +++ b/src/Rules/UnusedFunctionParametersCheck.php @@ -47,6 +47,17 @@ class UnusedFunctionParametersCheck if ($node instanceof Node\Expr\ClosureUse) { return [$node->var]; } + if ( + $node instanceof Node\Expr\FuncCall + && $node->name instanceof Node\Name + && (string) $node->name === 'compact' + ) { + foreach ($node->args as $arg) { + if ($arg->value instanceof Node\Scalar\String_) { + $variableNames[] = $arg->value->value; + } + } + } foreach ($node->getSubNodeNames() as $subNodeName) { if ($node instanceof Node\Expr\Closure && $subNodeName !== 'uses') { continue; diff --git a/tests/PHPStan/Rules/Classes/UnusedConstructorParametersRuleTest.php b/tests/PHPStan/Rules/Classes/UnusedConstructorParametersRuleTest.php index <HASH>..<HASH> 100644 --- a/tests/PHPStan/Rules/Classes/UnusedConstructorParametersRuleTest.php +++ b/tests/PHPStan/Rules/Classes/UnusedConstructorParametersRuleTest.php @@ -17,11 +17,11 @@ class UnusedConstructorParametersRuleTest extends \PHPStan\Rules\AbstractRuleTes $this->analyse([__DIR__ . '/data/unused-constructor-parameters.php'], [ [ 'Constructor of class UnusedConstructorParameters\Foo has an unused parameter $unusedParameter.', - 10, + 11, ], [ 'Constructor of class UnusedConstructorParameters\Foo has an unused parameter $anotherUnusedParameter.', - 10, + 11, ], ]); } diff --git a/tests/PHPStan/Rules/Classes/data/unused-constructor-parameters.php b/tests/PHPStan/Rules/Classes/data/unused-constructor-parameters.php index <HASH>..<HASH> 100644 --- a/tests/PHPStan/Rules/Classes/data/unused-constructor-parameters.php +++ b/tests/PHPStan/Rules/Classes/data/unused-constructor-parameters.php @@ -6,6 +6,7 @@ class Foo { private $foo; + private $bar; public function __construct( $usedParameter, @@ -14,6 +15,7 @@ class Foo $usedParameterInStringThree, $usedParameterInCondition, $usedParameterInClosureUse, + $usedParameterInCompact, $unusedParameter, $anotherUnusedParameter ) @@ -28,6 +30,7 @@ class Foo function ($anotherUnusedParameter) use ($usedParameterInClosureUse) { echo $anotherUnusedParameter; // different scope }; + $this->bar = compact('usedParameterInCompact'); } }
Added check for use within compact() call
phpstan_phpstan
train
450ba0ea0ef995a8bc7b43b7aacaa1445ad69ecf
diff --git a/openquake/calculators/classical.py b/openquake/calculators/classical.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/classical.py +++ b/openquake/calculators/classical.py @@ -94,10 +94,21 @@ def run_preclassical(csm, oqparam, h5): oqparam.maximum_distance) if csm.sitecol: logging.info('Sending %s', srcfilter.sitecol) + if oqparam.ps_grid_spacing: + # produce a preclassical task for each group + allargs = ((srcs, srcfilter, param) + for srcs in sources_by_grp.values()) + else: + # produce many preclassical task + maxw = sum(len(srcs) for srcs in sources_by_grp.values()) / ( + oqparam.concurrent_tasks or 1) + allargs = ((blk, srcfilter, param) + for srcs in sources_by_grp.values() + for blk in block_splitter(srcs, maxw)) res = parallel.Starmap( - preclassical, - ((srcs, srcfilter, param) for srcs in sources_by_grp.values()), - h5=h5, distribute=None if len(sources_by_grp) > 1 else 'no').reduce() + preclassical, allargs, h5=h5, + distribute=None if len(sources_by_grp) > 1 else 'no' + ).reduce() if res and res['before'] != res['after']: logging.info('Reduced the number of sources from {:_d} -> {:_d}'. diff --git a/openquake/hazardlib/source/base.py b/openquake/hazardlib/source/base.py index <HASH>..<HASH> 100644 --- a/openquake/hazardlib/source/base.py +++ b/openquake/hazardlib/source/base.py @@ -74,7 +74,9 @@ class BaseSeismicSource(metaclass=abc.ABCMeta): if not self.num_ruptures: self.num_ruptures = self.count_ruptures() w = self.num_ruptures * self.ngsims * (.1 if self.nsites == EPS else 1) - if not hasattr(self, 'nodal_plane_distribution'): # not pointlike + if hasattr(self, 'data'): # nonparametric rupture + w *= 30 # increase weight 30 times + elif not hasattr(self, 'nodal_plane_distribution'): # not pointlike w *= 10 # increase weight of non point sources return w
Better parallelization of the preclassical calculator
gem_oq-engine
train
12b1c6a842e9149730287891348744957c1eb277
diff --git a/src/easyComp.js b/src/easyComp.js index <HASH>..<HASH> 100644 --- a/src/easyComp.js +++ b/src/easyComp.js @@ -6,7 +6,7 @@ const OBSERVED_RENDER = Symbol('observed render') const IS_DIRECT_RENDER = Symbol('is direct render') const RENDER_RESULT = Symbol('render result') -export default function easyStateHOC (WrappedComp) { +export default function easyCompHOC (WrappedComp) { if (typeof WrappedComp !== 'function') { throw new TypeError('easyComp expects a component class or function as argument.') } @@ -24,7 +24,7 @@ export default function easyStateHOC (WrappedComp) { WrappedComp.defaultProps = renderer.defaultProps } - return class EasyStateWrapper extends WrappedComp { + return class EasyCompWrapper extends WrappedComp { constructor (props) { super(props) autoBind(this, WrappedComp.prototype, true)
refactor: rename easyState to easyComp inside easyComp file
solkimicreb_react-easy-state
train
926684c2872ade9835378a85f8ee86997df40042
diff --git a/endpoints/tv/tests/integration_test.js b/endpoints/tv/tests/integration_test.js index <HASH>..<HASH> 100644 --- a/endpoints/tv/tests/integration_test.js +++ b/endpoints/tv/tests/integration_test.js @@ -1,7 +1,7 @@ var request = require('request'); var helpers = require('../../../lib/test_helpers.js'); -describe('stod2', function () { +describe('tv - stod2', function () { it("should return an array of objects containing correct fields", function (done) { var fieldsToCheckFor = ["series", "title", "originalTitle", "description", "live", "premier"]; var params = helpers.testRequestParams("/tv/stod2"); @@ -10,7 +10,7 @@ describe('stod2', function () { }); }); -describe('ruv', function () { +describe('tv - ruv', function () { this.timeout(4000); it("should return an array of objects containing correct fields", function (done) { var fieldsToCheckFor = ["series", "title", "originalTitle", "description", "live", "premier"];
Rephrasing of tv tests
apis-is_apis
train
be45a6796c9b39d825638f6b1555c00099fc271c
diff --git a/src/python/twitter/pants/tasks/jvm_run.py b/src/python/twitter/pants/tasks/jvm_run.py index <HASH>..<HASH> 100644 --- a/src/python/twitter/pants/tasks/jvm_run.py +++ b/src/python/twitter/pants/tasks/jvm_run.py @@ -63,6 +63,7 @@ class JvmRun(JvmTask): def execute(self, targets): # Run the first target that is a binary. + self.context.lock.release() binaries = filter(is_binary, targets) if len(binaries) > 0: # We only run the first one. main = binaries[0].main diff --git a/src/python/twitter/pants/tasks/scala_repl.py b/src/python/twitter/pants/tasks/scala_repl.py index <HASH>..<HASH> 100644 --- a/src/python/twitter/pants/tasks/scala_repl.py +++ b/src/python/twitter/pants/tasks/scala_repl.py @@ -29,8 +29,6 @@ class ScalaRepl(JvmTask): def setup_parser(cls, option_group, args, mkflag): option_group.add_option(mkflag("jvmargs"), dest = "run_jvmargs", action="append", help = "Run the repl in a jvm with these extra jvm args.") - option_group.add_option(mkflag("args"), dest = "run_args", action="append", - help = "run the repl in a jvm with extra args.") def __init__(self, context): Task.__init__(self, context) @@ -41,16 +39,12 @@ class ScalaRepl(JvmTask): self.confs = context.config.getlist('scala-repl', 'confs') self.profile = context.config.get('scala-repl', 'profile') self.main = context.config.get('scala-repl', 'main') - self.args = context.config.getlist('scala-repl', 'args', default=[]) - if context.options.run_args: - for arg in context.options.run_args: - self.args.extend(shlex.split(arg)) def execute(self, targets): runjava( jvmargs=self.jvm_args, classpath=self.classpath(profile_classpath(self.profile), confs=self.confs), main=self.main, - args=self.args + args=[] )
Release lock before running a JVM process in pants. This is so we can run multiple processes concurrently, and/or use other pants commands concurrently with a run command. (sapling split of <I>e0d<I>c<I>f<I>bc<I>e<I>e8ffa)
pantsbuild_pants
train
9227abbfe15f17fc7513a9e074a7e4ca0f1a6d42
diff --git a/adventure/__init__.py b/adventure/__init__.py index <HASH>..<HASH> 100644 --- a/adventure/__init__.py +++ b/adventure/__init__.py @@ -9,7 +9,7 @@ def play(): from .interpret import read_data_from_nearby_file from .prompt import install_builtins - data = read_data_from_nearby_file() - game = Game(data, sys.stdout.write) - install_builtins(data, game) + game = Game(sys.stdout.write) + read_data_from_nearby_file(game) + install_builtins(game) game.start() diff --git a/adventure/data.py b/adventure/data.py index <HASH>..<HASH> 100644 --- a/adventure/data.py +++ b/adventure/data.py @@ -139,9 +139,8 @@ def section12(data, n, line): # Process every section of the file in turn. -def parse(datafile): +def parse(data, datafile): """Read the Adventure data file and return a ``Data`` object.""" - data = Data() data._last_travel = [0, [0]] # x and verbs used by section 3 while True: section_number = int(datafile.readline()) diff --git a/adventure/game.py b/adventure/game.py index <HASH>..<HASH> 100644 --- a/adventure/game.py +++ b/adventure/game.py @@ -2,10 +2,12 @@ YESNO_ANSWERS = {'y': True, 'yes': True, 'n': False, 'no': False} -class Game(object): +from .data import Data - def __init__(self, data, writer): - self.data = data +class Game(Data): + + def __init__(self, writer): + Data.__init__(self) self.writer = writer self.yesno_callback = False @@ -22,13 +24,13 @@ class Game(object): def start(self): """Start the game.""" - self.yesno(self.data.messages[65], self.instruct) # like instructions? + self.yesno(self.messages[65], self.instruct) # like instructions? def instruct(self, yes): """Print out instructions if the user wants them.""" if yes: - self.write(self.data.messages[1]) - self.data.hints[3].used = True + self.write(self.messages[1]) + self.hints[3].used = True # The central do_command() method, that should be called over and # over again with words supplied by the user. diff --git a/adventure/interpret.py b/adventure/interpret.py index <HASH>..<HASH> 100644 --- a/adventure/interpret.py +++ b/adventure/interpret.py @@ -4,10 +4,10 @@ import codecs import os from .data import parse -def read_data_from_nearby_file(): +def read_data_from_nearby_file(data): datapath = os.path.join(os.path.dirname(__file__), 'advent.dat') datafile = codecs.open(datapath, 'r', encoding='ascii') - return parse(datafile) + parse(data, datafile) def interpret(data, words): if words == ['?']: diff --git a/adventure/prompt.py b/adventure/prompt.py index <HASH>..<HASH> 100644 --- a/adventure/prompt.py +++ b/adventure/prompt.py @@ -12,7 +12,7 @@ class ReprTriggeredIdentifier(object): self.function(*self.args, **self.kw) return u'' -def install_builtins(data, game): +def install_builtins(game): for word in ('yes', 'no'): identifier = ReprTriggeredIdentifier(game.do_command, [ word ]) setattr(__builtin__, word, identifier) diff --git a/adventure/tests/test_data.py b/adventure/tests/test_data.py index <HASH>..<HASH> 100644 --- a/adventure/tests/test_data.py +++ b/adventure/tests/test_data.py @@ -3,8 +3,10 @@ import unittest class FooTest(unittest.TestCase): def setUp(self): + from adventure.data import Data from adventure.interpret import read_data_from_nearby_file - self.data = read_data_from_nearby_file() + self.data = Data() + read_data_from_nearby_file(self.data) def test_long_description(self): self.assertEqual(self.data.rooms[4].long_description, u"""\
Made Game inherit from Data to avoid saying `game.data` over and over again.
brandon-rhodes_python-adventure
train
4548b3bab7e9dc9c360e06400f56bb6720385a46
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ #### Changes * Nested memoization of the same method is now allowed and won't reset the memoization cache anymore. +* Remove unit "mhz" from `Address` of type `:radio_frequency`. ## 1.0.0 diff --git a/lib/aixm/component/address.rb b/lib/aixm/component/address.rb index <HASH>..<HASH> 100644 --- a/lib/aixm/component/address.rb +++ b/lib/aixm/component/address.rb @@ -93,7 +93,12 @@ module AIXM builder.comment! ["Address: #{TYPES.key(type)}", addressable&.id].compact.join(' for ') builder.tag!(as) do |tag| tag << to_uid(as: :"#{as}Uid", sequence: sequence).indent(2) - tag.txtAddress(address) + case type + when :radio_frequency + tag.txtAddress(address.freq.to_s) + else + tag.txtAddress(address) + end tag.txtRmk(remarks) if remarks end end diff --git a/spec/lib/aixm/document_spec.rb b/spec/lib/aixm/document_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/aixm/document_spec.rb +++ b/spec/lib/aixm/document_spec.rb @@ -590,7 +590,7 @@ describe AIXM::Document do <codeType>RADIO</codeType> <noSeq>1</noSeq> </AhaUid> - <txtAddress>123.35 mhz</txtAddress> + <txtAddress>123.35</txtAddress> <txtRmk>A/A (callsign PUJAUT)</txtRmk> </Aha> <Sah> @@ -1531,7 +1531,7 @@ describe AIXM::Document do <codeType>RADIO</codeType> <noSeq>1</noSeq> </AhaUid> - <txtAddress>123.35 mhz</txtAddress> + <txtAddress>123.35</txtAddress> <txtRmk>A/A (callsign PUJAUT)</txtRmk> </Aha> <Sah> @@ -2555,7 +2555,7 @@ describe AIXM::Document do <codeType>RADIO</codeType> <noSeq>1</noSeq> </AhaUid> - <txtAddress>123.35 mhz</txtAddress> + <txtAddress>123.35</txtAddress> <txtRmk>A/A (callsign PUJAUT)</txtRmk> </Aha> <Sah> diff --git a/spec/lib/aixm/feature/address_spec.rb b/spec/lib/aixm/feature/address_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/aixm/feature/address_spec.rb +++ b/spec/lib/aixm/feature/address_spec.rb @@ -57,7 +57,7 @@ describe AIXM::Component::Address do <codeType>RADIO</codeType> <noSeq>1</noSeq> </XxxUid> - <txtAddress>123.35 mhz</txtAddress> + <txtAddress>123.35</txtAddress> <txtRmk>A/A (callsign PUJAUT)</txtRmk> </Xxx> END diff --git a/spec/lib/aixm/feature/airport_spec.rb b/spec/lib/aixm/feature/airport_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/aixm/feature/airport_spec.rb +++ b/spec/lib/aixm/feature/airport_spec.rb @@ -556,7 +556,7 @@ describe AIXM::Feature::Airport do <codeType>RADIO</codeType> <noSeq>1</noSeq> </AhaUid> - <txtAddress>123.35 mhz</txtAddress> + <txtAddress>123.35</txtAddress> <txtRmk>A/A (callsign PUJAUT)</txtRmk> </Aha> <!-- Address: URL for LFNT -->
Remove "mhz" unit from address of type radio frequency
svoop_aixm
train
34ddf5b47264fdcd1d9bc50a756a96b8dfd53a51
diff --git a/src/main/java/com/samskivert/util/Config.java b/src/main/java/com/samskivert/util/Config.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/samskivert/util/Config.java +++ b/src/main/java/com/samskivert/util/Config.java @@ -91,11 +91,17 @@ public class Config /** * Constructs a config object which will obtain information from the supplied properties. */ - public Config (String path, Properties props) + public Config (Properties props) { _props = props; } + @Deprecated + public Config (String path, Properties props) + { + this(props); + } + /** * Fetches and returns the value for the specified configuration property. If the value is not * specified in the associated properties file, the supplied default value is returned instead.
Deprecated constructor with pointless argument.
samskivert_samskivert
train
8abaa06c2387c141b09dcfeee4146af2a12b4f0d
diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index <HASH>..<HASH> 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -38,10 +38,6 @@ def try_internet(url="http://httpbin.org/ip", timeout=1.5): resp.raise_for_status() -class ServerNotDead(Exception): - pass - - def check_internet(): has_internet = False for url in ("http://httpbin.org/ip", "http://clients3.google.com/generate_204"):
Remove extraneous exception added to conftest.py
pypa_pipenv
train
68594f4926818a7c2f4be2be693a9c5720a2f4e8
diff --git a/sllurp/llrp_proto.py b/sllurp/llrp_proto.py index <HASH>..<HASH> 100644 --- a/sllurp/llrp_proto.py +++ b/sllurp/llrp_proto.py @@ -1104,10 +1104,24 @@ Message_struct['C1G2RFControl'] = { # 16.3.1.2.1.3 C1G2SingulationControl Parameter def encode_C1G2SingulationControl (par): - raise NotImplementedError + msgtype = Message_struct['C1G2SingulationControl']['type'] + msg_header = '!HH' + data = struct.pack('!B', par['Session'] << 6) + data += struct.pack('!H', par['TagPopulation']) + data += struct.pack('!I', par['TagTransitTime']) + #data = struct.pack('!H', par['ModeIndex']) + #data += struct.pack('!H', par['Tari']) + data = struct.pack(msg_header, msgtype, + len(data) + struct.calcsize(msg_header)) + data + return data Message_struct['C1G2SingulationControl'] = { 'type': 336, + 'fields': [ + 'Session', + 'TagPopulation', + 'TagTransitTime', + ], } # 16.2.7.1 ROReportSpec Parameter
add support for C1G2SingulationControl
ransford_sllurp
train
2da39d27c596741e40a177b8f61928c425e3ef6d
diff --git a/framework/core/src/Flarum/Core/Support/Seeders/DiscussionTableSeeder.php b/framework/core/src/Flarum/Core/Support/Seeders/DiscussionTableSeeder.php index <HASH>..<HASH> 100644 --- a/framework/core/src/Flarum/Core/Support/Seeders/DiscussionTableSeeder.php +++ b/framework/core/src/Flarum/Core/Support/Seeders/DiscussionTableSeeder.php @@ -64,8 +64,7 @@ class DiscussionTableSeeder extends Seeder 'time' => $startTime = date_add($startTime, date_interval_create_from_date_string('1 second')), 'user_id' => rand(1, $users), 'type' => 'title', - 'content' => $discussion->title, - 'html_content' => $discussion->title + 'content' => $discussion->title ]); } else { $edited = rand(1, 20) == 1; @@ -82,7 +81,6 @@ class DiscussionTableSeeder extends Seeder 'user_id' => rand(1, $users), 'type' => 'comment', 'content' => $faker->realText(rand(50, 500)), - 'html_content' => $faker->realText(rand(50, 500)), 'edit_time' => $edited ? $startTime = date_add($startTime, date_interval_create_from_date_string('1 second')) : null, 'edit_user_id' => $edited ? rand(1, $users) : null, 'delete_time' => $deleted ? $startTime = date_add($startTime, date_interval_create_from_date_string('1 second')) : null, @@ -107,9 +105,10 @@ class DiscussionTableSeeder extends Seeder $discussion->last_user_id = $lastPost->user_id; $discussion->last_post_id = $lastPost->id; $discussion->last_post_number = $lastPost->number; - $discussion->number_index = $lastPost->number; } + $discussion->number_index = $j + 1 + $numberOffset; + $discussion->save(); // Give some users some random discussion state data.
Fix up bug in discussion seeder where number_index could be null. closes #<I>
flarum_core
train
e0fd7ab43172cc1a1fa988df85ff6fc5dcb167d1
diff --git a/bddrest/authoring/given.py b/bddrest/authoring/given.py index <HASH>..<HASH> 100644 --- a/bddrest/authoring/given.py +++ b/bddrest/authoring/given.py @@ -1,19 +1,18 @@ from ..context import Context from ..specification import FirstCall, AlteredCall, Call -from .story import Story from .manipulation import Manipulator +from .story import Story + + +# TODO: add autodoc_format argumnet class Given(Story, Context): """ :param application: A WSGI Application to examine - :param autodump: A string which indicates the filename to dump the story, - or a `callable(story) -> filename` to determine the - filename. A file-like object is also accepted. + :param autodump: A `callable(story) -> file-like` to write dumped story. Default is `None`, means autodump is disabled by default. - :param autodoc: A string which indicates the name of documentation file, or - a `callable(story) -> filename` to determine the filename. - A file-like object is also accepted. + :param autodoc: A `callable(story) -> file-like` to write documentation. Default is `None`, meana autodoc is disabled by default. Currently only markdown is supprted. :param fieldinfo: A callable(resource, verb, fieldname) to provide the @@ -62,22 +61,10 @@ class Given(Story, Context): return if self.autodump: - if hasattr(self.autodump, 'write'): - self.dump(self.autodump) - else: - filename = self.autodump(self) if callable(self.autodump) \ - else self.autodump - with open(filename, mode='w', encoding='utf-8') as f: - self.dump(f) + self.dump(self.autodump) if self.autodoc: - if hasattr(self.autodoc, 'write'): - self.dump(self.autodoc) - else: - filename = self.autodoc(self) if callable(self.autodoc) else \ - self.autodoc - with open(filename, mode='w', encoding='utf-8') as f: - self.document(f, fieldinfo=self.fieldinfo) + self.document(self.autodoc, fieldinfo=self.fieldinfo) @property def response(self): diff --git a/bddrest/documentary/__init__.py b/bddrest/documentary/__init__.py index <HASH>..<HASH> 100644 --- a/bddrest/documentary/__init__.py +++ b/bddrest/documentary/__init__.py @@ -5,6 +5,7 @@ from easycli import SubCommand, Argument from .formatters import * from .documenter import Documenter + class DocumentaryLauncher(SubCommand): __command__ = 'document' __help__ = 'Generates REST API Documentation from standard input to ' \ @@ -26,12 +27,12 @@ class DocumentaryLauncher(SubCommand): def __call__(self, args): self.convert_file(sys.stdin, sys.stdout, args.format) - def convert_file(self, source, destination, format): + def convert_file(self, source, destination, format_): from ..authoring import Story story = Story.load(source) story.document( destination, - formatter_factory=self.formatters[format] + formatter_factory=self.formatters[format_] ) diff --git a/tests/test_autodocumentation.py b/tests/test_autodocumentation.py index <HASH>..<HASH> 100644 --- a/tests/test_autodocumentation.py +++ b/tests/test_autodocumentation.py @@ -1,6 +1,4 @@ import io -import tempfile -from os import path from bddrest import Given, response @@ -10,19 +8,6 @@ def wsgi_application(environ, start_response): yield b'Nothing' -def test_autodoc_filename(): - filename = tempfile.mktemp() - with Given( - wsgi_application, - title='Testing auto documentation', - url='/apiv1/devices/name: SM-12345678', - autodoc=filename, - ): - assert response.status == 200 - - assert path.exists(filename) - - def test_autodoc_file_object(): file = io.StringIO() with Given( diff --git a/tests/test_autodumping.py b/tests/test_autodumping.py index <HASH>..<HASH> 100644 --- a/tests/test_autodumping.py +++ b/tests/test_autodumping.py @@ -1,6 +1,4 @@ import io -import tempfile -from os import path from bddrest import Given, response @@ -10,19 +8,6 @@ def wsgi_application(environ, start_response): yield b'Nothing' -def test_autodump_filename(): - filename = tempfile.mktemp() - with Given( - wsgi_application, - title='Testing auto dump', - url='/apiv1/devices/name: SM-12345678', - autodump=filename, - ): - assert response.status == 200 - - assert path.exists(filename) - - def test_autodump_file_object(): file = io.StringIO() with Given(
Accept only a `callable(story) -> file-like` for autodump and autodoc arguments of the Given class
Carrene_bddrest
train
9066412f896726296c7f273ffe026e5a279a0b57
diff --git a/src/Command/PlatformCommand.php b/src/Command/PlatformCommand.php index <HASH>..<HASH> 100644 --- a/src/Command/PlatformCommand.php +++ b/src/Command/PlatformCommand.php @@ -375,12 +375,20 @@ abstract class PlatformCommand extends Command if (!$project) { return null; } + + // Cache not found environments. + static $notFound = array(); + if (!$refresh && isset($notFound[$id])) { + return null; + } + $this->loadConfig(); $projectId = $project['id']; if ($refresh || empty($this->config['environments'][$projectId][$id])) { $client = $this->getPlatformClient($project['endpoint']); $environment = HalResource::get($id, $project['endpoint'] . '/environments', $client); if (!$environment) { + $notFound[$id] = true; return null; } $urlParts = parse_url($project['endpoint']); diff --git a/src/Model/HalResource.php b/src/Model/HalResource.php index <HASH>..<HASH> 100644 --- a/src/Model/HalResource.php +++ b/src/Model/HalResource.php @@ -26,13 +26,7 @@ class HalResource implements HalResourceInterface } /** - * Get a resource at a URL. - * - * @param string $id - * @param string $collectionUrl - * @param HttpClient $client - * - * @return HalResource|false + * @inheritdoc */ public static function get($id, $collectionUrl, HttpClient $client) { @@ -42,19 +36,16 @@ class HalResource implements HalResourceInterface ->json(); } catch (ClientErrorResponseException $e) { - return false; + if ($e->getCode() === 404) { + return false; + } + throw $e; } return new static($data, $client); } /** - * Create a resource. - * - * @param array $values - * @param string $collectionUrl - * @param HttpClient $client - * - * @return HalResource|false + * @inheritdoc */ public static function create(array $values, $collectionUrl, HttpClient $client) { diff --git a/src/Model/HalResourceInterface.php b/src/Model/HalResourceInterface.php index <HASH>..<HASH> 100644 --- a/src/Model/HalResourceInterface.php +++ b/src/Model/HalResourceInterface.php @@ -2,6 +2,7 @@ namespace CommerceGuys\Platform\Cli\Model; use Guzzle\Http\Client as HttpClient; +use Guzzle\Http\Exception\ClientErrorResponseException; interface HalResourceInterface { @@ -18,13 +19,17 @@ interface HalResourceInterface public static function create(array $values, $collectionUrl, HttpClient $client); /** - * Get a resource. + * Get a resource at a URL. * - * @param string $id - * @param string $collectionUrl + * @param string $id + * @param string $collectionUrl * @param HttpClient $client * - * @return HalResourceInterface|false + * @throws ClientErrorResponseException On failure. + * + * @return HalResource|false + * The resource, or false if it has not been found (if the response code + * is 404). */ public static function get($id, $collectionUrl, HttpClient $client);
Cache the <I> response from getEnvironment().
platformsh_platformsh-cli
train
390a873f4fb36906df6b109a511ae5f577b56e64
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ setup( packages=find_packages(), install_requires=[ 'pdfrw', + 'PyPDF3', 'Pillow', 'PySimpleGUI', 'reportlab',
Added PyPDF3 as an install requirement
mrstephenneal_pdfconduit
train
4c24ddaf8ed4ad928bd15db7b34604cfc66074f9
diff --git a/packages/table/src/table-column.js b/packages/table/src/table-column.js index <HASH>..<HASH> 100644 --- a/packages/table/src/table-column.js +++ b/packages/table/src/table-column.js @@ -270,7 +270,7 @@ export default { fixed: this.fixed === '' ? true : this.fixed, filterMethod: this.filterMethod, filters: this.filters, - filterable: (this.filters && this.filters.length) || this.filterMethod, + filterable: this.filters || this.filterMethod, filterMultiple: this.filterMultiple, filterOpened: false, filteredValue: this.filteredValue || [], diff --git a/packages/table/src/table-header.js b/packages/table/src/table-header.js index <HASH>..<HASH> 100644 --- a/packages/table/src/table-header.js +++ b/packages/table/src/table-header.js @@ -124,7 +124,7 @@ export default { : '' } { - (column.filters && column.filters.length) || column.filterMethod + column.filterable ? <span class="el-table__column-filter-trigger" on-click={ ($event) => this.handleFilterClick($event, column) }><i class={ ['el-icon-arrow-down', column.filterOpened ? 'el-icon-arrow-up' : ''] }></i></span> : '' }
Table: fix table filter (#<I>)
ElemeFE_element
train
ffdbec12fea1b0bb758ef54a3be797e5420da0a7
diff --git a/cake/libs/view/helpers/jquery_engine.php b/cake/libs/view/helpers/jquery_engine.php index <HASH>..<HASH> 100644 --- a/cake/libs/view/helpers/jquery_engine.php +++ b/cake/libs/view/helpers/jquery_engine.php @@ -45,14 +45,26 @@ class JqueryEngineHelper extends JsBaseEngineHelper { /** * Add an event to the script cache. Operates on the currently selected elements. * + * ### Options + * + * - 'wrap' - Whether you want the callback wrapped in an anonymous function. (defaults true) + * - 'stop' - Whether you want the event to stopped. (defaults true) + * * @param string $type Type of event to bind to the current dom id * @param string $callback The Javascript function you wish to trigger or the function literal - * @param boolean $wrap Whether you want your callback wrapped in ```function (event) { }``` + * @param array $options Options for the event. * @return string completed event handler **/ - function event($type, $callback, $wrap = false) { - if ($wrap) { - $callback = 'function (event) {' . $callback . '}'; + function event($type, $callback, $options = array()) { + $defaults = array('wrap' => true, 'stop' => true); + $options = array_merge($defaults, $options); + + $function = 'function (event) {%s}'; + if ($options['wrap'] && $options['stop']) { + $callback .= "\nreturn false;"; + } + if ($options['wrap']) { + $callback = sprintf($function, $callback); } $out = $this->selection . ".bind('{$type}', $callback);"; return $out; @@ -64,7 +76,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper { * @return string completed domReady method **/ function domReady($functionBody) { - return $this->get('document')->event('ready', $functionBody, true); + return $this->get('document')->event('ready', $functionBody, array('stop' => false)); } /** * Create an iteration over the current selection result. diff --git a/cake/libs/view/helpers/js.php b/cake/libs/view/helpers/js.php index <HASH>..<HASH> 100644 --- a/cake/libs/view/helpers/js.php +++ b/cake/libs/view/helpers/js.php @@ -497,12 +497,17 @@ class JsBaseEngineHelper extends AppHelper { /** * Add an event to the script cache. Operates on the currently selected elements. * + * ### Options + * + * - 'wrap' - Whether you want the callback wrapped in an anonymous function. (defaults to true) + * - 'stop' - Whether you want the event to stopped. (defaults to true) + * * @param string $type Type of event to bind to the current dom id * @param string $callback The Javascript function you wish to trigger or the function literal - * @param boolean $wrap Whether you want your callback wrapped in ```function (event) { }``` + * @param array $options Options for the event. * @return string completed event handler **/ - function event($type, $callback, $wrap = false) { + function event($type, $callback, $options = array()) { trigger_error(sprintf(__('%s does not have event() implemented', true), get_class($this)), E_USER_WARNING); } /** diff --git a/cake/tests/cases/libs/view/helpers/jquery_engine.test.php b/cake/tests/cases/libs/view/helpers/jquery_engine.test.php index <HASH>..<HASH> 100644 --- a/cake/tests/cases/libs/view/helpers/jquery_engine.test.php +++ b/cake/tests/cases/libs/view/helpers/jquery_engine.test.php @@ -68,12 +68,16 @@ class JqueryEngineHelperTestCase extends CakeTestCase { * @return void **/ function testEvent() { - $result = $this->Jquery->get('#myLink')->event('click', 'doClick'); + $result = $this->Jquery->get('#myLink')->event('click', 'doClick', array('wrap' => false)); $expected = "$('#myLink').bind('click', doClick);"; $this->assertEqual($result, $expected); - $result = $this->Jquery->get('#myLink')->event('click', '$(this).hide();', true); - $expected = "\$('#myLink').bind('click', function (event) {\$(this).hide();});"; + $result = $this->Jquery->get('#myLink')->event('click', '$(this).show();', array('stop' => false)); + $expected = "$('#myLink').bind('click', function (event) {\$(this).show();});"; + $this->assertEqual($result, $expected); + + $result = $this->Jquery->get('#myLink')->event('click', '$(this).hide();'); + $expected = "\$('#myLink').bind('click', function (event) {\$(this).hide();\nreturn false;});"; $this->assertEqual($result, $expected); } /**
Refactoring event() and adding ability to stop default events.
cakephp_cakephp
train
e128c0768dc7e8a5c82ea3a91e0a55a1ef4b33e1
diff --git a/cmd/api/http.go b/cmd/api/http.go index <HASH>..<HASH> 100644 --- a/cmd/api/http.go +++ b/cmd/api/http.go @@ -6,7 +6,7 @@ import ( "net/http" ) -func writeJSON(w http.ResponseWriter, v interface{}, status int) { +func writeJSON(w http.ResponseWriter, status int, v interface{}) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) if err := json.NewEncoder(w).Encode(v); err != nil { diff --git a/cmd/api/main.go b/cmd/api/main.go index <HASH>..<HASH> 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -107,15 +107,14 @@ func issueAsset(ctx context.Context, w http.ResponseWriter, req *http.Request) { var buf bytes.Buffer tx.Serialize(&buf) - resp := map[string]interface{}{ + writeJSON(w, 200, map[string]interface{}{ "template": wallet.Tx{ Unsigned: buf.Bytes(), BlockChain: "sandbox", Inputs: []*wallet.Input{asset.IssuanceInput()}, }, "change_addresses": []changeAddr{}, - } - writeJSON(w, resp, 200) + }) } // /v3/assets/transfer @@ -171,10 +170,8 @@ func walletFinalize(ctx context.Context, w http.ResponseWriter, req *http.Reques var buf bytes.Buffer tx.Serialize(&buf) - resp := map[string]interface{}{ + writeJSON(w, 200, map[string]interface{}{ "transaction_id": tx.TxSha().String(), "raw_transaction": chainjson.HexBytes(buf.Bytes()), - } - - writeJSON(w, resp, 200) + }) }
cmd/api: reorder writeJSON params for readability Closes chain/chainprv#<I>. Reviewers: @tessr
chain_chain
train
3f7d66aacf068e3b1324ed9628ee30e265133620
diff --git a/xwiki-commons-core/xwiki-commons-filter/xwiki-commons-filter-xml/src/main/java/org/xwiki/filter/xml/internal/serializer/DefaultXMLSerializer.java b/xwiki-commons-core/xwiki-commons-filter/xwiki-commons-filter-xml/src/main/java/org/xwiki/filter/xml/internal/serializer/DefaultXMLSerializer.java index <HASH>..<HASH> 100644 --- a/xwiki-commons-core/xwiki-commons-filter/xwiki-commons-filter-xml/src/main/java/org/xwiki/filter/xml/internal/serializer/DefaultXMLSerializer.java +++ b/xwiki-commons-core/xwiki-commons-filter/xwiki-commons-filter-xml/src/main/java/org/xwiki/filter/xml/internal/serializer/DefaultXMLSerializer.java @@ -26,6 +26,8 @@ import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; +import javanet.staxutils.XMLEventStreamWriter; + import javax.inject.Singleton; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; @@ -73,16 +75,25 @@ public class DefaultXMLSerializer implements InvocationHandler ConverterManager converter, XMLConfiguration configuration) throws XMLStreamException, FactoryConfigurationError { - // SAXResult is not supported by the standard XMLOutputFactory - if (xmlResult instanceof SAXResult) { - xmlResult = new StAXResult(new SAXEventWriter(((SAXResult) xmlResult).getHandler())); - } - - this.xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(xmlResult); this.parameterManager = parameterManager; this.descriptor = descriptor; this.converter = converter; this.configuration = configuration != null ? configuration : new XMLConfiguration(); + + if (xmlResult instanceof SAXResult) { + // SAXResult is not supported by the standard XMLOutputFactory + this.xmlStreamWriter = new XMLEventStreamWriter(new SAXEventWriter(((SAXResult) xmlResult).getHandler())); + } else if (xmlResult instanceof StAXResult) { + // XMLEventWriter is not supported as result of XMLOutputFactory#createXMLStreamWriter + StAXResult staxResult = (StAXResult) xmlResult; + if (staxResult.getXMLStreamWriter() != null) { + this.xmlStreamWriter = staxResult.getXMLStreamWriter(); + } else { + this.xmlStreamWriter = new XMLEventStreamWriter(staxResult.getXMLEventWriter()); + } + } else { + this.xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(xmlResult); + } } private boolean isValidBlockElementName(String blockName)
XCOMMONS-<I>: Provide a generic XML parser/serializer for filters * improve Result support in the serializer
xwiki_xwiki-commons
train
30755c6ad8aaeacf83de4257c957f70dea5f5008
diff --git a/test_sqlalchemy.py b/test_sqlalchemy.py index <HASH>..<HASH> 100755 --- a/test_sqlalchemy.py +++ b/test_sqlalchemy.py @@ -68,16 +68,24 @@ class BasicAppTestCase(unittest.TestCase): with self.app.test_request_context(): todo = self.Todo('Test 1', 'test') self.db.session.add(todo) + self.db.session.flush() + todo.done = True self.db.session.commit() queries = fsa.get_debug_queries() - self.assertEqual(len(queries), 1) + self.assertEqual(len(queries), 2) query = queries[0] self.assertTrue('insert into' in query.statement.lower()) self.assertEqual(query.parameters[0], 'Test 1') self.assertEqual(query.parameters[1], 'test') self.assertTrue('test_sqlalchemy.py' in query.context) self.assertTrue('test_query_recording' in query.context) + query = queries[1] + self.assertTrue('update' in query.statement.lower()) + self.assertEqual(query.parameters[0], 1) + self.assertEqual(query.parameters[1], 1) + self.assertTrue('test_sqlalchemy.py' in query.context) + self.assertTrue('test_query_recording' in query.context) def test_helper_api(self): self.assertEqual(self.db.metadata, self.db.Model.metadata)
Run more than one query in query recorder test Otherwise the case where the sqlalchemy_queries list already exists isn't tested.
pallets_flask-sqlalchemy
train
af438ce945c798e87aa1c374f8a7e4de61d7714c
diff --git a/src/typeahead/plugin.js b/src/typeahead/plugin.js index <HASH>..<HASH> 100644 --- a/src/typeahead/plugin.js +++ b/src/typeahead/plugin.js @@ -7,7 +7,7 @@ (function() { var old, typeaheadKey, methods; - old = jQuery.fn.typeahead; + old = $.fn.typeahead; typeaheadKey = 'ttTypeahead'; @@ -109,7 +109,7 @@ } }; - jQuery.fn.typeahead = function(method) { + $.fn.typeahead = function(method) { if (methods[method]) { return methods[method].apply(this, [].slice.call(arguments, 1)); } @@ -119,8 +119,8 @@ } }; - jQuery.fn.typeahead.noConflict = function noConflict() { - jQuery.fn.typeahead = old; + $.fn.typeahead.noConflict = function noConflict() { + $.fn.typeahead = old; return this; }; })();
Change jQuery to $ in function declaration When compiled, `window.jQuery` is passed in and is set to the variable `$` internally. We should maintain that variable when defining the typeahead function. <URL>
twitter_typeahead.js
train
38d70a1c3dceedb042249c792bf6a9e15a0d607d
diff --git a/internal/terraform/context_apply2_test.go b/internal/terraform/context_apply2_test.go index <HASH>..<HASH> 100644 --- a/internal/terraform/context_apply2_test.go +++ b/internal/terraform/context_apply2_test.go @@ -1042,11 +1042,38 @@ output "out" { state, diags := ctx.Apply(plan, m) assertNoErrors(t, diags) - // TODO: extend this to ensure the otherProvider is always properly - // configured during the destroy plan + otherProvider.ConfigureProviderCalled = false + otherProvider.ConfigureProviderFn = func(req providers.ConfigureProviderRequest) (resp providers.ConfigureProviderResponse) { + // check that our config is complete, even during a destroy plan + expected := cty.ObjectVal(map[string]cty.Value{ + "local": cty.ListVal([]cty.Value{cty.StringVal("first-ok"), cty.StringVal("second-ok")}), + "output": cty.ListVal([]cty.Value{cty.StringVal("first-ok"), cty.StringVal("second-ok")}), + "var": cty.MapVal(map[string]cty.Value{ + "a": cty.StringVal("first"), + "b": cty.StringVal("second"), + }), + }) + + if !req.Config.RawEquals(expected) { + resp.Diagnostics = resp.Diagnostics.Append(fmt.Errorf( + `incorrect provider config: +expected: %#v +got: %#v`, + expected, req.Config)) + } + + return resp + } opts.Mode = plans.DestroyMode + // skip refresh so that we don't configure the provider before the destroy plan + opts.SkipRefresh = true + // destroy only a single instance not included in the moved statements _, diags = ctx.Plan(m, state, opts) assertNoErrors(t, diags) + + if !otherProvider.ConfigureProviderCalled { + t.Fatal("failed to configure provider during destroy plan") + } } diff --git a/internal/terraform/node_provider.go b/internal/terraform/node_provider.go index <HASH>..<HASH> 100644 --- a/internal/terraform/node_provider.go +++ b/internal/terraform/node_provider.go @@ -37,10 +37,7 @@ func (n *NodeApplyableProvider) Execute(ctx EvalContext, op walkOperation) (diag case walkValidate: log.Printf("[TRACE] NodeApplyableProvider: validating configuration for %s", n.Addr) return diags.Append(n.ValidateProvider(ctx, provider)) - case walkPlan, walkApply, walkDestroy: - // walkPlanDestroy is purposely skipped here, since the config is not - // evaluated, and the provider is not needed to create delete actions - // for all instances. + case walkPlan, walkPlanDestroy, walkApply, walkDestroy: log.Printf("[TRACE] NodeApplyableProvider: configuring %s", n.Addr) return diags.Append(n.ConfigureProvider(ctx, provider, false)) case walkImport:
configure providers during destroy plan Now that we can fully evaluate a provider configuration, make sure we configure the provider before using it during a destroy plan.
hashicorp_terraform
train
074330707c208481b931504625a6b7fbb71cf537
diff --git a/src/ol/format/gml/base.js b/src/ol/format/gml/base.js index <HASH>..<HASH> 100644 --- a/src/ol/format/gml/base.js +++ b/src/ol/format/gml/base.js @@ -549,7 +549,8 @@ ol.format.GML.prototype.readFlatLinearRing_ = function(node, objectStack) { goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT); goog.asserts.assert(node.localName == 'LinearRing'); var ring = ol.xml.pushParseAndPop(/** @type {Array.<number>} */(null), - ol.format.GML.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, objectStack); + this.constructor.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, + objectStack, this); if (goog.isDefAndNotNull(ring)) { return ring; } else { @@ -590,7 +591,7 @@ ol.format.GML.prototype.readPolygon_ = function(node, objectStack) { goog.asserts.assert(node.localName == 'Polygon'); var flatLinearRings = ol.xml.pushParseAndPop( /** @type {Array.<Array.<number>>} */ ([null]), - ol.format.GML.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack); + this.constructor.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack, this); if (goog.isDef(flatLinearRings) && !goog.isNull(flatLinearRings[0])) { var polygon = new ol.geom.Polygon(null); @@ -692,7 +693,8 @@ ol.format.GML.prototype.readFlatCoordinatesFromNode_ = function(node, goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT); return /** @type {Array.<number>} */ (ol.xml.pushParseAndPop( null, - ol.format.GML.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, objectStack)); + this.constructor.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, + objectStack, this)); };
Call dedicated version format methods with 'this.constructor' object
openlayers_openlayers
train
73cbeffb282b6eb9ae1b564f2e6f76cdefb97ffb
diff --git a/errors.js b/errors.js index <HASH>..<HASH> 100644 --- a/errors.js +++ b/errors.js @@ -132,6 +132,19 @@ module.exports.ResponseFrameState = TypedError({ state: null }); +module.exports.RequestAlreadyDone = TypedError({ + type: 'tchannel.request-already-done', + message: 'cannot {attempted}, request already done', + attempted: null +}); + +module.exports.RequestFrameState = TypedError({ + type: 'tchannel.request-frame-state', + message: 'cannot send {attempted} in {state} request state', + attempted: null, + state: null +}); + module.exports.SocketError = WrappedError({ type: 'tchannel.socket', message: 'tchannel socket error ({code} from {syscall}): {origMessage}', diff --git a/outgoing_request.js b/outgoing_request.js index <HASH>..<HASH> 100644 --- a/outgoing_request.js +++ b/outgoing_request.js @@ -136,7 +136,10 @@ TChannelOutgoingRequest.prototype.sendParts = function sendParts(parts, isLast) case States.Done: // TODO: could probably happen normally, like say if a // streaming request is canceled - self.emit('error', new Error('got frame in done state')); // TODO: typed error + self.emit('error', errors.RequestFrameState({ + attempted: 'arg parts', + state: 'Done' + })); break; case States.Error: // TODO: log warn @@ -157,10 +160,15 @@ TChannelOutgoingRequest.prototype.sendCallRequestFrame = function sendCallReques else self.state = States.Streaming; break; case States.Streaming: - self.emit('error', new Error('first request frame already sent')); // TODO: typed error + self.emit('error', errors.RequestFrameState({ + attempted: 'call request', + state: 'Streaming' + })); break; case States.Done: - self.emit('error', new Error('request already done')); // TODO: typed error + self.emit('error', errors.RequestAlreadyDone({ + attempted: 'call request' + })); break; } }; @@ -169,14 +177,19 @@ TChannelOutgoingRequest.prototype.sendCallRequestContFrame = function sendCallRe var self = this; switch (self.state) { case States.Initial: - self.emit('error', new Error('first request frame not sent')); // TODO: typed error + self.emit('error', errors.RequestFrameState({ + attempted: 'call request continuation', + state: 'Initial' + })); break; case States.Streaming: self.sendFrame.callRequestCont(args, isLast); if (isLast) self.state = States.Done; break; case States.Done: - self.emit('error', new Error('request already done')); // TODO: typed error + self.emit('error', errors.RequestAlreadyDone({ + attempted: 'call request continuation' + })); break; } };
OutgoingRequest: add send state errors to match res
uber_tchannel-node
train
21aedc7050b23b7b50b80f4fb88af2f75b73cb12
diff --git a/settings/index.js b/settings/index.js index <HASH>..<HASH> 100644 --- a/settings/index.js +++ b/settings/index.js @@ -1,8 +1,11 @@ 'use strict'; const path = require('path'); +const chalk = require('chalk'); const pathExists = require('path-exists'); +const Logger = require('../logger'); + const settings = { raw: null, @@ -57,29 +60,35 @@ const settings = { }, dest() { - return this.isDistribution() ? path.join(this.project(), './dist') : path.join(this.project(), './build'); - }, - - htmlWebpackConfig: (function() { - var result; - function getConfig() { - if (!result) { - console.log('generating results'); - var templatePath = './index.html'; - var faviconPath = './favicon.ico'; - var hasLocalTemplate = pathExists.sync(path.join(this.app(), templatePath)); - var hasLocalFavicon = pathExists.sync(path.join(this.app(), faviconPath)); - console.log('Using ' + (hasLocalTemplate ? 'user defined' : 'workflow') + ' template'); - console.log('Using ' + (hasLocalFavicon ? 'user defined' : 'workflow') + ' favicon'); - result = { - template: hasLocalTemplate ? templatePath : path.relative(this.app(), path.join(__dirname, '../webpack', templatePath)), - favicon: hasLocalFavicon ? faviconPath : path.relative(this.app(), path.join(__dirname, '../webpack', faviconPath)) - }; - } - return result; + return this.isDistribution() ? + path.join(this.project(), './dist') : + path.join(this.project(), './build'); + }, + + asset(filePath) { + + let templatePath = filePath; + + const hasLocalTemplate = pathExists.sync(path.join(this.app(), templatePath)); + templatePath = hasLocalTemplate ? templatePath : path.relative(this.app(), path.join(__dirname, '../webpack', templatePath)); + const name = path.basename(templatePath); + + if (!hasLocalTemplate) { + Logger.warn(`Using from ${chalk.blue('availity-workflow/webpack/' + name)}`); } - return getConfig; - })(), + + + return templatePath; + + }, + + template() { + return this.asset('./index.html'); + }, + + favicon() { + return this.asset('./favicon.ico'); + }, ekko() { return { @@ -134,6 +143,10 @@ const settings = { return this.environment() === 'production'; }, + isAngular() { + return true; + }, + // Uses globby which defaults to process.cwd() and path.resolve(options.cwd, "/") js() { return [
refactor asset logic for index.html and favicon.ico
Availity_availity-workflow
train
3822429b91f265bff4fb4b14c4f16e49e26741fb
diff --git a/src/Screen/Fields/Group.php b/src/Screen/Fields/Group.php index <HASH>..<HASH> 100644 --- a/src/Screen/Fields/Group.php +++ b/src/Screen/Fields/Group.php @@ -170,4 +170,12 @@ class Group implements Fieldable, Groupable { return $this->set('align', 'align-items-end'); } + + /** + * @return string + */ + public function __toString(): string + { + return (string) $this->render(); + } }
Added the ability to convert a group to a string.
orchidsoftware_platform
train
3f5f454db5d94bca00f24c187bddb8460eb83ab4
diff --git a/book/src/main/java/module-info.java b/book/src/main/java/module-info.java index <HASH>..<HASH> 100644 --- a/book/src/main/java/module-info.java +++ b/book/src/main/java/module-info.java @@ -33,4 +33,4 @@ module com.semanticcms.dia.model.book { requires com.semanticcms.core.taglib; // <groupId>com.semanticcms</groupId><artifactId>semanticcms-core-taglib</artifactId> requires com.semanticcms.section.taglib; // <groupId>com.semanticcms</groupId><artifactId>semanticcms-section-taglib</artifactId> requires taglibs.standard.spec; // <groupId>org.apache.taglibs</groupId><artifactId>taglibs-standard-spec</artifactId> -} +} // TODO: Avoiding rewrite-maven-plugin-4.22.2 truncation diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index <HASH>..<HASH> 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -25,4 +25,4 @@ module com.semanticcms.dia.model { // Direct requires com.aoapps.lang; // <groupId>com.aoapps</groupId><artifactId>ao-lang</artifactId> requires com.semanticcms.core.model; // <groupId>com.semanticcms</groupId><artifactId>semanticcms-core-model</artifactId> -} +} // TODO: Avoiding rewrite-maven-plugin-4.22.2 truncation
Activated org.openrewrite.java.cleanup.Cleanup
aoindustries_semanticcms-dia-model
train
1b788f7152a421ed71a7cba41cd40555a1b1a19c
diff --git a/test/unit/specs/Searching.spec.js b/test/unit/specs/Searching.spec.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/Searching.spec.js +++ b/test/unit/specs/Searching.spec.js @@ -267,7 +267,7 @@ describe('Searching', () => { const { nodeMap } = wrapper.vm.forest expect(nodeMap).toEqual(Object.keys(nodeMap).reduce((prev, id) => ({ ...prev, - [id]: jasmine.objectContaining({ isMatched: idListOfNodesThatShouldBeMatched.includes(id) }) + [id]: jasmine.objectContaining({ isMatched: idListOfNodesThatShouldBeMatched.includes(id) }), }), {})) }
make eslint happy
riophae_vue-treeselect
train
f3d07cdf5732631646d5572cc76f6e2d053c1615
diff --git a/samples/chat/js/messages.js b/samples/chat/js/messages.js index <HASH>..<HASH> 100644 --- a/samples/chat/js/messages.js +++ b/samples/chat/js/messages.js @@ -62,7 +62,6 @@ function onMessage(userId, msg) { updateDialogsList(msg.dialog_id, msg.body); } - throw '123123123'; } function retrieveChatMessages(dialog, beforeDateSent){ @@ -207,7 +206,6 @@ function setupOnMessageListener() { // show typing status in chat or groupchat function onMessageTyping(isTyping, userId, dialogId) { showUserIsTypingView(isTyping, userId, dialogId); - throw '123123123'; } // start timer after keypress event
deleted throw '...'; from some listners in samples/chat/js/messages.js
QuickBlox_quickblox-javascript-sdk
train
38da796eaf4fbac06ed99595fd8feab2fc268799
diff --git a/public/js/embed.js b/public/js/embed.js index <HASH>..<HASH> 100644 --- a/public/js/embed.js +++ b/public/js/embed.js @@ -197,8 +197,8 @@ function embed(link) { var iframe = document.createElement('iframe'), resize = document.createElement('div'), url = link.href.replace(/edit/, 'embed'); - iframe.src = url; - iframe._src = url; // support for google slide embed + iframe.src = url.split('&')[0]; + iframe._src = url.split('&')[0]; // support for google slide embed iframe.className = link.className; // inherit all the classes from the link iframe.id = link.id; // also inherit, giving more style control to the user iframe.style.border = '1px solid #aaa';
fix bug: Embed bins do not respect ?panel,panel passing only 1st part of query as iframe src - assuming the 1st query parameter is always about panels
jsbin_jsbin
train
d8f1be55dd026129478142a9c684a12a8a3cf1be
diff --git a/picturefill.js b/picturefill.js index <HASH>..<HASH> 100644 --- a/picturefill.js +++ b/picturefill.js @@ -9,48 +9,22 @@ B) A major browser implements <picture> */ (function( w ){ - var document = w.document, - Modernizr = w.Modernizr; + var document = w.document; // Test if `<picture>` is supported natively. Store the boolean result for // later use. var hasNativePicture = !!( - document.createElement('picture') && window.HTMLPictureElement + document.createElement('picture') && w.HTMLPictureElement ); - // Register a Modernizr test for `<picture>`, if Modernizr is present. - // Modernizr is NOT required -- this just augments it if present. - // - // If you have support for Modernizr classes in your build, this will also - // give you a handy `.picture` or `.no-picture` class on the `html` element. - if (Modernizr) Modernizr.addTest('picture', function () { - return hasNativePicture; - }); - - // Exit early if `<picture>` is natively supported. - if (hasNativePicture) return; - var matchMedia = w.matchMedia; - - // A wrapper for `window.matchMedia` that gives us a consistent interface - // whether we are using `Modernizr.mq` or `matchMedia`. - var mqWrapper = function (query) { - return matchMedia(query).matches; - }; - - // Pick a media query function. If Modernizr is installed with the media - // query extension, use it; otherwise, use `window.matchMedia` wrapper - // defined above. - var mq = Modernizr && Modernizr.mq ? - Modernizr.mq : - (matchMedia && matchMedia( "only all" ) ? mqWrapper : null); - // Exit early if: - // - // * Browser supports `<picture>` - // * Browser does not support either `<picture>`, - // or Media Queries, or Modernizr-shimmed media queries. - if( !mq ) return; + // Exit early if `<picture>` is natively supported. + // If neither `<picture>` **or** `window.matchMedia is supported, exit + // as well -- we need `matchMedia` to be able to properly polyfill this + // feature. **Note**: there is a polyfill available for `matchMedia`: + // <https://github.com/paulirish/matchMedia.js/> + if ( hasNativePicture || !matchMedia || !matchMedia('only all') ) return; w.picturefill = function(){ var ps = document.getElementsByTagName( "picture" ); @@ -63,7 +37,7 @@ // See if which sources match for( var j = 0, jl = sources.length; j < jl; j++ ){ var media = sources[ j ].getAttribute( "media" ); - if( !media || mq( media ) ){ + if( !media || matchMedia( media ).matches ){ matches.push( sources[ j ] ); } }
Removed Modernizr hooks
scottjehl_picturefill
train
7f2e75781f849767b4b9f3f8adbe792b8c92cb93
diff --git a/src/java/voldemort/utils/KeyVersionFetcherCLI.java b/src/java/voldemort/utils/KeyVersionFetcherCLI.java index <HASH>..<HASH> 100644 --- a/src/java/voldemort/utils/KeyVersionFetcherCLI.java +++ b/src/java/voldemort/utils/KeyVersionFetcherCLI.java @@ -51,6 +51,7 @@ import voldemort.client.protocol.admin.AdminClientConfig; import voldemort.cluster.Cluster; import voldemort.routing.BaseStoreRoutingPlan; import voldemort.store.StoreDefinition; +import voldemort.versioning.Version; import voldemort.versioning.Versioned; /** @@ -237,10 +238,17 @@ public class KeyVersionFetcherCLI { .getZoneId(); int zoneNAry = storeRoutingPlan.getZoneNAry(zoneId, replicatingNodeId, key); + // Sort the versions so that on-disk order of concurrent + // versions is not visible. + TreeSet<Version> sortedVersions = new TreeSet<Version>(); + for(Versioned<byte[]> value: values) { + sortedVersions.add(value.getVersion()); + } + StringBuilder sb = new StringBuilder(); sb.append(ByteUtils.toHexString(key)); - for(Versioned<byte[]> value: values) { - sb.append(" : ").append(value.getVersion().toString()); + for(Version version: sortedVersions) { + sb.append(" : ").append(version.toString()); } if(details) {
Sort versions displayed by KeyVersionFetcherCLI
voldemort_voldemort
train
0ad326521213419a8b4b534c5fc13ba1cf2fcde4
diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/FileTimerPersistence.java b/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/FileTimerPersistence.java index <HASH>..<HASH> 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/FileTimerPersistence.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/FileTimerPersistence.java @@ -126,6 +126,7 @@ public class FileTimerPersistence implements TimerPersistence, Service<FileTimer final RiverMarshallerFactory factory = new RiverMarshallerFactory(); final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setClassResolver(ModularClassResolver.getInstance(moduleLoader.getValue())); + configuration.setVersion(3); this.configuration = configuration; this.factory = factory;
[WFLY-<I>] Fix legacy timer serialization
wildfly_wildfly
train
fc41ca0c2823270e85c34aa54ddeca49d5edd611
diff --git a/src/Routes/Collection.php b/src/Routes/Collection.php index <HASH>..<HASH> 100644 --- a/src/Routes/Collection.php +++ b/src/Routes/Collection.php @@ -4,6 +4,7 @@ namespace Lord\Laroute\Routes; use Illuminate\Routing\Route; use Illuminate\Routing\RouteCollection; +use Illuminate\Support\Arr; use Lord\Laroute\Routes\Exceptions\ZeroRoutesException; class Collection extends \Illuminate\Support\Collection @@ -66,7 +67,7 @@ class Collection extends \Illuminate\Support\Collection $uri = $route->uri(); $name = $route->getName(); $action = $route->getActionName(); - $laroute = array_get($route->getAction(), 'laroute', null); + $laroute = Arr::get($route->getAction(), 'laroute', null); if(!empty($namespace)) { $a = $route->getAction();
change global array helper to Arr equivalent
aaronlord_laroute
train
9fe0d3fae97f04f41bb81c1e4e044ec03cbc6034
diff --git a/lib/cequel/schema/migration_validator.rb b/lib/cequel/schema/migration_validator.rb index <HASH>..<HASH> 100644 --- a/lib/cequel/schema/migration_validator.rb +++ b/lib/cequel/schema/migration_validator.rb @@ -84,12 +84,25 @@ module Cequel def assert_data_columns_match! each_data_column_pair do |old_column, new_column| if old_column && new_column - assert_same_column_type!(old_column, new_column) + assert_valid_type_transition!(old_column, new_column) + assert_same_column_structure!(old_column, new_column) end end end - def assert_same_column_type!(old_column, new_column) + def assert_valid_type_transition!(old_column, new_column) + if old_column.type != new_column.type + valid_new_types = old_column.type.compatible_types + unless valid_new_types.include?(new_column.type) + fail InvalidSchemaMigration, + "Can't change #{old_column.name} from " \ + "#{old_column.type} to #{new_column.type}. #{old_column.type} " \ + "columns may only be altered to #{valid_new_types.to_sentence}." + end + end + end + + def assert_same_column_structure!(old_column, new_column) if old_column.class != new_column.class fail InvalidSchemaMigration, "Can't change #{old_column.name} from " \ diff --git a/lib/cequel/type.rb b/lib/cequel/type.rb index <HASH>..<HASH> 100644 --- a/lib/cequel/type.rb +++ b/lib/cequel/type.rb @@ -125,6 +125,17 @@ module Cequel end # + # CQL only allows changing column types when the old type's binary + # representation is compatible with the new type. + # + # @return [Array<Type>] new types that columns of this type may be + # altered to + # + def compatible_types + [Type[:blob]] + end + + # # A string representation of this type # def to_s @@ -152,6 +163,10 @@ module Cequel # @see TK CQL3 documentation for ascii type # class Ascii < String + def compatible_types + super + [Type[:text]] + end + private def encoding @@ -210,6 +225,10 @@ module Cequel ['org.apache.cassandra.db.marshal.CounterColumnType'] end + def compatible_types + [] + end + def cast(value) Integer(value) end diff --git a/spec/examples/schema/table_synchronizer_spec.rb b/spec/examples/schema/table_synchronizer_spec.rb index <HASH>..<HASH> 100644 --- a/spec/examples/schema/table_synchronizer_spec.rb +++ b/spec/examples/schema/table_synchronizer_spec.rb @@ -30,7 +30,7 @@ describe Cequel::Schema::TableSynchronizer do key :blog_subdomain, :text key :permalink, :text column :title, :text, :index => true - column :body, :text + column :body, :ascii column :created_at, :timestamp set :author_names, :text with :comment, 'Test Table' @@ -46,7 +46,7 @@ describe Cequel::Schema::TableSynchronizer do key :blog_subdomain, :text key :post_permalink, :text column :title, :text - column :body, :ascii + column :body, :text column :primary_author_id, :uuid, :index => true column :created_at, :timestamp, :index => true column :published_at, :timestamp @@ -81,7 +81,7 @@ describe Cequel::Schema::TableSynchronizer do end it 'should change column type' do - table.column(:body).type.should == Cequel::Type[:ascii] + table.column(:body).type.should == Cequel::Type[:text] end it 'should change properties' do @@ -162,7 +162,21 @@ describe Cequel::Schema::TableSynchronizer do }.to raise_error(Cequel::InvalidSchemaMigration) end - it 'should not allow changing of clustering order' + it 'should not allow invalid type transitions of a data column' do + expect { + cequel.schema.sync_table :posts do + key :blog_subdomain, :text + key :permalink, :text + column :title, :text, :index => true + column :body, :int + column :created_at, :timestamp + set :author_names, :text + with :comment, 'Test Table' + end + }.to raise_error(Cequel::InvalidSchemaMigration) + end + + it 'should not allow type change of an indexed column' end diff --git a/spec/examples/schema/table_updater_spec.rb b/spec/examples/schema/table_updater_spec.rb index <HASH>..<HASH> 100644 --- a/spec/examples/schema/table_updater_spec.rb +++ b/spec/examples/schema/table_updater_spec.rb @@ -5,7 +5,7 @@ describe Cequel::Schema::TableUpdater do cequel.schema.create_table(:posts) do key :blog_subdomain, :text key :permalink, :text - column :title, :text + column :title, :ascii column :body, :text end end @@ -83,12 +83,12 @@ describe Cequel::Schema::TableUpdater do describe '#change_column' do before do cequel.schema.alter_table(:posts) do - change_column :title, :ascii + change_column :title, :text end end it 'should change the type' do - table.data_column(:title).type.should == Cequel::Type[:ascii] + table.data_column(:title).type.should == Cequel::Type[:text] end end
Fail fast when attempting to change a column's type in an incompatible way Later patchlevels of Cassandra <I> and <I> only allow a small subset of all possible type transitions; fail fast when attempting one that's not allowed.
cequel_cequel
train
66abf24a55fb83424dc992c1e14d7a7dbdda7b12
diff --git a/runtime/runtime.js b/runtime/runtime.js index <HASH>..<HASH> 100644 --- a/runtime/runtime.js +++ b/runtime/runtime.js @@ -262,12 +262,28 @@ var rb_intern = Rt.Y = function(id) { if (!sym) { sym = new rb_cSymbol.$a(); sym.sym = id; + rb_symbol_tbl[id] = sym; } return sym; }; /** + All symbols +*/ +Rt.symbols = function() { + var symbols = []; + + for (var sym in rb_symbol_tbl) { + if (rb_symbol_tbl.hasOwnProperty(sym)) { + symbols.push(rb_symbol_tbl[sym]); + } + } + + return symbols; +}; + +/** Undefine methods */ Rt.um = function(kls) {
VM.symbols() for getting all symbols
opal_opal
train
6b7dd26d1be6fc508ddb05dcfe181dc11626fd67
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -8,6 +8,8 @@ tests_require = ['nose', 'mock', 'testfixtures', 'blinker'] if sys.version_info[0:2] >= (3, 5): tests_require.append('Flask>=1.0') + # For some reason, Flask 1.1.1 is pulling in Jinja2 3.0.0 which causes syntax errors. + tests_require.append('Jinja2<3.0.0') if sys.version_info[0:2] <= (3, 5): tests_require.append('Django>=1.11,<=2.2')
reinstate jinja2 constraint for test dependencies
honeybadger-io_honeybadger-python
train
97dcdae4aff3ae6ae5f5bcf356a72babaa9f293d
diff --git a/src/Propel/Generator/Behavior/Timestampable/TimestampableBehavior.php b/src/Propel/Generator/Behavior/Timestampable/TimestampableBehavior.php index <HASH>..<HASH> 100644 --- a/src/Propel/Generator/Behavior/Timestampable/TimestampableBehavior.php +++ b/src/Propel/Generator/Behavior/Timestampable/TimestampableBehavior.php @@ -83,8 +83,12 @@ class TimestampableBehavior extends Behavior public function preUpdate($builder) { if ($this->withUpdatedAt()) { + $valueSource = strtoupper($this->getTable()->getColumn($this->getParameter('update_column'))->getType()) === 'INTEGER' + ? 'time()' + : '\\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision()' + ; return "if (\$this->isModified() && !\$this->isColumnModified(" . $this->getColumnConstant('update_column', $builder) . ")) { - \$this->" . $this->getColumnSetter('update_column') . "(\\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision()); + \$this->" . $this->getColumnSetter('update_column') . "(${valueSource}); }"; } @@ -101,16 +105,24 @@ class TimestampableBehavior extends Behavior $script = ''; if ($this->withCreatedAt()) { + $valueSource = strtoupper($this->getTable()->getColumn($this->getParameter('create_column'))->getType()) === 'INTEGER' + ? 'time()' + : '\\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision()' + ; $script .= " if (!\$this->isColumnModified(" . $this->getColumnConstant('create_column', $builder) . ")) { - \$this->" . $this->getColumnSetter('create_column') . "(\\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision()); + \$this->" . $this->getColumnSetter('create_column') . "(${valueSource}); }"; } if ($this->withUpdatedAt()) { + $valueSource = strtoupper($this->getTable()->getColumn($this->getParameter('update_column'))->getType()) === 'INTEGER' + ? 'time()' + : '\\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision()' + ; $script .= " if (!\$this->isColumnModified(" . $this->getColumnConstant('update_column', $builder) . ")) { - \$this->" . $this->getColumnSetter('update_column') . "(\\Propel\\Runtime\\Util\\PropelDateTime::createHighPrecision()); + \$this->" . $this->getColumnSetter('update_column') . "(${valueSource}); }"; }
Allows the use of TimestampableBehavior with INTEGER columns (#<I>)
propelorm_Propel2
train
4c580f586a6cea7339da0dac572b64af353eb30c
diff --git a/public/source/staging.js b/public/source/staging.js index <HASH>..<HASH> 100644 --- a/public/source/staging.js +++ b/public/source/staging.js @@ -182,14 +182,12 @@ var FileViewModel = function(staging, type) { this.staging = staging; this.app = staging.app; this.type = type; - this.imageDiff = new ImageDiffViewModel(this); - this.fileDiff = new LineByLineDiffViewModel(this); + this.diff = type == 'image' ? new ImageDiffViewModel(this) : new LineByLineDiffViewModel(this); this.staged = ko.observable(true); this.name = ko.observable(); this.isNew = ko.observable(false); this.removed = ko.observable(false); this.conflict = ko.observable(false); - this.diffs = ko.observable([]); this.showingDiffs = ko.observable(false); this.diffsProgressBar = new ProgressBarViewModel('diffs-' + this.staging.repository.repoPath); } @@ -214,36 +212,22 @@ FileViewModel.prototype.toogleDiffs = function() { } } FileViewModel.prototype.invalidateDiff = function(drawProgressBar) { - if (this.type == 'image') { - this.imageDiff.invalidateDiff(drawProgressBar); - } else { - this.fileDiff.invalidateDiff(drawProgressBar); - } -} -FileViewModel.prototype.getDiffObject = function() { - if (this.type == 'image') { - return this.imageDiff; - } else { - return this.fileDiff; - } + this.diff.invalidateDiff(drawProgressBar); } var LineByLineDiffViewModel = function(ancestor) { this.ancestor = ancestor; this.templateName = 'textFileDiff'; + this.diffs = ko.observable(); } LineByLineDiffViewModel.prototype.invalidateDiff = function(drawProgressBar) { - var ancestor = this.ancestor; + var self = this; + var ancestor = self.ancestor; if (ancestor.showingDiffs()) { if (drawProgressBar) ancestor.diffsProgressBar.start(); var isTextType = ancestor.type == 'text' ? true : false; ancestor.app.get('/diff', { file: ancestor.name(), path: ancestor.staging.repository.repoPath}, function(err, diffs) { - if (diffs && diffs.length > 0 && diffs[0].type == 'image') { - ancestor.type = 'image'; - ancestor.imageDiff.invalidateDiff(drawProgressBar); - return; - } if (drawProgressBar) ancestor.diffsProgressBar.stop(); if (err) return; var newDiffs = []; @@ -260,7 +244,7 @@ LineByLineDiffViewModel.prototype.invalidateDiff = function(drawProgressBar) { } ); }); - ancestor.diffs(newDiffs); + self.diffs(newDiffs); }); } } @@ -268,9 +252,11 @@ LineByLineDiffViewModel.prototype.invalidateDiff = function(drawProgressBar) { var ImageDiffViewModel = function(ancestor) { this.ancestor = ancestor; this.templateName = 'imageFileDiff'; + this.diffs = ko.observable(); } ImageDiffViewModel.prototype.invalidateDiff = function(drawProgressBar) { - var ancestor = this.ancestor; + var self = this; + var ancestor = self.ancestor; if (ancestor.showingDiffs()) { if (drawProgressBar) ancestor.diffsProgressBar.start(); @@ -304,11 +290,11 @@ ImageDiffViewModel.prototype.invalidateDiff = function(drawProgressBar) { isSecondElementImage: isSecondElementImage }); - ancestor.diffs(newDiffs); + self.diffs(newDiffs); } } var getImageElement = function(imageFile, repoPath, version) { return '/api/diff/image?path=' + encodeURIComponent(repoPath) + '&filename=' + imageFile + '&version=' + version; } - \ No newline at end of file +
Change image file detection to check ext. instead of first line
FredrikNoren_ungit
train
d72da506c585ec6b761cc4276254b7c7127c53b2
diff --git a/upnp.go b/upnp.go index <HASH>..<HASH> 100644 --- a/upnp.go +++ b/upnp.go @@ -361,7 +361,7 @@ func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int // A single concatenation would break ARM compilation. message := "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" + "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) - message += "</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>" + message += "</NewExternalPort><NewProtocol>" + strings.ToUpper(protocol) + "</NewProtocol>" message += "<NewInternalPort>" + strconv.Itoa(internalPort) + "</NewInternalPort>" + "<NewInternalClient>" + n.ourIP + "</NewInternalClient>" + "<NewEnabled>1</NewEnabled><NewPortMappingDescription>" @@ -389,7 +389,7 @@ func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort message := "<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" + "<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) + - "</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>" + + "</NewExternalPort><NewProtocol>" + strings.ToUpper(protocol) + "</NewProtocol>" + "</u:DeletePortMapping>" response, err := soapRequest(n.serviceURL, "DeletePortMapping", message)
Some UPNP devices require the protocol to be uppercase. This matches what miniupnpc sends.
btcsuite_btcd
train
3a350f60b4bf24074445a1cc769d0bfa3bbf5095
diff --git a/rangeparser.py b/rangeparser.py index <HASH>..<HASH> 100644 --- a/rangeparser.py +++ b/rangeparser.py @@ -55,7 +55,11 @@ class ReprMixin: class Suit(ReprMixin): __slots__ = '_suit' - def __init__(self, suit: str): + def __init__(self, suit: str or Suit): + if isinstance(suit, Suit): + self._suit = suit._suit + return + suit = suit.lower() if suit in SUITS: self._suit = suit @@ -79,7 +83,11 @@ class Suit(ReprMixin): class Rank(ReprMixin): __slots__ = '_rank' - def __init__(self, rank: str): + def __init__(self, rank: str or Rank): + if isinstance(rank, Rank): + self._rank = rank._rank + return + rank = rank.upper() if len(rank) != 1: raise InvalidRank('{!r}, should be 1 char long. Rank has no suit.'.format(rank)) @@ -106,7 +114,12 @@ class Rank(ReprMixin): class Card(ReprMixin): __slots__ = ('_rank', '_suit') - def __init__(self, card: str): + def __init__(self, card: str or Card): + if isinstance(card, Card): + self.rank = card.rank + self.suit = card.suit + return + if len(card) != 2: raise InvalidCard('length should be two in {!r}'.format(card)) @@ -146,12 +159,10 @@ class Card(ReprMixin): @rank.setter def rank(self, value: str or Rank): - if isinstance(value, Rank): - self._rank = value - return try: self._rank = Rank(value) except InvalidRank: + # implicit exception chaining raise InvalidCard(repr(value)) @property @@ -159,8 +170,12 @@ class Card(ReprMixin): return self._suit @suit.setter - def suit(self, value: str): - self._suit = Suit(value) + def suit(self, value: str or Suit): + try: + self._suit = Suit(value) + except InvalidSuit: + # implicit exception chaining + raise InvalidCard(repr(value)) @total_ordering diff --git a/tests/test_card.py b/tests/test_card.py index <HASH>..<HASH> 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -108,3 +108,13 @@ def test_representation(): assert repr(Card('Ad')) == "Card('A♦')" assert repr(Card('Kh')) == "Card('K♥')" assert repr(Card('Jc')) == "Card('J♣')" + + +def test_passing_Card_instance_to__init__(): + c1 = Card('As') + c2 = Card(c1) + assert c1 == c2 + assert (c1 != c2) is False + assert id(c1) != id(c2) + assert repr(c1) == "Card('A♠')" + assert repr(c2) == "Card('A♠')" diff --git a/tests/test_rank.py b/tests/test_rank.py index <HASH>..<HASH> 100644 --- a/tests/test_rank.py +++ b/tests/test_rank.py @@ -45,3 +45,13 @@ def test_case_insensitive(): def test_invalid_rank_raises_InvalidRank_Exception(): with raises(InvalidRank): Rank('L') + + +def test_passing_Rank_instance_to__init__(): + r1 = Rank('A') + r2 = Rank(r1) + assert r1 == r2 + assert (r1 != r2) is False + assert id(r1) != id(r2) + assert repr(r1) == "Rank('A')" + assert repr(r2) == "Rank('A')" diff --git a/tests/test_suit.py b/tests/test_suit.py index <HASH>..<HASH> 100644 --- a/tests/test_suit.py +++ b/tests/test_suit.py @@ -66,3 +66,13 @@ def test_repr(): assert repr(Suit('d')) == "Suit('♦')" assert repr(Suit('h')) == "Suit('♥')" assert repr(Suit('s')) == "Suit('♠')" + + +def test_passing_Suit_instance_to__init__(): + s1 = Suit('c') + s2 = Suit(s1) + assert s1 == s2 + assert (s1 != s2) is False + assert id(s1) != id(s2) + assert repr(s1) == "Suit('♣')" + assert repr(s2) == "Suit('♣')"
Suit, Rank, and Card __init__()-s are all accepting instances.
pokerregion_poker
train
1338d815ffbd69f801f542b0d4c9ed8461bb1953
diff --git a/publ/cards.py b/publ/cards.py index <HASH>..<HASH> 100644 --- a/publ/cards.py +++ b/publ/cards.py @@ -15,7 +15,7 @@ class CardData(): # pylint: disable=too-few-public-methods def __init__(self): - self.description = '' + self.description = None self.images = [] @@ -32,9 +32,8 @@ class CardParser(misaka.BaseRenderer): def paragraph(self, content): """ Turn the first paragraph of text into the summary text """ - if self._out.description: - self._out.description += '\n\n' - self._out.description += content + if not self._out.description: + self._out.description = content return ' ' def image(self, raw_url, title='', alt=''):
Return to just a single card paragraph
PlaidWeb_Publ
train
4763af859fb50204be65ffeff42fc04a32cba099
diff --git a/drivers/openstack4j/src/main/java/de/uniulm/omi/cloudiator/sword/drivers/openstack4j/converters/ServerInRegionToVirtualMachine.java b/drivers/openstack4j/src/main/java/de/uniulm/omi/cloudiator/sword/drivers/openstack4j/converters/ServerInRegionToVirtualMachine.java index <HASH>..<HASH> 100644 --- a/drivers/openstack4j/src/main/java/de/uniulm/omi/cloudiator/sword/drivers/openstack4j/converters/ServerInRegionToVirtualMachine.java +++ b/drivers/openstack4j/src/main/java/de/uniulm/omi/cloudiator/sword/drivers/openstack4j/converters/ServerInRegionToVirtualMachine.java @@ -29,8 +29,12 @@ import de.uniulm.omi.cloudiator.sword.domain.VirtualMachineBuilder; import de.uniulm.omi.cloudiator.sword.drivers.openstack4j.domain.ServerInRegion; import de.uniulm.omi.cloudiator.sword.strategy.GetStrategy; import de.uniulm.omi.cloudiator.util.OneWayConverter; -import java.util.stream.Collectors; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; import javax.inject.Inject; +import org.openstack4j.model.compute.Address; /** * Created by daniel on 18.11.16. @@ -63,10 +67,50 @@ public class ServerInRegionToVirtualMachine .privateKey(serverInRegion.keypair().get().getPrivateKey()).build(); } - return VirtualMachineBuilder.newBuilder().name(serverInRegion.getName()) + VirtualMachineBuilder virtualMachineBuilder = VirtualMachineBuilder.newBuilder() + .name(serverInRegion.getName()) .image(imageGetStrategy.get(serverInRegion.getImageId())) .hardware(hardwareFlavorGetStrategy.get(serverInRegion.getFlavorId())) .id(serverInRegion.getId()).providerId(serverInRegion.providerId()) - .location(serverInRegion.region()).loginCredential(loginCredential).build(); + .location(serverInRegion.region()) + .loginCredential(loginCredential); + + //extract private Ips from serverInRegion + Set<Entry<String, List<? extends Address>>> addressSet = serverInRegion + .getAddresses().getAddresses().entrySet(); + + if(addressSet.size()>1){ + //TODO: server is configured with multiple network types, how to handle this? + //LOGGER.warn(String.format("VM %s is configured with multiple network types!", serverInRegion.getId())); + + } + + //adding only the addresses of the first network interface + if(addressSet.iterator().hasNext()){ + Entry<String, List<? extends Address>> addressEntry = addressSet.iterator().next(); + //LOGGER.warn(String.format("Using addresses for network: %s", addressEntry.getKey())); + + List<? extends Address> addressList = addressEntry.getValue(); + + Set<String> ipAdressesToAdd = new HashSet<>(); + + for (Address address : addressList){ + + //TODO: currently only adding fixed IPs, i.e. private IPs, public IPs will be resolved later + if(address.getType().equals("fixed")){ + //LOGGER.warn(String.format("Found private (fixed) IP: %s", address.getAddr())); + //virtualMachineBuilder.addPrivateIpAddress(address.getAddr()); + ipAdressesToAdd.add(address.getAddr()); + + } + } + + virtualMachineBuilder.addIpStrings(ipAdressesToAdd); + + } + + return virtualMachineBuilder.build(); + + } }
ported privateIpfix to <I> (#<I>)
cloudiator_sword
train
cc6bff3daa4da4d2c6935761d0ab059201f772e2
diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -491,7 +491,7 @@ module ActiveRecord assert_equal 0, Post.count ensure - reset_fixtures('posts') + reset_fixtures("posts") end def test_truncate_with_query_cache @@ -503,7 +503,7 @@ module ActiveRecord assert_equal 0, Post.count ensure - reset_fixtures('posts') + reset_fixtures("posts") @connection.disable_query_cache! end @@ -518,7 +518,7 @@ module ActiveRecord assert_equal 0, Author.count assert_equal 0, AuthorAddress.count ensure - reset_fixtures('posts', 'authors', 'author_addresses') + reset_fixtures("posts", "authors", "author_addresses") end def test_truncate_tables_with_query_cache @@ -534,7 +534,7 @@ module ActiveRecord assert_equal 0, Author.count assert_equal 0, AuthorAddress.count ensure - reset_fixtures('posts', 'authors', 'author_addresses') + reset_fixtures("posts", "authors", "author_addresses") @connection.disable_query_cache! end
Auto-correct `Style/StringLiterals` cop offences Somehow Code Climate is not working as expected for now?
rails_rails
train
3cf59a3cdb4f13b63adabc5cb7896deb212d1fe3
diff --git a/pants.ini b/pants.ini index <HASH>..<HASH> 100644 --- a/pants.ini +++ b/pants.ini @@ -35,13 +35,8 @@ pythonpath: [ "%(buildroot)s/pants-plugins/src/python", ] -backend_packages: [ - "pants.backend.graph_info", +backend_packages: +[ "pants.backend.docgen", - "pants.backend.python", - "pants.backend.jvm", - "pants.backend.codegen", - "pants.backend.project_info", "internal_backend.optional", "internal_backend.repositories", "internal_backend.sitegen", diff --git a/src/python/pants/bin/options_initializer.py b/src/python/pants/bin/options_initializer.py index <HASH>..<HASH> 100644 --- a/src/python/pants/bin/options_initializer.py +++ b/src/python/pants/bin/options_initializer.py @@ -11,6 +11,7 @@ import sys import pkg_resources from pants.base.build_environment import pants_version +from pants.base.deprecated import deprecated_conditional from pants.base.exceptions import BuildConfigurationError from pants.bin.extension_loader import load_backends_and_plugins from pants.bin.plugin_resolver import PluginResolver @@ -149,6 +150,20 @@ class OptionsInitializer(object): # Conditionally load backends/plugins and materialize a `BuildConfiguration` object. if not self._has_build_configuration(): + missing = (set(global_bootstrap_options.default_backend_packages).difference( + global_bootstrap_options.backend_packages)) + deprecated_conditional( + lambda: len(missing) > 0, + '1.3.0', + 'default_backend_packages option', + 'You are relying on the following backends being listed in the deprecated ' + 'default_backend_packages option: {}.\n ' + 'This is probably because you are overwriting the value of the backend_packages option ' + 'in your pants.ini, instead of appending to it.\n To get rid of this message, change ' + 'backend_packages: [...] to backend_packages: +[...] in your pants.ini.'.format( + ', '.join(missing)) + ) + backends = (global_bootstrap_options.default_backend_packages + global_bootstrap_options.backend_packages) build_configuration = self._load_plugins(self._working_set, diff --git a/src/python/pants/option/global_options.py b/src/python/pants/option/global_options.py index <HASH>..<HASH> 100644 --- a/src/python/pants/option/global_options.py +++ b/src/python/pants/option/global_options.py @@ -61,9 +61,19 @@ class GlobalOptionsRegistrar(Optionable): help='Cache resolved plugin requirements here.') register('--backend-packages', advanced=True, type=list, + default=['pants.backend.graph_info', + 'pants.backend.python', + 'pants.backend.jvm', + 'pants.backend.codegen', + 'pants.backend.project_info'], help='Load backends from these packages that are already on the path. ' 'Add contrib and custom backends to this list.') register('--default-backend-packages', advanced=True, type=list, + removal_version='1.3.0', + removal_hint='All backends must be specified using the backend_packages option. ' + 'That option has the same defaults as this one, and you can append' + 'and filter those using +[...] and -[...] syntax, as described here: ' + 'http://www.pantsbuild.org/options.html#list-options.', default=['pants.backend.graph_info', 'pants.backend.python', 'pants.backend.jvm',
Deprecate the default_backend_packages option. We don't need it now that we can append and filter list options. Repos can modify the backend_packages option directly, removing any default backends they don't need and appending their custom backends. Testing Done: Verified that we get the deprecation option under the right conditions. CI passes here: <URL>
pantsbuild_pants
train
485521d2dd8afa3f40f343c4e20330e45fab0dbe
diff --git a/dropwizard-core/src/main/java/com/yammer/dropwizard/config/ConfigurationFactory.java b/dropwizard-core/src/main/java/com/yammer/dropwizard/config/ConfigurationFactory.java index <HASH>..<HASH> 100644 --- a/dropwizard-core/src/main/java/com/yammer/dropwizard/config/ConfigurationFactory.java +++ b/dropwizard-core/src/main/java/com/yammer/dropwizard/config/ConfigurationFactory.java @@ -1,12 +1,9 @@ package com.yammer.dropwizard.config; -import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; -import com.google.common.io.Files; import com.yammer.dropwizard.json.Yaml; import com.yammer.dropwizard.validation.Validator; -import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -24,14 +21,9 @@ public class ConfigurationFactory<T> { } public T build(File file) throws IOException, ConfigurationException { - final BufferedReader reader = Files.newReader(file, Charsets.UTF_8); - try { - final T config = new Yaml(file).read(klass); - validate(file, config); - return config; - } finally { - reader.close(); - } + final T config = new Yaml(file).read(klass); + validate(file, config); + return config; } private void validate(File file, T config) throws ConfigurationException {
Removing unused Reader from ConfigurationFactory#build
dropwizard_dropwizard
train
7392497c7a6021afc8f82c0127be272699651ddf
diff --git a/llvmlite/binding/ffi.py b/llvmlite/binding/ffi.py index <HASH>..<HASH> 100644 --- a/llvmlite/binding/ffi.py +++ b/llvmlite/binding/ffi.py @@ -81,6 +81,7 @@ class ObjectRef(object): """ _closed = False _as_parameter_ = _DeadPointer() + # Whether this object pointer is owned by another one. _owned = False def __init__(self, ptr):
Add a comment for a possibly misleading attribute
numba_llvmlite
train
cc6087c58e0ad8bf7aa775e5eacedd817939dee6
diff --git a/webcam-capture/src/example/java/ParallelGetImageBytesExample.java b/webcam-capture/src/example/java/ParallelGetImageBytesExample.java index <HASH>..<HASH> 100644 --- a/webcam-capture/src/example/java/ParallelGetImageBytesExample.java +++ b/webcam-capture/src/example/java/ParallelGetImageBytesExample.java @@ -70,9 +70,9 @@ public class ParallelGetImageBytesExample { */ public void ready(ByteBuffer bb) { try { - exchange(bb, 0, TimeUnit.SECONDS); + exchange(bb, 500, TimeUnit.MILLISECONDS); } catch (InterruptedException | TimeoutException e) { - throw new IllegalStateException(e); + // do nothing, frame is dropped } }
Small fix in parallel buffer access example, refs #<I>
sarxos_webcam-capture
train
3c27a91997295b300348946eb7878e5e652ecd37
diff --git a/tornado/websocket.py b/tornado/websocket.py index <HASH>..<HASH> 100644 --- a/tornado/websocket.py +++ b/tornado/websocket.py @@ -105,6 +105,21 @@ class WebSocketHandler(tornado.web.RequestHandler): }; This script pops up an alert box that says "You said: Hello, world". + + Web browsers allow any site to open a websocket connection to any other, + instead of using the same-origin policy that governs other network + access from javascript. This can be surprising and is a potential + security hole, so since Tornado 4.0 `WebSocketHandler` requires + applications that wish to receive cross-origin websockets to opt in + by overriding the `~WebSocketHandler.check_origin` method (see that + method's docs for details). Failure to do so is the most likely + cause of 403 errors when making a websocket connection. + + When using a secure websocket connection (``wss://``) with a self-signed + certificate, the connection from a browser may fail because it wants + to show the "accept this certificate" dialog but has nowhere to show it. + You must first visit a regular HTML page using the same certificate + to accept it before the websocket connection will succeed. """ def __init__(self, application, request, **kwargs): tornado.web.RequestHandler.__init__(self, application, request, @@ -275,6 +290,19 @@ class WebSocketHandler(tornado.web.RequestHandler): browsers, since WebSockets are allowed to bypass the usual same-origin policies and don't use CORS headers. + To accept all cross-origin traffic (which was the default prior to + Tornado 4.0), simply override this method to always return true:: + + def check_origin(self, origin): + return True + + To allow connections from any subdomain of your site, you might + do something like:: + + def check_origin(self, origin): + parsed_origin = urllib.parse.urlparse(origin) + return parsed_origin.netloc.endswith(".mydomain.com") + .. versionadded:: 4.0 """ parsed_origin = urlparse(origin)
Expand documentation of WebSocketHandler.check_origin. Document the potential problems that arise with websockets and self-signed certificates.
tornadoweb_tornado
train
e59f04c13cb8e9a0b61469d3346442317575b135
diff --git a/downhill/__init__.py b/downhill/__init__.py index <HASH>..<HASH> 100644 --- a/downhill/__init__.py +++ b/downhill/__init__.py @@ -1,7 +1,7 @@ -from .adaptive import RProp, RMSProp, ADADELTA, ESGD +from .adaptive import * from .base import build, Optimizer from .dataset import Dataset -from .first_order import SGD, NAG +from .first_order import * def minimize(loss, params, inputs, train, valid, diff --git a/downhill/adaptive.py b/downhill/adaptive.py index <HASH>..<HASH> 100644 --- a/downhill/adaptive.py +++ b/downhill/adaptive.py @@ -12,6 +12,8 @@ from .first_order import SGD logging = climate.get_logger(__name__) +__all__ = ['RProp', 'RMSProp', 'ADADELTA', 'ESGD'] + class RProp(SGD): r'''Trainer for neural nets using resilient backpropagation. diff --git a/downhill/first_order.py b/downhill/first_order.py index <HASH>..<HASH> 100644 --- a/downhill/first_order.py +++ b/downhill/first_order.py @@ -8,6 +8,8 @@ from .base import Optimizer, as_float, shared_like logging = climate.get_logger(__name__) +__all__ = ['SGD', 'NAG'] + class SGD(Optimizer): r'''Optimize using stochastic gradient descent with momentum.
Add __all__ to facilitate imports.
lmjohns3_downhill
train
a35f1dd7c94e409085e03d0eed8fc9aad8e32d11
diff --git a/lib/arel/nodes/postgresql.rb b/lib/arel/nodes/postgresql.rb index <HASH>..<HASH> 100644 --- a/lib/arel/nodes/postgresql.rb +++ b/lib/arel/nodes/postgresql.rb @@ -33,6 +33,10 @@ module Arel def visit_Arel_Nodes_ArrayConcat o, *a "#{visit o.left, *a} #{ARRAY_CONCAT} #{visit o.right, *a}" end + + def visit_Arel_Nodes_UnionDistinct o, *a + "( #{visit o.left, *a} UNION DISTINCT #{visit o.right, *a} )" + end else def visit_Arel_Nodes_PostgresArray o, collector collector << ARRAY_OPENING @@ -45,11 +49,11 @@ module Arel collector << ARRAY_CONCAT visit o.right, collector end - end - def visit_Arel_Nodes_UnionDistinct o, collector - collector << "( " - infix_value(o, collector, " UNION DISTINCT ") << " )" + def visit_Arel_Nodes_UnionDistinct o, collector + collector << "( " + infix_value(o, collector, " UNION DISTINCT ") << " )" + end end end end
Add support for UNION DISTINCT for Rails prior to <I>
take-five_activerecord-hierarchical_query
train
13e31a1a0c373c43af11edda2076fbdfe1ebc1d7
diff --git a/gtfspy/filter.py b/gtfspy/filter.py index <HASH>..<HASH> 100644 --- a/gtfspy/filter.py +++ b/gtfspy/filter.py @@ -113,6 +113,8 @@ class FilterExtract(object): assert isinstance(self.copy_db_conn, sqlite3.Connection) self._delete_rows_by_start_and_end_date() + if self.copy_db_conn.execute('SELECT count(*) FROM days').fetchone() == (0,): + raise ValueError('No data left after filtering') self._filter_by_calendar() self._filter_by_agency() self._filter_by_area()
Raise an error if filter delete everything
CxAalto_gtfspy
train
25b0c12e120e14114601d884fdb595b6b09c5221
diff --git a/colorful/core.py b/colorful/core.py index <HASH>..<HASH> 100644 --- a/colorful/core.py +++ b/colorful/core.py @@ -20,7 +20,7 @@ from . import ansi from . import rgb from . import styles from . import terminal -from .utils import PY2, DEFAULT_ENCODE, UNICODE +from .utils import PY2, DEFAULT_ENCODING, UNICODE #: Holds the name of the env variable which is # used as path to the default rgb.txt file @@ -209,7 +209,7 @@ def style_string(string, ansi_style, colormode, nested=False): # replace nest placeholders with the current begin style if PY2: if isinstance(string, str): - string = string.decode('utf-8' if DEFAULT_ENCODE is None else DEFAULT_ENCODE) + string = string.decode(DEFAULT_ENCODING) string = UNICODE(string).replace(ansi.NEST_PLACEHOLDER, ansi_start_code) return '{start_code}{string}{end_code}{nest_ph}'.format( @@ -232,7 +232,7 @@ class ColorfulString(object): return self.styled_string def __str__(self): - return self.styled_string.encode('utf-8' if DEFAULT_ENCODE is None else DEFAULT_ENCODE) + return self.styled_string.encode(DEFAULT_ENCODING) else: def __str__(self): return self.styled_string diff --git a/colorful/utils.py b/colorful/utils.py index <HASH>..<HASH> 100644 --- a/colorful/utils.py +++ b/colorful/utils.py @@ -19,7 +19,12 @@ if PY2: else: UNICODE = str -DEFAULT_ENCODE = sys.stdout.encoding +# Catch error in case sys.stdout was patched with an object that doesn't provide +# the 'encoding' attribute. +try: + DEFAULT_ENCODING = sys.stdout.encoding or 'utf-8' +except AttributeError: + DEFAULT_ENCODING = 'utf-8' def hex_to_rgb(value):
Catch AttributeError in case sys.stdout was monkey patched (#<I>) .. and the custom object doesn't provide the 'encoding' attribute. Also renamed DEFAULT_ENCODE -> DEFAULT_ENCODING and avoided the repeated usage of if expressions by directly setting the DEFAULT_ENCODING to 'utf-8' in case it is None or Empty.
timofurrer_colorful
train
ed2e51ffb798765e1c79dfe76cee95c486eca3bb
diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "scroungejs", - "version": "1.2.9", + "version": "1.3.0", "license": "MIT", "readmeFilename": "README.md", "main": "src/scrounge.js", diff --git a/src/scrounge_adapt.js b/src/scrounge_adapt.js index <HASH>..<HASH> 100644 --- a/src/scrounge_adapt.js +++ b/src/scrounge_adapt.js @@ -1,5 +1,5 @@ // Filename: scrounge_adapt.js -// Timestamp: 2017.07.29-19:16:36 (last modified) +// Timestamp: 2017.10.07-01:38:29 (last modified) // Author(s): bumblehead <chris@bumblehead.com> const umd = require('umd'), @@ -61,12 +61,12 @@ module.exports = (o => { if (!skip) { //str = uglifyjs.minify(str, { fromString: true }).code; - str = babel.transform(str, { compact: opts.iscompress && !skip, presets: opts.ises2015 ? [ babelpresetenv - ] : [] + ] : [], + plugins: opts.babelpluginarr || [] }).code; } diff --git a/src/scrounge_opts.js b/src/scrounge_opts.js index <HASH>..<HASH> 100644 --- a/src/scrounge_opts.js +++ b/src/scrounge_opts.js @@ -1,5 +1,5 @@ // Filename: scrounge_opts.js -// Timestamp: 2017.07.29-19:37:13 (last modified) +// Timestamp: 2017.10.07-01:35:50 (last modified) // Author(s): bumblehead <chris@bumblehead.com> const fs = require('fs'), @@ -67,6 +67,7 @@ module.exports = (o => { finopt.globalarr = castas.arr(opt.globalarr, []); finopt.prependarr = castas.arr(opt.prependarr, []); finopt.aliasarr = castas.arr(opt.aliasarr, []); + finopt.babelpluginarr = castas.arr(opt.babelpluginarr, []); finopt.isconcat = castas.bool(opt.isconcatenated, true); finopt.iscompress = castas.bool(opt.iscompressed, false);
added ability to specify babel plugins from callee
iambumblehead_scroungejs
train
1a714be96297bc9a6532b4ff5a08be9fc01624c5
diff --git a/java/example/src/main/java/com/youtube/vitess/example/VitessClientExample.java b/java/example/src/main/java/com/youtube/vitess/example/VitessClientExample.java index <HASH>..<HASH> 100644 --- a/java/example/src/main/java/com/youtube/vitess/example/VitessClientExample.java +++ b/java/example/src/main/java/com/youtube/vitess/example/VitessClientExample.java @@ -31,7 +31,7 @@ import com.youtube.vitess.proto.Topodata.TabletType; * </pre> */ public class VitessClientExample { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: VitessClientExample <vtgate-host:port>"); System.exit(1); @@ -68,6 +68,10 @@ public class VitessClientExample { System.out.format("(%d, %s)\n", id, new String(msg)); } } + } catch (Exception e) { + System.out.println("Vitess Java example failed."); + System.out.println("Error Details:"); + e.printStackTrace(); } } }
java/example: Print exception ourselves instead of throwing it.
vitessio_vitess
train
a0916c36733da1799fdd62ba01e39aea519f30c6
diff --git a/client/lib/analytics/index.js b/client/lib/analytics/index.js index <HASH>..<HASH> 100644 --- a/client/lib/analytics/index.js +++ b/client/lib/analytics/index.js @@ -87,7 +87,7 @@ function checkForBlockedTracks() { } } - loadScript( '/nostats.js?_ut=' + encodeURIComponent( _ut ) + '&_ui=' + encodeURIComponent( _ui ) ); + loadScript( '/public/nostats.js?_ut=' + encodeURIComponent( _ut ) + '&_ui=' + encodeURIComponent( _ui ) ); } loadScript( '//stats.wp.com/w.js?56', function( error ) { diff --git a/server/boot/index.js b/server/boot/index.js index <HASH>..<HASH> 100644 --- a/server/boot/index.js +++ b/server/boot/index.js @@ -53,11 +53,11 @@ function setup() { express.static( path.resolve( __dirname, '..', '..', 'client', 'lib', 'service-worker', 'service-worker.js' ) ) ); // loaded when we detect stats blockers - see lib/analytics/index.js - app.get( '/nostats.js', function( request, response ) { + app.get( '/public/nostats.js', function( request, response ) { const analytics = require( '../lib/analytics' ); analytics.tracks.recordEvent( 'calypso_nostats', {}, request ); response.setHeader( 'content-type', 'application/javascript' ); - response.end( "console.log('Your browser appears to be blocking our stats');" ); + response.end( "console.log('Stats are disabled');" ); } ); // serve files when not in production so that the source maps work correctly
Move stats block detection to public route and simplify error message
Automattic_wp-calypso
train
834d3cd46fa614a0f1d94785f8d314ac821c4751
diff --git a/test/simulation/makers.py b/test/simulation/makers.py index <HASH>..<HASH> 100644 --- a/test/simulation/makers.py +++ b/test/simulation/makers.py @@ -56,11 +56,11 @@ def simulate_image_from_galaxies_and_output_to_fits( add_noise=True, ) - # Now, lets output this simulated ccd-instrument to the test/instrument folder. + # Now, lets output this simulated ccd-instrument to the test/data folder. test_path = "{}/../".format(os.path.dirname(os.path.realpath(__file__))) data_path = af.path_util.make_and_return_path_from_path_and_folder_names( - path=test_path, folder_names=["instrument", data_type, data_resolution] + path=test_path, folder_names=["data", data_type, data_resolution] ) ccd.output_ccd_data_to_fits( diff --git a/test/simulation/simulation_util.py b/test/simulation/simulation_util.py index <HASH>..<HASH> 100644 --- a/test/simulation/simulation_util.py +++ b/test/simulation/simulation_util.py @@ -73,7 +73,7 @@ def load_test_ccd_data(data_type, data_resolution, psf_shape=(11, 11), lens_name pixel_scale = pixel_scale_from_data_resolution(data_resolution=data_resolution) data_path = af.path_util.make_and_return_path_from_path_and_folder_names( - path=test_path, folder_names=["instrument", data_type, data_resolution] + path=test_path, folder_names=["data", data_type, data_resolution] ) return ccd.load_ccd_data_from_fits(
Refining splitting of data and instrument.
Jammy2211_PyAutoLens
train
d0f3bfd4cc81202705857b4bd3ba7a3dceb7025a
diff --git a/common/src/main/java/io/netty/util/DefaultAttributeMap.java b/common/src/main/java/io/netty/util/DefaultAttributeMap.java index <HASH>..<HASH> 100644 --- a/common/src/main/java/io/netty/util/DefaultAttributeMap.java +++ b/common/src/main/java/io/netty/util/DefaultAttributeMap.java @@ -90,6 +90,9 @@ public class DefaultAttributeMap implements AttributeMap { DefaultAttribute<T> attr = new DefaultAttribute<T>(head, key); curr.next = attr; attr.prev = curr; + return attr; + } else { + curr = next; } } } diff --git a/common/src/test/java/io/netty/util/DefaultAttributeMapTest.java b/common/src/test/java/io/netty/util/DefaultAttributeMapTest.java index <HASH>..<HASH> 100644 --- a/common/src/test/java/io/netty/util/DefaultAttributeMapTest.java +++ b/common/src/test/java/io/netty/util/DefaultAttributeMapTest.java @@ -67,4 +67,16 @@ public class DefaultAttributeMapTest { one.remove(); assertNull(one.get()); } + + // See https://github.com/netty/netty/issues/2523 + @Test + public void testSetRemove() { + AttributeKey<Integer> key = AttributeKey.valueOf("key"); + + map.attr(key).set(1); + assertSame(1, map.attr(key).getAndRemove()); + + map.attr(key).set(2); + assertSame(2, map.attr(key).get()); + } }
[#<I>] Fix infinite-loop when remove attribute and create the same attribute again Motivation: The current DefaultAttributeMap cause an infinite-loop when the user removes an attribute and create the same attribute again. This regression was introduced by c3bd7a8ff<I>b0c<I>d<I>f<I>dbbf4fe<I>. Modification: Correctly break out loop Result: No infinite-loop anymore.
netty_netty
train