hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
e5829355821bd930e00bed76e2acd15ce96d8816
diff --git a/forms/HtmlEditorField.php b/forms/HtmlEditorField.php index <HASH>..<HASH> 100644 --- a/forms/HtmlEditorField.php +++ b/forms/HtmlEditorField.php @@ -515,7 +515,8 @@ class HtmlEditorField_Toolbar extends RequestHandler { } // Instanciate file wrapper and get fields based on its type - if($file && $file->appCategory() == 'image') { + // Check if appCategory is an image and exists on the local system, otherwise use oEmbed to refference a remote image + if($file && $file->appCategory() == 'image' && Director::is_site_url($url)) { $fileWrapper = new HtmlEditorField_Image($url, $file); } elseif(!Director::is_site_url($url)) { $fileWrapper = new HtmlEditorField_Embed($url, $file); diff --git a/oembed/Oembed.php b/oembed/Oembed.php index <HASH>..<HASH> 100644 --- a/oembed/Oembed.php +++ b/oembed/Oembed.php @@ -131,6 +131,13 @@ class Oembed { // Build the url manually - we gave all needed information. $oembedUrl = Controller::join_links($endpoint, '?format=json&url=' . rawurlencode($url)); } + + // If autodescovery failed the resource might be a direct link to a file + if(!$oembedUrl) { + if(File::get_app_category(File::get_file_extension($url))) { + return new Oembed_Result($url, $url, $type, $options); + } + } if($oembedUrl) { // Inject the options into the Oembed URL. @@ -233,7 +240,20 @@ class Oembed_Result extends ViewableData { $body = $body->getBody(); $data = json_decode($body, true); if(!$data) { + // if the response is no valid JSON we might have received a binary stream to an image $data = array(); + $image = @imagecreatefromstring($body); + if($image !== FALSE) { + preg_match("/^(http:\/\/)?([^\/]+)/i", $this->url, $matches); + $protocoll = $matches[1]; + $host = $matches[2]; + $data['type'] = "photo"; + $data['title'] = basename($this->url) . " ($host)"; + $data['url'] = $this->url; + $data['provider_url'] = $protocoll.$host; + $data['width'] = imagesx($image); + $data['height'] = imagesy($image); + } } // Convert all keys to lowercase
BUGFIX insertion of images (trac #<I>) Allow insertion of images via oEmbed dialog using a direct url
silverstripe_silverstripe-framework
train
edc188be570f7a104d91ed6ce6c1b150c396fc67
diff --git a/source/awesome_tool/mvc/models/state.py b/source/awesome_tool/mvc/models/state.py index <HASH>..<HASH> 100644 --- a/source/awesome_tool/mvc/models/state.py +++ b/source/awesome_tool/mvc/models/state.py @@ -74,6 +74,7 @@ class StateModel(ModelMT): self.outcomes = [] self.reload_input_data_port_models() self.reload_output_data_port_models() + self.reload_outcome_models() def update_attributes(self): """Update table model with state model
bug fix for not updating outcome names - add again disappeared line in StateModel
DLR-RM_RAFCON
train
b36cf8d866d51c26383cba4ea65d5a552a3322a2
diff --git a/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/ElementHelper.java b/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/ElementHelper.java index <HASH>..<HASH> 100644 --- a/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/ElementHelper.java +++ b/blueprints/blueprints-core/src/main/java/com/tinkerpop/blueprints/util/ElementHelper.java @@ -70,11 +70,12 @@ public class ElementHelper { * * @param keyValues a list of key/value pairs * @return the value associated with {@link Property.Key#LABEL} + * @throws ClassCastException if the value of the label is not a {@link String} */ public static Optional<String> getLabelValue(final Object... keyValues) { for (int i = 0; i < keyValues.length; i = i + 2) { if (keyValues[i].equals(Property.Key.LABEL)) - return Optional.of(keyValues[i + 1].toString()); + return Optional.of((String) keyValues[i + 1]); } return Optional.empty(); } diff --git a/blueprints/blueprints-test/src/test/java/com/tinkerpop/blueprints/util/ElementHelperTest.java b/blueprints/blueprints-test/src/test/java/com/tinkerpop/blueprints/util/ElementHelperTest.java index <HASH>..<HASH> 100644 --- a/blueprints/blueprints-test/src/test/java/com/tinkerpop/blueprints/util/ElementHelperTest.java +++ b/blueprints/blueprints-test/src/test/java/com/tinkerpop/blueprints/util/ElementHelperTest.java @@ -122,4 +122,9 @@ public class ElementHelperTest { public void shouldNotFindAnLabelValue() { assertFalse(ElementHelper.getLabelValue("test", 321, "xyz", "friend", "testagain", "that").isPresent()); } + + @Test(expected = ClassCastException.class) + public void shouldErrorIfLabelIsNotString() { + assertFalse(ElementHelper.getLabelValue("test", 321, Property.Key.LABEL, 4545, "testagain", "that").isPresent()); + } }
Getting label with ElementHelper now throws ClassCastException if the value is not a String.
apache_tinkerpop
train
2b0ac0b481d4c4c174e0b15bccdf04a00acda63a
diff --git a/lib/TreasureChest/Autoloader.php b/lib/TreasureChest/Autoloader.php index <HASH>..<HASH> 100644 --- a/lib/TreasureChest/Autoloader.php +++ b/lib/TreasureChest/Autoloader.php @@ -6,7 +6,7 @@ namespace TreasureChest; class Autoloader { /** - * Registers Twig\Autoloader as an SPL autoloader. + * Registers TreasureChest\Autoloader as an SPL autoloader. */ static public function register() {
Fixed docblock of autoloader
jamesmoss_treasure-chest
train
62e570a4e49999798d3f80ea6e2370ffc0b1234d
diff --git a/core/connect.js b/core/connect.js index <HASH>..<HASH> 100644 --- a/core/connect.js +++ b/core/connect.js @@ -1,6 +1,5 @@ 'use strict'; -var R_PATH = /^(?:\w+:\/\/[^\/]*)?([\s\S]*)$/; var STATUS_CODES = require('http').STATUS_CODES; var Track = /** @type Track */ require('./track'); @@ -452,7 +451,7 @@ Connect.prototype._getUrlObj = function $Connect$getUrlObj() { * @returns {String} * */ Connect.prototype._getUrlHref = function $Connect$getUrlHref() { - return this.getProtocol() + '://' + this.getHost() + R_PATH.exec(this.req.url)[1]; + return this.getProtocol() + '://' + this.getHost() + this.req.url; }; /** diff --git a/core/server.js b/core/server.js index <HASH>..<HASH> 100644 --- a/core/server.js +++ b/core/server.js @@ -176,25 +176,25 @@ function $Server$handleRequest(self, req, res, logger) { } // wait for init - promise.then(function () { + promise.done(function () { $Server$runTrack(self, req, res, logger); }); } function $Server$runTrack(self, req, res, logger) { var matches; - var path = req.url; + var method = req.method; + var path = req.url = req.url.replace(/^\w+:\/\/[^\/]+/, '') || '/'; var router = self.router; - var verb = req.method; var track; - if (!router.isImplemented(verb)) { + if (!router.isImplemented(method)) { res.statusCode = 501; res.end(STATUS_CODES[501]); return; } - matches = router.matchAll(path, verb); + matches = router.matchAll(path, method); if (matches.length) { track = new Connect(self, logger, req, res); diff --git a/test/core.connect.js b/test/core.connect.js index <HASH>..<HASH> 100644 --- a/test/core.connect.js +++ b/test/core.connect.js @@ -321,24 +321,6 @@ describe('core/connect', function () { set('X-Forwarded-Proto', 'http'). expect(200, done); }); - - it('Should correctly handle not only path urls', function (done) { - var spy = 0; - supertest(function (req, res) { - var connect; - req.url = 'http://localhost:1337/foo'; - connect = new Connect(new Server(), logger, req, res); - assert.strictEqual(connect.url.path, '/foo'); - spy = 1; - res.end(); - }). - get('/'). - expect(200). - end(function () { - assert.strictEqual(spy, 1); - done(); - }); - }); }); describe('connect.header()', function () { diff --git a/test/core.server.js b/test/core.server.js index <HASH>..<HASH> 100644 --- a/test/core.server.js +++ b/test/core.server.js @@ -295,10 +295,44 @@ describe('core/server', function () { }); }); }); + + it('Should correctly handle fqdn urls', function (done) { + var app = new Server(); + var handler; + var req = { + method: 'GET', + socket: {}, + headers: {}, + url: 'http://ya.ru' + }; + var res = { + on: function () {}, + getHeader: function () {}, + setHeader: function () {}, + removeHeader: function () {}, + end: function (body) { + assert.strictEqual(req.url, '/'); + assert.strictEqual(body, '!'); + done(); + } + }; + + app.unit({ + name: 'index', + main: function (track) { + track.send('!'); + } + }); + + app.route('GET /', 'index'); + handler = app.getHandler(); + + handler(req, res); + }); }); describe('server.listen()', function () { - var asker = require('vow-asker'); + var vowAsker = require('vow-asker'); it('Should create and run http server', function () { var server = new Server(); @@ -319,7 +353,7 @@ describe('core/server', function () { srv = server.listen(port); - return asker({ + return vowAsker({ host: 'localhost', path: '/', port: port,
server: Support fqdn urls * Remove fqdn support from connect * Normalize req.url in server handler
fistlabs_fist
train
42b398c45aebfc99240e102db816fa162d47ce0a
diff --git a/core/ArchiveProcessor/Loader.php b/core/ArchiveProcessor/Loader.php index <HASH>..<HASH> 100644 --- a/core/ArchiveProcessor/Loader.php +++ b/core/ArchiveProcessor/Loader.php @@ -31,8 +31,6 @@ use Psr\Log\LoggerInterface; */ class Loader { - const MIN_VISIT_TIME_TTL = 3600; - /** * @var Parameters */ @@ -410,36 +408,12 @@ class Loader private function hasSiteVisitsBetweenTimeframe($idSite, Period $period) { - $minVisitTimesPerSite = $this->getMinVisitTimesPerSite($idSite); - if (empty($minVisitTimesPerSite)) { - return false; - } - $timezone = Site::getTimezoneFor($idSite); list($date1, $date2) = $period->getBoundsInTimezone($timezone); - if ($date2->getTimestamp() < $minVisitTimesPerSite) { - return false; - } return $this->rawLogDao->hasSiteVisitsBetweenTimeframe($date1->getDatetime(), $date2->getDatetime(), $idSite); } - private function getMinVisitTimesPerSite($idSite) - { - $cache = Cache::getLazyCache(); - $cacheKey = 'Archiving.minVisitTime.' . $idSite; - - $value = $cache->fetch($cacheKey); - if ($value === false) { - $value = $this->rawLogDao->getMinimumVisitTimeForSite($idSite); - if (!empty($value)) { - $cache->save($cacheKey, $value, $ttl = self::MIN_VISIT_TIME_TTL); - } - } - - return $value; - } - public static function invalidateMinVisitTimeCache($idSite) { $cache = Cache::getLazyCache(); diff --git a/core/DataAccess/RawLogDao.php b/core/DataAccess/RawLogDao.php index <HASH>..<HASH> 100644 --- a/core/DataAccess/RawLogDao.php +++ b/core/DataAccess/RawLogDao.php @@ -452,10 +452,4 @@ class RawLogDao return $columns; } - - public function getMinimumVisitTimeForSite($idSite) - { - $sql = "SELECT MIN(visit_last_action_time) FROM " . Common::prefixTable('log_visit') . ' WHERE idsite = ?'; - return Db::fetchOne($sql, [$idSite]); - } }
Remove unneeded code (#<I>) * Remove unneeded code * remove constant
matomo-org_matomo
train
718dccfa5ea0d5f841ed7578dc2167419f91ab31
diff --git a/shardingsphere-jdbc/shardingsphere-jdbc-governance/src/main/java/org/apache/shardingsphere/driver/governance/internal/datasource/GovernanceShardingSphereDataSource.java b/shardingsphere-jdbc/shardingsphere-jdbc-governance/src/main/java/org/apache/shardingsphere/driver/governance/internal/datasource/GovernanceShardingSphereDataSource.java index <HASH>..<HASH> 100644 --- a/shardingsphere-jdbc/shardingsphere-jdbc-governance/src/main/java/org/apache/shardingsphere/driver/governance/internal/datasource/GovernanceShardingSphereDataSource.java +++ b/shardingsphere-jdbc/shardingsphere-jdbc-governance/src/main/java/org/apache/shardingsphere/driver/governance/internal/datasource/GovernanceShardingSphereDataSource.java @@ -58,14 +58,14 @@ import java.util.logging.Logger; @Getter public final class GovernanceShardingSphereDataSource extends AbstractUnsupportedOperationDataSource implements AutoCloseable { - @SuppressWarnings("UseOfSystemOutOrSystemErr") - @Setter - private PrintWriter logWriter = new PrintWriter(System.out); - private final SchemaContexts schemaContexts; private final TransactionContexts transactionContexts; + @SuppressWarnings("UseOfSystemOutOrSystemErr") + @Setter + private PrintWriter logWriter = new PrintWriter(System.out); + public GovernanceShardingSphereDataSource(final GovernanceConfiguration governanceConfig) throws SQLException { GovernanceFacade governanceFacade = createGovernanceFacade(governanceConfig); schemaContexts = new GovernanceSchemaContexts(createSchemaContexts(governanceFacade), governanceFacade);
Adjust the order of members (#<I>)
apache_incubator-shardingsphere
train
e95d33b77e9cff79771f6f1057c790d01cc8db10
diff --git a/lib/ModuleGraph.js b/lib/ModuleGraph.js index <HASH>..<HASH> 100644 --- a/lib/ModuleGraph.js +++ b/lib/ModuleGraph.js @@ -75,11 +75,22 @@ class ExportsInfo { } _sortExports() { - const newMap = new Map(); - for (const name of Array.from(this._exports.keys()).sort()) { - newMap.set(name, this._exports.get(name)); + const exports = this._exports; + if (exports.size > 1) { + const entriesInOrder = Array.from(exports.values()); + if ( + entriesInOrder.length !== 2 || + entriesInOrder[0].name > entriesInOrder[1].name + ) { + entriesInOrder.sort((a, b) => { + return a.name < b.name ? -1 : 1; + }); + exports.clear(); + for (const entry of entriesInOrder) { + exports.set(entry.name, entry); + } + } } - this._exports = newMap; this._exportsAreOrdered = true; }
Improve performance of ExportsInfo.sortExports
webpack_webpack
train
dff509ddf352967251e4cde6b386c57a7705719b
diff --git a/core-bundle/contao/library/Contao/System.php b/core-bundle/contao/library/Contao/System.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/library/Contao/System.php +++ b/core-bundle/contao/library/Contao/System.php @@ -377,10 +377,10 @@ abstract class System { // Generate the cache files $objCacheFallback = new \File('system/cache/language/en/' . $strName . '.php'); - $objCacheFallback->write('<?php'); + $objCacheFallback->write('<?php '); // add one space to prevent the "unexpected $end" error $objCacheFile = new \File('system/cache/language/' . $strLanguage . '/' . $strName . '.php'); - $objCacheFile->write('<?php'); + $objCacheFile->write('<?php '); // add one space to prevent the "unexpected $end" error // Parse all active modules foreach (\Config::getInstance()->getActiveModules() as $strModule)
[Core] Prevent the "unexpected $end" error triggered by cache files which only contain `<?php`
contao_contao
train
1e3963b74340ebdf0e2ff0bb5538b11de39d81c8
diff --git a/pebble/pool/process.py b/pebble/pool/process.py index <HASH>..<HASH> 100644 --- a/pebble/pool/process.py +++ b/pebble/pool/process.py @@ -19,6 +19,7 @@ import time from itertools import count from collections import namedtuple from multiprocessing import cpu_count +from multiprocessing.pool import RemoteTraceback from signal import SIG_IGN, SIGINT, signal from concurrent.futures import CancelledError, TimeoutError try: @@ -277,6 +278,8 @@ class TaskManager: if task.future.cancelled(): task.set_running_or_notify_cancel() elif isinstance(result, BaseException): + if hasattr(result, 'traceback'): + result.__cause__ = RemoteTraceback(result.traceback) task.future.set_exception(result) else: task.future.set_result(result)
Use RemoteTraceback to output the cause of an exception when it is thrown
noxdafox_pebble
train
113bfcb4eacaa3346e28f1e5103928aaa4c47c83
diff --git a/moto/s3/responses.py b/moto/s3/responses.py index <HASH>..<HASH> 100644 --- a/moto/s3/responses.py +++ b/moto/s3/responses.py @@ -336,6 +336,12 @@ class ResponseObject(_TemplateEnvironmentMixin): self.backend.set_bucket_website_configuration(bucket_name, body) return "" else: + if body: + try: + region_name = xmltodict.parse(body)['CreateBucketConfiguration']['LocationConstraint'] + except KeyError: + pass + try: new_bucket = self.backend.create_bucket( bucket_name, region_name) diff --git a/tests/test_s3/test_s3.py b/tests/test_s3/test_s3.py index <HASH>..<HASH> 100644 --- a/tests/test_s3/test_s3.py +++ b/tests/test_s3/test_s3.py @@ -1208,6 +1208,22 @@ def test_boto3_bucket_create(): @mock_s3 +def test_bucket_create_duplicate(): + s3 = boto3.resource('s3', region_name='us-west-2') + s3.create_bucket(Bucket="blah", CreateBucketConfiguration={ + 'LocationConstraint': 'us-west-2', + }) + with assert_raises(ClientError) as exc: + s3.create_bucket( + Bucket="blah", + CreateBucketConfiguration={ + 'LocationConstraint': 'us-west-2', + } + ) + exc.exception.response['Error']['Code'].should.equal('BucketAlreadyExists') + + +@mock_s3 def test_boto3_bucket_create_eu_central(): s3 = boto3.resource('s3', region_name='eu-central-1') s3.create_bucket(Bucket="blah")
Fix duplicate bucket creation with LocationConstraint. Closes #<I>.
spulec_moto
train
f871a2b8c0353a45b3b55d71ef8d131b10e4e11a
diff --git a/testing/src/main/java/org/togglz/testing/fallback/FallbackTestFeatureManager.java b/testing/src/main/java/org/togglz/testing/fallback/FallbackTestFeatureManager.java index <HASH>..<HASH> 100644 --- a/testing/src/main/java/org/togglz/testing/fallback/FallbackTestFeatureManager.java +++ b/testing/src/main/java/org/togglz/testing/fallback/FallbackTestFeatureManager.java @@ -1,6 +1,7 @@ package org.togglz.testing.fallback; import java.util.Collections; +import java.util.List; import java.util.Set; import org.togglz.core.Feature; @@ -8,6 +9,7 @@ import org.togglz.core.manager.FeatureManager; import org.togglz.core.metadata.EmptyFeatureMetaData; import org.togglz.core.metadata.FeatureMetaData; import org.togglz.core.repository.FeatureState; +import org.togglz.core.spi.ActivationStrategy; import org.togglz.core.user.FeatureUser; /** @@ -54,4 +56,9 @@ public class FallbackTestFeatureManager implements FeatureManager { throw new UnsupportedOperationException(); } + @Override + public List<ActivationStrategy> getActivationStrategies() { + return Collections.emptyList(); + } + }
adding new method to fallback test feature manager
togglz_togglz
train
42ee39af43abb5cd93c4361d02385d82e8892cb3
diff --git a/src/core.js b/src/core.js index <HASH>..<HASH> 100755 --- a/src/core.js +++ b/src/core.js @@ -960,7 +960,7 @@ var initialized = false; // to handle mouse event - var registeredMouseEventObj = []; + //var registeredMouseEventObj = []; // to keep track of deferred stuff var pendingDefer = null; @@ -1152,11 +1152,13 @@ // add the object in the game obj list gameObjects.push(object); + /* // TO BE REMOVED if (object.isClickable) { // also add a reference in the object even list registeredMouseEventObj.push(object); } + */ // cache the number of object objCount = gameObjects.length; @@ -1254,10 +1256,12 @@ } }; + /**- * propagate mouse event to objects * @private */ + /* api.mouseEvent = function(v) { for (var i = registeredMouseEventObj.length, obj; i--, obj = registeredMouseEventObj[i];) { if (obj.isClickable && obj.collisionBox.containsPoint(v)) { @@ -1269,6 +1273,7 @@ } } }; + */ /** * update all objects of the game manager @@ -1321,11 +1326,13 @@ // remove the object from the object to draw drawManager.remove(obj); - + + /* if (obj.mouseEvent) { // remove object from the mouse event list registeredMouseEventObj.splice(registeredMouseEventObj.indexOf(obj), 1); } + */ // remove the object from the object list /** @private */ @@ -1353,7 +1360,7 @@ //empty everything objCount = 0; gameObjects = []; - registeredMouseEventObj = []; + //registeredMouseEventObj = []; // make sure it's empty there as well drawManager.flush(); @@ -1377,9 +1384,11 @@ }); // also sort the clickable items per z order + /* registeredMouseEventObj.sort(function(a, b) { return (a.z - b.z); }); + */ // make sure we redraw everything api.repaint();
Commented out the "old" mouse code
melonjs_melonJS
train
6468d792bc173340cc6fafa224c7ceac5a4b089b
diff --git a/remoto/tests/test_util.py b/remoto/tests/test_util.py index <HASH>..<HASH> 100644 --- a/remoto/tests/test_util.py +++ b/remoto/tests/test_util.py @@ -10,3 +10,7 @@ class TestAdminCommand(object): def test_skip_prepend_if_not_sudo(self): result = util.admin_command(False, ['ls']) assert result == ['ls'] + + def test_command_that_is_not_a_list(self): + result = util.admin_command(True, 'ls') + assert result == ['sudo', 'ls'] diff --git a/remoto/util.py b/remoto/util.py index <HASH>..<HASH> 100644 --- a/remoto/util.py +++ b/remoto/util.py @@ -10,5 +10,7 @@ def admin_command(sudo, command): :param command: A list of the actual command to execute with Popen. """ if sudo: - command.insert(0, 'sudo') + if not isinstance(command, list): + command = [command] + return ['sudo'] + [cmd for cmd in command] return command
do not mangle the command if it needs sudo
alfredodeza_remoto
train
a787ad472da020f4b55732984ca7f497604e32f2
diff --git a/java/client/src/org/openqa/selenium/remote/AddWebDriverSpecHeaders.java b/java/client/src/org/openqa/selenium/remote/AddWebDriverSpecHeaders.java index <HASH>..<HASH> 100644 --- a/java/client/src/org/openqa/selenium/remote/AddWebDriverSpecHeaders.java +++ b/java/client/src/org/openqa/selenium/remote/AddWebDriverSpecHeaders.java @@ -20,7 +20,6 @@ package org.openqa.selenium.remote; import org.openqa.selenium.json.Json; import org.openqa.selenium.remote.http.Filter; import org.openqa.selenium.remote.http.HttpHandler; -import org.openqa.selenium.remote.http.HttpResponse; public class AddWebDriverSpecHeaders implements Filter { @Override diff --git a/java/server/test/org/openqa/selenium/grid/router/NewSessionCreationTest.java b/java/server/test/org/openqa/selenium/grid/router/NewSessionCreationTest.java index <HASH>..<HASH> 100644 --- a/java/server/test/org/openqa/selenium/grid/router/NewSessionCreationTest.java +++ b/java/server/test/org/openqa/selenium/grid/router/NewSessionCreationTest.java @@ -137,23 +137,18 @@ public class NewSessionCreationTest { uri, uri, registrationSecret) - .add(Browser.detect().getCapabilities(), new TestSessionFactory((id, caps) -> new Session(id, uri, Browser.detect().getCapabilities(), caps, Instant.now()))) + .add( + Browser.detect().getCapabilities(), + new TestSessionFactory( + (id, caps) -> + new Session(id, uri, Browser.detect().getCapabilities(), caps, Instant.now()))) .build(); distributor.add(node); HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl()); - // Attempt to create a session without setting the content type - HttpResponse res = client.execute( - new HttpRequest(POST, "/session") - .setContent(Contents.asJson(ImmutableMap.of( - "capabilities", ImmutableMap.of( - "alwaysMatch", Browser.detect().getCapabilities()))))); - - assertThat(res.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); - // Attempt to create a session with an origin header but content type set - res = client.execute( + HttpResponse res = client.execute( new HttpRequest(POST, "/session") .addHeader("Content-Type", JSON_UTF_8) .addHeader("Origin", "localhost")
[grid] Making NewSessionCreationTest aware of the improvements on AddWebDriverSpecHeaders
SeleniumHQ_selenium
train
e4c87ff3659d9bdab2f2c85ad92445fbbb575e37
diff --git a/lib/router/router.js b/lib/router/router.js index <HASH>..<HASH> 100644 --- a/lib/router/router.js +++ b/lib/router/router.js @@ -142,7 +142,7 @@ Router.prototype = { */ reset: function() { if (this.state) { - forEach(this.state.handlerInfos, function(handlerInfo) { + forEach(this.state.handlerInfos.slice().reverse(), function(handlerInfo) { var handler = handlerInfo.handler; if (handler.exit) { handler.exit(); diff --git a/test/tests/router_test.js b/test/tests/router_test.js index <HASH>..<HASH> 100644 --- a/test/tests/router_test.js +++ b/test/tests/router_test.js @@ -1341,15 +1341,19 @@ test("calling transitionTo on a dynamic parent route causes non-dynamic child co test("reset exits and clears the current and target route handlers", function() { var postIndexExited = false; var showAllPostsExited = false; + var steps = 0; + equal(++steps, 1); var postIndexHandler = { exit: function() { postIndexExited = true; + equal(++steps, 4); } }; var showAllPostsHandler = { exit: function() { showAllPostsExited = true; + equal(++steps, 3); } }; handlers = { @@ -1359,8 +1363,8 @@ test("reset exits and clears the current and target route handlers", function() transitionTo(router, "/posts/all"); + equal(++steps, 2); router.reset(); - router.reset(); // two resets back to back should work ok(postIndexExited, "Post index handler did not exit"); ok(showAllPostsExited, "Show all posts handler did not exit");
reset() should trigger exit from leaf up The reset() function documentation describes that it should trigger the exit from leaf up the ancestor chain. However, it was doing the reverse. I added some assertions to the reset-test to make sure that this works as described. Additionally, I removed the second call for reset() since the tests seem to work without calling it twice. Possibly a previous bug?!
tildeio_router.js
train
3dd9b6da8c7a1cb670c0bb4db208cfd965a5ad10
diff --git a/lib/api/units/validateBody.js b/lib/api/units/validateBody.js index <HASH>..<HASH> 100644 --- a/lib/api/units/validateBody.js +++ b/lib/api/units/validateBody.js @@ -11,11 +11,10 @@ function isPlainText(mediaType) { } function isJson(mediaType) { - return mediaType.type === 'application' && mediaType.subtype === 'json'; -} - -function isJsonWeak(mediaType) { - return isJson(mediaType) || mediaType.suffix === 'json'; + return ( + (mediaType.type === 'application' && mediaType.subtype === 'json') || + mediaType.suffix === 'json' + ); } function isJsonSchema(mediaType) { @@ -54,7 +53,7 @@ function isJsonContentType(contentType) { // Silence an error on purporse because contentType // may contain any kind of rubbish. - return error ? false : isJsonWeak(mediaType); + return error ? false : isJson(mediaType); } /** @@ -153,7 +152,7 @@ function getBodyValidator(realType, expectedType) { return isJson(real) && isJsonSchema(expected); } ], - [JsonExample, both(isJsonWeak)] + [JsonExample, both(isJson)] ]; const validator = validators.find(([_name, predicate]) => {
refactor: removes "isJsonWeak" from "validateBody"
apiaryio_gavel.js
train
1c12b8a680ae9a9765609add63dc60f89fb5451e
diff --git a/lib/cucumber/platform.rb b/lib/cucumber/platform.rb index <HASH>..<HASH> 100644 --- a/lib/cucumber/platform.rb +++ b/lib/cucumber/platform.rb @@ -4,7 +4,7 @@ require 'rbconfig' module Cucumber unless defined?(Cucumber::VERSION) - VERSION = '1.3.1' + VERSION = '2.0' BINARY = File.expand_path(File.dirname(__FILE__) + '/../../bin/cucumber') LIBDIR = File.expand_path(File.dirname(__FILE__) + '/../../lib') JRUBY = defined?(JRUBY_VERSION)
Master branch now targets <I>
cucumber_cucumber-ruby
train
412264a1f7d354aa53403498b536ac057d933e9b
diff --git a/app/models/camaleon_cms/category.rb b/app/models/camaleon_cms/category.rb index <HASH>..<HASH> 100644 --- a/app/models/camaleon_cms/category.rb +++ b/app/models/camaleon_cms/category.rb @@ -15,6 +15,7 @@ class CamaleonCms::Category < CamaleonCms::TermTaxonomy has_many :children, class_name: "CamaleonCms::Category", foreign_key: :parent_id, dependent: :destroy belongs_to :parent, class_name: "CamaleonCms::Category", foreign_key: :parent_id belongs_to :post_type_parent, class_name: "CamaleonCms::PostType", foreign_key: :parent_id, inverse_of: :categories + belongs_to :site, class_name: 'CamaleonCms::Site', foreign_key: :site_id scope :no_empty, ->{ where("count > 0") } # return all categories that contains at least one post scope :empty, ->{ where(count: [0,nil]) } # return all categories that does not contain any post @@ -39,7 +40,7 @@ class CamaleonCms::Category < CamaleonCms::TermTaxonomy private def set_site pt = self.post_type - self.term_group = pt.site.id unless self.term_group.present? + self.site_id = pt.site_id unless self.site_id.present? self.status = pt.id unless self.status.present? end diff --git a/app/models/camaleon_cms/custom_field_group.rb b/app/models/camaleon_cms/custom_field_group.rb index <HASH>..<HASH> 100644 --- a/app/models/camaleon_cms/custom_field_group.rb +++ b/app/models/camaleon_cms/custom_field_group.rb @@ -9,6 +9,7 @@ class CamaleonCms::CustomFieldGroup < CamaleonCms::CustomField self.primary_key = :id # attrs required: name, slug, description + alias_attribute :site_id, :parent_id default_scope { where.not(object_class: '_fields').reorder("#{CamaleonCms::CustomField.table_name}.field_order ASC") } has_many :metas, ->{ where(object_class: 'CustomFieldGroup')}, :class_name => "CamaleonCms::Meta", foreign_key: :objectid, dependent: :destroy diff --git a/app/models/camaleon_cms/post_type.rb b/app/models/camaleon_cms/post_type.rb index <HASH>..<HASH> 100644 --- a/app/models/camaleon_cms/post_type.rb +++ b/app/models/camaleon_cms/post_type.rb @@ -7,6 +7,7 @@ See the GNU Affero General Public License (GPLv3) for more details. =end class CamaleonCms::PostType < CamaleonCms::TermTaxonomy + alias_attribute :site_id, :parent_id default_scope { where(taxonomy: :post_type) } has_many :metas, ->{ where(object_class: 'PostType')}, :class_name => "CamaleonCms::Meta", foreign_key: :objectid, dependent: :delete_all has_many :categories, :class_name => "CamaleonCms::Category", foreign_key: :parent_id, dependent: :destroy, inverse_of: :post_type_parent diff --git a/app/models/concerns/camaleon_cms/custom_fields_read.rb b/app/models/concerns/camaleon_cms/custom_fields_read.rb index <HASH>..<HASH> 100644 --- a/app/models/concerns/camaleon_cms/custom_fields_read.rb +++ b/app/models/concerns/camaleon_cms/custom_fields_read.rb @@ -144,6 +144,15 @@ module CamaleonCms::CustomFieldsRead extend ActiveSupport::Concern values = values.with_indifferent_access group = get_field_groups(kind).where(slug: values[:slug]).first unless group.present? + site = case self.class.to_s.parseCamaClass + when 'Category','Post','PostTag' + self.post_type.site + when 'Site' + self + else + self.site + end + values[:parent_id] = site.id if site.present? group = get_field_groups(kind).create(values) end group
- fixed site id for custom field groups created by code
owen2345_camaleon-cms
train
fb224f23f03b2e537fb94027f0b2a84ded836d44
diff --git a/hiwenet/test_hiwenet.py b/hiwenet/test_hiwenet.py index <HASH>..<HASH> 100644 --- a/hiwenet/test_hiwenet.py +++ b/hiwenet/test_hiwenet.py @@ -14,12 +14,13 @@ if version_info.major==2 and version_info.minor==7: elif version_info.major > 2: from hiwenet import extract as hiwenet from hiwenet import run_cli as CLI + from hiwenet.pairwise_dist import metric_list, semi_metric_list # from hiwenet.hiwenet import extract as hiwenet # from hiwenet.hiwenet import run_cli as CLI else: raise NotImplementedError('hiwenet supports only 2.7.13 or 3+. Upgrate to Python 3+ is recommended.') - +list_weight_methods = metric_list + semi_metric_list sys.dont_write_bytecode = True from pytest import raises, warns, set_trace @@ -189,19 +190,22 @@ def test_CLI_output_matches_API(): # turning groups into strings to correspond with CLI groups_str = np.array([str(grp) for grp in groups]) - api_result = hiwenet(features, groups_str, weight_method='cosine') + featrs_path = abspath(pjoin(cur_dir, '..', 'examples', 'test_features.txt')) groups_path = abspath(pjoin(cur_dir, '..', 'examples', 'test_groups.txt')) result_path = abspath(pjoin(cur_dir, '..', 'examples', 'test_result.txt')) np.savetxt(featrs_path, features, fmt='%20.9f') np.savetxt(groups_path, groups, fmt='%d') - sys.argv = shlex.split('hiwenet -f {} -g {} -o {} -w cosine'.format(featrs_path, groups_path, result_path)) - CLI() - cli_result = np.genfromtxt(result_path, delimiter=',') + for weight_method in list_weight_methods: + api_result = hiwenet(features, groups_str, weight_method=weight_method) + + sys.argv = shlex.split('hiwenet -f {} -g {} -o {} -w {}'.format(featrs_path, groups_path, result_path, weight_method)) + CLI() + cli_result = np.genfromtxt(result_path, delimiter=',') - if not bool(np.allclose(cli_result, api_result, rtol=1e-2, atol=1e-3, equal_nan=True)): - raise ValueError('CLI results differ from API.') + if not bool(np.allclose(cli_result, api_result, rtol=1e-2, atol=1e-3, equal_nan=True)): + raise ValueError('CLI results differ from API for {}'.format(weight_method)) def test_CLI_nonexisting_paths(): @@ -276,7 +280,7 @@ def test_input_callable_on_orig_data(): # test_directed_nx() # test_directed_mat() -# test_CLI_output_matches_API() +test_CLI_output_matches_API() # test_input_callable() -test_more_metrics() \ No newline at end of file +# test_more_metrics() \ No newline at end of file
extending CLI vs API test to all metrics and semi metrics
raamana_hiwenet
train
3d73e6233cd302970cd4b64b3462eb1fe4538247
diff --git a/cleverhans/attacks.py b/cleverhans/attacks.py index <HASH>..<HASH> 100644 --- a/cleverhans/attacks.py +++ b/cleverhans/attacks.py @@ -357,17 +357,17 @@ class FastGradientMethod(Attack): class ProjectedGradientDescent(Attack): """ - Class implements either the Basic Iterative Method (Kurakin et al. 2016) - when rand_minmax is set to 0. or the Madry et al. (2017) method when - rand_minmax is larger than 0. The original Kurakin et al. (2016) paper used - hard labels for this attack; no label smoothing. + This class implements either the Basic Iterative Method + (Kurakin et al. 2016) when rand_init is set to 0. or the + Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf """ FGM_CLASS = FastGradientMethod - def __init__(self, model, back='tf', sess=None, dtypestr='float32'): + def __init__(self, model, back='tf', sess=None, dtypestr='float32', + rand_init=True): """ Create a ProjectedGradientDescent instance. Note: the model parameter should be an instance of the @@ -386,8 +386,8 @@ class ProjectedGradientDescent(Attack): 'clip_min': self.np_dtype, 'clip_max': self.np_dtype } - self.structural_kwargs = ['ord', 'nb_iter', 'rand_init'] - self.child = None + self.structural_kwargs = ['ord', 'nb_iter'] + self.rand_init = rand_init def generate(self, x, **kwargs): """ @@ -398,10 +398,12 @@ class ProjectedGradientDescent(Attack): compared to original input :param eps_iter: (required float) step size for each attack iteration :param nb_iter: (required int) Number of attack iterations. - :param y: (optional) A tensor with the model labels. + :param y: (optional) A tensor with the true class labels + NOTE: do not use smoothed labels here :param y_target: (optional) A tensor with the labels to target. Leave y_target=None if y is also set. Labels should be one-hot-encoded. + NOTE: do not use smoothed labels here :param ord: (optional) Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param clip_min: (optional float) Minimum input component value @@ -413,8 +415,11 @@ class ProjectedGradientDescent(Attack): assert self.parse_params(**kwargs) # Initialize loop variables - eta = tf.random_uniform(tf.shape(x), -self.rand_minmax, + if self.rand_init: + eta = tf.random_uniform(tf.shape(x), -self.rand_minmax, self.rand_minmax, dtype=self.tf_dtype) + else: + eta = tf.zeros(tf.shape(x)) eta = clip_eta(eta, self.ord, self.eps) # Fix labels to the first model predictions for loss computation @@ -502,15 +507,14 @@ class ProjectedGradientDescent(Attack): :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ - if self.child is not None: - if self.child == 'BasicIterativeMethod': - rand_minmax = 0. - elif self.child == 'MadryEtAl': - if 'rand_init' in kwargs and not kwargs['rand_init']: - rand_minmax = 0. + # Save attack-specific parameters self.eps = eps + if self.rand_init: + self.rand_minmax = eps + else: + self.rand_minmax = 0. self.eps_iter = eps_iter self.nb_iter = nb_iter self.y = y @@ -518,7 +522,6 @@ class ProjectedGradientDescent(Attack): self.ord = ord self.clip_min = clip_min self.clip_max = clip_max - self.rand_minmax = rand_minmax if self.y is not None and self.y_target is not None: raise ValueError("Must not set both y and y_target") @@ -532,15 +535,14 @@ class ProjectedGradientDescent(Attack): class BasicIterativeMethod(ProjectedGradientDescent): def __init__(self, model, back='tf', sess=None, dtypestr='float32'): super(BasicIterativeMethod, self).__init__(model, back, sess=sess, - dtypestr=dtypestr) - self.child = 'BasicIterativeMethod' + dtypestr=dtypestr, + rand_init=False) class MadryEtAl(ProjectedGradientDescent): def __init__(self, model, back='tf', sess=None, dtypestr='float32'): super(MadryEtAl, self).__init__(model, back, sess=sess, - dtypestr=dtypestr) - self.child = 'MadryEtAl' + dtypestr=dtypestr, rand_init=True) class MomentumIterativeMethod(Attack):
get rid of "self.child"
tensorflow_cleverhans
train
64b15fbdd614b8cf41518ae523db9d4e0dabd697
diff --git a/PyParse.py b/PyParse.py index <HASH>..<HASH> 100644 --- a/PyParse.py +++ b/PyParse.py @@ -9,7 +9,7 @@ import csv class Parser(object): def __init__(self, filepath, field_map, dialect=None, - has_header=None, line_skip=0, firstRow_kw=''): + has_header=None, line_skip=0, firstRow_kw='', read_mode='rb'): """Initializes parser Arguments: filepath (str) : path of target file @@ -32,7 +32,12 @@ class Parser(object): NOTE: you must manually specify the has_header keyword argument, if using this feature + read_mode (str) : optional, default = 'rb'; + opener method to use when reading file; sometimes a + file will need to be opened in universial read-mode + (ie: 'rU') """ + self.read_mode = read_mode self.has_header = has_header self.field_map = field_map self.header = field_map.keys() @@ -42,12 +47,12 @@ class Parser(object): if not dialect: dialect = self._dialect(filepath) self.dialect = dialect - self.reader = csv.reader(open(filepath, 'rb'), dialect=dialect) + self.reader = csv.reader(open(filepath, read_mode), dialect=dialect) # skip junk data if firstRow_kw specified if firstRow_kw != '': try: - reader_cp = csv.reader(open(filepath, 'rb'), dialect=dialect) + reader_cp = csv.reader(open(filepath, read_mode), dialect=dialect) while True: row = reader_cp.next() if row[0].upper().startswith(firstRow_kw.upper()): @@ -97,7 +102,7 @@ class Parser(object): Arguments: filepath (str): filepath of target csv file """ - with open(filepath, 'rb') as csvfile: + with open(filepath, self.read_mode) as csvfile: sample = csvfile.read(1024) dialect = csv.Sniffer().sniff(sample) if self.has_header == None: diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from distutils.core import setup setup(name='PyParse', author='Matt Johnson, PharmD.', author_email='johnson.matthew.h@gmail.com', - version='1.1.5', + version='1.1.6', py_modules=['PyParse'], url = 'https://github.com/mhjohnson/PyParse', description = "Parse text files in an easier and more maintainable manner",
option to open file in different read modes
mhjohnson_PyParse
train
8ce7e71a223cbbd48d7547d69daebb96c8102b87
diff --git a/src/main/java/tachyon/CommonUtils.java b/src/main/java/tachyon/CommonUtils.java index <HASH>..<HASH> 100644 --- a/src/main/java/tachyon/CommonUtils.java +++ b/src/main/java/tachyon/CommonUtils.java @@ -1,5 +1,6 @@ package tachyon; +import java.io.IOException; import java.nio.ByteBuffer; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -21,7 +22,10 @@ public final class CommonUtils { private CommonUtils () { } - public static String cleanPath(String path) { + public static String cleanPath(String path) throws IOException { + if (path == null || path.isEmpty()) { + throw new IOException("Path is (" + path + ") is invalid."); + } while (path.endsWith("/") && path.length() > 1) { path = path.substring(0, path.length() - 1); }
fix a cleanpath non-pointer exception bug.
Alluxio_alluxio
train
2ea77ec5eeea2351de50b268994ba69f876b815c
diff --git a/lib/coveralls/api.rb b/lib/coveralls/api.rb index <HASH>..<HASH> 100644 --- a/lib/coveralls/api.rb +++ b/lib/coveralls/api.rb @@ -20,7 +20,7 @@ module Coveralls Coveralls::Output.puts("#{ JSON.pretty_generate(hash) }", :color => "green") if ENV['COVERALLS_DEBUG'] hash = apified_hash hash Coveralls::Output.puts("[Coveralls] Submitting to #{API_BASE}", :color => "cyan") - response = RestClient::Request.execute(:method => :post, :url => url, :payload => { :json_file => hash_to_file(hash) }, :ssl_version => 'SSLv23') + response = RestClient::Request.execute(:method => :post, :url => url, :payload => { :json_file => hash_to_file(hash) }, :ssl_version => 'TLSv1', :verify_ssl => false) response_hash = JSON.load(response.to_str) Coveralls::Output.puts("[Coveralls] #{ response_hash['message'] }", :color => "cyan") if response_hash['message'] diff --git a/lib/coveralls/version.rb b/lib/coveralls/version.rb index <HASH>..<HASH> 100644 --- a/lib/coveralls/version.rb +++ b/lib/coveralls/version.rb @@ -1,3 +1,3 @@ module Coveralls - VERSION = "0.8.1" + VERSION = "0.8.2" end
swap SSL<I> for TLSv1 version bump
lemurheavy_coveralls-ruby
train
33245c8f83e854b4eef0e562ae4c64ddbd213c62
diff --git a/base.php b/base.php index <HASH>..<HASH> 100644 --- a/base.php +++ b/base.php @@ -2055,12 +2055,28 @@ final class Base extends Prefab implements ArrayAccess { $_SERVER['SERVER_NAME']=gethostname(); if (PHP_SAPI=='cli') { // Emulate HTTP request - if (isset($_SERVER['argc']) && $_SERVER['argc']<2) { + $_SERVER['REQUEST_METHOD']='GET'; + if (!isset($_SERVER['argv'][1])) { $_SERVER['argc']++; $_SERVER['argv'][1]='/'; } - $_SERVER['REQUEST_METHOD']='GET'; - $_SERVER['REQUEST_URI']=$_SERVER['argv'][1]; + if (substr($_SERVER['argv'][1],0,1)=='/') + $_SERVER['REQUEST_URI']=$_SERVER['argv'][1]; + else { + $req=$opts=''; + foreach($_SERVER['argv'] as $i=>$arg) { + if (!$i) continue; + if (preg_match('/^\-(\-)?(\w+)(?:\=(.*))?$/',$arg,$m)) { + foreach($m[1]?[$m[2]]:str_split($m[2]) as $k) + $opts.=($opts?'&':'').$k.'='; + if (isset($m[3])) + $opts.=$m[3]; + } else + $req.='/'.$arg; + } + $_SERVER['REQUEST_URI']=($req?:'/').'?'.$opts; + parse_str($opts,$GLOBALS['_GET']); + } } $headers=[]; if (PHP_SAPI!='cli')
NEW: console-friendly CLI mode (#<I>)
bcosca_fatfree-core
train
06c4937cb555870b7c929c0692437b9e33aa7fe7
diff --git a/bin/jade.js b/bin/jade.js index <HASH>..<HASH> 100755 --- a/bin/jade.js +++ b/bin/jade.js @@ -190,19 +190,11 @@ function renderFile(path) { var dir = resolve(dirname(path)); mkdirp(dir, 0755, function(err){ if (err) throw err; - try { - var output = options.client ? fn : fn(options); - fs.writeFile(path, output, function(err){ - if (err) throw err; - console.log(' \033[90mrendered \033[36m%s\033[0m', path); - }); - } catch (e) { - if (options.watch) { - console.error(e.stack || e.message || e); - } else { - throw e - } - } + var output = options.client ? fn : fn(options); + fs.writeFile(path, output, function(err){ + if (err) throw err; + console.log(' \033[90mrendered \033[36m%s\033[0m', path); + }); }); }); // Found directory
Remove another now-useless special exception handling for watch mode I have already removed two in <I>b<I>e<I>e<I>f<I>aae<I>e8d9ca<I>e0b<I>.
pugjs_then-pug
train
9676e864f0d37f852ff6c6ba3f99e1b7b134e135
diff --git a/molgenis-data-import/src/main/java/org/molgenis/data/importer/OptionsWizardPage.java b/molgenis-data-import/src/main/java/org/molgenis/data/importer/OptionsWizardPage.java index <HASH>..<HASH> 100644 --- a/molgenis-data-import/src/main/java/org/molgenis/data/importer/OptionsWizardPage.java +++ b/molgenis-data-import/src/main/java/org/molgenis/data/importer/OptionsWizardPage.java @@ -77,7 +77,7 @@ public class OptionsWizardPage extends AbstractWizardPage { String fileName = tmpFile.getName(); - int index = fileName.indexOf('.'); + int index = fileName.lastIndexOf('.'); String extension = (index > -1) ? fileName.substring(index) : ""; File file = new File(tmpFile.getParent(), userGivenName + extension);
fix: Some imported VCF files report errors in data explorer #<I>
molgenis_molgenis
train
09af5972ebdc5698feda2d3e139dea0723bd8e87
diff --git a/cmd_build.go b/cmd_build.go index <HASH>..<HASH> 100644 --- a/cmd_build.go +++ b/cmd_build.go @@ -921,7 +921,7 @@ func (cto *createTemplateOp) Invoke(ctx context.Context, logger *zerolog.Logger) // TODO - turn this into a Parameter block with defaults... if nil != cto.userdata.s3SiteContext.s3Site { exportErr := cto.userdata.s3SiteContext.s3Site.export(cto.userdata.serviceName, - cto.buildContext.compiledBinaryOutput, + SpartaBinaryName, gocf.Ref(StackParamS3CodeBucketName), s3CodeResource, gocf.Ref(StackParamS3SiteArchiveKey).String(),
Ensure S3 site uses proper binary name
mweagle_Sparta
train
69264490c276058217c4ffd669ba722db0f96ff4
diff --git a/packages/openneuro-server/datalad/__tests__/dataset.spec.js b/packages/openneuro-server/datalad/__tests__/dataset.spec.js index <HASH>..<HASH> 100644 --- a/packages/openneuro-server/datalad/__tests__/dataset.spec.js +++ b/packages/openneuro-server/datalad/__tests__/dataset.spec.js @@ -51,7 +51,7 @@ describe('dataset model operations', () => { describe('createSnapshot()', () => { it('posts to the DataLad /datasets/{dsId}/snapshots/{snapshot} endpoint', async done => { const tag = 'snapshot' - const dsId = await createDataset() + const dsId = await createDataset('a label') // Reset call count for request.post request.post.mockClear() await createSnapshot(dsId, tag)
Server: Fix minor issue in dataset snapshot creation test.
OpenNeuroOrg_openneuro
train
558625b30a79d15656d49714bbb53a06e3c4e62c
diff --git a/public/js/clients/firefox.js b/public/js/clients/firefox.js index <HASH>..<HASH> 100644 --- a/public/js/clients/firefox.js +++ b/public/js/clients/firefox.js @@ -109,7 +109,7 @@ function initPage(actions) { // makes the server iterate over them and fire individual // `newSource` notifications. We don't need to do anything with the // response since `newSource` notifications are fired. - threadClient.getSources(); + return threadClient.getSources(); } module.exports = { diff --git a/public/js/main.js b/public/js/main.js index <HASH>..<HASH> 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -103,8 +103,8 @@ if (connTarget) { bootstrap: ({ threadClient, tabTarget }) => { firefox.setThreadClient(threadClient); firefox.setTabTarget(tabTarget); - firefox.initPage(actions); renderRoot(App); + return firefox.initPage(actions); }, destroy: () => { unmountRoot();
update bootstrap to block on sources loading (#<I>)
firefox-devtools_debugger
train
4ed831ca74098cd228d5f792e8ca10ff8317b9ae
diff --git a/Bundle/SeoBundle/Repository/HttpErrorRepository.php b/Bundle/SeoBundle/Repository/HttpErrorRepository.php index <HASH>..<HASH> 100644 --- a/Bundle/SeoBundle/Repository/HttpErrorRepository.php +++ b/Bundle/SeoBundle/Repository/HttpErrorRepository.php @@ -5,6 +5,7 @@ namespace Victoire\Bundle\SeoBundle\Repository; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\QueryBuilder; use Victoire\Bundle\CoreBundle\Repository\StateFullRepositoryTrait; +use Victoire\Bundle\SeoBundle\Entity\HttpError; /** * Class HttpErrorRepository. @@ -14,6 +15,8 @@ class HttpErrorRepository extends EntityRepository use StateFullRepositoryTrait; /** + * Get every errors in the repository. + * * @param bool $exceptRedirected * * @return HttpErrorRepository @@ -32,15 +35,44 @@ class HttpErrorRepository extends EntityRepository } /** + * Get every route errors in the repository. + * + * @param string $order + * @param string $direction + * + * @return QueryBuilder + */ + public function getRouteErrors($order = 'error.counter', $direction = 'DESC') + { + $this->getAll(true); + + /** @var QueryBuilder $qb */ + $qb = $this->qb; + + return $qb + ->andWhere('error.type = :type') + ->setParameter('type', HttpError::TYPE_ROUTE) + ->orderBy($order, $direction); + } + + /** + * Get every file errors in the repository. + * * @param string $order * @param string $direction * * @return QueryBuilder */ - public function getUnresolvedQuery($order = 'error.counter', $direction = 'DESC') + public function getFileErrors($order = 'error.counter', $direction = 'DESC') { $this->getAll(true); - return $this->qb->orderBy($order, $direction); + /** @var QueryBuilder $qb */ + $qb = $this->qb; + + return $qb + ->andWhere('error.type = :type') + ->setParameter('type', HttpError::TYPE_FILE) + ->orderBy($order, $direction); } } \ No newline at end of file
add new methods to fetch <I> errors by type
Victoire_victoire
train
d213d25a493550a035e13482dc97fcca3a5d3061
diff --git a/src/Behat/Mink/Element/NodeElement.php b/src/Behat/Mink/Element/NodeElement.php index <HASH>..<HASH> 100644 --- a/src/Behat/Mink/Element/NodeElement.php +++ b/src/Behat/Mink/Element/NodeElement.php @@ -168,7 +168,9 @@ class NodeElement extends TraversableElement return; } - $opt = $this->find('named', array('option', $option)); + $opt = $this->find('named', array( + 'option', $this->getSession()->getSelectorsHandler()->xpathLiteral($option) + )); if (null === $opt) { throw new ElementNotFoundException( diff --git a/tests/Behat/Mink/Driver/GeneralDriverTest.php b/tests/Behat/Mink/Driver/GeneralDriverTest.php index <HASH>..<HASH> 100644 --- a/tests/Behat/Mink/Driver/GeneralDriverTest.php +++ b/tests/Behat/Mink/Driver/GeneralDriverTest.php @@ -349,8 +349,8 @@ abstract class GeneralDriverTest extends TestCase $maillist->uncheck(); $this->assertFalse($maillist->isChecked()); - $select->selectOption('ten'); - $this->assertEquals('10', $select->getValue()); + $select->selectOption('thirty'); + $this->assertEquals('30', $select->getValue()); $sex->selectOption('m'); $this->assertEquals('m', $sex->getValue()); @@ -372,7 +372,7 @@ array ( 'first_name' = 'Foo "item"', 'last_name' = 'Bar', 'email' = 'ever.zet@gmail.com', - 'select_number' = '10', + 'select_number' = '30', 'sex' = 'm', 'agreement' = 'on', )
fixed literal escaping in select option finding
minkphp_Mink
train
feec6820fe2f3ece26ceeea240cb0d1ff6c719d4
diff --git a/protokube/pkg/gossip/dns/hosts/hosts.go b/protokube/pkg/gossip/dns/hosts/hosts.go index <HASH>..<HASH> 100644 --- a/protokube/pkg/gossip/dns/hosts/hosts.go +++ b/protokube/pkg/gossip/dns/hosts/hosts.go @@ -20,11 +20,13 @@ import ( "bytes" "fmt" "io/ioutil" + math_rand "math/rand" "os" "path/filepath" "sort" "strings" "sync" + "time" "k8s.io/klog" ) @@ -113,15 +115,50 @@ func UpdateHostsFileWithRecords(p string, addrToHosts map[string][]string) error // Note that because we are bind mounting /etc/hosts, we can't do a normal atomic file write // (where we write a temp file and rename it) - // TODO: We should just hold the file open while we read & write it - err = ioutil.WriteFile(p, updated, stat.Mode().Perm()) - if err != nil { + if err := pseudoAtomicWrite(p, updated, stat.Mode()); err != nil { return fmt.Errorf("error writing file %q: %v", p, err) } return nil } +// Because we are bind-mounting /etc/hosts, we can't do a normal +// atomic file write (where we write a temp file and rename it); +// instead we write the file, pause, re-read and see if anyone else +// wrote in the meantime; if so we rewrite again. By pausing for a +// random amount of time, eventually we'll win the write race and +// exit. This doesn't guarantee fairness, but it should mean that the +// end-result is not malformed (i.e. partial writes). +func pseudoAtomicWrite(p string, b []byte, mode os.FileMode) error { + attempt := 0 + for { + attempt++ + if attempt > 10 { + return fmt.Errorf("failed to consistently write file %q - too many retries", p) + } + + if err := ioutil.WriteFile(p, b, mode); err != nil { + klog.Warningf("error writing file %q: %v", p, err) + continue + } + + n := 1 + math_rand.Intn(20) + time.Sleep(time.Duration(n) * time.Millisecond) + + contents, err := ioutil.ReadFile(p) + if err != nil { + klog.Warningf("error re-reading file %q: %v", p, err) + continue + } + + if bytes.Equal(contents, b) { + return nil + } + + klog.Warningf("detected concurrent write to file %q, will retry", p) + } +} + func atomicWriteFile(filename string, data []byte, perm os.FileMode) error { dir := filepath.Dir(filename)
Avoid concurrent write corruption to /etc/hosts When we have multiple writers racing to write /etc/hosts, we could have file corruption where we see a mix of both files. We can't use a traditional atomic file write, because we are bind-mounting /etc/hosts. Instead we write to /etc/hosts, pause, then re-read the contents. If the contents don't match, we repeat. This will not result in fair queuing, but will avoid corruption.
kubernetes_kops
train
0219d61af5067b064983e1c48241580949fd9817
diff --git a/src/Entity/Crossword.php b/src/Entity/Crossword.php index <HASH>..<HASH> 100644 --- a/src/Entity/Crossword.php +++ b/src/Entity/Crossword.php @@ -8,6 +8,7 @@ use Doctrine\ORM\Mapping\PrePersist; use Doctrine\ORM\Mapping\PreUpdate; use PlaygroundGame\Entity\Game; +use Gedmo\Mapping\Annotation as Gedmo; use Laminas\InputFilter\Factory as InputFactory; use Laminas\InputFilter\InputFilter; @@ -46,11 +47,13 @@ class Crossword extends Game implements InputFilterAwareInterface protected $gameType = 'crossword'; /** + * @Gedmo\Translatable * @ORM\Column(name="layout_rows", type="integer", nullable=true) */ protected $layoutRows; /** + * @Gedmo\Translatable * @ORM\Column(name="layout_columns", type="integer", nullable=true) */ protected $layoutColumns;
size of the crossword is translatable
gregorybesson_PlaygroundGame
train
339618abf2d2f941addac4597fae25fab4d9a3e0
diff --git a/claripy/simplifications.py b/claripy/simplifications.py index <HASH>..<HASH> 100644 --- a/claripy/simplifications.py +++ b/claripy/simplifications.py @@ -605,9 +605,6 @@ class SimplificationManager: if body.op == 'Not': return body.args[0] - if body.op == 'If': - return ast.all_operations.If(body.args[0], body.args[2], body.args[1]) - if body.op == 'SLT': return ast.all_operations.SGE(body.args[0], body.args[1]) elif body.op == 'SLE':
Remove incorrect Not(If()) simplification; closes angr/angr#<I>
angr_claripy
train
f8bdd43f518e625914f6dd2bfa9e282a60389753
diff --git a/test/unit/_bootstrap.js b/test/unit/_bootstrap.js index <HASH>..<HASH> 100644 --- a/test/unit/_bootstrap.js +++ b/test/unit/_bootstrap.js @@ -7,6 +7,10 @@ var chai = require('chai'), chai.use(sinonChai); +global.nobrowser = function (it) { + return (typeof window === 'undefined' ? it : it.skip); +}; + before(function () { global.expect && (_expect = global.expect); global.expect = chai.expect; @@ -21,6 +25,8 @@ after(function () { _sinon ? (global.sinon = _sinon) : (delete global.sinon); _sinon = null; + + delete global.nobrowser; }); describe('_bootstrap', function () { diff --git a/test/unit/sandbox-assertions.test.js b/test/unit/sandbox-assertions.test.js index <HASH>..<HASH> 100644 --- a/test/unit/sandbox-assertions.test.js +++ b/test/unit/sandbox-assertions.test.js @@ -96,7 +96,7 @@ describe('sandbox test assertion', function () { }); }); - it('should call the assertion event on async test', function (done) { + nobrowser(it)('should call the assertion event on async test', function (done) { Sandbox.createContext({debug: true}, function (err, ctx) { if (err) { return done(err); } @@ -131,7 +131,7 @@ describe('sandbox test assertion', function () { }); }); - it('should not wait if async done is not called', function (done) { + nobrowser(it)('should not wait if async done is not called', function (done) { Sandbox.createContext({debug: true}, function (err, ctx) { if (err) { return done(err); } @@ -157,7 +157,7 @@ describe('sandbox test assertion', function () { }); }); - it('should terminate script if async done is not called in an async script', function (done) { + nobrowser(it)('should terminate script if async done is not called in an async script', function (done) { Sandbox.createContext({debug: true}, function (err, ctx) { if (err) { return done(err); } @@ -185,7 +185,7 @@ describe('sandbox test assertion', function () { }); }); - it('should forward errors from asynchronous callback', function (done) { + nobrowser(it)('should forward errors from asynchronous callback', function (done) { Sandbox.createContext({debug: true}, function (err, ctx) { if (err) { return done(err); } @@ -224,7 +224,7 @@ describe('sandbox test assertion', function () { }); }); - it('should forward synchronous errors from asynchronous tests', function (done) { + nobrowser(it)('should forward synchronous errors from asynchronous tests', function (done) { Sandbox.createContext({debug: true}, function (err, ctx) { if (err) { return done(err); } diff --git a/test/unit/sandbox-libraries/ajv.test.js b/test/unit/sandbox-libraries/ajv.test.js index <HASH>..<HASH> 100644 --- a/test/unit/sandbox-libraries/ajv.test.js +++ b/test/unit/sandbox-libraries/ajv.test.js @@ -70,7 +70,7 @@ describe('sandbox library - AJV', function () { `, done); }); - (typeof window === 'undefined' ? it : it.skip)('compileAsync', function (done) { + nobrowser(it)('compileAsync', function (done) { context.execute(` var Ajv = require('ajv'), diff --git a/test/unit/sandbox-libraries/chai-postman.test.js b/test/unit/sandbox-libraries/chai-postman.test.js index <HASH>..<HASH> 100644 --- a/test/unit/sandbox-libraries/chai-postman.test.js +++ b/test/unit/sandbox-libraries/chai-postman.test.js @@ -462,7 +462,7 @@ describe('sandbox library - chai-postman', function () { }); // eslint-disable-next-line max-len - (typeof window === 'undefined' ? it : it.skip)('should have a way to be asserted for absence', function (done) { + nobrowser(it)('should have a way to be asserted for absence', function (done) { context.execute(` var response = new (require('postman-collection').Response)({ responseTime: NaN diff --git a/test/unit/sandbox-timeout.test.js b/test/unit/sandbox-timeout.test.js index <HASH>..<HASH> 100644 --- a/test/unit/sandbox-timeout.test.js +++ b/test/unit/sandbox-timeout.test.js @@ -1,4 +1,4 @@ -(typeof window === 'undefined' ? describe : describe.skip)('sandbox timeout', function () { +nobrowser(describe)('sandbox timeout', function () { this.timeout(1000 * 60); var Sandbox = require('../../lib'); diff --git a/test/unit/sandbox-timers.test.js b/test/unit/sandbox-timers.test.js index <HASH>..<HASH> 100644 --- a/test/unit/sandbox-timers.test.js +++ b/test/unit/sandbox-timers.test.js @@ -1,4 +1,4 @@ -(typeof window === 'undefined' ? describe : describe.skip)('timers inside sandbox', function () { +nobrowser(describe)('timers inside sandbox', function () { this.timeout(1000 * 60); var Sandbox = require('../../lib'), ctx;
Prevented the assertion async tests from running in browser (since setTimeout is not supported) In the process, cleaned the way of specifying `nobrowser`
postmanlabs_postman-sandbox
train
b88ce147115baf5379bf7dbfbf432ec058f7dca1
diff --git a/packages/micro-journeys/src/interactive-pathways.js b/packages/micro-journeys/src/interactive-pathways.js index <HASH>..<HASH> 100644 --- a/packages/micro-journeys/src/interactive-pathways.js +++ b/packages/micro-journeys/src/interactive-pathways.js @@ -29,11 +29,14 @@ class BoltInteractivePathways extends withLitHtml() { connectedCallback() { super.connectedCallback(); - // wait till children are mounted before trying to find them + // @todo remove setTimeout(() => { - this.style.opacity = 1; - this.showPathway(0); - }, 0); + // wait till children are mounted before trying to find them + setTimeout(() => { + this.style.opacity = 1; + this.showPathway(0); + }, 0); + }); } /**
fix(micro-journeys): pathways should wait for children
bolt-design-system_bolt
train
6f49cad3075d7a2b4b8ad246838d7528065ceee9
diff --git a/src/Case.js b/src/Case.js index <HASH>..<HASH> 100644 --- a/src/Case.js +++ b/src/Case.js @@ -80,9 +80,9 @@ }, Case = { _: _, - of: function(s) { + of: function(s, arg2) { for (var i=0,m=_.types.length; i<m; i++) { - if (Case[_.types[i]](s) === s){ return _.types[i]; } + if (Case[_.types[i]](s, arg2) === s){ return _.types[i]; } } }, flip: function(s) { @@ -149,7 +149,7 @@ return s; } }; - + // TODO: Remove "squish" in a future breaking release. types.squish = types.pascal; diff --git a/src/toCase.js b/src/toCase.js index <HASH>..<HASH> 100644 --- a/src/toCase.js +++ b/src/toCase.js @@ -8,8 +8,8 @@ (function(Case, _) { function create(type) { var fn = 'to'+_.cap(type)+'Case'; - String.prototype[fn] = function() { - return Case[type](this); + String.prototype[fn] = function(arg) { + return Case[type](this, arg); }; } for (var i=0,m=_.types.length; i<m; i++) { diff --git a/test/Case_test.js b/test/Case_test.js index <HASH>..<HASH> 100644 --- a/test/Case_test.js +++ b/test/Case_test.js @@ -7,18 +7,20 @@ upper: 'THIS IS NICE AND TIDY, NATHAN.', lower: 'this is nice and tidy, nathan.', header: 'This-Is-Nice-And-Tidy-Nathan', - sentence: 'This is nice and tidy, nathan.', + sentence: 'This is nice and tidy, Nathan.', capital: 'This Is Nice And Tidy, Nathan.', title: 'This Is Nice and Tidy, Nathan.', constant: 'THIS_IS_NICE_AND_TIDY_NATHAN' }, + properNames = ['Nathan'], _ = Case._; function convert(a, b) { test(a+' to '+b, function() { expect(2); - var direct = Case[b](types[a]), - viaTo = types[a]['to'+_.cap(b)+'Case'](), + var arg = b === "sentence" ? properNames : undefined, + direct = Case[b](types[a], arg), + viaTo = types[a]['to'+_.cap(b)+'Case'](arg), lossy = direct.length < types[b].length, expected = lossy ? types[b].replace(/[^\w ]/g,'') : types[b]; strictEqual(direct, expected); @@ -29,7 +31,7 @@ function identify(a) { test('identify '+a, function() { expect(1); - var actual = Case.of(types[a]); + var actual = Case.of(types[a], a === "sentence" ? properNames : undefined); strictEqual(actual, a); }); } @@ -172,6 +174,10 @@ equal(Case.sentence(''), ''); }); + test('#22 - Case.of should support specifying proper names', function() { + equal(Case.of("Hello, Sue, how is Bob?", ['Sue', 'Bob']), "sentence"); + }); + test('outliers', function() { equal(Case.lower(undefined), '', "empty should be empty string"); equal(Case.sentence(null), '', "empty should be empty string");
fixes #<I> - Case.of and toSentenceCase should support passing proper names
nbubna_Case
train
8726ade31036904b5c6f8778b816ec622882b73b
diff --git a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php +++ b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php @@ -14,6 +14,7 @@ namespace Symfony\Bundle\TwigBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Finder\Finder; /** * Command that will validate your template syntax and output encountered errors. @@ -36,6 +37,16 @@ the first encountered syntax error. The command will get the contents of "filename" and will validates its syntax. +<info>php %command.full_name% dirname</info> + +The command will find all twig templates in dirname and will validate the syntax +of each Twig template. + +<info>php %command.full_name% @AcmeMyBundle</info> + +The command will find all twig templates in bundle AcmeMyBundle and will validate +the syntax of each one. + <info>cat filename | php %command.full_name%</info> The command will get the template contents from stdin and will validates its syntax. @@ -54,34 +65,43 @@ EOF $template = null; $filename = $input->getArgument('filename'); - if ($filename && !is_readable($filename)) { - $output->writeln(sprintf('<error>File %s is not readable</error>', $filename)); - - return 2; - } - - if ($filename) { - $template = file_get_contents($filename); - } else { + if (!$filename) { if (0 !== ftell(STDIN)) { - $output->writeln(sprintf('<error>Please provide a filename or pipe template content to stdin.</error>')); - - return 2; + throw new \RuntimeException("Please provide a filename or pipe template content to stdin."); } + while (!feof(STDIN)) { $template .= fread(STDIN, 1024); } + + return $twig->parse($twig->tokenize($template)); + } + + if (0 !== strpos($filename, '@') && !is_readable($filename)) { + throw new \RuntimeException("File or directory '%s' is not readable"); } - try { - $twig->parse($twig->tokenize($template)); - } catch(\Twig_Error_Syntax $e) { - $output->writeln($e->getMessage()); + $files = array(); + if (is_file($filename)) { + $files = array($filename); + } elseif (is_dir($filename)) { + $files = Finder::create()->files()->in($filename)->name('*.twig'); + } else { + $dir = $this->getApplication()->getKernel()->locateResource($filename); + $files = Finder::create()->files()->in($dir)->name('*.twig'); + } - return 1; + foreach ($files as $file) { + try { + $twig->parse($twig->tokenize(file_get_contents($file))); + } catch (\Exception $e) { + $output->writeln(sprintf('<error>Syntax error in %s</error>', $file)); + + throw $e; + } } - $output->writeln("<info>Template's syntax is valid.</info>"); + $output->writeln('<info>No syntax error detected.</info>'); } }
Adds more features to twig:lint command
symfony_symfony
train
3cb40ecfb885386982fa3452eb8001051908c81a
diff --git a/TYPO3.TYPO3CR/Classes/FLOW3/Persistence/F3_TYPO3CR_FLOW3_Persistence_Query.php b/TYPO3.TYPO3CR/Classes/FLOW3/Persistence/F3_TYPO3CR_FLOW3_Persistence_Query.php index <HASH>..<HASH> 100644 --- a/TYPO3.TYPO3CR/Classes/FLOW3/Persistence/F3_TYPO3CR_FLOW3_Persistence_Query.php +++ b/TYPO3.TYPO3CR/Classes/FLOW3/Persistence/F3_TYPO3CR_FLOW3_Persistence_Query.php @@ -28,6 +28,7 @@ namespace F3::TYPO3CR::FLOW3::Persistence; * @subpackage FLOW3 * @version $Id$ * @license http://opensource.org/licenses/gpl-license.php GNU Public License, version 2 + * @scope prototype */ class Query implements F3::FLOW3::Persistence::QueryInterface { @@ -124,7 +125,7 @@ class Query implements F3::FLOW3::Persistence::QueryInterface { * @author Karsten Dambekalns <karsten@typo3.org> */ public function execute() { - $query = $this->QOMFactory->createQuery($this->QOMFactory->selector('flow3:' . $this->className), $this->constraint, array(), array()); + $query = $this->QOMFactory->createQuery($this->QOMFactory->selector('flow3:' . str_replace('::', '_', $this->className)), $this->constraint, array(), array()); foreach ($this->operands as $name => $value) { $valueObject = $this->valueFactory->createValue($value); $query->bindValue($name, $valueObject);
TYPO3, TYPO3CR: * two fixes for bugs following the component factory refactoring Original-Commit-Hash: 1bea<I>f<I>aabd3c<I>d<I>c<I>d<I>c<I>
neos_neos-development-collection
train
4715f414f56d6f571cff107e932da6d4a5e8560d
diff --git a/capsule/src/main/java/Capsule.java b/capsule/src/main/java/Capsule.java index <HASH>..<HASH> 100644 --- a/capsule/src/main/java/Capsule.java +++ b/capsule/src/main/java/Capsule.java @@ -83,8 +83,6 @@ import static java.util.Arrays.asList; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXConnectorServer; -import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; /** @@ -4748,13 +4746,25 @@ public class Capsule implements Runnable { //<editor-fold defaultstate="collapsed" desc="JMX"> /////////// JMX /////////////////////////////////// private JMXServiceURL startJMXServer() { + final String LOCAL_CONNECTOR_ADDRESS_PROP = "com.sun.management.jmxremote.localConnectorAddress"; + try { log(LOG_VERBOSE, "Starting JMXConnectorServer"); - final JMXConnectorServer jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL("rmi", null, 0), null, ManagementFactory.getPlatformMBeanServer()); - jmxServer.start(); - log(LOG_VERBOSE, "JMXConnectorServer started JMX at " + jmxServer.getAddress()); - return jmxServer.getAddress(); - } catch (IOException e) { + + final Properties agentProps = sun.misc.VMSupport.getAgentProperties(); + if (agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP) == null) { + log(LOG_VERBOSE, "Starting management agent"); + sun.management.Agent.agentmain(null); // starts a JMXConnectorServer that does not prevent the app from shutting down + } + final JMXServiceURL url = new JMXServiceURL((String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP)); + +// final JMXConnectorServer jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL("rmi", null, 0), null, ManagementFactory.getPlatformMBeanServer()); +// jmxServer.start(); // prevents the app from shutting down (requires jmxServer.stop()) +// final JMXServiceURL url = jmxServer.getAddress(); + + log(LOG_VERBOSE, "JMXConnectorServer started JMX at " + url); + return url; + } catch (Exception e) { log(LOG_VERBOSE, "JMXConnectorServer failed: " + e.getMessage()); if (isLogging(LOG_VERBOSE)) e.printStackTrace(STDERR);
use management agent for JMX (disabled) This does not prevent the app from shutting down (unlike manually starting our own JMXConnectorServer).
puniverse_capsule
train
a493cf8542c55007edfec2926ef46175c529daa0
diff --git a/src/back/index.js b/src/back/index.js index <HASH>..<HASH> 100644 --- a/src/back/index.js +++ b/src/back/index.js @@ -1,6 +1,6 @@ var models = require('./models'); var adapters = require('./adapters'); -var settings = require('./settings') +var settings = require('./settings'); /** * Contains all back{4}app's entity implementations. * @module back4app/entity diff --git a/src/back/models/Entity.js b/src/back/models/Entity.js index <HASH>..<HASH> 100644 --- a/src/back/models/Entity.js +++ b/src/back/models/Entity.js @@ -807,10 +807,10 @@ Entity.new = _getNewFunction(Entity); * _getAdapter(Entity).registerEntity(Entity);; */ var _getAdapter = function (CurrentEntity) { - if(CurrentEntity.adapter && settings.ADAPTERS[CurrentEntity.adapter]){ + if (CurrentEntity.adapter && settings.ADAPTERS[CurrentEntity.adapter]) { return settings.ADAPTERS[CurrentEntity.adapter]; } else { - if(settings.ADAPTERS.default) { + if (settings.ADAPTERS.default) { return settings.ADAPTERS.default; } else { throw 'No valid Adapter on settings.ADAPTERS'; diff --git a/src/back/settings.js b/src/back/settings.js index <HASH>..<HASH> 100644 --- a/src/back/settings.js +++ b/src/back/settings.js @@ -5,7 +5,8 @@ module.exports = {}; /** - * Constant with the path to the adapters dictionary. It will be used to find the adapters + * Constant with the path to the adapters dictionary. It will be + * used to find the adapters * always that on of them is referenced in the code. * @type {!string} * @example diff --git a/tests/unit/back/adapters/index.test.js b/tests/unit/back/adapters/index.test.js index <HASH>..<HASH> 100644 --- a/tests/unit/back/adapters/index.test.js +++ b/tests/unit/back/adapters/index.test.js @@ -38,7 +38,8 @@ describe('index', function () { }).then(function () { entity.settings.ADAPTERS.default.getMongooseModel('Person') .then(function (model) { - expect(entity.settings.ADAPTERS.default.entitySchema).to.equal(model); + expect(entity.settings.ADAPTERS.default.entitySchema) + .to.equal(model); }); done(); });
Fixes lint issues.
back4app_back4app-entity
train
ab29ac0e5115b7a6f098e476f8851931f4e51779
diff --git a/src/Psalm/Internal/Analyzer/Statements/EchoAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/EchoAnalyzer.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Internal/Analyzer/Statements/EchoAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/EchoAnalyzer.php @@ -37,7 +37,7 @@ class EchoAnalyzer $expr_type = $statements_analyzer->node_data->getType($expr); - if ($expr_type) { + if ($codebase->taint && $expr_type) { $expr_type = CastAnalyzer::castStringAttempt( $statements_analyzer, $context, diff --git a/tests/ToStringTest.php b/tests/ToStringTest.php index <HASH>..<HASH> 100644 --- a/tests/ToStringTest.php +++ b/tests/ToStringTest.php @@ -161,7 +161,7 @@ class ToStringTest extends TestCase '<?php class A {} echo (new A);', - 'error_message' => 'InvalidCast', + 'error_message' => 'InvalidArgument', ], 'echoCastClass' => [ '<?php
Only cast in echo when tracking taints
vimeo_psalm
train
07997731e078db10068af6db67d4cfb95004e63f
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index <HASH>..<HASH> 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -186,12 +186,6 @@ SQL_STRINGS = { "mysql": "SELECT * FROM iris WHERE `Name` LIKE '%'", "postgresql": "SELECT * FROM iris WHERE \"Name\" LIKE '%'", }, - "create_view": { - "sqlite": """ - CREATE VIEW iris_view AS - SELECT * FROM iris - """ - }, } @@ -256,6 +250,23 @@ def create_and_load_iris(conn, iris_file: Path, dialect: str): conn.execute(stmt) +def create_and_load_iris_view(conn): + stmt = "CREATE VIEW iris_view AS SELECT * FROM iris" + if isinstance(conn, sqlite3.Connection): + cur = conn.cursor() + cur.execute(stmt) + else: + from sqlalchemy import text + from sqlalchemy.engine import Engine + + stmt = text(stmt) + if isinstance(conn, Engine): + with conn.connect() as conn: + conn.execute(stmt) + else: + conn.execute(stmt) + + @pytest.fixture def iris_path(datapath): iris_path = datapath("io", "data", "csv", "iris.csv") @@ -391,10 +402,6 @@ class PandasSQLTest: else: create_and_load_iris(self.conn, iris_path, self.flavor) - def _load_iris_view(self): - self.drop_table("iris_view") - self._get_exec().execute(SQL_STRINGS["create_view"][self.flavor]) - def _check_iris_loaded_frame(self, iris_frame): pytype = iris_frame.dtypes[0].type row = iris_frame.iloc[0] @@ -697,7 +704,7 @@ class _TestSQLApi(PandasSQLTest): self.load_test_data_and_sql() def load_test_data_and_sql(self): - self._load_iris_view() + create_and_load_iris_view(self.conn) self._load_raw_sql() def test_read_sql_iris(self):
TST: refactor iris_view table in SQL test (#<I>)
pandas-dev_pandas
train
b946cbd56ff7c35019fd36086d6be46677510fc8
diff --git a/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/PredicateLevelProposalImpl.java b/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/PredicateLevelProposalImpl.java index <HASH>..<HASH> 100644 --- a/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/PredicateLevelProposalImpl.java +++ b/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/PredicateLevelProposalImpl.java @@ -32,6 +32,10 @@ public class PredicateLevelProposalImpl implements PredicateLevelProposal { */ public PredicateLevelProposalImpl(List<CQIE> parentRules, HashMap<Predicate, PredicateLevelProposal> childProposalIndex) throws TypeLiftTools.MultiTypeException { + if (parentRules.isEmpty()) { + throw new IllegalArgumentException("Parent rules are required for making a proposal."); + } + /** * Computes the RuleLevelProposals and the global substitution. */ diff --git a/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/TypeLift.java b/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/TypeLift.java index <HASH>..<HASH> 100644 --- a/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/TypeLift.java +++ b/reformulation-core/src/main/java/org/semanticweb/ontop/owlrefplatform/core/unfolding/TypeLift.java @@ -254,6 +254,18 @@ public class TypeLift { */ final HashMap<Predicate, PredicateLevelProposal> childProposalIndex = retrieveChildrenProposals(parentZipper); + + final TypeLiftNode parentLabel = parentZipper.getLabel(); + final List<CQIE> parentRules = parentLabel.getDefinitionRules(); + + /** + * If the current (parent) node has no definition rule, no proposal can be made. + * ---> returns the same zipper. + */ + if (parentRules.isEmpty()) { + return parentZipper; + } + /** * Aggregates all these proposals according to the rules defining the parent predicate * into a PredicateLevelProposal. @@ -261,8 +273,7 @@ public class TypeLift { * If such aggregation is not possible, a MultiTypeException will be thrown. * */ - final TypeLiftNode parentLabel = parentZipper.getLabel(); - final PredicateLevelProposal proposal = makeProposal(parentLabel.getDefinitionRules(), childProposalIndex); + final PredicateLevelProposal proposal = makeProposal(parentRules, childProposalIndex); /** * Updated rules: type is applied to these rules (heads and bodies). @@ -341,10 +352,14 @@ public class TypeLift { /** * Creates a PredicateLevelProposal from the parent rules and the child proposals. + * */ private static PredicateLevelProposal makeProposal(List<CQIE> parentRules, HashMap<Predicate, PredicateLevelProposal> childProposalIndex) throws TypeLiftTools.MultiTypeException { + if (parentRules.isEmpty()) { + throw new IllegalArgumentException("Parent rules are required for making a proposal."); + } return new PredicateLevelProposalImpl(parentRules, childProposalIndex); }
Fixes the case where some predicates have no definition (semantic index mode).
ontop_ontop
train
90f25f339e74bd75b4467a7bfc4bb05759cb55ef
diff --git a/lib/cinch/plugin.rb b/lib/cinch/plugin.rb index <HASH>..<HASH> 100644 --- a/lib/cinch/plugin.rb +++ b/lib/cinch/plugin.rb @@ -1,15 +1,19 @@ module Cinch class Plugin class << self - # Set the match pattern. + Pattern = Struct.new(:pattern, :use_prefix, :method) + # Set a match pattern. # # @param [Regexp, String] pattern A pattern - # @param [Boolean] prefix If true, the plugin prefix will - # automatically be prepended to the pattern. + # @option options [Symbol] :method (:execute) The method to execute + # @option options [Boolean] :use_prefix (true) If true, the + # plugin prefix will automatically be prepended to the + # pattern. # @return [void] - def match(pattern, prefix = true) - @__newton_pattern = pattern - @__newton_use_prefix = prefix + def match(pattern, options = {}) + options = {:use_prefix => true, :method => :execute}.merge(options) + @__newton_patterns ||= [] + @__newton_patterns << Pattern.new(pattern, options[:use_prefix], options[:method]) end # Events to listen to. @@ -78,30 +82,36 @@ module Cinch end end - pattern = @__newton_pattern || plugin_name - prefix = @__newton_prefix || bot.config.plugins.prefix - if (@__newton_use_prefix || @__newton_use_prefix.nil?) && prefix - case pattern - when Regexp - pattern = /^#{prefix}#{pattern}/ - when String - pattern = prefix + pattern - end + if @__newton_patterns.empty? + @__newton_patterns << Pattern.new(plugin_name, true, nil) end - react_on = @__newton_react_on || :message + @__newton_patterns.each do |pattern| + prefix = @__newton_prefix || bot.config.plugins.prefix + if pattern.use_prefix && prefix + case pattern.pattern + when Regexp + pattern.pattern = /^#{prefix}#{pattern.pattern}/ + when String + pattern.pattern = prefix + pattern.pattern + end + end + + react_on = @__newton_react_on || :message - bot.debug "[plugin] #{plugin_name}: Registering executor with pattern `#{pattern}`, reacting on `#{react_on}`" + bot.debug "[plugin] #{plugin_name}: Registering executor with pattern `#{pattern.pattern}`, reacting on `#{react_on}`" - bot.on(react_on, pattern, instance) do |message, plugin, *args| - if plugin.respond_to?(:execute) - arity = plugin.method(:execute).arity - 1 - if arity > 0 - args = args[0..arity - 1] - elsif arity == 0 - args = [] + bot.on(react_on, pattern.pattern, instance, pattern) do |message, plugin, pattern, *args| + if plugin.respond_to?(pattern.method) + method = plugin.method(pattern.method) + arity = method.arity - 1 + if arity > 0 + args = args[0..arity - 1] + elsif arity == 0 + args = [] + end + method.call(message, *args) end - plugin.execute(message, *args) end end
allow for more than one match pattern per plugin
cinchrb_cinch
train
3c1b05683dc420dab111b0a1c1ce015238f41211
diff --git a/src/scs_core/particulate/exegesis/exegete.py b/src/scs_core/particulate/exegesis/exegete.py index <HASH>..<HASH> 100644 --- a/src/scs_core/particulate/exegesis/exegete.py +++ b/src/scs_core/particulate/exegesis/exegete.py @@ -3,7 +3,7 @@ Created on 26 Oct 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) -a catalogue of particulates exegesis models +a catalogue of particulate exegesis models """ from scs_core.particulate.exegesis.isece001 import ISECEv1 @@ -16,6 +16,13 @@ class Exegete(object): classdocs """ + __ROOT = 'exg' + + @classmethod + def root(cls): + return cls.__ROOT + + # ---------------------------------------------------------------------------------------------------------------- @staticmethod diff --git a/src/scs_core/particulate/exegesis/isece001.py b/src/scs_core/particulate/exegesis/isece001.py index <HASH>..<HASH> 100644 --- a/src/scs_core/particulate/exegesis/isece001.py +++ b/src/scs_core/particulate/exegesis/isece001.py @@ -3,13 +3,14 @@ Created on 26 Oct 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) -THIS CODE SHALL BE TREATED AS IMMUTABLE. THUS, ANY ALTERATIONS TO EQUATIONS OR DEFAULT COEFFICIENTS SHALL BE -PRESENTED AS A NEW CLASS, WITH AN INCREMENTED VERSION NUMBER. +THIS CODE SHALL BE TREATED AS IMMUTABLE. THUS, ANY ALTERATIONS TO EQUATIONS OR STANDARD COEFFICIENTS SHALL BE +PRESENTED AS A NEW CLASS, WITH AN INCREMENTED CLASS VERSION NUMBER. method: Immediate Scaling Error / Exponential Curve (ISECE), version 1 domain: 0 <= rH <= max_rh -curve: error = ce * e ^ (cx * x) +model: error = ce * e ^ (cx * x) +range: x / error """ from collections import OrderedDict @@ -42,7 +43,7 @@ class ISECEv1(PersistentJSONable): # ---------------------------------------------------------------------------------------------------------------- - __FILENAME = "exegete_particulates_isece1_calib.json" + __FILENAME = "particulate_exegete_isece1_calib.json" @classmethod def persistence_location(cls, host):
Added particle exegesis framework.
south-coast-science_scs_core
train
2ae54583f040587e1e72853ec39dcf6f0ebf9a18
diff --git a/test/Resque/Tests/bootstrap.php b/test/Resque/Tests/bootstrap.php index <HASH>..<HASH> 100644 --- a/test/Resque/Tests/bootstrap.php +++ b/test/Resque/Tests/bootstrap.php @@ -30,6 +30,7 @@ if($returnVar != 0) { } exec('cd ' . TEST_MISC . '; redis-server ' . REDIS_CONF, $output, $returnVar); +usleep(500000); if($returnVar != 0) { echo "Cannot start redis-server.\n"; exit(1); @@ -46,8 +47,11 @@ if(!preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches)) { Resque::setBackend('localhost:' . $matches[1]); // Shutdown -function killRedis() +function killRedis($pid) { + if (getmypid() !== $pid) { + return; // don't kill from a forked worker + } $config = file_get_contents(REDIS_CONF); if(!preg_match('#^\s*pidfile\s+([^\s]+)#m', $config, $matches)) { return; @@ -76,7 +80,7 @@ function killRedis() unlink($filename); } } -register_shutdown_function('killRedis'); +register_shutdown_function('killRedis', getmypid()); if(function_exists('pcntl_signal')) { // Override INT and TERM signals, so they do a clean shutdown and also
Fixes unit test reliability - redis-server is killed only from parent process, not from a worker - sleeps for half a second after starting server
wa0x6e_php-resque-ex
train
33c432c90552d3517d0e2c2fc61f259e88dc30c0
diff --git a/vendor/plugins/pages/app/models/page.rb b/vendor/plugins/pages/app/models/page.rb index <HASH>..<HASH> 100644 --- a/vendor/plugins/pages/app/models/page.rb +++ b/vendor/plugins/pages/app/models/page.rb @@ -4,7 +4,7 @@ class Page < ActiveRecord::Base acts_as_tree :order => "position" - has_friendly_id :title + has_friendly_id :title, :use_slug => true, :strip_diacritics => true belongs_to :image diff --git a/vendor/plugins/pages/app/models/page_part.rb b/vendor/plugins/pages/app/models/page_part.rb index <HASH>..<HASH> 100644 --- a/vendor/plugins/pages/app/models/page_part.rb +++ b/vendor/plugins/pages/app/models/page_part.rb @@ -4,6 +4,6 @@ class PagePart < ActiveRecord::Base validates_presence_of :title - has_friendly_id :title + has_friendly_id :title, :use_slug => true, :strip_diacritics => true end \ No newline at end of file
Friendly ids should strip diacritics and use slugs for pages and page parts. This commit resolves that issue.
refinery_refinerycms
train
1d1c5e1ba8f415bba3f5745af7cbb9c21aaf662f
diff --git a/lib/shoulda.rb b/lib/shoulda.rb index <HASH>..<HASH> 100644 --- a/lib/shoulda.rb +++ b/lib/shoulda.rb @@ -13,7 +13,6 @@ module Test # :nodoc: all end end -require 'shoulda/private_helpers' require 'shoulda/general' require 'shoulda/active_record' require 'shoulda/controller' diff --git a/lib/shoulda/active_record/macros.rb b/lib/shoulda/active_record/macros.rb index <HASH>..<HASH> 100644 --- a/lib/shoulda/active_record/macros.rb +++ b/lib/shoulda/active_record/macros.rb @@ -679,9 +679,6 @@ module ThoughtBot # :nodoc: end end - private - - include ThoughtBot::Shoulda::Private end end end diff --git a/lib/shoulda/macros.rb b/lib/shoulda/macros.rb index <HASH>..<HASH> 100644 --- a/lib/shoulda/macros.rb +++ b/lib/shoulda/macros.rb @@ -1,3 +1,5 @@ +require 'shoulda/private_helpers' + module ThoughtBot # :nodoc: module Shoulda # :nodoc: module Macros @@ -69,6 +71,10 @@ module ThoughtBot # :nodoc: assert_equal @_before_should_not_change, new_value, "#{expression.inspect} changed" end end + + private + + include ThoughtBot::Shoulda::Private end end end
Moved include of Private helpers from AR::Macros to general Macros
thoughtbot_shoulda-matchers
train
d5ea153b93f24f57006ce0ee8f99c06e7ccaf8ac
diff --git a/lib/csv_record/callbacks.rb b/lib/csv_record/callbacks.rb index <HASH>..<HASH> 100644 --- a/lib/csv_record/callbacks.rb +++ b/lib/csv_record/callbacks.rb @@ -50,6 +50,13 @@ module CsvRecord is_valid end + def save(*args) + self.run_before_save_callbacks + is_saved = super + self.run_after_save_callbacks if is_saved + is_saved + end + def append_registry self.run_before_create_callbacks is_saved = super diff --git a/test/csv_record/callbacks_test.rb b/test/csv_record/callbacks_test.rb index <HASH>..<HASH> 100644 --- a/test/csv_record/callbacks_test.rb +++ b/test/csv_record/callbacks_test.rb @@ -62,5 +62,13 @@ describe CsvRecord::Callbacks do it 'after_update' do object_updated.after_update_called.must_equal true end + + it 'before_save' do + object_created.before_save_called.must_equal true + end + + it 'after_update' do + object_created.after_save_called.must_equal true + end end end \ No newline at end of file diff --git a/test/models/callback_test_class.rb b/test/models/callback_test_class.rb index <HASH>..<HASH> 100644 --- a/test/models/callback_test_class.rb +++ b/test/models/callback_test_class.rb @@ -7,6 +7,7 @@ class CallbackTestClass attr_accessor :before_create_called, :after_create_called attr_accessor :before_validation_called, :after_validation_called attr_accessor :before_update_called, :after_update_called + attr_accessor :before_save_called, :after_save_called after_initialize do self.after_initialize_called = true @@ -35,4 +36,12 @@ class CallbackTestClass after_update do self.after_update_called = true end + + before_save do + self.before_save_called = true + end + + after_save do + self.after_save_called = true + end end \ No newline at end of file
Adding the before & after save callbacks
lukelex_csv_record
train
a1cb4c0020893e0876f4d3f202c6b65017070bfb
diff --git a/webwhatsapi/js/wapi.js b/webwhatsapi/js/wapi.js index <HASH>..<HASH> 100755 --- a/webwhatsapi/js/wapi.js +++ b/webwhatsapi/js/wapi.js @@ -369,12 +369,14 @@ window.WAPI.sendMessageToID = function (id, message, done) { if(Store.Chat.models.length == 0) return false; - Store.Chat.models[0].id = id + var originalID = Store.Chat.models[0].id; + Store.Chat.models[0].id = id; if (done !== undefined) { - Store.Chat.models[0].sendMessage(message).then(function(){ done(true); }); + Store.Chat.models[0].sendMessage(message).then(function(){ Store.Chat.models[0].id = originalID; done(true); }); return true; } else { Store.Chat.models[0].sendMessage(message); + Store.Chat.models[0].id = originalID; return true; }
Revert recipient ID to original after sending message
mukulhase_WebWhatsapp-Wrapper
train
a44a27456cdc7810545489809089536f382f2f18
diff --git a/lib/active_scaffold/extensions/action_controller_rendering.rb b/lib/active_scaffold/extensions/action_controller_rendering.rb index <HASH>..<HASH> 100644 --- a/lib/active_scaffold/extensions/action_controller_rendering.rb +++ b/lib/active_scaffold/extensions/action_controller_rendering.rb @@ -2,7 +2,7 @@ module ActionController #:nodoc: class Base def render_with_active_scaffold(*args, &block) - if self.class.uses_active_scaffold? and params[:adapter] and @rendering_adapter.nil? + if self.class.uses_active_scaffold? and params[:adapter] and @rendering_adapter.nil? and request.xhr? @rendering_adapter = true # recursion control # if we need an adapter, then we render the actual stuff to a string and insert it into the adapter template opts = args.blank? ? Hash.new : args.first
fix loading inline action links in a new window
activescaffold_active_scaffold
train
d0fd8d6fc29ec859650adf30718e2b06786e854f
diff --git a/common/hexutil/hexutil.go b/common/hexutil/hexutil.go index <HASH>..<HASH> 100644 --- a/common/hexutil/hexutil.go +++ b/common/hexutil/hexutil.go @@ -39,6 +39,7 @@ import ( const uintBits = 32 << (uint64(^uint(0)) >> 63) +// Errors var ( ErrEmptyString = &decError{"empty hex string"} ErrSyntax = &decError{"invalid hex string"} diff --git a/common/math/big.go b/common/math/big.go index <HASH>..<HASH> 100644 --- a/common/math/big.go +++ b/common/math/big.go @@ -22,12 +22,13 @@ import ( "math/big" ) +// Various big integer limit values. var ( tt255 = BigPow(2, 255) tt256 = BigPow(2, 256) tt256m1 = new(big.Int).Sub(tt256, big.NewInt(1)) - MaxBig256 = new(big.Int).Set(tt256m1) tt63 = BigPow(2, 63) + MaxBig256 = new(big.Int).Set(tt256m1) MaxBig63 = new(big.Int).Sub(tt63, big.NewInt(1)) ) diff --git a/common/math/integer.go b/common/math/integer.go index <HASH>..<HASH> 100644 --- a/common/math/integer.go +++ b/common/math/integer.go @@ -21,8 +21,8 @@ import ( "strconv" ) +// Integer limit values. const ( - // Integer limit values. MaxInt8 = 1<<7 - 1 MinInt8 = -1 << 7 MaxInt16 = 1<<15 - 1 diff --git a/common/mclock/mclock.go b/common/mclock/mclock.go index <HASH>..<HASH> 100644 --- a/common/mclock/mclock.go +++ b/common/mclock/mclock.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. -// package mclock is a wrapper for a monotonic clock source +// Package mclock is a wrapper for a monotonic clock source package mclock import ( @@ -23,8 +23,10 @@ import ( "github.com/aristanetworks/goarista/monotime" ) -type AbsTime time.Duration // absolute monotonic time +// AbsTime represents absolute monotonic time. +type AbsTime time.Duration +// Now returns the current absolute monotonic time. func Now() AbsTime { return AbsTime(monotime.Now()) } diff --git a/common/number/int.go b/common/number/int.go index <HASH>..<HASH> 100644 --- a/common/number/int.go +++ b/common/number/int.go @@ -22,9 +22,11 @@ import ( "github.com/ethereum/go-ethereum/common" ) -var tt256 = new(big.Int).Lsh(big.NewInt(1), 256) -var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) -var tt255 = new(big.Int).Lsh(big.NewInt(1), 255) +var ( + tt256 = new(big.Int).Lsh(big.NewInt(1), 256) + tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) + tt255 = new(big.Int).Lsh(big.NewInt(1), 255) +) func limitUnsigned256(x *Number) *Number { x.num.And(x.num, tt256m1) @@ -181,7 +183,6 @@ func (i *Number) FirstBitSet() int { } // Variables - var ( Zero = Uint(0) One = Uint(1) diff --git a/common/types.go b/common/types.go index <HASH>..<HASH> 100644 --- a/common/types.go +++ b/common/types.go @@ -29,6 +29,7 @@ import ( "github.com/ethereum/go-ethereum/crypto/sha3" ) +// Lengths of hashes and addresses in bytes. const ( HashLength = 32 AddressLength = 20
common: all golint warnings removed (#<I>) * common: all golint warnings removed * common: fixups
ethereum_go-ethereum
train
d5ff235875d52a9abcfec1a14929b854af40f1b4
diff --git a/core/src/main/java/org/infinispan/eviction/impl/ActivationManagerImpl.java b/core/src/main/java/org/infinispan/eviction/impl/ActivationManagerImpl.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/infinispan/eviction/impl/ActivationManagerImpl.java +++ b/core/src/main/java/org/infinispan/eviction/impl/ActivationManagerImpl.java @@ -3,7 +3,6 @@ package org.infinispan.eviction.impl; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.BOTH; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.PRIVATE; -import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.SHARED; import java.util.concurrent.atomic.AtomicLong; @@ -88,7 +87,7 @@ public class ActivationManagerImpl implements ActivationManager { } else { //the entry already exists in data container. It may be put during the load by the CacheLoaderInterceptor //so it was already activate in the private stores. - if (primaryOwner && persistenceManager.deleteFromAllStores(key, SHARED) && statisticsEnabled) { + if (primaryOwner && persistenceManager.deleteFromAllStores(key, BOTH) && statisticsEnabled) { activations.incrementAndGet(); } } diff --git a/core/src/test/java/org/infinispan/eviction/impl/EvictionWithPassivationTest.java b/core/src/test/java/org/infinispan/eviction/impl/EvictionWithPassivationTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/org/infinispan/eviction/impl/EvictionWithPassivationTest.java +++ b/core/src/test/java/org/infinispan/eviction/impl/EvictionWithPassivationTest.java @@ -35,6 +35,7 @@ public class EvictionWithPassivationTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "testCache"; private final int EVICTION_MAX_ENTRIES = 2; private StorageType storage; + private EvictionListener evictionListener; public EvictionWithPassivationTest() { // Cleanup needs to be after method, else LIRS can cause failures due to it not caching values due to hot @@ -72,6 +73,9 @@ public class EvictionWithPassivationTest extends SingleCacheManagerTest { protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(getDefaultStandaloneCacheConfig(true)); cacheManager.defineConfiguration(CACHE_NAME, buildCfg().build()); + evictionListener = new EvictionListener(); + Cache<String, String> testCache = cacheManager.getCache(CACHE_NAME); + testCache.addListener(evictionListener); return cacheManager; } @@ -227,7 +231,7 @@ public class EvictionWithPassivationTest extends SingleCacheManagerTest { testCache.put("key" + i, "value" + i); } - String evictedKey = "key0"; + String evictedKey = evictionListener.getEvictedKey(); assertTrue(isEntryInStore(evictedKey)); testCache.remove(evictedKey); assertFalse(testCache.containsKey(evictedKey)); @@ -240,7 +244,7 @@ public class EvictionWithPassivationTest extends SingleCacheManagerTest { testCache.put("key" + i, "value" + i); } - String evictedKey = "key0"; + String evictedKey = evictionListener.getEvictedKey(); assertTrue(isEntryInStore(evictedKey)); testCache.compute(evictedKey, (k ,v) -> v + "-modfied"); assertFalse(isEntryInStore(evictedKey)); @@ -252,7 +256,7 @@ public class EvictionWithPassivationTest extends SingleCacheManagerTest { testCache.put("key" + i, "value" + i); } - String evictedKey = "key0"; + String evictedKey = evictionListener.getEvictedKey(); assertTrue(isEntryInStore(evictedKey)); testCache.compute(evictedKey, (k ,v) -> null); assertFalse(testCache.containsKey(evictedKey));
ISPN-<I> Remove entries from all stored on entry removal
infinispan_infinispan
train
9fdd1cbf4343e4b791b4d97c79c2616ee7832cde
diff --git a/aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModuleAgent.java b/aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModuleAgent.java index <HASH>..<HASH> 100644 --- a/aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModuleAgent.java +++ b/aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModuleAgent.java @@ -1734,6 +1734,7 @@ final class ConsensusModuleAgent implements Agent { if (ex.errorCode() == ArchiveException.STORAGE_SPACE) { + ctx.countedErrorHandler().onError(ex); unexpectedTermination(); }
[Java] Log archive error due to storage space before termination when starting to record cluster log.
real-logic_aeron
train
0d95987055c87bc2247b1c1d8dd6db4fef5e71d6
diff --git a/lib/routeparam.js b/lib/routeparam.js index <HASH>..<HASH> 100644 --- a/lib/routeparam.js +++ b/lib/routeparam.js @@ -27,6 +27,9 @@ exports.options = { } } exports.newDocletHandler = function (e) { + if (e.doclet.kind !== "member") + return; + const parameters = e.doclet.params if (parameters) { const table = tableBuilder.build('Route Parameters', parameters)
now routeparam handler should react only on routes
vmarchaud_jsdoc-http-plugin
train
240b0d7d45005a3faaf701e9095172888dc48ce4
diff --git a/rules/predicates.py b/rules/predicates.py index <HASH>..<HASH> 100644 --- a/rules/predicates.py +++ b/rules/predicates.py @@ -298,8 +298,8 @@ def is_group_member(*groups): def fn(user): if not hasattr(user, 'groups'): return False # swapped user model, doesn't support groups - if not hasattr(user, '_group_names_cache'): # pragma: no cover - user._group_names_cache = set(user.groups.values_list('name', flat=True)) - return set(groups).issubset(user._group_names_cache) + group_names = set(user.groups.values_list('name', flat=True)) + user._group_names_cache = group_names # just in case people were using this + return set(groups).issubset(group_names) return fn
Fixed undesired caching in `is_group_member` factory Fixes #<I>
dfunckt_django-rules
train
79d359839506a8417cf719a2633e09f4991d768e
diff --git a/packages/ember-runtime/lib/ext/rsvp.js b/packages/ember-runtime/lib/ext/rsvp.js index <HASH>..<HASH> 100644 --- a/packages/ember-runtime/lib/ext/rsvp.js +++ b/packages/ember-runtime/lib/ext/rsvp.js @@ -69,7 +69,6 @@ RSVP.onerrorDefault = function (e) { Ember.onerror(error); } else { Logger.error(error.stack); - Ember.assert(error, false); } } };
[BUGFIX beta] Don’t assert uncaught RSVP rejections Fixes #<I>. We already loudly log a stack trace, and the assert ends up breaking everything else on the run loop queue and given that it doesn’t even preserve a meaningful stack trace related to the source of error, it doesn’t add a lot of value (and causes real problems a la #<I>).
emberjs_ember.js
train
e21cd5d6f9faa230a5b3998facc61f52f31e5b25
diff --git a/Command/LoadFixtureCommand.php b/Command/LoadFixtureCommand.php index <HASH>..<HASH> 100644 --- a/Command/LoadFixtureCommand.php +++ b/Command/LoadFixtureCommand.php @@ -91,7 +91,7 @@ EOT $input->getOption('session') ); - $dm = $this->getHelperSet()->get('phpcr'); + $dm = $this->getHelperSet()->get('phpcr')->getDocumentManager(); $noInitialize = $input->getOption('no-initialize'); if ($input->isInteractive() && !$input->getOption('append')) {
Fixed LoadFixtureCommand
doctrine_DoctrinePHPCRBundle
train
40fbb6e16d17dfac7ace78e49b9ce570ceecd2c4
diff --git a/lib/functions.php b/lib/functions.php index <HASH>..<HASH> 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -527,7 +527,7 @@ function wait(Promise $promise, Reactor $reactor = null) { */ function coroutine(callable $func, Reactor $reactor = null) { return function() use ($func, $reactor) { - $result = \call_user_func_array($func, func_get_args()); + $result = \call_user_func_array($func, \func_get_args()); return ($result instanceof \Generator) ? resolve($result, $reactor) : $result; @@ -550,7 +550,6 @@ function resolve(\Generator $generator, Reactor $reactor = null) { $cs->generator = $generator; $cs->returnValue = null; $cs->currentPromise = null; - $cs->isResolved = false; __coroutineAdvance($cs); @@ -572,28 +571,30 @@ function __coroutineAdvance($cs) { } } elseif (($key = $cs->generator->key()) === "return") { $cs->returnValue = $yielded; - $cs->reactor->immediately("Amp\__coroutineNextTick", ["cb_data" => $cs]); + __coroutineSend(null, null, $cs); } elseif ($yielded instanceof Promise) { $cs->currentPromise = $yielded; $cs->reactor->immediately("Amp\__coroutineNextTick", ["cb_data" => $cs]); } else { - $cs->isResolved = true; - $cs->promisor->fail(new \DomainException( - __coroutineYieldError($cs->generator, $key, $yielded) + $error = makeGeneratorError($cs->generator, sprintf( + 'Unexpected yield (Promise|null|"return" expected); %s yielded at key %s', + is_object($yielded) ? get_class($yielded) : gettype($yielded), + $key )); + $cs->reactor->immediately(function() use ($cs, $error) { + $cs->promisor->fail(new \DomainException($error)); + }); } } catch (\Exception $uncaught) { - if ($cs->isResolved) { - throw new \RuntimeException("", 0, $uncaught); - } else { - $cs->isResolved = true; + $cs->reactor->immediately(function() use ($cs, $uncaught) { $cs->promisor->fail($uncaught); - } + }); } } function __coroutineNextTick($reactor, $watcherId, $cs) { - if ($promise = $cs->currentPromise) { + if ($cs->currentPromise) { + $promise = $cs->currentPromise; $cs->currentPromise = null; $promise->when("Amp\__coroutineSend", $cs); } else { @@ -610,32 +611,32 @@ function __coroutineSend($error, $result, $cs) { } __coroutineAdvance($cs); } catch (\Exception $uncaught) { - if ($cs->isResolved) { - throw new \RuntimeException("", 0, $uncaught); - } else { - $cs->isResolved = true; + $cs->reactor->immediately(function() use ($cs, $uncaught) { $cs->promisor->fail($uncaught); - } + }); } } -function __coroutineYieldError($generator, $key, $yielded) { - $type = is_object($yielded) ? get_class($yielded) : gettype($yielded); - $msg = "Unexpected Generator yield (Promise|\"return\"|null expected); {$type} yielded at key {$key}"; - if (PHP_MAJOR_VERSION < 7) { - return $msg; +/** + * A general purpose function for creating error messages from generator yields + * + * @param \Generator $generator + * @param string $prefix + * @return string + */ +function makeGeneratorError(\Generator $generator, $prefix = "Generator error") { + if (PHP_MAJOR_VERSION < 7 || !$generator->valid()) { + return $prefix; } $reflGen = new \ReflectionGenerator($generator); $exeGen = $reflGen->getExecutingGenerator(); - if ($exeGen !== $generator) { - // We're executing a subgenerator; use the correct reflection + if ($isSubgenerator = ($exeGen !== $generator)) { $reflGen = new \ReflectionGenerator($exeGen); } return sprintf( - "%s on line %s in %s", - $msg, + "{$prefix} on line %s in %s", $reflGen->getExecutingLine(), $reflGen->getExecutingFile() );
Minor coroutine refactoring/optimization; add makeGeneratorError()
amphp_amp
train
11b40dcbeab660f599c49e0dd9e00937795d70bf
diff --git a/src/Select.js b/src/Select.js index <HASH>..<HASH> 100644 --- a/src/Select.js +++ b/src/Select.js @@ -801,6 +801,24 @@ const Select = React.createClass({ } }, + renderOuter (options, valueArray, focusedOption) { + let menu = this.renderMenu(options, valueArray, focusedOption); + if (!menu) { + return null; + } + + return ( + <div ref="menuContainer" className="Select-menu-outer" style={this.props.menuContainerStyle}> + <div ref="menu" className="Select-menu" + style={this.props.menuStyle} + onScroll={this.handleMenuScroll} + onMouseDown={this.handleMouseDownOnMenu}> + {menu} + </div> + </div> + ); + }, + render () { let valueArray = this.getValueArray(); let options = this._visibleOptions = this.filterOptions(this.props.multi ? valueArray : null); @@ -817,6 +835,7 @@ const Select = React.createClass({ 'is-searchable': this.props.searchable, 'has-value': valueArray.length, }); + return ( <div ref="wrapper" className={className} style={this.props.wrapperStyle}> {this.renderHiddenField(valueArray)} @@ -834,16 +853,7 @@ const Select = React.createClass({ {this.renderClear()} {this.renderArrow()} </div> - {isOpen ? ( - <div ref="menuContainer" className="Select-menu-outer" style={this.props.menuContainerStyle}> - <div ref="menu" className="Select-menu" - style={this.props.menuStyle} - onScroll={this.handleMenuScroll} - onMouseDown={this.handleMouseDownOnMenu}> - {this.renderMenu(options, !this.props.multi ? valueArray : null, focusedOption)} - </div> - </div> - ) : null} + {isOpen ? this.renderOuter(options, !this.props.multi ? valueArray : null, focusedOption) : null} </div> ); } diff --git a/test/Select-test.js b/test/Select-test.js index <HASH>..<HASH> 100644 --- a/test/Select-test.js +++ b/test/Select-test.js @@ -2224,6 +2224,17 @@ describe('Select', () => { 'to contain no elements matching', '.Select-noresults'); }); + it('doesn\'t displays outer when menu is null', () => { + + wrapper.setPropsForChild({ + noResultsText: '' + }); + + typeSearchText('DOES NOT EXIST'); + expect(ReactDOM.findDOMNode(instance), + 'to contain no elements matching', '.Select-menu-outer'); + }); + it('supports updating the text', () => { wrapper.setPropsForChild({
Does not render outer when it does not contain anything
HubSpot_react-select-plus
train
9a377ddcd3f127603d4170e3704431a890c726f1
diff --git a/tensorflow_probability/python/sts/local_level.py b/tensorflow_probability/python/sts/local_level.py index <HASH>..<HASH> 100644 --- a/tensorflow_probability/python/sts/local_level.py +++ b/tensorflow_probability/python/sts/local_level.py @@ -297,14 +297,13 @@ class LocalLevel(StructuralTimeSeries): dtype = dtype_util.common_dtype([level_scale_prior, initial_level_prior]) - if level_scale_prior is None or initial_level_prior is None: - if observed_time_series is not None: - _, observed_stddev, observed_initial = ( - sts_util.empirical_statistics(observed_time_series)) - else: - observed_stddev, observed_initial = (tf.convert_to_tensor( - value=1., dtype=dtype), tf.convert_to_tensor( - value=0., dtype=dtype)) + if observed_time_series is not None: + _, observed_stddev, observed_initial = ( + sts_util.empirical_statistics(observed_time_series)) + else: + observed_stddev, observed_initial = (tf.convert_to_tensor( + value=1., dtype=dtype), tf.convert_to_tensor( + value=0., dtype=dtype)) # Heuristic default priors. Overriding these may dramatically # change inference performance and results.
Fix bug in which necessary stats were not computed when both a level_scale_prior and initial_level_prior were specified for a LocalLevel model. PiperOrigin-RevId: <I>
tensorflow_probability
train
b1e0c157df9cc1d8f6a17e5416c316e64a75840f
diff --git a/lib/mongo/error/operation_failure.rb b/lib/mongo/error/operation_failure.rb index <HASH>..<HASH> 100644 --- a/lib/mongo/error/operation_failure.rb +++ b/lib/mongo/error/operation_failure.rb @@ -71,6 +71,8 @@ module Mongo def_delegators :@result, :operation_time + # @!method connection_description + # # @return [ Server::Description ] Server description of the server that # the operation that this exception refers to was performed on. #
RUBY-<I> fix connection_description docstring
mongodb_mongo-ruby-driver
train
d6f92d422406bbdcfc5ee6cb3472b16f6627a657
diff --git a/main.go b/main.go index <HASH>..<HASH> 100644 --- a/main.go +++ b/main.go @@ -84,6 +84,7 @@ func main() { applyOp := func(op interface{}) error { var result interface{} + session.Refresh() if err := session.Run(bson.M{"applyOps": []interface{}{op}}, &result); err != nil { return err }
call Refresh() before applying an op I don't really understand why this is necessary, but it resolved problems I was seeing with large #s of ops <URL>
Clever_ARCHIVED-oplog-replay
train
0cb49edd9bd9c90f54449abdf2efc7d2efdb97b3
diff --git a/charset.go b/charset.go index <HASH>..<HASH> 100644 --- a/charset.go +++ b/charset.go @@ -25,7 +25,12 @@ type Glyph struct { func (g *Glyph) GetTexturePositions(font FontLike) (tP1, tP2 Point) { // Quad width/height - vw := float32(g.Width) + + // Originally the ttf width value was being used. This, however, differs from the Advance value. + // This has been changed to advance so that the resulting quads that are generated for text to not + // overlap one another. + vw := float32(g.Advance) + vh := float32(g.Height) // Unfortunately with the current font, if I don't add a small offset to the Y axis location diff --git a/v4.1/text.go b/v4.1/text.go index <HASH>..<HASH> 100644 --- a/v4.1/text.go +++ b/v4.1/text.go @@ -448,7 +448,9 @@ func (t *Text) makeBufferData(indices []rune) { fmt.Printf("%s png index %3d: %s rune %+v line at %f", prefix, glyphIndex, string(r), glyphs[glyphIndex], lineX) } advance := float32(glyphs[glyphIndex].Advance) - vw := float32(glyphs[glyphIndex].Width) + + // Originally the glyph Width was used, but that results in quads that overlap one another. + vw := float32(glyphs[glyphIndex].Advance) vh := float32(glyphs[glyphIndex].Height) // used to determine which character inside of the text was clicked diff --git a/v4.5/text.go b/v4.5/text.go index <HASH>..<HASH> 100644 --- a/v4.5/text.go +++ b/v4.5/text.go @@ -448,7 +448,9 @@ func (t *Text) makeBufferData(indices []rune) { fmt.Printf("%s png index %3d: %s rune %+v line at %f", prefix, glyphIndex, string(r), glyphs[glyphIndex], lineX) } advance := float32(glyphs[glyphIndex].Advance) - vw := float32(glyphs[glyphIndex].Width) + + // Originally the glyph Width was used, but that results in quads that overlap one another. + vw := float32(glyphs[glyphIndex].Advance) vh := float32(glyphs[glyphIndex].Height) // used to determine which character inside of the text was clicked
During TTF glyph preparation, a width, height, and advance value are created. It seems to me that quad positioning of the rune should rely on advance width rather than width so I have done just that. It is possible that I am not understanding something about how TTF works. If so, this is easy enough to revert.
4ydx_gltext
train
b6a79a5a2e02bfd7fb2b74f9279367382b6d603a
diff --git a/lib/assertions.js b/lib/assertions.js index <HASH>..<HASH> 100644 --- a/lib/assertions.js +++ b/lib/assertions.js @@ -131,7 +131,8 @@ module.exports = function (expect) { }); } else if (properties && typeof properties === 'object') { // TODO the not flag does not make a lot of sense in this case - if (this.flags.not) { + var flags = this.flags; + if (flags.not) { Object.keys(properties).forEach(function (property) { expect(subject, 'not to have [own] property', property); }); @@ -151,10 +152,10 @@ module.exports = function (expect) { var expected = extend({}, properties); var actual = {}; for (var propertyName in subject) { - if ((!this.flags.own || subject.hasOwnProperty(propertyName)) && !(propertyName in properties)) { + if ((!flags.own || subject.hasOwnProperty(propertyName)) && !(propertyName in properties)) { expected[propertyName] = subject[propertyName]; } - if (!this.flags.own && !(propertyName in actual)) { + if (!flags.own && !(propertyName in actual)) { actual[propertyName] = subject[propertyName]; } }
Store flags for diff in to have properties assertion
unexpectedjs_unexpected
train
85a71c42346f1acc75e054c606c975bd8e0ca397
diff --git a/src/components/timeslider/timeslider.js b/src/components/timeslider/timeslider.js index <HASH>..<HASH> 100644 --- a/src/components/timeslider/timeslider.js +++ b/src/components/timeslider/timeslider.js @@ -186,7 +186,7 @@ var TimeSlider = Component.extend({ //Slide this.slide.call(this.brush); - + this.slider_outer.on("mousewheel", function () { //do nothing and dont pass the event on if we are currently dragging the slider if(_this.model.time.dragging){ @@ -196,7 +196,7 @@ var TimeSlider = Component.extend({ return false; } }); - + this.slide.selectAll(".extent,.resize") .remove(); @@ -407,7 +407,7 @@ var TimeSlider = Component.extend({ .interrupt() .interrupt('text') .transition('text'); - this.valueText + this.valueText .attr("transform", "translate(" + new_pos + "," + (this.height / 2) + ")") .text(this.model.time.timeFormat(value)); } diff --git a/src/tools/bubblechart/bubblechart-panzoom.js b/src/tools/bubblechart/bubblechart-panzoom.js index <HASH>..<HASH> 100644 --- a/src/tools/bubblechart/bubblechart-panzoom.js +++ b/src/tools/bubblechart/bubblechart-panzoom.js @@ -359,8 +359,8 @@ export default Class.extend({ stop: function(){ _this.draggingNow = false; - - if (this.quitZoom) return; + + if (this.quitZoom) return; //Force the update of the URL and history, with the same values _this.model.marker.axis_x.set(_this._zoomZoomedDomains.x, true, true); @@ -553,7 +553,7 @@ export default Class.extend({ zoomer.translate([ zoomer.translate()[0] + x1 - x2, zoomer.translate()[1] + y1 - y2 - ]) + ]); } var xRangeBounds = [0, _this.width];
Issue #<I>: Block page scrolling when dragging Remove whitespace and add style fix.
vizabi_vizabi
train
da064e2ede7cc041ac16842b6993d88b18743da0
diff --git a/dvc/analytics.py b/dvc/analytics.py index <HASH>..<HASH> 100644 --- a/dvc/analytics.py +++ b/dvc/analytics.py @@ -81,12 +81,21 @@ def is_enabled(): def send(report): + """ + Side effect: Removes the report after sending it. + + The report is generated and stored in a temporary file, see: + `collect_and_send_report`. Sending happens on another process, + thus, the need of removing such file afterwards. + """ url = "https://analytics.dvc.org" headers = {"content-type": "application/json"} with open(report, "rb") as fobj: requests.post(url, data=fobj, headers=headers, timeout=5) + os.remove(report) + def scm_in_use(): try: diff --git a/dvc/command/daemon.py b/dvc/command/daemon.py index <HASH>..<HASH> 100644 --- a/dvc/command/daemon.py +++ b/dvc/command/daemon.py @@ -1,7 +1,5 @@ from __future__ import unicode_literals -import os - from dvc.command.base import CmdBaseNoRepo from dvc.command.base import fix_subparsers @@ -12,6 +10,7 @@ class CmdDaemonBase(CmdBaseNoRepo): class CmdDaemonUpdater(CmdDaemonBase): def run(self): + import os from dvc.repo import Repo from dvc.updater import Updater @@ -27,10 +26,7 @@ class CmdDaemonAnalytics(CmdDaemonBase): def run(self): from dvc import analytics - report = self.args.target - - analytics.send(report) - os.remove(report) + analytics.send(self.args.target) return 0 diff --git a/tests/func/test_analytics.py b/tests/func/test_analytics.py index <HASH>..<HASH> 100644 --- a/tests/func/test_analytics.py +++ b/tests/func/test_analytics.py @@ -5,13 +5,11 @@ from dvc.utils.compat import fspath @mock.patch("dvc.analytics.send") -@mock.patch("os.remove") -def test_daemon_analytics(mock_remove, mock_send, tmp_path): +def test_daemon_analytics(mock_send, tmp_path): report = fspath(tmp_path) assert 0 == main(["daemon", "analytics", report]) mock_send.assert_called_with(report) - mock_remove.assert_called_with(report) @mock.patch("dvc.daemon._spawn")
analytics: remove the report after sending it
iterative_dvc
train
e62e5b032d100c1078e88022b872759e63f13465
diff --git a/lib/fiatrateservice.js b/lib/fiatrateservice.js index <HASH>..<HASH> 100644 --- a/lib/fiatrateservice.js +++ b/lib/fiatrateservice.js @@ -119,6 +119,7 @@ FiatRateService.prototype.getRate = function(code, opts, cb) { return cb(null, { ts: +ts, rate: rate ? rate.value : undefined, + fetchedOn: rate ? rate.ts : undefined, }); }); }, function(err, res) { diff --git a/test/integration/fiatrateservice.js b/test/integration/fiatrateservice.js index <HASH>..<HASH> 100644 --- a/test/integration/fiatrateservice.js +++ b/test/integration/fiatrateservice.js @@ -48,7 +48,7 @@ describe.only('Fiat rate service', function() { }); }); }); - it('should get current for different currency', function(done) { + it('should get current rate for different currency', function(done) { service.storage.storeFiatRate('BitPay', [{ code: 'USD', value: 123.45, @@ -69,6 +69,7 @@ describe.only('Fiat rate service', function() { }); it('should get rate for specific ts', function(done) { var clock = sinon.useFakeTimers(0, 'Date'); + clock.tick(20); service.storage.storeFiatRate('BitPay', [{ code: 'USD', value: 123.45, @@ -84,7 +85,9 @@ describe.only('Fiat rate service', function() { ts: 50, }, function(err, res) { should.not.exist(err); + res.ts.should.equal(50); res.rate.should.equal(123.45); + res.fetchedOn.should.equal(20); clock.restore(); done(); }); @@ -106,17 +109,27 @@ describe.only('Fiat rate service', function() { }, function(err) { should.not.exist(err); service.getRate('USD', { - ts: [50, 100, 500], + ts: [50, 100, 199, 500], }, function(err, res) { should.not.exist(err); - res.length.should.equal(3); + res.length.should.equal(4); res[0].ts.should.equal(50); should.not.exist(res[0].rate); + should.not.exist(res[0].fetchedOn); + res[1].ts.should.equal(100); res[1].rate.should.equal(1.00); - res[2].ts.should.equal(500); - res[2].rate.should.equal(4.00); + res[1].fetchedOn.should.equal(100); + + res[2].ts.should.equal(199); + res[2].rate.should.equal(1.00); + res[2].fetchedOn.should.equal(100); + + res[3].ts.should.equal(500); + res[3].rate.should.equal(4.00); + res[3].fetchedOn.should.equal(400); + clock.restore(); done(); });
add fetchedOn to returned rates
bitpay_bitcore-wallet-service
train
5da25ac192731eb10bd6e5dd0be9c6be4dae0946
diff --git a/test/test_jsonschema_draft3.rb b/test/test_jsonschema_draft3.rb index <HASH>..<HASH> 100644 --- a/test/test_jsonschema_draft3.rb +++ b/test/test_jsonschema_draft3.rb @@ -107,7 +107,7 @@ class JSONSchemaDraft3Test < Test::Unit::TestCase data['a'] = true assert(!JSON::Validator.validate(schema,data)) - assert(JSON::Validator.validate({'type' => 'objec'}, {'a' => true})) + assert(JSON::Validator.validate({'type' => 'object'}, {'a' => true})) assert(JSON::Validator.validate({'type' => 'object'}, {})) assert(!JSON::Validator.validate({'type' => 'object'}, [])) assert(!JSON::Validator.validate({'type' => 'object'}, 3))
Fixing test fat-finger. Thanks @myronmarston!
ruby-json-schema_json-schema
train
c92792f808f13e06af2f69ccb5567226107799b4
diff --git a/bcbio/rnaseq/sailfish.py b/bcbio/rnaseq/sailfish.py index <HASH>..<HASH> 100644 --- a/bcbio/rnaseq/sailfish.py +++ b/bcbio/rnaseq/sailfish.py @@ -45,6 +45,7 @@ def sailfish(fq1, fq2, align_dir, gtf_file, ref_file, strandedness, data): fq2_cmd = "{fq2}" if not is_gzipped(fq2) else "<(gzip -cd {fq2})" fq2_cmd = fq2_cmd.format(fq2=fq2) cmd += " -1 {fq1_cmd} -2 {fq2_cmd} " + cmd += "--useVBOpt --numBootstraps 30 " cmd += "-o {tx_out_dir}" message = "Quantifying transcripts in {fq1} and {fq2}." with file_transaction(data, align_dir) as tx_out_dir: @@ -127,8 +128,7 @@ def combine_sailfish(samples): def _sailfish_expression_parser(sailfish_file, samplename): col_names = ["name", "length", "tpm", "numreads"] - df = pd.io.parsers.read_table(sailfish_file, skiprows=11, header=None, - index_col=0, - names=col_names) + df = pd.read_csv(sailfish_file, comment="#", header=None, index_col=0, + names=col_names, sep="\t") df["sample"] = samplename return df
Run Sailfish bootstraps for use with Sleuth.
bcbio_bcbio-nextgen
train
b70b628c9e4b4ac16e899ced78089027122cb15b
diff --git a/open511/validator/__init__.py b/open511/validator/__init__.py index <HASH>..<HASH> 100644 --- a/open511/validator/__init__.py +++ b/open511/validator/__init__.py @@ -13,9 +13,16 @@ RELAXNG_LXML = etree.RelaxNG(etree.parse(RELAXNG_PATH)) SCHEMATRON_LXML = isoschematron.Schematron(etree.parse(SCHEMATRON_PATH)) def validate(doc): + errors = [] for schema_name, schema in (('Schematron', SCHEMATRON_LXML), ('RELAX NG', RELAXNG_LXML)): try: schema.assertValid(doc) except etree.DocumentInvalid as e: - raise Open511ValidationError(u"%s check failed: %s" % (schema_name, e)) + if schema == SCHEMATRON_LXML: + error = etree.fromstring(str(e)) + errors.extend(error.xpath('//svrl:text/text()', namespaces={'svrl': 'http://purl.oclc.org/dsdl/svrl'})) + else: + errors.append(u"Schema check failed: " + unicode(e)) + if errors: + raise Open511ValidationError("\n\n".join(errors)) return True \ No newline at end of file
Nicer error for Schematron violations
open511_open511
train
9ba4cef1bac8ebc8fe71123bd20cfc681fdb78a8
diff --git a/cookie.go b/cookie.go index <HASH>..<HASH> 100644 --- a/cookie.go +++ b/cookie.go @@ -31,6 +31,9 @@ const ( CookieSameSiteLaxMode // CookieSameSiteStrictMode sets the SameSite flag with the "Strict" parameter CookieSameSiteStrictMode + // CookieSameSiteNoneMode sets the SameSite flag with the "None" parameter + // see https://tools.ietf.org/html/draft-west-cookie-incrementalism-00 + CookieSameSiteNoneMode ) // AcquireCookie returns an empty Cookie object from the pool. @@ -119,8 +122,12 @@ func (c *Cookie) SameSite() CookieSameSite { } // SetSameSite sets the cookie's SameSite flag to the given value. +// set value CookieSameSiteNoneMode will set Secure to true also to avoid browser rejection func (c *Cookie) SetSameSite(mode CookieSameSite) { c.sameSite = mode + if mode == CookieSameSiteNoneMode { + c.SetSecure(true) + } } // Path returns cookie path. @@ -288,6 +295,11 @@ func (c *Cookie) AppendBytes(dst []byte) []byte { dst = append(dst, strCookieSameSite...) dst = append(dst, '=') dst = append(dst, strCookieSameSiteStrict...) + case CookieSameSiteNoneMode: + dst = append(dst, ';', ' ') + dst = append(dst, strCookieSameSite...) + dst = append(dst, '=') + dst = append(dst, strCookieSameSiteNone...) } return dst } @@ -386,6 +398,10 @@ func (c *Cookie) ParseBytes(src []byte) error { if caseInsensitiveCompare(strCookieSameSiteStrict, kv.value) { c.sameSite = CookieSameSiteStrictMode } + case 'n': // "none" + if caseInsensitiveCompare(strCookieSameSiteNone, kv.value) { + c.sameSite = CookieSameSiteNoneMode + } } } } diff --git a/cookie_test.go b/cookie_test.go index <HASH>..<HASH> 100644 --- a/cookie_test.go +++ b/cookie_test.go @@ -121,6 +121,29 @@ func TestCookieSameSite(t *testing.T) { t.Fatalf("missing SameSite flag in cookie %q", s) } + if err := c.Parse("foo=bar; samesite=none"); err != nil { + t.Fatalf("unexpected error: %s", err) + } + if c.SameSite() != CookieSameSiteNoneMode { + t.Fatalf("SameSite None Mode must be set") + } + s = c.String() + if !strings.Contains(s, "; SameSite=None") { + t.Fatalf("missing SameSite flag in cookie %q", s) + } + + if err := c.Parse("foo=bar"); err != nil { + t.Fatalf("unexpected error: %s", err) + } + c.SetSameSite(CookieSameSiteNoneMode) + s = c.String() + if !strings.Contains(s, "; SameSite=None") { + t.Fatalf("missing SameSite flag in cookie %q", s) + } + if !strings.Contains(s, "; secure") { + t.Fatalf("missing Secure flag in cookie %q", s) + } + if err := c.Parse("foo=bar"); err != nil { t.Fatalf("unexpected error: %s", err) } diff --git a/strings.go b/strings.go index <HASH>..<HASH> 100644 --- a/strings.go +++ b/strings.go @@ -62,6 +62,7 @@ var ( strCookieSameSite = []byte("SameSite") strCookieSameSiteLax = []byte("Lax") strCookieSameSiteStrict = []byte("Strict") + strCookieSameSiteNone = []byte("None") strClose = []byte("close") strGzip = []byte("gzip")
Support SameSite value "None" cookie attribute (#<I>) * Support SameSite value "None" cookie attribute * Fix typo in CookieSameSiteNoneMode comment * fix comment for SameSite None
valyala_fasthttp
train
865750cb7273dee614219d6e9d95017339431cd6
diff --git a/src/channel.py b/src/channel.py index <HASH>..<HASH> 100644 --- a/src/channel.py +++ b/src/channel.py @@ -68,17 +68,14 @@ def cmode ( self, channel, modes = '' ): return self.recv().split() [4] else: self.rsend ( 'MODE ' + channel + ' ' + modes ) - while 1: - data = self.recv() - ncode = data.split() [1] + data = self.recv() + ncode = data.split() [1] - if ncode in self.err_replies.keys(): - if ncode in self.err_replies.keys(): - self.exception ( ncode ) - elif self.find ( data, 'MODE' ) and self.hide_called_events: - pass - else: self.buffer.append ( data ) - break + if ncode in self.err_replies.keys(): + self.exception ( ncode ) + elif self.find ( data, 'MODE' ) and self.hide_called_events: + pass + else: self.buffer.append ( data ) def banlist ( self, channel ): self.rsend ( 'MODE ' + channel + ' +b' ) bans = [] @@ -127,8 +124,10 @@ def topic ( self, channel, rtopic = None ): self.rsend ( 'TOPIC ' + channel + ' :' + rtopic ) else: self.rsend ( 'TOPIC ' + channel ) - topic = None - while topic == None: + topic = '' + set_by = '' + time_set = '' + while self.readable() == True: data = self.recv() ncode = data.split() [1] if ncode in self.err_replies.keys(): @@ -139,11 +138,12 @@ def topic ( self, channel, rtopic = None ): elif self.find ( data, 'TOPIC' ) and self.hide_called_events: pass elif self.find ( data, '333' ): - # implement topic, tupleter and time tuple collection - pass + segments = data.split() + time_set = self.time.ctime ( int ( segments [5] ) ) + set_by = self.who_is_it ( segments [4] ) elif data.find ( '331' ) != -1: topic = '' else: self.buffer.append ( data ) - return topic + return topic, set_by, time_set def names ( self, channel ): self.rsend ( 'NAMES ' + channel ) names = ()
Path to cmode() and topic().
jamieleshaw_lurklib
train
adf7ce857d12a743df50b91f82dd94578ee28b19
diff --git a/expression/builtin_cast_vec.go b/expression/builtin_cast_vec.go index <HASH>..<HASH> 100644 --- a/expression/builtin_cast_vec.go +++ b/expression/builtin_cast_vec.go @@ -537,11 +537,48 @@ func (b *builtinCastIntAsDecimalSig) vecEvalDecimal(input *chunk.Chunk, result * } func (b *builtinCastIntAsJSONSig) vectorized() bool { - return false + return true } func (b *builtinCastIntAsJSONSig) vecEvalJSON(input *chunk.Chunk, result *chunk.Column) error { - return errors.Errorf("not implemented") + n := input.NumRows() + buf, err := b.bufAllocator.get(types.ETInt, n) + if err != nil { + return err + } + defer b.bufAllocator.put(buf) + if err := b.args[0].VecEvalInt(b.ctx, input, buf); err != nil { + return err + } + nums := buf.Int64s() + result.ReserveJSON(n) + if mysql.HasIsBooleanFlag(b.args[0].GetType().Flag) { + for i := 0; i < n; i++ { + if buf.IsNull(i) { + result.AppendNull() + } else { + result.AppendJSON(json.CreateBinary(nums[i] != 0)) + } + } + } else if mysql.HasUnsignedFlag(b.args[0].GetType().Flag) { + for i := 0; i < n; i++ { + if buf.IsNull(i) { + result.AppendNull() + } else { + result.AppendJSON(json.CreateBinary(uint64(nums[i]))) + } + } + } else { + for i := 0; i < n; i++ { + if buf.IsNull(i) { + result.AppendNull() + } else { + result.AppendJSON(json.CreateBinary(nums[i])) + } + } + } + + return nil } func (b *builtinCastJSONAsJSONSig) vectorized() bool { diff --git a/expression/builtin_cast_vec_test.go b/expression/builtin_cast_vec_test.go index <HASH>..<HASH> 100644 --- a/expression/builtin_cast_vec_test.go +++ b/expression/builtin_cast_vec_test.go @@ -45,7 +45,7 @@ var vecBuiltinCastCases = map[string][]vecExprBenchCase{ {retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETReal}}, {retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETJson}}, {retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETDecimal}}, - + {retEvalType: types.ETJson, childrenTypes: []types.EvalType{types.ETInt}}, {retEvalType: types.ETJson, childrenTypes: []types.EvalType{types.ETReal}}, }, }
expression: implement vectorized evaluation for `builtinCastIntAsJSONSig` (#<I>)
pingcap_tidb
train
ba22e56262d6761f3fbd25652b906c3c9802bf92
diff --git a/server/camlistored/ui/camli.js b/server/camlistored/ui/camli.js index <HASH>..<HASH> 100644 --- a/server/camlistored/ui/camli.js +++ b/server/camlistored/ui/camli.js @@ -241,12 +241,12 @@ function camliUploadFileHelper(file, contentsBlobRef, opts) { function camliUploadString(s, opts) { opts = saneOpts(opts); var blobref = "sha1-" + Crypto.SHA1(s); + var parts = [s]; - bb = new WebKitBlobBuilder(); - bb.append(s); + var bb = new Blob(parts); var fd = new FormData(); - fd.append(blobref, bb.getBlob()); + fd.append(blobref, bb); var uploadCb = {}; uploadCb.success = function(resj) {
Conform to W3C File API Replace WebKitBlobBuilder with Blob() interface implementation of web browser. Make it working on Firefox as well. Change-Id: I3b7e<I>dbba3aff6b3f3d<I>f<I>af<I>ab8
perkeep_perkeep
train
486e41a792f571a03e67f7074b08d1596dffe6b7
diff --git a/distutilazy/clean.py b/distutilazy/clean.py index <HASH>..<HASH> 100644 --- a/distutilazy/clean.py +++ b/distutilazy/clean.py @@ -19,7 +19,7 @@ from distutils.command import clean from . import util -__version__ = "0.3.0" +__version__ = "0.4.0" class clean_pyc(Command): description = """Clean root dir from complied python files""" @@ -28,11 +28,13 @@ class clean_pyc(Command): def initialize_options(self): self.root = os.getcwd() self.extensions = "pyc,pyo,pyd" + self.directories = "__pycache__," def finalize_options(self): if not os.path.exists(self.root): raise IOError("Failed to access root path %s" % self.root) self.extensions = [ext.strip() for ext in self.extensions.split(',')] + self.directories = [dirname.strip() for dirname in self.directories.split(',')] def find_compiled_files(self): """Find compiled Python files recursively in the root path @@ -48,6 +50,16 @@ class clean_pyc(Command): self.announce("found %d compiled python files in %s" % (len(files), self.root)) return files + def find_cache_directories(self): + directories = [] + for dirname in self.directories: + dirs = util.find_directories(self.root, dirname) + log.debug("found {0} directories in {1}".format(len(dirs), self.root)) + directories.extend(dirs) + del dirs + self.announce("found {0} python cache directories in %s".format(len(directories), self.root)) + return directories + def _clean_file(self, filename): """Clean a file if exists""" if not os.path.exists(filename): @@ -57,12 +69,28 @@ class clean_pyc(Command): if not self.dry_run: os.remove(filename) + def _clean_directory(self, dirname): + """Clean a directory if exists""" + if not os.path.exists(dirname): + return + self.announce("removing directory %s and all it's contents" % dirname) + if not self.dry_run: + shutil.rmtree(dirname, True) + def run(self): + dirs = self.find_cache_directories() + if dirs: + self.announce("cleaning python cache directories in %s ..." % self.root) + if not self.dry_run: + for dirname in dirs: + self._clean_directory(dirname) + files = self.find_compiled_files() - self.announce("cleaning compiled python files in %s ..." % self.root) - if not self.dry_run: - for filename in files: - self._clean_file(filename) + if files: + self.announce("cleaning compiled python files in %s ..." % self.root) + if not self.dry_run: + for filename in files: + self._clean_file(filename) class clean_all(clean.clean, clean_pyc): description = """Clean root dir from temporary files, complied files, etc.""" diff --git a/tests/test_clean.py b/tests/test_clean.py index <HASH>..<HASH> 100755 --- a/tests/test_clean.py +++ b/tests/test_clean.py @@ -9,18 +9,35 @@ from __future__ import absolute_import -__version__ = "0.3.0" - import sys import os +from os import path +import shutil import unittest -from .setup_test_env import * +from .setup_test_env import TEST_DIR from distutilazy import clean from distutils.dist import Distribution class TestClean(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.test_cache_dir = path.join(TEST_DIR, '_test_py_cache_') + if path.exists(cls.test_cache_dir): + raise Error( + "Test python cache directory exsits in {0}. Please remove this path".format( + cls.test_cache_dir + ) + ) + else: + os.mkdir(cls.test_cache_dir) + + @classmethod + def tearDownAfter(cls): + if path.exists(cls.test_cache_dir): + shutil.rmtree(cls.test_cache_dir, True) + def test_clean_all(self): dist = Distribution() dist.metadata.name = "testdist" @@ -52,3 +69,22 @@ class TestClean(unittest.TestCase): cl.finalize_options() self.assertEqual(cl.extensions, ["ppyycc", "ppyyoo"]) self.assertEqual(cl.find_compiled_files(), []) + + def test_clean_py_cache_dirs(self): + dist = Distribution() + cl = clean.clean_pyc(dist) + cl.directories = "_test_py_cache_" + cl.finalize_options() + self.assertEqual(cl.directories, ["_test_py_cache_"]) + self.assertEqual(cl.find_cache_directories(), [self.__class__.test_cache_dir]) + cl.run() + self.assertFalse(path.exists(self.__class__.test_cache_dir)) + + def test_clean_py_cache_dirs_finds_nothing(self): + dist = Distribution() + cl = clean.clean_pyc(dist) + cl.extensions = "ppyycc, ppyyoo" + cl.directories = "not_exist, and_not_found" + cl.finalize_options() + self.assertEqual(cl.directories, ["not_exist", "and_not_found"]) + self.assertEqual(cl.find_cache_directories(), [])
clean_pyc command class cleans Python cached directories
farzadghanei_distutilazy
train
e8e9bc15f62baaa1b469a7f97c1c2fe8bbe81ccb
diff --git a/src/main/java/eu/interedition/collatex/rest/BeckettResource.java b/src/main/java/eu/interedition/collatex/rest/BeckettResource.java index <HASH>..<HASH> 100644 --- a/src/main/java/eu/interedition/collatex/rest/BeckettResource.java +++ b/src/main/java/eu/interedition/collatex/rest/BeckettResource.java @@ -36,14 +36,20 @@ public class BeckettResource extends ServerResource { final WitnessSegmentPhrases pc = sse.getWitnessSegmentPhrases("08-1"); final WitnessSegmentPhrases pd = sse.getWitnessSegmentPhrases("08-2"); final WitnessSegmentPhrases pe = sse.getWitnessSegmentPhrases("09-1"); + final WitnessSegmentPhrases pf = sse.getWitnessSegmentPhrases("09-2"); + final WitnessSegmentPhrases pg = sse.getWitnessSegmentPhrases("10-1"); + final WitnessSegmentPhrases ph = sse.getWitnessSegmentPhrases("10-2"); System.out.println(pa.toString()); System.out.println(pb.toString()); System.out.println(pc.toString()); System.out.println(pd.toString()); System.out.println(pe.toString()); + System.out.println(pf.toString()); + System.out.println(pg.toString()); + System.out.println(ph.toString()); - final AlignmentTable2 alignmentTable = NewAlignmentTableCreator.createNewAlignmentTable(pa, pb, pc, pd, pe); + final AlignmentTable2 alignmentTable = NewAlignmentTableCreator.createNewAlignmentTable(pa, pb, pc, pd, pe, pf, pg, ph); // HTML html = "<html><body> " + AlignmentTable2.alignmentTableToHTML(alignmentTable) + "</body></html>"; } catch (final Exception e) {
[RHD] Beckett resource added extra witnesses.
interedition_collatex
train
9ee625bac02fcd98e8bd57fc915a9933aa13392e
diff --git a/src/Yubikey.php b/src/Yubikey.php index <HASH>..<HASH> 100644 --- a/src/Yubikey.php +++ b/src/Yubikey.php @@ -632,7 +632,7 @@ class Yubikey { * @param int $num * @return string */ - protected static function randomBytes($num = 16) + protected static function getRandomBytes($num = 16) { static $which = null; if ($which === null) {
Renamed randomBytes to getRandomBytes
bitbeans_Yubikey
train
e3b452eaf6d21984e44be51161fd57ec4c443777
diff --git a/src/ci.js b/src/ci.js index <HASH>..<HASH> 100644 --- a/src/ci.js +++ b/src/ci.js @@ -3,5 +3,5 @@ export default function (services, chosenService, options) { if (service) return service.scaffolder(options); - return undefined; + return {}; } diff --git a/test/unit/ci-test.js b/test/unit/ci-test.js index <HASH>..<HASH> 100644 --- a/test/unit/ci-test.js +++ b/test/unit/ci-test.js @@ -15,9 +15,7 @@ suite('ci', () => { return assert.becomes(scaffoldCi(scaffolders, chosenService, options), scaffolderResult); }); - test('that choosing a scaffolder without a defined service does not result in an error', () => scaffoldCi( - any.simpleObject(), - any.word(), - any.simpleObject() - )); + test('that choosing a scaffolder without a defined service does not result in an error', async () => { + assert.deepEqual(scaffoldCi(any.simpleObject(), any.word(), any.simpleObject()), {}); + }); });
fix(ci): returned an empty object for `Other` since later code assumes at least an object to be returned
travi_javascript-scaffolder
train
1061122917e5839bc18bc12b34261533d61c8276
diff --git a/lib/capybara/selenium/extensions/find.rb b/lib/capybara/selenium/extensions/find.rb index <HASH>..<HASH> 100644 --- a/lib/capybara/selenium/extensions/find.rb +++ b/lib/capybara/selenium/extensions/find.rb @@ -33,7 +33,7 @@ module Capybara var texts = arguments[1] return arguments[0].filter(function(el){ var content = el.textContent.toLowerCase(); - return texts.every(function(txt){ return content.includes(txt.toLowerCase()) }); + return texts.every(function(txt){ return content.indexOf(txt.toLowerCase()) != -1 }); }) JS end diff --git a/spec/selenium_spec_ie.rb b/spec/selenium_spec_ie.rb index <HASH>..<HASH> 100644 --- a/spec/selenium_spec_ie.rb +++ b/spec/selenium_spec_ie.rb @@ -23,44 +23,37 @@ Capybara.register_driver :selenium_ie do |app| # ::Selenium::WebDriver.logger.level = "debug" options = ::Selenium::WebDriver::IE::Options.new options.require_window_focus = true - Capybara::Selenium::Driver.new( - app, - browser: :ie, - desired_capabilities: ::Selenium::WebDriver::Remote::Capabilities.ie, - options: options - ) -end + # options.add_option("log", {"level": "trace"}) -if ENV['REMOTE'] - Capybara.register_driver :selenium_ie do |app| - url = "http://#{selenium_host}:#{selenium_port}/wd/hub" - options = ::Selenium::WebDriver::IE::Options.new - options.require_window_focus = true + if ENV['REMOTE'] + Capybara.server_host = server_host + url = "http://#{selenium_host}:#{selenium_port}/wd/hub" Capybara::Selenium::Driver.new(app, browser: :remote, - desired_capabilities: ::Selenium::WebDriver::Remote::Capabilities.ie, options: options, url: url).tap do |driver| + puts driver.browser.capabilities.inspect driver.browser.file_detector = lambda do |args| str = args.first.to_s str if File.exist?(str) end end + else + Capybara::Selenium::Driver.new( + app, + browser: :ie, + options: options + ).tap do |driver| + puts driver.browser.capabilities.inspect + end end - - Capybara.server_host = server_host end module TestSessions SeleniumIE = Capybara::Session.new(:selenium_ie, TestApp) end -# TestSessions::SeleniumIE.driver.browser.file_detector = lambda do |args| -# str = args.first.to_s -# str if File.exist?(str) -# end if ENV['REMOTE'] - TestSessions::SeleniumIE.current_window.resize_to(800, 500) skipped_tests = %i[response_headers status_code trigger modals hover form_attribute windows] @@ -106,8 +99,9 @@ Capybara::SpecHelper.run_specs TestSessions::SeleniumIE, 'selenium', capybara_sk pending "IE requires all files be uploaded from same directory. Selenium doesn't provide that." if ENV['REMOTE'] when %r{#attach_file with multipart form should send content type image/jpeg when uploading an image$} pending 'IE gets text/plain type for some reason' - when /#click should not retry clicking when wait is disabled$/ - pending "IE driver doesn't error when clicking on covered elements, it just clicks the wrong element" + # when /#click should not retry clicking when wait is disabled$/ + # Fixed in IEDriverServer 3.141.0.5 + # pending "IE driver doesn't error when clicking on covered elements, it just clicks the wrong element" when /#click should go to the same page if href is blank$/ pending 'IE treats blank href as a parent request (against HTML spec)' end
IE doesn't provide String.prototype.includes - and other IE updates
teamcapybara_capybara
train
7bc48f9fbf60fdb627e2db16e8e8bdb1551b8110
diff --git a/arpy/hamming_marker.py b/arpy/hamming_marker.py index <HASH>..<HASH> 100644 --- a/arpy/hamming_marker.py +++ b/arpy/hamming_marker.py @@ -3,6 +3,7 @@ import cv2 from numpy import array, mean, binary_repr, zeros from numpy.random import randint from scipy.ndimage import zoom +from PIL import Image from arpy.hamming import encode, msg_size, data_size @@ -30,13 +31,19 @@ class HammingMarker(object): return mean(self.contours, axis=0).flatten() - def toimage(self, size=marker_size): + def toimage(self, size=marker_size, output=None): img = zeros((marker_size, marker_size)) img[1:-1, 1:-1] = self.hamming_code img = 1 - img - scale = size / float(marker_size) - return zoom(img, zoom=scale, order=0) + # scale = size / float(marker_size) + # return zoom(img, zoom=scale, output=output, order=0) + + cv2.imwrite('/tmp/bob.png', img) + im = Image.open('/tmp/bob.png') + im2 = im.resize((size, size)) + im2.save('/tmp/bob.png') + return cv2.imread('/tmp/bob.png') def draw_contour(self, img, color=(0, 255, 0), linewidth=5): cv2.drawContours(img, [self.contours], -1, color, linewidth)
Use a very dirty fix to use PIL for rescaling instead of scipy (zoom function seems to have changed).
pierre-rouanet_hampy
train
ba755806cd518809d24968d89d51f64d8d6fdf4c
diff --git a/salt/minion.py b/salt/minion.py index <HASH>..<HASH> 100644 --- a/salt/minion.py +++ b/salt/minion.py @@ -19,7 +19,11 @@ import sys import signal # Import third party libs -import zmq +try: + import zmq +except: + # Running in local, zmq not needed + pass import yaml HAS_RANGE = False
Allow zmq-less deployment
saltstack_salt
train
5c925673617d0d6277711a0ea1d51c5c5d31ecc1
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -15,14 +15,6 @@ module.exports = { getConfig: function() { var brocfileConfig = {}; - if (!!this.app) { - if (!!this.app.options.coffeeOptions) { - console.log(chalk.yellow("Passing in coffeeOptions from Brocfile.js is \n" + - "deprecated and support will be removed in the next minor release. \n" + - "Please use config/environment.js instead. See README on GitHub for more details.")); - } - brocfileConfig = this.app.options.coffeeOptions || {}; - } var coffeeOptions = defaults(this.project.config(process.env.EMBER_ENV).coffeeOptions || {}, brocfileConfig, { blueprints: true
Remove deprecated config warning. This will not work in <I>.x, and was already slated to be removed...
kimroen_ember-cli-coffeescript
train
0b285b1817c0c52c8e32e64e22dbcf6c9fe70121
diff --git a/lib/assertions.js b/lib/assertions.js index <HASH>..<HASH> 100644 --- a/lib/assertions.js +++ b/lib/assertions.js @@ -786,13 +786,13 @@ module.exports = function (expect) { } }); - function wrapDiffWithTypePrefixAndSuffix(e, type) { + function wrapDiffWithTypePrefixAndSuffix(e, type, subject) { var createDiff = e.createDiff; if (createDiff) { return function (output) { // ... - type.prefix.call(e, output); + type.prefix.call(type, output, subject); var result = createDiff.apply(this, arguments); - type.suffix.call(e, output); + type.suffix.call(type, output, subject); return result; }; } @@ -808,7 +808,7 @@ module.exports = function (expect) { }, function (e) { expect.fail({ label: e.label, - diff: wrapDiffWithTypePrefixAndSuffix(e, type) + diff: wrapDiffWithTypePrefixAndSuffix(e, type, subject) }); }); } else { @@ -819,7 +819,7 @@ module.exports = function (expect) { }, function (e) { expect.fail({ label: 'should satisfy', - diff: wrapDiffWithTypePrefixAndSuffix(e, subjectType) + diff: wrapDiffWithTypePrefixAndSuffix(e, subjectType, subject) }); }); }
Fixed: Provide context for type.prefix and type.suffix
unexpectedjs_unexpected
train
70508a8fa01c8770ba5fd37cec0b79c4f9eda0ba
diff --git a/de.tudarmstadt.ukp.wikipedia.timemachine/src/main/java/de/tudarmstadt/ukp/wikipedia/timemachine/domain/Revision.java b/de.tudarmstadt.ukp.wikipedia.timemachine/src/main/java/de/tudarmstadt/ukp/wikipedia/timemachine/domain/Revision.java index <HASH>..<HASH> 100755 --- a/de.tudarmstadt.ukp.wikipedia.timemachine/src/main/java/de/tudarmstadt/ukp/wikipedia/timemachine/domain/Revision.java +++ b/de.tudarmstadt.ukp.wikipedia.timemachine/src/main/java/de/tudarmstadt/ukp/wikipedia/timemachine/domain/Revision.java @@ -29,7 +29,7 @@ public class Revision { */ private static final Long TIME_ZERO = 946724195435l; /** - * We measure the time not from 1th Janury 1900 but from 1th January 2000 + * We measure the time not from 1th January 1900 but from 1th January 2000 */ private static final Integer MS_IN_SEC = 1000; @@ -65,10 +65,6 @@ public class Revision { /** * Merge two unsigned integer values (text id and time stamp) to one long * value (revision) to use GNU Trove container. - * - * @param textId - * @param timestamp - * @return */ public static long createRevision(int textId, int timestamp) { return (long) textId << 32 | (long) timestamp; @@ -77,7 +73,6 @@ public class Revision { /** * Extract a time stamp from the revision long. * - * @param revision * @return time stamp */ public static int getTimestamp(long revision) { @@ -87,7 +82,6 @@ public class Revision { /** * Extract a text ID from the revision long * - * @param revision * @return text ID */ public static int getTextId(long revision) {
No issue. Fix JavaDoc.
dkpro_dkpro-jwpl
train
baccdb4cfc241cbcfd02d21aada56100c6c9c132
diff --git a/lib/handlebars/base.js b/lib/handlebars/base.js index <HASH>..<HASH> 100644 --- a/lib/handlebars/base.js +++ b/lib/handlebars/base.js @@ -7,11 +7,12 @@ var Handlebars = {}; // BEGIN(BROWSER) Handlebars.VERSION = "1.0.0-rc.3"; -Handlebars.COMPILER_REVISION = 2; +Handlebars.COMPILER_REVISION = 3; Handlebars.REVISION_CHANGES = { 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '>= 1.0.0-rc.3' + 2: '== 1.0.0-rc.3', + 3: '>= 1.0.0-rc.4' }; Handlebars.helpers = {}; diff --git a/lib/handlebars/compiler/compiler.js b/lib/handlebars/compiler/compiler.js index <HASH>..<HASH> 100644 --- a/lib/handlebars/compiler/compiler.js +++ b/lib/handlebars/compiler/compiler.js @@ -993,12 +993,7 @@ JavaScriptCompiler.prototype = { else { programParams.push("depth" + (depth - 1)); } } - if(depths.length === 0) { - return "self.program(" + programParams.join(", ") + ")"; - } else { - programParams.shift(); - return "self.programWithDepth(" + programParams.join(", ") + ")"; - } + return (depths.length === 0 ? "self.program(" : "self.programWithDepth(") + programParams.join(", ") + ")"; }, register: function(name, val) { diff --git a/lib/handlebars/runtime.js b/lib/handlebars/runtime.js index <HASH>..<HASH> 100644 --- a/lib/handlebars/runtime.js +++ b/lib/handlebars/runtime.js @@ -12,13 +12,11 @@ Handlebars.VM = { program: function(i, fn, data) { var programWrapper = this.programs[i]; if(data) { - return Handlebars.VM.program(fn, data); - } else if(programWrapper) { - return programWrapper; - } else { - programWrapper = this.programs[i] = Handlebars.VM.program(fn); - return programWrapper; + programWrapper = Handlebars.VM.program(i, fn, data); + } else if (!programWrapper) { + programWrapper = this.programs[i] = Handlebars.VM.program(i, fn); } + return programWrapper; }, programWithDepth: Handlebars.VM.programWithDepth, noop: Handlebars.VM.noop, @@ -50,21 +48,27 @@ Handlebars.VM = { }; }, - programWithDepth: function(fn, data, $depth) { - var args = Array.prototype.slice.call(arguments, 2); + programWithDepth: function(i, fn, data /*, $depth */) { + var args = Array.prototype.slice.call(arguments, 3); - return function(context, options) { + var program = function(context, options) { options = options || {}; return fn.apply(this, [context, options.data || data].concat(args)); }; + program.program = i; + program.depth = args.length; + return program; }, - program: function(fn, data) { - return function(context, options) { + program: function(i, fn, data) { + var program = function(context, options) { options = options || {}; return fn(context, options.data || data); }; + program.program = i; + program.depth = 0; + return program; }, noop: function() { return ""; }, invokePartial: function(partial, name, context, helpers, partials, data) {
Add program metadata Include program id and depth on the generated wrapper objects. This allows helpers who are passed these objects to differentiate between helpers for cases where they may want to cache the generated DOM structure.
wycats_handlebars.js
train
887f2338cb9d59cb361c3e83cc3d91100a3c7421
diff --git a/Tests/Unit/Controller/Ajax/AbstractPageSeoControllerTest.php b/Tests/Unit/Controller/Ajax/AbstractPageSeoControllerTest.php index <HASH>..<HASH> 100644 --- a/Tests/Unit/Controller/Ajax/AbstractPageSeoControllerTest.php +++ b/Tests/Unit/Controller/Ajax/AbstractPageSeoControllerTest.php @@ -214,7 +214,12 @@ abstract class AbstractPageSeoControllerTest extends UnitTestCase */ protected function getDataHandlerMock() { - return $this->getMock('TYPO3\\CMS\\Core\\DataHandling\\DataHandler'); + $mock = $this->getMock('TYPO3\\CMS\\Core\\DataHandling\\DataHandler'); + $mock + ->expects($this->any()) + ->method('getExcludeListArray') + ->will($this->returnValue(array())); + return $mock; } /**
[BUGFIX] Testsuite failed permission check Fixes #<I> Issue #<I>
webdevops_TYPO3-metaseo
train
74b84d00b38e81a00d105d4755919c3710afd05d
diff --git a/integration-cli/docker_cli_inspect_test.go b/integration-cli/docker_cli_inspect_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_cli_inspect_test.go +++ b/integration-cli/docker_cli_inspect_test.go @@ -42,8 +42,7 @@ func (s *DockerCLIInspectSuite) TestInspectImage(c *testing.T) { // fails, fix the difference in the image serialization instead of // updating this hash. imageTestID := "sha256:11f64303f0f7ffdc71f001788132bca5346831939a956e3e975c93267d89a16d" - usesContainerdSnapshotter := false // TODO(vvoland): Check for feature flag - if usesContainerdSnapshotter { + if containerdSnapshotterEnabled() { // Under containerd ID of the image is the digest of the manifest list. imageTestID = "sha256:e43ca824363c5c56016f6ede3a9035afe0e9bd43333215e0b0bde6193969725d" } diff --git a/integration-cli/requirements_test.go b/integration-cli/requirements_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/requirements_test.go +++ b/integration-cli/requirements_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/containerd/containerd/plugin" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/versions" @@ -99,6 +100,17 @@ func Devicemapper() bool { return strings.HasPrefix(testEnv.DaemonInfo.Driver, "devicemapper") } +// containerdSnapshotterEnabled checks if the daemon in the test-environment is +// configured with containerd-snapshotters enabled. +func containerdSnapshotterEnabled() bool { + for _, v := range testEnv.DaemonInfo.DriverStatus { + if v[0] == "driver-type" { + return v[1] == string(plugin.SnapshotPlugin) + } + } + return false +} + func IPv6() bool { cmd := exec.Command("test", "-f", "/proc/net/if_inet6") return cmd.Run() != nil
integration-cli: add utility to check if snapshotters are enabled
moby_moby
train
3f48b606821395826b8c85acfe7d8be47ab2ae69
diff --git a/cli.js b/cli.js index <HASH>..<HASH> 100755 --- a/cli.js +++ b/cli.js @@ -5,24 +5,14 @@ const meow = require('meow') const findup = require('find-up') const readPkg = require('read-pkg-up').sync const openBrowser = require('react-dev-utils/openBrowser') +const log = require('@compositor/log') const chalk = require('chalk') const clipboard = require('clipboardy') const config = require('pkg-conf').sync('x0') const pkg = readPkg().pkg -const log = (...args) => { - console.log( - chalk.black.bgCyan(' x0 '), - ...args - ) -} -log.error = (...args) => { - console.log( - chalk.black.bgRed(' err '), - chalk.red(...args) - ) -} +log.name = 'x0' const cli = meow(` Usage @@ -131,23 +121,23 @@ const handleError = err => { switch (cmd) { case 'build': - log('building static site') + log.start('building static site') const { build } = require('.') build(opts) .then(res => { - log('site saved to ' + opts.outDir) + log.stop('site saved to ' + opts.outDir) }) .catch(handleError) break case 'dev': default: - log('starting dev server') + log.start('starting dev server') const { dev } = require('.') dev(opts) .then(res => { const { port } = res.options const url = `http://localhost:${port}` - log( + log.stop( 'dev server listening on', chalk.green(url), chalk.gray('(copied to clipboard)')
Use c8r/log for cli
c8r_x0
train
b0865aa0e94fa4395e495af2621e9c707e78e604
diff --git a/utils/babel-preset-app/polyfills.js b/utils/babel-preset-app/polyfills.js index <HASH>..<HASH> 100644 --- a/utils/babel-preset-app/polyfills.js +++ b/utils/babel-preset-app/polyfills.js @@ -1,6 +1,6 @@ const { addSideEffect } = require('@babel/helper-module-imports') -// slightly modifiled from @babel/preset-env/src/utils +// slightly modified from @babel/preset-env/src/utils // use an absolute path for core-js modules, to fix conflicts of different core-js versions // TODO: remove the `useAbsolutePath` option in v5, // because `core-js` is sure to be present in newer projects;
chore(utils): fix typo in quasar/babel-preset-app (#<I>)
quasarframework_quasar
train
7f03c7de5b49d75b59b1c32d336357c96c634370
diff --git a/translator/src/main/java/com/google/devtools/j2objc/gen/StatementGenerator.java b/translator/src/main/java/com/google/devtools/j2objc/gen/StatementGenerator.java index <HASH>..<HASH> 100644 --- a/translator/src/main/java/com/google/devtools/j2objc/gen/StatementGenerator.java +++ b/translator/src/main/java/com/google/devtools/j2objc/gen/StatementGenerator.java @@ -1765,16 +1765,18 @@ public class StatementGenerator extends ErrorReportingASTVisitor { // Returns a string where all characters that will interfer in // a valid Objective-C string are quoted. private static String makeQuotedString(String originalString) { - int location; + int location = 0; StringBuffer buffer = new StringBuffer(originalString); - while ((location = buffer.indexOf("\\")) != -1) { - buffer.replace(location, location + 1, "\\\\"); + while ((location = buffer.indexOf("\\", location)) != -1) { + buffer.replace(location++, location++, "\\\\"); } - while ((location = buffer.indexOf("\"")) != -1) { - buffer.replace(location, location + 1, "\\\""); + location = 0; + while ((location = buffer.indexOf("\"", location)) != -1) { + buffer.replace(location++, location++, "\\\""); } + location = 0; while ((location = buffer.indexOf("\n")) != -1) { - buffer.replace(location, location + 1, "\\n"); + buffer.replace(location++, location++, "\\n"); } return buffer.toString(); } diff --git a/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java b/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java index <HASH>..<HASH> 100644 --- a/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java +++ b/translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java @@ -1614,4 +1614,11 @@ public class StatementGeneratorTest extends GenerationTest { "Test", "Test.m"); assertTranslation(translation, "return [Test_TypeEnum TYPE_BOOL_];"); } + + public void testMakeQuotedStringHang() throws IOException { + // Test hangs if bug makeQuotedString() isn't fixed. + translateSourceFile( + "public class Test { void test(String s) { assert !\"null\\foo\\nbar\".equals(s); }}", + "Test", "Test.m"); + } }
Issue <I>: fixed hang in makeQuotedString().
google_j2objc
train
124691c9b8112245cb86ba84ac4204428f45d643
diff --git a/es/chain/node.js b/es/chain/node.js index <HASH>..<HASH> 100644 --- a/es/chain/node.js +++ b/es/chain/node.js @@ -45,8 +45,18 @@ async function sendTransaction (tx, options = {}) { } } - const { txHash } = await this.api.postTransaction({ tx }) - return waitMined ? { ...(await this.poll(txHash, options, tx)), rawTx: tx } : { hash: txHash, rawTx: tx } + try { + const { txHash } = await this.api.postTransaction({ tx }) + return waitMined ? { ...(await this.poll(txHash, options)), rawTx: tx } : { hash: txHash, rawTx: tx } + } catch (e) { + throw Object.assign( + (new Error(e.message)), + { + rawTx: tx, + verifyTx: () => this.unpackAndVerify(tx) + } + ) + } } async function balance (address, { height, hash, format = false } = {}) { @@ -97,7 +107,7 @@ async function topBlock () { return top[R.head(R.keys(top))] } -async function poll (th, { blocks = 10, interval = 5000 } = {}, raw) { +async function poll (th, { blocks = 10, interval = 5000 } = {}) { const instance = this const max = await this.height() + blocks @@ -110,12 +120,7 @@ async function poll (th, { blocks = 10, interval = 5000 } = {}, raw) { await pause(interval) return probe() } - throw Object.assign( - (new Error(`Giving up after ${blocks} blocks mined.`)), - { - verifyTx: () => instance.unpackAndVerify(raw) - } - ) + throw new Error(`Giving up after ${blocks} blocks mined.`) } return probe() diff --git a/es/tx/tx.js b/es/tx/tx.js index <HASH>..<HASH> 100644 --- a/es/tx/tx.js +++ b/es/tx/tx.js @@ -139,6 +139,7 @@ async function contractCreateTx ({ ownerId, code, vmVersion, abiVersion, deposit // Get VM_ABI version for minerva const { splitedVmAbi, contractVmVersion } = getContractVmVersion.bind(this)() // Calculate fee, get absolute ttl (ttl + height), get account nonce + const { fee, ttl, nonce } = await this.prepareTxParams(TX_TYPE.contractCreate, { senderId: ownerId, ...R.head(arguments), vmVersion: splitedVmAbi, gasPrice }) // Build transaction using sdk (if nativeMode) or build on `AETERNITY NODE` side
Refactor error handling in sendTransaction (#<I>) Fix contractCreate fee calculation
aeternity_aepp-sdk-js
train
65301199182dfb713a8302547465253f2c17c0f3
diff --git a/src/ol/control/ZoomSlider.js b/src/ol/control/ZoomSlider.js index <HASH>..<HASH> 100644 --- a/src/ol/control/ZoomSlider.js +++ b/src/ol/control/ZoomSlider.js @@ -1,7 +1,6 @@ /** * @module ol/control/ZoomSlider */ -import {inherits} from '../util.js'; import ViewHint from '../ViewHint.js'; import Control from '../control/Control.js'; import {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js'; @@ -43,15 +42,19 @@ const Direction = { * map.addControl(new ZoomSlider()); * * @constructor - * @extends {module:ol/control/Control} * @param {module:ol/control/ZoomSlider~Options=} opt_options Zoom slider options. * @api */ -class ZoomSlider { +class ZoomSlider extends Control { constructor(opt_options) { const options = opt_options ? opt_options : {}; + super({ + element: document.createElement('div'), + render: options.render || render + }); + /** * Will hold the current resolution of the view. * @@ -124,7 +127,7 @@ class ZoomSlider { const thumbElement = document.createElement('button'); thumbElement.setAttribute('type', 'button'); thumbElement.className = className + '-thumb ' + CLASS_UNSELECTABLE; - const containerElement = document.createElement('div'); + const containerElement = this.element; containerElement.className = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; containerElement.appendChild(thumbElement); /** @@ -142,11 +145,6 @@ class ZoomSlider { listen(containerElement, EventType.CLICK, this.handleContainerClick_, this); listen(thumbElement, EventType.CLICK, stopPropagation); - - Control.call(this, { - element: containerElement, - render: options.render || render - }); } /** @@ -154,14 +152,14 @@ class ZoomSlider { */ disposeInternal() { this.dragger_.dispose(); - Control.prototype.disposeInternal.call(this); + super.disposeInternal(); } /** * @inheritDoc */ setMap(map) { - Control.prototype.setMap.call(this, map); + super.setMap(map); if (map) { map.render(); } @@ -341,8 +339,6 @@ class ZoomSlider { } } -inherits(ZoomSlider, Control); - /** * Update the zoomslider element.
Use extends and super for control/ZoomSlider
openlayers_openlayers
train
ff6414c64b03a5b170da9b97d80d949f28ffc742
diff --git a/quart/datastructures.py b/quart/datastructures.py index <HASH>..<HASH> 100644 --- a/quart/datastructures.py +++ b/quart/datastructures.py @@ -128,6 +128,7 @@ class Authorization: class AcceptOption(NamedTuple): value: str quality: float + parameters: dict class Accept: @@ -136,21 +137,18 @@ class Accept: self.options: List[AcceptOption] = [] for accept_option in parse_http_list(header_value): option, params = parse_header(accept_option) - if 'q' in params: - quality = float(params['q']) - else: - quality = 1.0 - self.options.append(AcceptOption(option, quality)) + quality = float(params.pop('q', 1.0)) + self.options.append(AcceptOption(option, quality, params)) def best_match(self, matches: List[str], default: Optional[str]=None) -> Optional[str]: - best_match = AcceptOption(default, -1.0) + best_match = AcceptOption(default, -1.0, {}) for possible_match in matches: for option in self.options: if ( self._values_match(possible_match, option.value) and option.quality > best_match.quality ): - best_match = AcceptOption(possible_match, option.quality) + best_match = AcceptOption(possible_match, option.quality, {}) return best_match.value def _values_match(self, lhs: str, rhs: str) -> bool: diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py index <HASH>..<HASH> 100644 --- a/tests/test_datastructures.py +++ b/tests/test_datastructures.py @@ -7,8 +7,8 @@ def test_accept() -> None: 'application/vnd.google-earth.kmz;googleearth=context.kmz;q=0.7' ) assert accept.options == [ - AcceptOption(value='application/vnd.google-earth.kml+xml', quality=1.0), - AcceptOption(value='application/vnd.google-earth.kmz', quality=0.7), + AcceptOption('application/vnd.google-earth.kml+xml', 1.0, {'googleearth': 'context.kml'}), + AcceptOption('application/vnd.google-earth.kmz', 0.7, {'googleearth': 'context.kmz'}), ]
Bugfix make params available in Accept options The previous commit (ba2d<I>cadfe<I>ce7f2d<I>e8e8) would strip them out. Note this is a different API to Werkzeug which doesn't parse the params from the value.
pgjones_quart
train
95085ece13847551b08a65eb1d4826a76786870b
diff --git a/lib/pseudohiki/converter.rb b/lib/pseudohiki/converter.rb index <HASH>..<HASH> 100755 --- a/lib/pseudohiki/converter.rb +++ b/lib/pseudohiki/converter.rb @@ -146,10 +146,6 @@ module PseudoHiki @formatter ||= @options.html_template.new end - def create_plain_table_of_contents(tree) - @plain_composer.create_table_of_contents(tree) - end - def create_gfm_table_of_contents(tree) @gfm_composer.create_table_of_contents(tree) end @@ -158,7 +154,7 @@ module PseudoHiki return "" unless @options[:toc] gfm_chosen = @options[:html_version].version == "gfm" return create_gfm_table_of_contents(tree) if gfm_chosen - return create_plain_table_of_contents(tree) unless @options.html_template + return @plain_composer.create_table_of_contents(tree) unless @options.html_template @html_composer.create_table_of_contents(tree) end diff --git a/test/test_pseudohiki2html.rb b/test/test_pseudohiki2html.rb index <HASH>..<HASH> 100644 --- a/test/test_pseudohiki2html.rb +++ b/test/test_pseudohiki2html.rb @@ -161,7 +161,7 @@ HIKI assert_equal(collected_nodes, toc_nodes) end - def test_create_plain_table_of_contents + def test_plain_composer_create_table_of_contents toc_in_plain_text = <<TEXT * Heading1 * Heading2 @@ -171,8 +171,8 @@ TEXT options = OptionManager.new options.set_options_from_command_line - - toc = PageComposer.new(options).create_plain_table_of_contents(@parsed_tree) + page_composer = PageComposer.new(options) + toc = PageComposer::PlainComposer.new(options, page_composer).create_table_of_contents(@parsed_tree) assert_equal(toc_in_plain_text, toc) end
inline method: removed PageComposer#create_plain_table_of_contents()
nico-hn_PseudoHikiParser
train
98ce3b08f535343d42c572da4a57770f40a6590c
diff --git a/test/copy.test.js b/test/copy.test.js index <HASH>..<HASH> 100644 --- a/test/copy.test.js +++ b/test/copy.test.js @@ -9,7 +9,7 @@ var DIR = ''; describe('fs-extra', function() { beforeEach(function(done) { - DIR = testutil.createTempDir(); + DIR = testutil.createTestDir('fs-extra'); done(); }) diff --git a/test/mkdir.test.js b/test/mkdir.test.js index <HASH>..<HASH> 100644 --- a/test/mkdir.test.js +++ b/test/mkdir.test.js @@ -2,11 +2,16 @@ var fs = require('../lib') , path = require('path-extra') , testutil = require('testutil'); +var TEST_DIR = '' + describe('fs-extra', function() { - + beforeEach(function() { + TEST_DIR = testutil.createTestDir('fs-extra') + }) + describe('+ mkdirs()', function() { it('should make the directory', function(done) { - var dir = path.join(path.tempdir(), 'tmp-' + Date.now() + Math.random()); + var dir = path.join(TEST_DIR, 'tmp-' + Date.now() + Math.random()); F (fs.existsSync(dir)); @@ -20,7 +25,7 @@ describe('fs-extra', function() { it('should make the entire directory path', function(done) { var dir = path.join(path.tempdir(), 'tmp-' + Date.now() + Math.random()) - , newDir = path.join(dir, 'dfdf', 'ffff', 'aaa'); + , newDir = path.join(TEST_DIR, 'dfdf', 'ffff', 'aaa'); F (fs.existsSync(dir)); @@ -35,7 +40,7 @@ describe('fs-extra', function() { describe('+ mkdirsSync()', function() { it('should make the directory', function(done) { - var dir = path.join(path.tempdir(), 'tmp-' + Date.now() + Math.random()); + var dir = path.join(TEST_DIR, 'tmp-' + Date.now() + Math.random()); F (fs.existsSync(dir)); fs.mkdirsSync(dir); @@ -45,7 +50,7 @@ describe('fs-extra', function() { }) it('should make the entire directory path', function(done) { - var dir = path.join(path.tempdir(), 'tmp-' + Date.now() + Math.random()) + var dir = path.join(TEST_DIR, 'tmp-' + Date.now() + Math.random()) , newDir = path.join(dir, 'dfdf', 'ffff', 'aaa'); F (fs.existsSync(dir)); diff --git a/test/read.test.js b/test/read.test.js index <HASH>..<HASH> 100644 --- a/test/read.test.js +++ b/test/read.test.js @@ -5,9 +5,8 @@ var fs = require('../lib') var DIR = ''; describe('fs-extra', function() { - beforeEach(function(done) { - DIR = testutil.createTempDir(); - done(); + beforeEach(function() { + DIR = testutil.createTestDir('fs-extra') }) afterEach(function(done) { diff --git a/test/remove.test.js b/test/remove.test.js index <HASH>..<HASH> 100644 --- a/test/remove.test.js +++ b/test/remove.test.js @@ -1,6 +1,6 @@ var crypto = require('crypto') , fs = require('../lib') - , path = require('path-extra') + , path = require('path') , testutil = require('testutil') , mkdir = require('mkdirp'); @@ -15,20 +15,19 @@ var DIR = ''; bytesWritten += 1; } ex = Date.now(); - baseDir = path.join(path.tempdir(), "TEST_fs-extra_rmrf-" + ex); + baseDir = path.join(DIR, "TEST_fs-extra_rmrf-" + ex); fs.mkdirSync(baseDir); fs.writeFileSync(path.join(baseDir, Math.random() + ''), buf); fs.writeFileSync(path.join(baseDir, Math.random() + ''), buf); - subDir = path.join(path.tempdir(), Math.random() + ''); + subDir = path.join(DIR, Math.random() + ''); fs.mkdirSync(subDir); fs.writeFileSync(path.join(subDir, Math.random() + '')); return baseDir; }; describe('fs-extra', function() { - beforeEach(function(done) { - DIR = testutil.createTempDir(); - done(); + beforeEach(function() { + DIR = testutil.createTestDir('fs-extra'); }) afterEach(function(done) {
Changed creation of testing diretories so the /tmp dir is not littered.
jprichardson_node-fs-extra
train
d1fcfa43f02c41053c70e6fcd425de50e102e8ef
diff --git a/src/server/pachyderm_test.go b/src/server/pachyderm_test.go index <HASH>..<HASH> 100644 --- a/src/server/pachyderm_test.go +++ b/src/server/pachyderm_test.go @@ -3174,8 +3174,8 @@ func TestPipelinePartialResourceRequest(t *testing.T) { Cmd: []string{"true"}, }, ResourceSpec: &pps.ResourceSpec{ - Cpu: 0.5, - Gpu: 1, + Cpu: 0.5, + Memory: "100M", }, Inputs: []*pps.PipelineInput{{ Repo: &pfs.Repo{dataRepo}, @@ -3192,7 +3192,7 @@ func TestPipelinePartialResourceRequest(t *testing.T) { Cmd: []string{"true"}, }, ResourceSpec: &pps.ResourceSpec{ - Gpu: 1, + Memory: "100M", }, Inputs: []*pps.PipelineInput{{ Repo: &pfs.Repo{dataRepo},
Remove gpu requests since those won't pass on CI.
pachyderm_pachyderm
train
3a78720bb475c3e73db63eb14cdbb2535a0586f6
diff --git a/flask_application_factory/__init__.py b/flask_application_factory/__init__.py index <HASH>..<HASH> 100644 --- a/flask_application_factory/__init__.py +++ b/flask_application_factory/__init__.py @@ -2,12 +2,13 @@ from .bundle import Bundle from .factory import FlaskApplicationFactory from .factory_hook import FactoryHook from .utils import ( - de_camel, get_boolean_env, get_members, + kebab_case, pluralize, safe_import_module, singularize, + snake_case, title_case, utcnow, ) diff --git a/flask_application_factory/utils.py b/flask_application_factory/utils.py index <HASH>..<HASH> 100644 --- a/flask_application_factory/utils.py +++ b/flask_application_factory/utils.py @@ -22,6 +22,10 @@ def get_members(module, predicate): yield (name, obj) +def kebab_case(string): + return de_camel(string, '-') + + def safe_import_module(module_name): """ Like importlib's import_module, except it does not raise ImportError @@ -34,8 +38,12 @@ def safe_import_module(module_name): raise e +def snake_case(string): + return de_camel(string) + + def title_case(string): - return de_camel(string).replace('_', ' ').title() + return de_camel(string, ' ').title() def utcnow():
do not export de_camel at the package level, add kebab_case and snake_case instead
briancappello_flask-unchained
train