hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
3b066dd8ceb6c39cf6a7dc3fed9b6f373e1eec4a
diff --git a/nitroSdk.js b/nitroSdk.js index <HASH>..<HASH> 100644 --- a/nitroSdk.js +++ b/nitroSdk.js @@ -19,6 +19,8 @@ String.prototype.toCamelCase = function camelize() { }); } +var httpAgent; +var httpsAgent; var dest = {}; var rateLimitEvents = 0; var inFlight = 0; @@ -107,6 +109,7 @@ function makeRequest(host,path,key,query,settings,callback,err){ proto: 'http', port: null, backoff : 31000, + timeout : 120000, payload: {} } @@ -126,11 +129,23 @@ function makeRequest(host,path,key,query,settings,callback,err){ 'User-Agent': settings.User_Agent } }; + var proto = (settings.proto == 'http' ? http : https); + if (settings.proto == 'http') { + if (!httpAgent) { + httpAgent = new http.Agent({ keepAlive: true }); + } + options.agent = httpAgent; + } + else { + if (!httpsAgent) { + httpsAgent = new https.Agent({ keepAlive: true }); + } + options.agent = httpsAgent; + } var list = ''; var obj; var json = (settings.Accept == 'application/json'); - var proto = (settings.proto == 'http' ? http : https); var req = proto.request(options, function(res) { res.setEncoding('utf8'); @@ -222,9 +237,10 @@ function makeRequest(host,path,key,query,settings,callback,err){ debuglog('** '+list); } }); - }); + }).setTimeout(settings.timeout); req.on('error', function(e) { console.log('Problem with request: ' + e.message); + if (list) console.log(list); }); req.end(); }
nitroSdk; set up request agents using keepAlive true
MikeRalphson_bbcparse
train
12aaafc1714da82b3b95ac2f9bd3a3778ef16b2c
diff --git a/test/app/site.js b/test/app/site.js index <HASH>..<HASH> 100644 --- a/test/app/site.js +++ b/test/app/site.js @@ -10,4 +10,19 @@ require("redux") const {render} = require("react-dom") -render(<App />, document.getElementById("app")) +console.log("Increment site.js reload counter...") +window._siteReloadCounter = "_siteReloadCounter" in window ? window._siteReloadCounter + 1 : 0 + + +const MyApp = React.createClass({ + render() { + return window._siteReloadCounter === 0 ? <App /> : ( + <div> + This text should never occur because propagation guards should + stop reloading to app.js + </div> + ) + } +}) + +render(<MyApp />, document.getElementById("app")) diff --git a/test/utils.js b/test/utils.js index <HASH>..<HASH> 100644 --- a/test/utils.js +++ b/test/utils.js @@ -8,7 +8,7 @@ const {exec} = require("shelljs") console.log(resolve(__dirname, "app/src/*")) export function startServer() { execInApp("mkdir -p .src && rm -rf .src/* && cp src/* .src") - //execInApp("mkdir -p node_modules && rm -rf node_modules/livereactload") + execInApp("mkdir -p node_modules && rm -rf node_modules/livereactload") execInApp("npm i") return execInApp("npm start", {async: true}) }
Add test setup in order to test broken reload propagation guards, #<I>
milankinen_livereactload
train
d297703f18a4327e4614e4f1adb199a3a35c7d96
diff --git a/engine/src/main/java/org/camunda/bpm/engine/impl/db/sql/DbSqlSessionFactory.java b/engine/src/main/java/org/camunda/bpm/engine/impl/db/sql/DbSqlSessionFactory.java index <HASH>..<HASH> 100644 --- a/engine/src/main/java/org/camunda/bpm/engine/impl/db/sql/DbSqlSessionFactory.java +++ b/engine/src/main/java/org/camunda/bpm/engine/impl/db/sql/DbSqlSessionFactory.java @@ -294,6 +294,7 @@ public class DbSqlSessionFactory implements SessionFactory { addDatabaseSpecificStatement(ORACLE, "selectHistoricTaskInstanceCountByTaskNameReport", "selectHistoricTaskInstanceCountByTaskNameReport_oracle"); addDatabaseSpecificStatement(ORACLE, "selectFilterByQueryCriteria", "selectFilterByQueryCriteria_oracleDb2"); addDatabaseSpecificStatement(ORACLE, "selectHistoricProcessInstanceIdsForCleanup", "selectHistoricProcessInstanceIdsForCleanup_oracle"); + addDatabaseSpecificStatement(ORACLE, "selectHierarchicalHistoricProcessInstanceIdsForCleanup", "selectHierarchicalHistoricProcessInstanceIdsForCleanup_oracle"); addDatabaseSpecificStatement(ORACLE, "selectHistoricDecisionInstanceIdsForCleanup", "selectHistoricDecisionInstanceIdsForCleanup_oracle"); addDatabaseSpecificStatement(ORACLE, "selectHistoricCaseInstanceIdsForCleanup", "selectHistoricCaseInstanceIdsForCleanup_oracle"); addDatabaseSpecificStatement(ORACLE, "selectHistoricBatchIdsForCleanup", "selectHistoricBatchIdsForCleanup_oracle"); diff --git a/engine/src/main/resources/org/camunda/bpm/engine/impl/mapping/entity/HistoricProcessInstance.xml b/engine/src/main/resources/org/camunda/bpm/engine/impl/mapping/entity/HistoricProcessInstance.xml index <HASH>..<HASH> 100644 --- a/engine/src/main/resources/org/camunda/bpm/engine/impl/mapping/entity/HistoricProcessInstance.xml +++ b/engine/src/main/resources/org/camunda/bpm/engine/impl/mapping/entity/HistoricProcessInstance.xml @@ -486,7 +486,7 @@ </sql> <select id="selectHistoricProcessInstanceIdsForCleanup" parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject" resultType="string"> - SELECT ${limitBeforeWithoutOffset} pi.PROC_INST_ID_, pi.REMOVAL_TIME_ + SELECT ${limitBeforeWithoutOffset} pi.PROC_INST_ID_, pi.END_TIME_ <include refid="selectHistoricProcessInstanceIdsForCleanupSql"/> <include refid="andWhereMinuteInDateBetweenSql"/> ${limitAfterWithoutOffset} diff --git a/engine/src/test/java/org/camunda/bpm/engine/test/api/history/HistoryCleanupTest.java b/engine/src/test/java/org/camunda/bpm/engine/test/api/history/HistoryCleanupTest.java index <HASH>..<HASH> 100644 --- a/engine/src/test/java/org/camunda/bpm/engine/test/api/history/HistoryCleanupTest.java +++ b/engine/src/test/java/org/camunda/bpm/engine/test/api/history/HistoryCleanupTest.java @@ -1278,7 +1278,7 @@ public class HistoryCleanupTest { .singleResult(); // when - ClockUtil.setCurrentTime(DateUtils.addDays(now, 2)); + ClockUtil.setCurrentTime(DateUtils.addSeconds(DateUtils.addDays(now, 1), 1)); runHistoryCleanup(true); assertEquals(expectedInstances, historyService.createHistoricProcessInstanceQuery() @@ -1295,7 +1295,7 @@ public class HistoryCleanupTest { processEngineConfiguration.getTaskService().complete(parentTask.getId()); // then - ClockUtil.setCurrentTime(DateUtils.addDays(now, 4)); + ClockUtil.setCurrentTime(DateUtils.addSeconds(DateUtils.addDays(now, 3), 2)); runHistoryCleanup(true); assertEquals(0, historyService.createHistoricProcessInstanceQuery().processInstanceId(parentProcessInstanceId).count());
fix(engine): add missing oracle query mapping * Map new (hierarchical) cleanup select for Oracle in DbSqlSessionFactory * Adjust timestamps in new test case Related to CAM-<I>
camunda_camunda-bpm-platform
train
f27f2688846a1d56dceabc2b4e55bd3ffc35f530
diff --git a/vyper/parser/stmt.py b/vyper/parser/stmt.py index <HASH>..<HASH> 100644 --- a/vyper/parser/stmt.py +++ b/vyper/parser/stmt.py @@ -176,6 +176,13 @@ class Stmt(object): self.context.set_in_assignment(False) return o + def _check_implicit_conversion(self, var_id, sub): + target_typ = self.context.vars[var_id].typ + assign_typ = sub.typ + if isinstance(target_typ, BaseType) and isinstance(assign_typ, BaseType): + if not assign_typ.is_literal and assign_typ.typ != target_typ.typ: + raise TypeMismatchException('Invalid type {}, expected: {}'.format(assign_typ.typ, target_typ.typ, self.stmt)) + def assign(self): # Assignment (e.g. x[4] = y) if len(self.stmt.targets) != 1: @@ -196,8 +203,7 @@ class Stmt(object): raise VariableDeclarationException("Variable type not defined", self.stmt) # Check against implicit conversion - if isinstance(sub, BaseType) and not sub.typ.is_literal and sub.typ.typ != self.context.vars[self.stmt.targets[0].id].typ.typ: - raise TypeMismatchException('Invalid type {}, expected: {}'.format(sub.typ.typ, self.context.vars[self.stmt.targets[0].id].typ, self.stmt)) + self._check_implicit_conversion(self.stmt.targets[0].id, sub) # Do no allow tuple-to-tuple assignment if isinstance(self.stmt.targets[0], ast.Tuple) and isinstance(self.stmt.value, ast.Tuple):
Refactor implicit conversion checking into its own helper function, add BaseType check for variable being assigned to
ethereum_vyper
train
06e12bf16220ec55e0ac665551c62a5ff8f104d6
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ expect(a).to.equal(b); ### .keys(key1[, key2, ...[, keyN]]) -- **@param** *{ String... | Array }* key*N* +- **@param** *{ String... | Array | Object }* key*N* Asserts that the keyed collection contains all of the passed-in keys. diff --git a/chai-immutable.js b/chai-immutable.js index <HASH>..<HASH> 100644 --- a/chai-immutable.js +++ b/chai-immutable.js @@ -98,7 +98,7 @@ module.exports = function (chai, utils) { * ``` * * @name keys - * @param {String...|Array} keyN + * @param {String...|Array|Object} keyN * @alias key * @api public */ @@ -108,7 +108,10 @@ module.exports = function (chai, utils) { var obj = this._obj; if (obj && obj instanceof KeyedCollection) { - if (utils.type(keys) !== 'array') { + if (utils.type(keys) === 'object') { + keys = Object.keys(keys); + } + else if (utils.type(keys) !== 'array') { keys = Array.prototype.slice.call(arguments); } diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -73,6 +73,10 @@ describe('chai-immutable', function () { it('should accept an Array of keys to check against', function () { expect(mapFoobar).to.have.keys(['bar', 'foo']); }); + + it('should accept an Object to check against', function () { + expect(mapFoobar).to.have.keys({ 'bar': 6, 'foo': 7 }); + }); }); describe('size method', function () {
Make keys assertion also accept an Object and use its keys to check against
astorije_chai-immutable
train
ca48e726cd3c1d75c69dc1bc0014b789cf595c6a
diff --git a/lib/decor/virtuals.js b/lib/decor/virtuals.js index <HASH>..<HASH> 100644 --- a/lib/decor/virtuals.js +++ b/lib/decor/virtuals.js @@ -21,11 +21,11 @@ module.exports = { model.set(property, value); }); } else { - if (loadingModel || !model.load) return; + /*if (loadingModel || !model.load) return; loadingModel = true; model.load(function () { loadingModel = false; - }); + });*/ } }); } diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mojo-models", - "version": "0.1.24", + "version": "0.1.25", "description": "mojo-models ===========", "main": "./lib/index.js", "scripts": { diff --git a/test/model-virtuals-test.js b/test/model-virtuals-test.js index <HASH>..<HASH> 100644 --- a/test/model-virtuals-test.js +++ b/test/model-virtuals-test.js @@ -85,7 +85,7 @@ describe("model-virtuals#", function () { }).now(); }); - it("calls load on a model if a property doesn't exist", function () { + xit("calls load on a model if a property doesn't exist", function () { var i = 0; @@ -106,7 +106,7 @@ describe("model-virtuals#", function () { expect(i).to.be(1); }); - it("doesn't call load more than once", function () { + xit("doesn't call load more than once", function () { var i = 0; var Model = models.Base.extend({ @@ -127,7 +127,7 @@ describe("model-virtuals#", function () { expect(i).to.be(1); }); - it("calls load if a property still doesn't exist", function () { + xit("calls load if a property still doesn't exist", function () { var i = 0; var Model = models.Base.extend({
don't load model if property doesn't exist
crcn_mojo-models
train
0b768ad0d439655bc4463f4d2ccb10ce726c4871
diff --git a/bsdploy/tests/test_bootstrap_mfsbsd.py b/bsdploy/tests/test_bootstrap_mfsbsd.py index <HASH>..<HASH> 100644 --- a/bsdploy/tests/test_bootstrap_mfsbsd.py +++ b/bsdploy/tests/test_bootstrap_mfsbsd.py @@ -131,7 +131,7 @@ def test_bootstrap(bootstrap, put_mock, run_mock, tempdir, yesno_mock): ('sysctl -n kern.disks', {}, 'ada0 cd0\n'), ('ifconfig -l', {}, 'em0 lo0'), ('destroygeom -d ada0 -p system -p tank', {}, ''), - ('zfsinstall -d ada0 -p system -u /cdrom/9.2-RELEASE-amd64 -s 1024M -z 20G', {}, ''), + ('zfsinstall -d ada0 -p system -V 28 -u /cdrom/9.2-RELEASE-amd64 -s 1024M -z 20G', {}, ''), ('gpart add -t freebsd-zfs -l tank_ada0 ada0', {}, ''), ('cp /etc/resolv.conf /mnt/etc/resolv.conf', {}, ''), ('mkdir -p "/mnt/usr/local/etc/pkg/repos"', {'shell': False}, ''),
test adjustment to the fixup of the revert.... (in <I>d7bd<I>ea<I>c<I>c<I>f7c<I>f<I>)
ployground_bsdploy
train
1cdb9c5f78fd07f491846558092ae1d1d09f7e5c
diff --git a/app/patients/edit/route.js b/app/patients/edit/route.js index <HASH>..<HASH> 100644 --- a/app/patients/edit/route.js +++ b/app/patients/edit/route.js @@ -4,9 +4,10 @@ import PatientId from 'hospitalrun/mixins/patient-id'; export default AbstractEditRoute.extend(PatientId, { editTitle: 'Edit Patient', modelName: 'patient', + maxValue: '\uffff', newTitle: 'New Patient', photos: null, - + actions: { appointmentDeleted: function(model) { this.controller.send('appointmentDeleted', model); @@ -44,22 +45,36 @@ export default AbstractEditRoute.extend(PatientId, { setupController: function(controller, model) { this._super(controller, model); //Load appointments, photos and visits asynchronously. - var promises = [], + var maxValue = this.get('maxValue'), + promises = [], patientId = 'patient_'+model.get('id'); - + promises.push(this.store.find('appointment', { - patient: patientId - })); - promises.push(this.store.find('photo', { - patient: patientId + options: { + startkey: [,, patientId, 'appointment_'], + endkey: [maxValue, maxValue, patientId, 'appointment_'+maxValue] + }, + mapReduce: 'appointments_by_date' + })); + promises.push(this.store.find('photo', { + options: { + startkey: [patientId, 'photo_'], + endkey: [patientId, 'photo_'+maxValue] + }, + mapReduce: 'photo_by_patient' })); promises.push(this.store.find('visit', { - patient: patientId + options: { + startkey: [,,, patientId, 'visit_'], + endkey: [maxValue, maxValue, maxValue, patientId, 'visit_'+maxValue] + }, + mapReduce: 'visit_by_patient' })); + Ember.RSVP.all(promises, 'Retrieving patient child objects').then(function(records) { controller.set('appointments', records[0]); controller.set('photos', records[1]); - controller.set('visits', records[2]); + controller.set('visits', records[2]); }); }
Changed to use views to get child records.
HospitalRun_hospitalrun-frontend
train
3083798c97f453c3dbd5c9b16cf91846f69bb26f
diff --git a/src/pharext/Cli/Command.php b/src/pharext/Cli/Command.php index <HASH>..<HASH> 100644 --- a/src/pharext/Cli/Command.php +++ b/src/pharext/Cli/Command.php @@ -3,6 +3,7 @@ namespace pharext\Cli; use pharext\Archive; +use pharext\Metadata; use Phar; @@ -10,7 +11,7 @@ trait Command { /** * Command line arguments - * @var pharext\Cli\Args + * @var Args */ private $args; @@ -28,21 +29,25 @@ trait Command * @return mixed */ public function metadata($key = null) { - if (extension_loaded("Phar")) { - $running = new Phar(Phar::running(false)); - } else { - $running = new Archive(PHAREXT_PHAR); - } + try { + if (extension_loaded("Phar")) { + $running = new Phar(Phar::running(false)); + } else { + $running = new Archive(PHAREXT_PHAR); + } - if ($key === "signature") { - $sig = $running->getSignature(); - return sprintf("%s signature of %s\n%s", - $sig["hash_type"], - $this->metadata("name"), - chunk_split($sig["hash"], 64, "\n")); - } + if ($key === "signature") { + $sig = $running->getSignature(); + return sprintf("%s signature of %s\n%s", + $sig["hash_type"], + $this->metadata("name"), + chunk_split($sig["hash"], 64, "\n")); + } - $metadata = $running->getMetadata(); + $metadata = $running->getMetadata(); + } catch (\Exception $e) { + $metadata = Metadata::all(); + } if (isset($key)) { return $metadata[$key]; }
fix metadata retrieval when not running as phar
pharext_pharext
train
01b061ace943ab26cd5c87965851cb7e1c2e35a9
diff --git a/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/NonblockingSocketClientHandler.java b/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/NonblockingSocketClientHandler.java index <HASH>..<HASH> 100644 --- a/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/NonblockingSocketClientHandler.java +++ b/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/NonblockingSocketClientHandler.java @@ -10,6 +10,7 @@ import net.morimekta.providence.serializer.SerializerException; import net.morimekta.providence.thrift.io.FramedBufferInputSteram; import net.morimekta.providence.thrift.io.FramedBufferOutputStream; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -21,51 +22,70 @@ import java.nio.channels.SocketChannel; * Client handler for thrift RPC using the TNonblockingServer, or similar that * uses the TFramedTransport message wrapper. * - * TODO: Reuse socket channel until closed. + * When using this client handler make sure to close it when no longer in use. + * Otherwise it will keep the socket channel open almost indefinitely. */ -public class NonblockingSocketClientHandler implements PClientHandler { +public class NonblockingSocketClientHandler implements PClientHandler, Closeable { private final Serializer serializer; private final SocketAddress address; + private final int connect_timeout; + private final int read_timeout; + + private SocketChannel channel; public NonblockingSocketClientHandler(Serializer serializer, SocketAddress address) { + this(serializer, address, 10000, 10000); + } + + public NonblockingSocketClientHandler(Serializer serializer, SocketAddress address, int connect_timeout, int read_timeout) { this.serializer = serializer; this.address = address; + this.connect_timeout = connect_timeout; + this.read_timeout = read_timeout; } private SocketChannel connect() throws IOException { - SocketChannel channel = SocketChannel.open(); - Socket socket = channel.socket(); - socket.setSoLinger(false, 0); - socket.setTcpNoDelay(true); - socket.setKeepAlive(true); - socket.setSoTimeout(1000); + if (channel == null) { + channel = SocketChannel.open(); + Socket socket = channel.socket(); + socket.setSoLinger(false, 0); + socket.setTcpNoDelay(true); + socket.setKeepAlive(true); + socket.setSoTimeout(read_timeout); - channel.configureBlocking(true); - if (!channel.connect(address)) { - if (!channel.finishConnect()) { - throw new IOException(); - } + // The channel is always in blocking mode. + channel.configureBlocking(true); + channel.socket().connect(address, connect_timeout); } return channel; } @Override + public void close() throws IOException { + if (channel != null) { + try { + channel.close(); + } finally { + channel = null; + } + } + } + + @Override public <RQ extends PMessage<RQ>, RS extends PMessage<RS>> PServiceCall<RS> handleCall(PServiceCall<RQ> call, PService service) throws IOException, SerializerException { - try (SocketChannel channel = connect()) { - OutputStream out = new FramedBufferOutputStream(channel); - serializer.serialize(out, call); - out.flush(); + SocketChannel channel = connect(); - channel.shutdownOutput(); - channel.configureBlocking(true); + OutputStream out = new FramedBufferOutputStream(channel); + serializer.serialize(out, call); + out.flush(); - if (call.getType() != PServiceCallType.ONEWAY) { - InputStream in = new FramedBufferInputSteram(channel); - return serializer.deserialize(in, service); - } + if (call.getType() != PServiceCallType.ONEWAY) { + InputStream in = new FramedBufferInputSteram(channel); + return serializer.deserialize(in, service); } + return null; } } diff --git a/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/SocketClientHandler.java b/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/SocketClientHandler.java index <HASH>..<HASH> 100644 --- a/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/SocketClientHandler.java +++ b/providence-thrift/src/main/java/net/morimekta/providence/thrift/client/SocketClientHandler.java @@ -23,10 +23,18 @@ import java.net.SocketAddress; public class SocketClientHandler implements PClientHandler { private final Serializer serializer; private final SocketAddress address; + private final int connect_timeout; + private final int read_timeout; public SocketClientHandler(Serializer serializer, SocketAddress address) { + this(serializer, address, 10000, 10000); + } + + public SocketClientHandler(Serializer serializer, SocketAddress address, int connect_timeout, int read_timeout) { this.serializer = serializer; this.address = address; + this.connect_timeout = connect_timeout; + this.read_timeout = read_timeout; } private synchronized Socket connect() throws IOException { @@ -34,7 +42,8 @@ public class SocketClientHandler implements PClientHandler { socket.setSoLinger(false, 0); socket.setTcpNoDelay(true); socket.setKeepAlive(true); - socket.connect(address, 100); + socket.setSoTimeout(read_timeout); + socket.connect(address, connect_timeout); return socket; }
Make thrift clients handle timeouts.
morimekta_providence
train
2941453de87390567560d376fd92ec43c5ea10c7
diff --git a/src/Mpociot/BotMan/Conversation.php b/src/Mpociot/BotMan/Conversation.php index <HASH>..<HASH> 100644 --- a/src/Mpociot/BotMan/Conversation.php +++ b/src/Mpociot/BotMan/Conversation.php @@ -48,13 +48,22 @@ abstract class Conversation public function repeat($question = '') { $conversation = $this->bot->getStoredConversation(); - if (! $question instanceof Question && ! $question) { + + if (!$question instanceof Question && !$question) { $question = unserialize($conversation['question']); } + $next = $conversation['next']; $additionalParameters = unserialize($conversation['additionalParameters']); + if (is_string($next)) { $next = unserialize($next)->getClosure(); + } elseif (is_array($next)) { + $next = collect($next)->map(function($callback) { + $callback['callback'] = unserialize($callback['callback'])->getClosure(); + + return $callback; + })->toArray(); } $this->ask($question, $next, $additionalParameters); }
Make repeat work for array of callbacks too
botman_botman
train
362ac43bf921491a9520e6db4073f66ad103a7fd
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -55,7 +55,11 @@ mod_names.sort() # create extension modules list ext_modules = [] -mod_src_dir = os.path.join('src', 'swig-gp' + gphoto2_version) +mod_src_dir = os.path.join('src', 'swig-bi-gp' + gphoto2_version + + '-py' + str(sys.version_info[0])) +if sys.version_info >= (3, 5) or not os.path.isdir(mod_src_dir): + mod_src_dir = os.path.join('src', 'swig-gp' + gphoto2_version + + '-py' + str(sys.version_info[0])) extra_compile_args = [ '-O3', '-Wno-unused-variable', '-Wno-strict-prototypes', '-Werror'] libraries = list(map(lambda x: x.replace('-l', ''), gphoto2_libs)) @@ -96,43 +100,53 @@ class build_swig(Command): if gp_version not in gp_versions: gp_versions.append(gp_version) self.announce('swigging gphoto2 versions %s' % str(gp_versions), 2) - # make options list - swig_opts = ['-python', '-nodefaultctor', '-O', '-Wextra', '-Werror'] + # do -builtin and not -builtin + swig_bis = [False] swig_version = str(subprocess.check_output( ['swig', '-version'], universal_newlines=True)) for line in swig_version.split('\n'): if 'Version' in line: swig_version = line.split()[-1] - if swig_version != '2.0.11' and sys.version_info < (3, 5): - swig_opts.append('-builtin') + if swig_version != '2.0.11': + swig_bis.append(True) break - if sys.version_info[0] >= 3: - swig_opts.append('-py3') - # do each gphoto2 version - for gp_version in gp_versions: - output_dir = os.path.join('src', 'swig-gp' + gp_version) - self.mkpath(output_dir) - version_opts = [ - '-DGPHOTO2_' + gp_version.replace('.', ''), - '-outdir', output_dir, - ] - inc_dir = os.path.join('include', 'gphoto2-' + gp_version) - if os.path.isdir(inc_dir): - version_opts.append('-I' + inc_dir) - else: - version_opts += gphoto2_include - # do each swig module - for mod_name in mod_names: - in_file = os.path.join('src', 'gphoto2', mod_name + '.i') - out_file = os.path.join(output_dir, mod_name + '_wrap.c') - self.spawn(['swig'] + swig_opts + version_opts + - ['-o', out_file, in_file]) - # create init module - init_file = os.path.join(output_dir, '__init__.py') - with open(init_file, 'w') as im: - im.write('__version__ = "{}"\n\n'.format(version)) + for bi in swig_bis: + # make options list + swig_opts = [ + '-python', '-nodefaultctor', '-O', '-Wextra', '-Werror'] + if bi: + swig_opts.append('-builtin') + if sys.version_info[0] >= 3: + swig_opts.append('-py3') + # do each gphoto2 version + for gp_version in gp_versions: + output_dir = os.path.join('src', 'swig') + if bi: + output_dir += '-bi' + output_dir += '-gp' + gp_version + output_dir += '-py' + str(sys.version_info[0]) + self.mkpath(output_dir) + version_opts = [ + '-DGPHOTO2_' + gp_version.replace('.', ''), + '-outdir', output_dir, + ] + inc_dir = os.path.join('include', 'gphoto2-' + gp_version) + if os.path.isdir(inc_dir): + version_opts.append('-I' + inc_dir) + else: + version_opts += gphoto2_include + # do each swig module for mod_name in mod_names: - im.write('from gphoto2.{} import *\n'.format(mod_name)) + in_file = os.path.join('src', 'gphoto2', mod_name + '.i') + out_file = os.path.join(output_dir, mod_name + '_wrap.c') + self.spawn(['swig'] + swig_opts + version_opts + + ['-o', out_file, in_file]) + # create init module + init_file = os.path.join(output_dir, '__init__.py') + with open(init_file, 'w') as im: + im.write('__version__ = "{}"\n\n'.format(version)) + for mod_name in mod_names: + im.write('from gphoto2.{} import *\n'.format(mod_name)) cmdclass['build_swig'] = build_swig
Easier selection of appropriate SWIG options 'build_swig' now builds both '-builtin' and not built in versions (unless old SWIG with deffective -builtin is in use). 'build' now chooses -builtin unless Python <I> is in use. This should make it safe for Python <I> users to install from PyPI and for anyone to build from source.
jim-easterbrook_python-gphoto2
train
c5535c60314e7444dcc4f56640bd871fae9a1e40
diff --git a/test/Buybrain/Nervus/Adapter/SignalAdapterTest.php b/test/Buybrain/Nervus/Adapter/SignalAdapterTest.php index <HASH>..<HASH> 100644 --- a/test/Buybrain/Nervus/Adapter/SignalAdapterTest.php +++ b/test/Buybrain/Nervus/Adapter/SignalAdapterTest.php @@ -8,6 +8,7 @@ use Buybrain\Nervus\Adapter\Message\SignalRequest; use Buybrain\Nervus\EntityId; use Buybrain\Nervus\MockIO; use PHPUnit_Framework_TestCase; +use RuntimeException; class SignalAdapterTest extends PHPUnit_Framework_TestCase { @@ -15,9 +16,9 @@ class SignalAdapterTest extends PHPUnit_Framework_TestCase { $request = new SignalRequest(); $signal = new Signal([new EntityId('test', '123')]); - $response = new SignalAckRequest(true); + $ackRequest = new SignalAckRequest(true); - $io = (new MockIO())->write($request)->write($response); + $io = (new MockIO())->write($request)->write($ackRequest); $ackResponse = null; $SUT = (new SignalAdapter(new CallableSignaler(function (SignalCallback $callback) use ($signal, &$ackResponse) { @@ -44,9 +45,8 @@ class SignalAdapterTest extends PHPUnit_Framework_TestCase { $io = (new MockIO())->write(new SignalRequest()); - $ackResponse = null; $SUT = (new SignalAdapter(new CallableSignaler(function (SignalCallback $callback) { - throw new \RuntimeException('Oh no'); + throw new RuntimeException('Oh no'); }))) ->in($io->input()) ->out($io->output()) @@ -67,14 +67,15 @@ class SignalAdapterTest extends PHPUnit_Framework_TestCase ->write(new SignalAckRequest(true))// This one will fail, try again ->write(new SignalAckRequest(true)); // This one will succeed - $counter = 0; $SUT = (new SignalAdapter(new CallableSignaler(function (SignalCallback $callback) use (&$counter) { $callback->onSignal([], function ($ack) use (&$counter) { - if ($counter++ === 0) { - throw new \RuntimeException('Oh no'); + $counter++; + if ($counter === 1) { + // First time, error + throw new RuntimeException('Oh no'); } - // okay, no problem + // Second time, no problem }); }))) ->in($io->input())
Little cleaning up in signal adapter test
buybrain_nervus-php
train
65f4dd2e95bfa875b07bdae67c3352d909150a69
diff --git a/lib/jmespath/nodes/subexpression.rb b/lib/jmespath/nodes/subexpression.rb index <HASH>..<HASH> 100644 --- a/lib/jmespath/nodes/subexpression.rb +++ b/lib/jmespath/nodes/subexpression.rb @@ -12,18 +12,52 @@ module JMESPath end def optimize - left = @left.optimize - right = @right.optimize - if left.is_a?(Field) && right.is_a?(Field) - left.chain(right) - else - self - end + Chain.new(flatten).optimize end protected attr_reader :left, :right + + def flatten + nodes = [@left, @right] + until nodes.none? { |node| node.is_a?(Subexpression) } + nodes = nodes.flat_map do |node| + if node.is_a?(Subexpression) + [node.left, node.right] + else + [node] + end + end + end + nodes.map(&:optimize) + end + end + + class Chain + def initialize(children) + @children = children + end + + def visit(value) + @children.reduce(value) do |v, child| + child.visit(v) + end + end + + def optimize + children = @children.dup + index = 0 + while index < children.size - 1 + if children[index].is_a?(Field) && children[index + 1].is_a?(Field) + children[index] = children[index].chain(children[index + 1]) + children.delete_at(index + 1) + else + index += 1 + end + end + Chain.new(children) + end end end end
Flatten runs of Subexpression Also combine runs of Field
jmespath_jmespath.rb
train
2c92ea635ed01288772a89ac0568abc368c09de6
diff --git a/src/runner.js b/src/runner.js index <HASH>..<HASH> 100644 --- a/src/runner.js +++ b/src/runner.js @@ -146,16 +146,16 @@ function deepEquals(x, y) { return arrayEquals(x, y) } } - else if (isObject(x)) { - if (isObject(y)) { - return objectEquals(x, y) - } - } else if (isSet(x)) { if (isSet(y)) { return setEquals(x, y) } } + else if (isObject(x)) { + if (isObject(y)) { + return objectEquals(x, y) + } + } else if (x === y) { return true }
fix: stop doing object comparison on sets
aleclarson_testpass
train
e88c8b026096710289d3d9342fbd490956b576fd
diff --git a/src/board.py b/src/board.py index <HASH>..<HASH> 100644 --- a/src/board.py +++ b/src/board.py @@ -124,6 +124,9 @@ elif board_id == ap_board.ORANGE_PI_3: elif board_id == ap_board.BANANA_PI_M2_ZERO: from adafruit_blinka.board.bananapi.bpim2zero import * +elif board_id == ap_board.BANANA_PI_M5: + from adafruit_blinka.board.bananapi.bpim5 import * + elif board_id == ap_board.GIANT_BOARD: from adafruit_blinka.board.giantboard import *
Add Banana Pi M5 support to board.py
adafruit_Adafruit_Blinka
train
9fa0f84503e1175ab256e8c65355f92424a89d68
diff --git a/integration_tests/benchmarks/index.js b/integration_tests/benchmarks/index.js index <HASH>..<HASH> 100644 --- a/integration_tests/benchmarks/index.js +++ b/integration_tests/benchmarks/index.js @@ -56,7 +56,7 @@ async function runBenchmark(artifactsDir, modelName, config) { const trainTimeMs = (trainEndMs - trainBeginMs) / benchmarkData.train_epochs; // Perform predict() burn-in. - tfc.tidy(() => { + return tfc.tidy(() => { let output; for (let i = 0; i < PREDICT_BURNINS; ++i) { output = tfc.tidy(() => { @@ -73,14 +73,14 @@ async function runBenchmark(artifactsDir, modelName, config) { // After all the model.predict() calls, invoke dataSync() once to let the // scheduled GPU operations complete before proceeding. output.dataSync(); + const predictEndMs = performance.now(); + const predictTimeMs = (predictEndMs - predictBeginMs) / PREDICT_RUNS; + return { + originalData: benchmarkData, + predictTimeMs: predictTimeMs, + trainTimeMs: trainTimeMs, + }; }); - const predictEndMs = performance.now(); - const predictTimeMs = (predictEndMs - predictBeginMs) / PREDICT_RUNS; - return { - originalData: benchmarkData, - predictTimeMs: predictTimeMs, - trainTimeMs: trainTimeMs, - }; } function getRunAllBenchmarks(artifactsDir, benchmarks) {
Fix bad bug in benchmarks (#<I>) * Fix bad bug in benchmarks
tensorflow_tfjs
train
d04aa08b194ed5cd853f7265863e36e52424f546
diff --git a/quarkc/lib/datawire-quark-core.rb b/quarkc/lib/datawire-quark-core.rb index <HASH>..<HASH> 100644 --- a/quarkc/lib/datawire-quark-core.rb +++ b/quarkc/lib/datawire-quark-core.rb @@ -1043,12 +1043,8 @@ module DatawireQuarkCore end def self.cast(value, &block) - type = begin block.call rescue Object end - - unless value.is_a?(type) || value.nil? - raise TypeError, "`#{value.inspect}` is not an instance of `#{type}`" - end - + # For now there is no easy way to check in Ruby that Quark class C is + # subclass of of Quark class B, so don't check anything until that's fixed. value end diff --git a/quarkc/lib/quark_runtime.js b/quarkc/lib/quark_runtime.js index <HASH>..<HASH> 100644 --- a/quarkc/lib/quark_runtime.js +++ b/quarkc/lib/quark_runtime.js @@ -73,20 +73,10 @@ } function cast(value, callback) { - try { - var type = callback(); - if (value == null || is_instance_of(value, type)) { - return value; - } else { - throw TypeError, - '`' + value + '` is not an instance of `' + type + '`'; - } - } catch (error) { - if (error instanceof ReferenceError) { - return value; - } - throw error; - } + // For now there is no easy way to check in Javascript that Quark class + // C is subclass of of Quark class B, so don't check anything until + // that's fixed. + return value; } exports.cast = cast; diff --git a/quarkc/lib/quark_runtime.py b/quarkc/lib/quark_runtime.py index <HASH>..<HASH> 100644 --- a/quarkc/lib/quark_runtime.py +++ b/quarkc/lib/quark_runtime.py @@ -63,17 +63,9 @@ def _map_remove(m, key): return None def _cast(value, callback): - try: - type = callback() - except: - type = object - if type is unicode: - type = (unicode, str) - if isinstance(value, type) or value is None: - return value - else: - template = '`{value}` is not an instance of `{type}`'.format - raise TypeError(template(value=repr(value), type=type)) + # For now there is no easy way to check in Python that Quark class C is + # subclass of of Quark class B, so don't check anything until that's fixed. + return value class _JSONObject(object): _backend = json diff --git a/quarkc/test/lib/casting_test.q b/quarkc/test/lib/casting_test.q index <HASH>..<HASH> 100644 --- a/quarkc/test/lib/casting_test.q +++ b/quarkc/test/lib/casting_test.q @@ -53,7 +53,6 @@ class CastingTest { local.C asSuperFromObject = ?asObject; checkEqual(d, asSuperFromObject); } - } void main(List<String> args) {
Disable runtime type checking on Python, Javascript and Ruby (hopefully temporarily) since it's blocking Promise usage.
datawire_quark
train
001e42124934411925e03dcaee0ed37da2f45626
diff --git a/src-test/morfologik/fsa/FSA5Test.java b/src-test/morfologik/fsa/FSA5Test.java index <HASH>..<HASH> 100644 --- a/src-test/morfologik/fsa/FSA5Test.java +++ b/src-test/morfologik/fsa/FSA5Test.java @@ -60,9 +60,9 @@ public final class FSA5Test { final FSA fsa3 = Dictionary.getForLanguage("pl").fsa; FSAInfo info3 = new FSAInfo(fsa3); - assertEquals(297009, info3.nodeCount); - assertEquals(665415, info3.arcsCount); - assertEquals(3564930, info3.finalStatesCount); + assertEquals(299903, info3.nodeCount); + assertEquals(687834, info3.arcsCount); + assertEquals(3565575, info3.finalStatesCount); } @Test
JUnit test corrected after dictionary update.
morfologik_morfologik-stemming
train
b1dba206ab55a371c0645d9a274c6dbd6f314683
diff --git a/test/1_process_engine/parallel_gateway_test.js b/test/1_process_engine/parallel_gateway_test.js index <HASH>..<HASH> 100644 --- a/test/1_process_engine/parallel_gateway_test.js +++ b/test/1_process_engine/parallel_gateway_test.js @@ -1,7 +1,7 @@ 'use strict'; const should = require('should'); -const TestFixtureProvider = require('../../dist/commonjs').TestFixtureProvider; +const {TestFixtureProvider} = require('../../dist/commonjs'); describe('Parallel Gateway execution', () => { @@ -21,7 +21,7 @@ describe('Parallel Gateway execution', () => { await testFixtureProvider.tearDown(); }); - it('should successfully run multiple parallel running branchs and return each result with the token.', async () => { + it('should successfully run multiple parallel branchs and return each result with the token.', async () => { const processModelId = 'parallel_gateway_test'; const result = await testFixtureProvider.executeProcess(processModelId, startEventId); diff --git a/test/1_process_engine/user_task_tests.js b/test/1_process_engine/user_task_tests.js index <HASH>..<HASH> 100644 --- a/test/1_process_engine/user_task_tests.js +++ b/test/1_process_engine/user_task_tests.js @@ -3,8 +3,7 @@ const uuid = require('uuid'); const should = require('should'); -const TestFixtureProvider = require('../../dist/commonjs').TestFixtureProvider; -const ProcessInstanceHandler = require('../../dist/commonjs').ProcessInstanceHandler; +const {ProcessInstanceHandler, TestFixtureProvider} = require('../../dist/commonjs'); describe('UserTasks - ', () => {
:recycle: :white_check_mark: Use short-form imports in some tests
process-engine_process_engine_runtime
train
a1e34db592a0df4e900eee72351409928b5ede3b
diff --git a/tools/format.js b/tools/format.js index <HASH>..<HASH> 100755 --- a/tools/format.js +++ b/tools/format.js @@ -6,7 +6,9 @@ require('colors'); var fs = require('fs'); var program = require('commander'); -require('../node_modules/babel-core/register'); +require('babel-register')({ + presets: ['es2015'] +}); var Resolver = require('../src/lib/resolver'); var MockContext = require('../tests/lib/resolver/header').MockContext; var lang = require('../src/lib/mocks').lang;
Fix tools/format to work with babel6
l20n_l20n.js
train
4ca83e4c25d6cb1c97be6a2e1177d916355f274e
diff --git a/examples/crypton/app.js b/examples/crypton/app.js index <HASH>..<HASH> 100644 --- a/examples/crypton/app.js +++ b/examples/crypton/app.js @@ -8,12 +8,7 @@ function start (session) { options: { session: session } - }); - - setTimeout(function () { - // render the result of an ls() on page log - displayFiles(); - }, 1000); + }, displayFiles); // when a delete button is clicked $('#files .file .delete').live('click', function (e) { diff --git a/src/core.js b/src/core.js index <HASH>..<HASH> 100644 --- a/src/core.js +++ b/src/core.js @@ -1,7 +1,7 @@ 'use strict'; -var Crate = function Crate (options) { +var Crate = function Crate (options, callback) { options = options || {}; var driver = options.driver || 'memory'; @@ -12,6 +12,8 @@ var Crate = function Crate (options) { this.superblock = new Crate.Superblock({ system: this + }, function () { + callback(); }); };
don't wait a second for files to be ready - add fs init callback
ecto_crate
train
3166adb9a40013b26f54588415c525c30e7d856b
diff --git a/axes/middleware.py b/axes/middleware.py index <HASH>..<HASH> 100644 --- a/axes/middleware.py +++ b/axes/middleware.py @@ -1,31 +1,11 @@ -from django.contrib import admin from django.contrib.auth import views as auth_views + from axes.decorators import watch_login class FailedLoginMiddleware(object): - def __init__(self, *args, **kwargs): super(FailedLoginMiddleware, self).__init__(*args, **kwargs) - # watch the admin login page - admin.site.login = watch_login(admin.site.login) - - # and the regular auth login page - auth_views.login = watch_login(auth_views.login) - - -class FailedAdminLoginMiddleware(object): - def __init__(self, *args, **kwargs): - super(FailedAdminLoginMiddleware, self).__init__(*args, **kwargs) - - # watch the admin login page - admin.site.login = watch_login(admin.site.login) - - -class FailedAuthLoginMiddleware(object): - def __init__(self, *args, **kwargs): - super(FailedAuthLoginMiddleware, self).__init__(*args, **kwargs) - - # watch the admin login page + # watch the auth login auth_views.login = watch_login(auth_views.login)
Removed duplicated watching for the login function, because admin uses the login function from auth.views too. Fixes #<I>
jazzband_django-axes
train
9dfdc3eb3668971523d7d2f24f87f5b1333b545a
diff --git a/tsdb/index/postings_test.go b/tsdb/index/postings_test.go index <HASH>..<HASH> 100644 --- a/tsdb/index/postings_test.go +++ b/tsdb/index/postings_test.go @@ -818,10 +818,13 @@ func TestWithoutPostings(t *testing.T) { func BenchmarkPostings_Stats(b *testing.B) { p := NewMemPostings() + var seriesID uint64 + createPostingsLabelValues := func(name, valuePrefix string, count int) { for n := 1; n < count; n++ { value := fmt.Sprintf("%s-%d", valuePrefix, n) - p.Add(uint64(n), labels.FromStrings(name, value)) + p.Add(seriesID, labels.FromStrings(name, value)) + seriesID++ } }
Speed up BenchmarkPostings_Stats (#<I>) The previous code re-used series IDs 1-<I> many times over, so a lot of time was spent ensuring the lists of series were in ascending order. The intended use of `MemPostings.Add()` is that all series IDs are unique, and changing the benchmark to do this lets it finish ten times faster. (It doesn't affect the benchmark result, just the setup code)
prometheus_prometheus
train
e0c7837a70912a285ca6b336b3aea03f0ec48a34
diff --git a/server/irc/state.js b/server/irc/state.js index <HASH>..<HASH> 100755 --- a/server/irc/state.js +++ b/server/irc/state.js @@ -17,11 +17,19 @@ var State = function (client, save_state) { this.client.on('dispose', function () { if (!that.save_state) { _.each(that.irc_connections, function (irc_connection, i, cons) { - if (irc_connection) { + if (!irc_connection) { + return; + } + + if (irc_connection.connected) { + irc_connection.once('close', irc_connection.dispose.bind(irc_connection)); irc_connection.end('QUIT :' + (irc_connection.quit_message || global.config.quit_message || '')); - global.servers.removeConnection(irc_connection); - cons[i] = null; + } else { + irc_connection.dispose(); } + + global.servers.removeConnection(irc_connection); + cons[i] = null; }); that.dispose();
Disposing IrcConnection object correctly when Client is disposed
prawnsalad_KiwiIRC
train
4141b823bb81404efdb1178335440af2c2d53772
diff --git a/lib/version.rb b/lib/version.rb index <HASH>..<HASH> 100644 --- a/lib/version.rb +++ b/lib/version.rb @@ -1,3 +1,3 @@ module JekyllToc - VERSION = '0.8.0'.freeze + VERSION = '0.9.0.beta1'.freeze end
Strat developing <I>.beta1
toshimaru_jekyll-toc
train
40828c7ad823a5f9677cf1043c85e91ce9253202
diff --git a/holoviews/streams.py b/holoviews/streams.py index <HASH>..<HASH> 100644 --- a/holoviews/streams.py +++ b/holoviews/streams.py @@ -14,6 +14,9 @@ from .core import util from contextlib import contextmanager +# Types supported by Pointer derived streams +pointer_types = (Number, util.basestring, tuple)+util.datetime_types + @contextmanager def triggering_streams(streams): @@ -559,7 +562,7 @@ class PointerX(LinkedStream): plot bounds, the position is set to None. """ - x = param.ClassSelector(class_=(Number, util.basestring), default=None, + x = param.ClassSelector(class_=pointer_types, default=None, constant=True, doc=""" Pointer position along the x-axis in data coordinates""") @@ -575,7 +578,7 @@ class PointerY(LinkedStream): """ - y = param.ClassSelector(class_=(Number, util.basestring), default=None, + y = param.ClassSelector(class_=pointer_types, default=None, constant=True, doc=""" Pointer position along the y-axis in data coordinates""") @@ -590,11 +593,11 @@ class PointerXY(LinkedStream): the plot bounds, the position values are set to None. """ - x = param.ClassSelector(class_=(Number, util.basestring, tuple), default=None, + x = param.ClassSelector(class_=pointer_types, default=None, constant=True, doc=""" Pointer position along the x-axis in data coordinates""") - y = param.ClassSelector(class_=(Number, util.basestring, tuple), default=None, + y = param.ClassSelector(class_=pointer_types, default=None, constant=True, doc=""" Pointer position along the y-axis in data coordinates""")
Added support for date types on Pointer derived streams (#<I>)
pyviz_holoviews
train
6aeeaf7a5cbb4b9f0448fb5362de679f8668754d
diff --git a/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/RuleTester.java b/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/RuleTester.java index <HASH>..<HASH> 100644 --- a/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/RuleTester.java +++ b/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/RuleTester.java @@ -26,6 +26,7 @@ import com.google.common.collect.ImmutableMap; import java.io.Closeable; import java.util.List; +import java.util.Map; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static java.util.Collections.emptyList; @@ -49,11 +50,21 @@ public class RuleTester public RuleTester(List<Plugin> plugins) { - session = testSessionBuilder() + this(plugins, ImmutableMap.of()); + } + + public RuleTester(List<Plugin> plugins, Map<String, String> properties) + { + Session.SessionBuilder sessionBuilder = testSessionBuilder() .setCatalog(CATALOG_ID) .setSchema("tiny") - .setSystemProperty("task_concurrency", "1") // these tests don't handle exchanges from local parallel - .build(); + .setSystemProperty("task_concurrency", "1"); // these tests don't handle exchanges from local parallel + + for (Map.Entry<String, String> entry : properties.entrySet()) { + sessionBuilder.setSystemProperty(entry.getKey(), entry.getValue()); + } + + session = sessionBuilder.build(); queryRunner = new LocalQueryRunner(session); queryRunner.createCatalog(session.getCatalog().get(),
Accept system properties in RuleTester
prestodb_presto
train
ab1bf389c892b9232161f0a72f7bb5d8ac531b74
diff --git a/hangups/ui/__main__.py b/hangups/ui/__main__.py index <HASH>..<HASH> 100644 --- a/hangups/ui/__main__.py +++ b/hangups/ui/__main__.py @@ -716,6 +716,7 @@ class ConversationEventListWalker(urwid.ListWalker): self._conversation.on_watermark_notification.add_observer( self._on_watermark_notification ) + super().__init__() def _handle_event(self, conv_event): """Handle updating and scrolling when a new event is added.
Fix pylint warning after upgrading urwid
tdryer_hangups
train
ddc8a59192f27b327061dd16b718592fc944d0ba
diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index <HASH>..<HASH> 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -9,8 +9,8 @@ }, { "ImportPath": "github.com/bitrise-io/envman/models", - "Comment": "0.9.3-16-gf513cb3", - "Rev": "f513cb3c57d3876d703fa2597d7f720b8a664211" + "Comment": "0.9.3-17-g1dbd994", + "Rev": "1dbd994f891c5dbbf3ac3afab707e8b88762fcb4" }, { "ImportPath": "github.com/bitrise-io/go-utils/cmdex", diff --git a/cli/share_create.go b/cli/share_create.go index <HASH>..<HASH> 100644 --- a/cli/share_create.go +++ b/cli/share_create.go @@ -64,6 +64,9 @@ func create(c *cli.Context) { Git: gitURI, Commit: commit, } + if err := stepModel.ValidateStep(true); err != nil { + log.Fatal(err) + } // Copy step.yml to steplib share, err := ReadShareSteplibFromFile() diff --git a/models/models_methods.go b/models/models_methods.go index <HASH>..<HASH> 100644 --- a/models/models_methods.go +++ b/models/models_methods.go @@ -3,6 +3,7 @@ package models import ( "errors" "fmt" + "strings" envmanModels "github.com/bitrise-io/envman/models" "github.com/bitrise-io/go-utils/pointers" @@ -62,6 +63,14 @@ func (source StepSourceModel) ValidateSource() error { if source.Git == "" { return errors.New("Invalid step: missing or empty required 'source.git' property") } + + if !strings.HasPrefix(source.Git, "http://") && !strings.HasPrefix(source.Git, "https://") { + return errors.New("Invalid step: step source should start with http:// or https://") + } + if !strings.HasSuffix(source.Git, ".git") { + return errors.New("Invalid step: step source should ends with .git") + } + if source.Commit == "" { return errors.New("Invalid step: missing or empty required 'source.commit' property") } diff --git a/models/models_methods_test.go b/models/models_methods_test.go index <HASH>..<HASH> 100644 --- a/models/models_methods_test.go +++ b/models/models_methods_test.go @@ -31,6 +31,75 @@ var ( testValueOptions = []string{testKey2, testValue2} ) +func TestValidateStep(t *testing.T) { + step := StepModel{ + Title: pointers.NewStringPtr("title"), + Summary: pointers.NewStringPtr("summary"), + Website: pointers.NewStringPtr("website"), + Source: StepSourceModel{ + Git: "https://github.com/bitrise-io/bitrise.git", + Commit: "1e1482141079fc12def64d88cb7825b8f1cb1dc3", + }, + } + + if err := step.ValidateStep(true); err != nil { + t.Fatal(err) + } + + step.Title = nil + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: no Title defined") + } + step.Title = new(string) + + *step.Title = "" + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: empty Title") + } + + step.Description = nil + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: no Description defined") + } + step.Description = new(string) + + *step.Description = "" + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: empty Description") + } + + step.Website = nil + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: no Website defined") + } + step.Website = new(string) + + *step.Website = "" + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: empty Website") + } + + step.Source.Git = "" + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: empty Source.Git") + } + + step.Source.Git = "[email protected]:bitrise-io/bitrise.git" + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: Source.Git has invalid prefix") + } + + step.Source.Git = "https://github.com/bitrise-io/bitrise" + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: Source.Git has invalid suffix") + } + + step.Source.Commit = "" + if err := step.ValidateStep(true); err == nil { + t.Fatal("Invalid step: empty Source.Commit") + } +} + func TestValidateStepInputOutputModel(t *testing.T) { // Filled env env := envmanModels.EnvironmentItemModel{ @@ -86,9 +155,6 @@ func TestValidateStepInputOutputModel(t *testing.T) { } } -// func TestNormalize(t *testing.T) { -// } - func TestFillMissingDefaults(t *testing.T) { title := "name 1" // desc := "desc 1"
PR fixes (<I> squashed commit) Squashed commits: [<I>f<I>] godep-update (<I> squashed commits) Squashed commits: [f8a<I>b] code style [<I>] validate step source
bitrise-io_stepman
train
b641f0f6eea2979604cb5e785b581bfeb54bfcf5
diff --git a/themes/phenomic-theme-base/webpack.config.babel.js b/themes/phenomic-theme-base/webpack.config.babel.js index <HASH>..<HASH> 100644 --- a/themes/phenomic-theme-base/webpack.config.babel.js +++ b/themes/phenomic-theme-base/webpack.config.babel.js @@ -47,7 +47,7 @@ export const makeConfig = (config = {}) => { ], loaders: [ "babel-loader?cacheDirectory=true", - "eslint-loader?fix", + "eslint-loader", ], },
Removed: eslint-loader "fix" option has been removed from theme-base (#<I>) Closes #<I>.
phenomic_phenomic
train
ff693eb143afecb9d30739d9b22c4687aff0f26f
diff --git a/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_6_0.java b/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_6_0.java index <HASH>..<HASH> 100644 --- a/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_6_0.java +++ b/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_6_0.java @@ -1353,6 +1353,7 @@ public final class InfinispanSubsystemXMLReader_6_0 implements XMLElementReader< case NAME: { name = value; BaseLoaderResource.NAME.parseAndSetParameter(value, loader, reader); + break; } case SHARED: { BaseLoaderResource.SHARED.parseAndSetParameter(value, loader, reader); @@ -1374,6 +1375,7 @@ public final class InfinispanSubsystemXMLReader_6_0 implements XMLElementReader< case NAME: { name = value; BaseStoreResource.NAME.parseAndSetParameter(value, store, reader); + break; } case SHARED: { BaseStoreResource.SHARED.parseAndSetParameter(value, store, reader); diff --git a/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_7_0.java b/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_7_0.java index <HASH>..<HASH> 100644 --- a/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_7_0.java +++ b/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/InfinispanSubsystemXMLReader_7_0.java @@ -1448,6 +1448,7 @@ public final class InfinispanSubsystemXMLReader_7_0 implements XMLElementReader< case NAME: { name = value; BaseLoaderResource.NAME.parseAndSetParameter(value, loader, reader); + break; } case SHARED: { BaseLoaderResource.SHARED.parseAndSetParameter(value, loader, reader); @@ -1469,6 +1470,7 @@ public final class InfinispanSubsystemXMLReader_7_0 implements XMLElementReader< case NAME: { name = value; BaseStoreResource.NAME.parseAndSetParameter(value, store, reader); + break; } case SHARED: { BaseStoreResource.SHARED.parseAndSetParameter(value, store, reader);
ISPN-<I> Custom cache store and cache loader sets SHARED attribute to the value of NAME attribute
infinispan_infinispan
train
cbc39d5c0a74846a40e02cafdc4bad4399a00d31
diff --git a/lib/core/engine/collector.js b/lib/core/engine/collector.js index <HASH>..<HASH> 100644 --- a/lib/core/engine/collector.js +++ b/lib/core/engine/collector.js @@ -113,7 +113,7 @@ class Collector { results.info.description = allData.description; results.info.title = allData.title; - if (allData.screenshots.length > 0) { + if (allData.screenshots && allData.screenshots.length > 0) { results.files.screenshot.push(allData.screenshots); }
Catch if navigation fails so the result is still generated. (#<I>)
sitespeedio_browsertime
train
b444a08306fdb95a2eee2926a5b3f962d4522212
diff --git a/formats/gff.py b/formats/gff.py index <HASH>..<HASH> 100644 --- a/formats/gff.py +++ b/formats/gff.py @@ -239,27 +239,15 @@ def get_piles(allgenes): """ Before running uniq, we need to compute all the piles. The piles are a set of redundant features we want to get rid of. Input are a list of GffLines - features. Output is a Grouper object that contain distinct "piles". - """ - from jcvi.utils.grouper import Grouper - from jcvi.utils.range import range_overlap - - g = Grouper() - ngenes = len(allgenes) - - for i, a in enumerate(allgenes): - arange = (a.seqid, a.start, a.end) - g.join(a) - for j in xrange(i + 1, ngenes): - b = allgenes[j] - brange = (b.seqid, b.start, b.end) - g.join(b) - if range_overlap(arange, brange): - g.join(a, b) - else: - break + features. Output are list of list of features distinct "piles". + """ + from jcvi.utils.range import Range, range_piles + + ranges = [Range(a.seqid, a.start, a.end, 0, i) \ + for i, a in enumerate(allgenes)] - return g + for pile in range_piles(ranges): + yield [allgenes[x] for x in pile] def uniq(args): diff --git a/utils/range.py b/utils/range.py index <HASH>..<HASH> 100644 --- a/utils/range.py +++ b/utils/range.py @@ -238,6 +238,32 @@ def _make_endpoints(ranges): return sorted(endpoints) +def range_piles(ranges): + """ + Return piles of intervals that overlap. The piles are only interrupted by + regions of zero coverage. + + >>> ranges = [Range("2", 0, 1, 3, 0), Range("2", 1, 4, 3, 1), Range("3", 5, 7, 3, 2)] + >>> list(range_piles(ranges)) + [[0, 1], [2]] + """ + endpoints = _make_endpoints(ranges) + + for seqid, ends in groupby(endpoints, lambda x: x[0]): + active = [] + depth = 0 + for seqid, pos, leftright, i, score in ends: + if leftright == LEFT: + active.append(i) + depth += 1 + else: + depth -= 1 + + if depth == 0 and active: + yield active + active = [] + + def range_conflict(ranges, depth=1): """ Find intervals that are overlapping in 1-dimension. @@ -245,7 +271,7 @@ def range_conflict(ranges, depth=1): >>> ranges = [Range("2", 0, 1, 3, 0), Range("2", 1, 4, 3, 1), Range("3", 5, 7, 3, 2)] >>> list(range_conflict(ranges)) - [[Range(seqid='2', start=0, end=1, score=3, id=0), Range(seqid='2', start=1, end=4, score=3, id=1)]] + [(0, 1)] """ overlap = set() active = set() @@ -263,8 +289,7 @@ def range_conflict(ranges, depth=1): overlap.add(tuple(sorted(active))) for ov in overlap: - selected = [ranges[x] for x in ov] - yield selected + yield ov def range_chain(ranges):
improve run time performance for formats.gff.uniq()
tanghaibao_jcvi
train
f16fcdfc6e0195e4b7b2e338c34f4aa8c5e80f48
diff --git a/src/Processor/Link.php b/src/Processor/Link.php index <HASH>..<HASH> 100755 --- a/src/Processor/Link.php +++ b/src/Processor/Link.php @@ -135,7 +135,11 @@ class Link implements ProcessorInterface if (isset($config['link-file'])) { return $config['link-file']; } - $target = Handler\AbstractHandler::getTarget(); + if (isset($config['color-only'])) { + $target=Handler\AbstractHandler::getColor(); + } else { + $target = Handler\AbstractHandler::getTarget(); + } if (isset($config['use-hostname'])) { $hostname=gethostname(); $target=$target.'_'.$hostname;
introduce color-only for link-type
20steps_bricks-platform-composer-extras
train
a30bb57aa16cb6290eda37c4045546a2c83cea7c
diff --git a/estnltk/annotation_validator.py b/estnltk/annotation_validator.py index <HASH>..<HASH> 100644 --- a/estnltk/annotation_validator.py +++ b/estnltk/annotation_validator.py @@ -285,3 +285,31 @@ def find_short_sentences_generator( text: 'Text', min_words:int=2 ): results['sentences'].append( next_sent ) yield results + +def find_sentences_containing_paragraphs_generator( text: 'Text', + max_paragraph_endings:int = 3 ): + ''' Analyses given Text object, and yields sentences which contain + more than max_paragraph_endings paragraph markers ('\n\n'). + It is possible that such sentences consist of (many) smaller + sentences mistakenly joined together. + + As a result, yields a dict containing start/end position of the + detected sentence (under keys 'start' and 'end'). + ''' + # Check the layer requirements + requirements = ['words', 'sentences'] + for requirement in requirements: + assert requirement in text.layers, \ + '(!) The input text is missing the layer "'+requirement+'"!' + # Iterate over sentences and detect mistakenly joined ones + words_spans = text['words'].spans + sentence_spans = text['sentences'].spans + for sid, sentence in enumerate( sentence_spans ): + content = sentence.enclosing_text + if content.count('\n\n') > max_paragraph_endings: + # The sentence is "suspiciously long" + # (contains a paragraph change) + results = { 'start': sentence.start, \ + 'end': sentence.end } + yield results + diff --git a/estnltk/tests/test_tokenizers/test_sentence_tokenizer.py b/estnltk/tests/test_tokenizers/test_sentence_tokenizer.py index <HASH>..<HASH> 100644 --- a/estnltk/tests/test_tokenizers/test_sentence_tokenizer.py +++ b/estnltk/tests/test_tokenizers/test_sentence_tokenizer.py @@ -451,7 +451,10 @@ def test_merge_mistakenly_split_sentences_5(): 'expected_sentence_texts': ["siin kommentaariumis ongi läbilõige 00nia ühiskonnast.", "M.O.T.T. igaüks sikutab vankrit enda poole"] }, \ { 'text': "Lisaks sellele valiti nominentide hulgast välja neli edukat turismiobjekti/ projekti, milleks said Vanaõue Puhkekeskus, Otepää Golf, Kalevipoja Uisumaraton ja MTÜ R.A.A.A.M. teatrietendused Suurel Munamäel", \ 'expected_sentence_texts': ["Lisaks sellele valiti nominentide hulgast välja neli edukat turismiobjekti/ projekti, milleks said Vanaõue Puhkekeskus, Otepää Golf, Kalevipoja Uisumaraton ja MTÜ R.A.A.A.M. teatrietendused Suurel Munamäel"] }, \ - + + { 'text': "Selle seltsi mainekamate uurijatena tuleb nimetada G. Adelheimi, O. M. von Stackelbergi ja E. von Notbecki.", \ + 'expected_sentence_texts': ["Selle seltsi mainekamate uurijatena tuleb nimetada G. Adelheimi, O. M. von Stackelbergi ja E. von Notbecki."] }, \ + ] for test_text in test_texts: text = Text( test_text['text'] )
Updated annotation validator: detection of sentences containing paragraph endings
estnltk_estnltk
train
3a5bf8d280eb817107bde9f6b6f423c30196bd0d
diff --git a/tests/AllTests.php b/tests/AllTests.php index <HASH>..<HASH> 100644 --- a/tests/AllTests.php +++ b/tests/AllTests.php @@ -10,12 +10,9 @@ class AllTests { public static function suite() { - $suite = new \PHPUnit_Framework_TestSuite('ErdikoTests'); $testFiles = AllTests::_getTestFiles(); - - foreach ($testFiles as $file) { - $suite->addTestFile($file); - } + $suite = new \PHPUnit_Framework_TestSuite(array_shift($testFiles),'ErdikoUsersTest'); + $suite->addTestFiles($testFiles); return $suite; }
ER-<I> * Improved AllTests class
Erdiko_authorize
train
19ec2ef81424251ce73437b92dfe976c2372d67f
diff --git a/vstutils/api/filter_backends.py b/vstutils/api/filter_backends.py index <HASH>..<HASH> 100644 --- a/vstutils/api/filter_backends.py +++ b/vstutils/api/filter_backends.py @@ -4,8 +4,7 @@ from django.utils.encoding import force_str from django.db import models from rest_framework.filters import BaseFilterBackend, OrderingFilter from django_filters.rest_framework.backends import DjangoFilterBackend as BaseDjangoFilterBackend -from django_filters.rest_framework import filters -from django_filters import compat +from django_filters import compat, filters from vstutils.utils import raise_context from .filters import extra_filter diff --git a/vstutils/models/base.py b/vstutils/models/base.py index <HASH>..<HASH> 100644 --- a/vstutils/models/base.py +++ b/vstutils/models/base.py @@ -7,6 +7,7 @@ from copy import deepcopy from django_filters import rest_framework as filters, filterset from django.core.cache import caches as django_caches from django.db.models.base import ModelBase +from django.db.models import fields as django_model_fields from django.db.models.fields.related import ManyToManyField, OneToOneField, ForeignKey from django.utils.functional import SimpleLazyObject, lazy from django.db.models.signals import post_save, post_delete @@ -433,6 +434,8 @@ class ModelBaseClass(ModelBase, metaclass=classproperty.meta): ), help_text=f"Search by {field_name}'s primary key or {related_name}" ) + elif isinstance(field, django_model_fields.BooleanField): + filterset_fields_types[field_name] = filters.BooleanFilter() return filterset.FilterSetMetaclass( f'{cls.__name__}FilterSetClass',
Fix: show boolean filter as boolean in schema.
vstconsulting_vstutils
train
0c4854553b4615f63530e4e0763e93890d5e41ad
diff --git a/openfisca_core/scenarios.py b/openfisca_core/scenarios.py index <HASH>..<HASH> 100644 --- a/openfisca_core/scenarios.py +++ b/openfisca_core/scenarios.py @@ -185,7 +185,7 @@ class AbstractScenario(object): # All parallel axes have the same count and entity. first_axis = parallel_axes[0] axis_count = first_axis['count'] - axis_entity = simulation.getVariableEntity(first_axis['name']) + axis_entity = simulation.get_variable_entity(first_axis['name']) for axis in parallel_axes: axis_period = axis['period'] or simulation_period holder = simulation.get_or_new_holder(axis['name']) @@ -212,7 +212,7 @@ class AbstractScenario(object): # All parallel axes have the same count and entity. first_axis = parallel_axes[0] axis_count = first_axis['count'] - axis_entity = simulation.getVariableEntity(first_axis['name']) + axis_entity = simulation.get_variable_entity(first_axis['name']) for axis in parallel_axes: axis_period = axis['period'] or simulation_period holder = simulation.get_or_new_holder(axis['name']) diff --git a/openfisca_core/simulations.py b/openfisca_core/simulations.py index <HASH>..<HASH> 100644 --- a/openfisca_core/simulations.py +++ b/openfisca_core/simulations.py @@ -220,7 +220,7 @@ class Simulation(object): def get_or_new_holder(self, column_name): holder = self.holder_by_name.get(column_name) if holder is None: - entity = self.getVariableEntity(column_name) + entity = self.get_variable_entity(column_name) column = self.tax_benefit_system.get_column(column_name) self.holder_by_name[column_name] = holder = holders.Holder(column = column, entity = entity) if column.formula_class is not None: @@ -264,6 +264,6 @@ class Simulation(object): def to_input_variables_json(self): return None - def getVariableEntity(self, variable_name): + def get_variable_entity(self, variable_name): column = self.tax_benefit_system.get_column(variable_name) return self.entity_by_key_plural[column.entity_key_plural] diff --git a/openfisca_core/taxbenefitsystems.py b/openfisca_core/taxbenefitsystems.py index <HASH>..<HASH> 100644 --- a/openfisca_core/taxbenefitsystems.py +++ b/openfisca_core/taxbenefitsystems.py @@ -95,7 +95,7 @@ class TaxBenefitSystem(object): def load_variable(self, variable_class, update = False): name = unicode(variable_class.__name__) variable_type = variable_class.__bases__[0] - attributes = variable_class.__dict__ + attributes = dict(variable_class.__dict__) existing_column = self.get_column(name) diff --git a/openfisca_core/variables.py b/openfisca_core/variables.py index <HASH>..<HASH> 100644 --- a/openfisca_core/variables.py +++ b/openfisca_core/variables.py @@ -5,7 +5,7 @@ from openfisca_core.formulas import SimpleFormula, DatedFormula, EntityToPerson, from openfisca_core import columns -class AbstractVariable(): +class AbstractVariable(object): def __init__(self, name, attributes, variable_class): self.name = name self.attributes = {attr_name.strip('_'): attr_value for (attr_name, attr_value) in attributes.iteritems()}
Minor fixes From a @cbenz commit erased my mistake
openfisca_openfisca-core
train
0d35ba9b94369c72e46ed7b57b2bb3427faf66a8
diff --git a/rafthttp/pipeline_test.go b/rafthttp/pipeline_test.go index <HASH>..<HASH> 100644 --- a/rafthttp/pipeline_test.go +++ b/rafthttp/pipeline_test.go @@ -67,9 +67,9 @@ func TestPipelineKeepSendingWhenPostError(t *testing.T) { } func TestPipelineExceedMaximumServing(t *testing.T) { - tr := newRoundTripperBlocker() + rt := newRoundTripperBlocker() picker := mustNewURLPicker(t, []string{"http://localhost:2380"}) - tp := &Transport{pipelineRt: tr} + tp := &Transport{pipelineRt: rt} p := startTestPipeline(tp, picker) defer p.stop() @@ -91,12 +91,12 @@ func TestPipelineExceedMaximumServing(t *testing.T) { } // unblock the senders and force them to send out the data - tr.unblock() + rt.unblock() // It could send new data after previous ones succeed select { case p.msgc <- raftpb.Message{}: - case <-time.After(10 * time.Millisecond): + case <-time.After(time.Second): t.Errorf("failed to send out message") } }
rafthttp: fix TestPipelineExceedMaximumServing The timeout is too short. It might take more than <I>ms to send request over a blocking chan (buffer is full). Changing the timeout to 1 second can fix this issue.
etcd-io_etcd
train
13e9d53fdfa599d05dfcd42298501212baeb6f98
diff --git a/xwiki-rendering-transformations/xwiki-rendering-transformation-linkchecker/src/main/java/org/xwiki/rendering/internal/transformation/linkchecker/DefaultHTTPChecker.java b/xwiki-rendering-transformations/xwiki-rendering-transformation-linkchecker/src/main/java/org/xwiki/rendering/internal/transformation/linkchecker/DefaultHTTPChecker.java index <HASH>..<HASH> 100644 --- a/xwiki-rendering-transformations/xwiki-rendering-transformation-linkchecker/src/main/java/org/xwiki/rendering/internal/transformation/linkchecker/DefaultHTTPChecker.java +++ b/xwiki-rendering-transformations/xwiki-rendering-transformation-linkchecker/src/main/java/org/xwiki/rendering/internal/transformation/linkchecker/DefaultHTTPChecker.java @@ -25,8 +25,11 @@ import javax.inject.Singleton; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.params.HttpMethodParams; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; +import org.xwiki.component.phase.Initializable; +import org.xwiki.component.phase.InitializationException; /** * Default implementation using Apache Http Client. @@ -36,7 +39,7 @@ import org.xwiki.component.annotation.Component; */ @Component @Singleton -public class DefaultHTTPChecker implements HTTPChecker +public class DefaultHTTPChecker implements HTTPChecker, Initializable { /** * The logger to log. @@ -44,19 +47,32 @@ public class DefaultHTTPChecker implements HTTPChecker @Inject private Logger logger; + /** + * The client to connect to the remote site using HTTP. + */ + private HttpClient httpClient; + + @Override + public void initialize() throws InitializationException + { + this.httpClient = new HttpClient(); + + // Set our user agent to be a good citizen. + this.httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "XWiki Link Checker"); + } + @Override public int check(String url) { int responseCode; - HttpClient client = new HttpClient(); try { GetMethod method = new GetMethod(url); // Ignore cookies since this can cause errors in logs and we don't need cookies when checking sites. method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); // Execute the method. - responseCode = client.executeMethod(method); + responseCode = this.httpClient.executeMethod(method); this.logger.debug("Result of pinging [{}]: code = [{}]", url, responseCode); } catch (Exception e) {
XRENDERING-<I>: Set a XWiki user-agent in the Link Checker to be a good citizen + improved performance by reusing the HttpClient object
xwiki_xwiki-rendering
train
a8479829b180c4da74027b220a629a794a894091
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java @@ -36,6 +36,7 @@ import com.orientechnologies.orient.core.serialization.OSerializableStream; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; import com.orientechnologies.orient.core.storage.OStorage; +import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; @@ -114,7 +115,7 @@ public class OEdgeDelegate implements OEdge { if (element != null) { return element.getPropertyNames(); } - return null; + return Collections.EMPTY_SET; } public OEdge delete() {
fix NPE on HTTP API with lightweight edges
orientechnologies_orientdb
train
6d770f8a864ec89509d696276da42936f1f92592
diff --git a/core/files/changelog.txt b/core/files/changelog.txt index <HASH>..<HASH> 100644 --- a/core/files/changelog.txt +++ b/core/files/changelog.txt @@ -1,4 +1,5 @@ 0.9 + EncodedDoubleValue requires maxValue/factor to be a natural number #954 default base algorithm for all modes is bidirectional A* (except speed mode) introduced landmarks based hybrid mode, #780 moving all prepare.xy configs to prepare.ch.xy and e.g. disallow the old diff --git a/core/src/main/java/com/graphhopper/routing/util/EncodedDoubleValue.java b/core/src/main/java/com/graphhopper/routing/util/EncodedDoubleValue.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/routing/util/EncodedDoubleValue.java +++ b/core/src/main/java/com/graphhopper/routing/util/EncodedDoubleValue.java @@ -31,6 +31,10 @@ public class EncodedDoubleValue extends EncodedValue { public EncodedDoubleValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue, boolean allowZero) { super(name, shift, bits, factor, defaultValue, maxValue, allowZero); + double factorDivision = maxValue / factor; + if (factorDivision != (int) factorDivision) { + throw new IllegalStateException("MaxValue needs to be divisible by factor without remainder"); + } } @Override @@ -54,7 +58,7 @@ public class EncodedDoubleValue extends EncodedValue { // scale value long tmpValue = Math.round(value / factor); - checkValue(Math.round(tmpValue * factor)); + checkValue((long) (tmpValue * factor)); tmpValue <<= shift; // clear value bits diff --git a/core/src/test/java/com/graphhopper/routing/util/EncodedDoubleValueTest.java b/core/src/test/java/com/graphhopper/routing/util/EncodedDoubleValueTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/com/graphhopper/routing/util/EncodedDoubleValueTest.java +++ b/core/src/test/java/com/graphhopper/routing/util/EncodedDoubleValueTest.java @@ -32,6 +32,11 @@ public class EncodedDoubleValueTest { assertEquals(10.12, instance.getDoubleValue(instance.setDoubleValue(0, 10.12)), 1e-4); } + @Test(expected = IllegalStateException.class) + public void testIllegalFactorMaxValueCombination() { + new EncodedDoubleValue("illegalcombination", 6, 2, 2, 0, 3); + } + @Test public void testMaxValue() { EncodedDoubleValue instance1 = new EncodedDoubleValue("test1", 0, 8, 0.5, 60, 100);
Fix encoded value issue #<I> (#<I>)
graphhopper_graphhopper
train
97cdc8f4738e7cdc3c2fd9edc7387579d36945ab
diff --git a/test/test_config.rb b/test/test_config.rb index <HASH>..<HASH> 100644 --- a/test/test_config.rb +++ b/test/test_config.rb @@ -69,6 +69,6 @@ class TestConfig < Test::Unit::TestCase def test_clears_config Sauce.config {|c|} - assert_not_equal [["Windows 2003", "firefox", "3.6."]], Sauce::Config.new.browsers + assert_equal [["Windows 2003", "firefox", "3.6."]], Sauce::Config.new.browsers end end
Yea that was a weird test
saucelabs_sauce_ruby
train
53d2520320412eb66469efce8cfef18229dfe23d
diff --git a/container/lxd/container.go b/container/lxd/container.go index <HASH>..<HASH> 100644 --- a/container/lxd/container.go +++ b/container/lxd/container.go @@ -6,13 +6,13 @@ package lxd import ( "fmt" "math" - "strconv" "strings" "github.com/juju/errors" "github.com/juju/utils/arch" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" + "github.com/lxc/lxd/shared/version" "github.com/juju/juju/constraints" "github.com/juju/juju/network" @@ -51,13 +51,13 @@ func (c *ContainerSpec) ApplyConstraints(serverVersion string, cons constraints. if cons.HasMem() { // Ensure that for LXD versions 3.10+, we use the correct "MiB" suffix. template := "%dMB" - version := strings.Split(serverVersion, ".") - if major, _ := strconv.Atoi(version[0]); major > 2 { - if minor, _ := strconv.Atoi(version[1]); minor >= 9 || major > 3 { - template = "%dMiB" + if current, err := version.Parse(serverVersion); err == nil { + if min, err := version.NewDottedVersion("3.10"); err == nil { + if current.Compare(min) >= 0 { + template = "%dMiB" + } } } - c.Config["limits.memory"] = fmt.Sprintf(template, *cons.Mem) } }
Use the LXD version package to parse LXD version strings.
juju_juju
train
e7c37736e26be8fd0232050a67aa4b8cc06ca01a
diff --git a/lib/pdk/generators/module.rb b/lib/pdk/generators/module.rb index <HASH>..<HASH> 100644 --- a/lib/pdk/generators/module.rb +++ b/lib/pdk/generators/module.rb @@ -96,6 +96,9 @@ module PDK 'dependencies' => [ { 'name' => 'puppetlabs-stdlib', 'version_requirement' => '>= 4.13.1 < 5.0.0' }, ], + 'requirements' => [ + { 'name' => 'puppet', 'version_requirement' => '>= 4.7.0 < 6.0.0' }, + ], } defaults['author'] = PDK.answers['author'] unless PDK.answers['author'].nil? defaults['license'] = PDK.answers['license'] unless PDK.answers['license'].nil? diff --git a/lib/pdk/module/metadata.rb b/lib/pdk/module/metadata.rb index <HASH>..<HASH> 100644 --- a/lib/pdk/module/metadata.rb +++ b/lib/pdk/module/metadata.rb @@ -34,6 +34,7 @@ module PDK 'operatingsystemrelease' => ['2012 R2'], }, ], + 'requirements' => Set.new.freeze, }.freeze def initialize(params = {})
(PDK-<I>) Add puppet version requirements to metadata.json generation
puppetlabs_pdk
train
40e5b253a3cd1fa3bb6f79335af1f5c1e838af15
diff --git a/core/src/main/java/com/graphhopper/reader/OSMElement.java b/core/src/main/java/com/graphhopper/reader/OSMElement.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/reader/OSMElement.java +++ b/core/src/main/java/com/graphhopper/reader/OSMElement.java @@ -197,4 +197,10 @@ public abstract class OSMElement { return this.type == type; } + + @Override + public String toString() + { + return properties.toString(); + } } diff --git a/core/src/main/java/com/graphhopper/reader/OSMWay.java b/core/src/main/java/com/graphhopper/reader/OSMWay.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/reader/OSMWay.java +++ b/core/src/main/java/com/graphhopper/reader/OSMWay.java @@ -23,7 +23,6 @@ import gnu.trove.list.array.TLongArrayList; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; -import java.util.Map; /** * Represents an OSM Way @@ -75,6 +74,6 @@ public class OSMWay extends OSMElement @Override public String toString() { - return "Way (" + getId() + ", " + nodes.size() + " nodes)"; + return "Way id:" + getId() + ", nodes:" + nodes.size() + ", tags:" + super.toString(); } } diff --git a/core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java b/core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java +++ b/core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java @@ -259,7 +259,7 @@ public class BikeCommonFlagEncoder extends AbstractFlagEncoder { if ((way.hasTag("highway", "cycleway")) && (way.hasTag("sac_scale", "hiking"))) - return 1; // This combination is fine with every kind of bike, including a racingbike + return acceptBit; if (!allowedSacScale(sacScale)) return 0; } diff --git a/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java b/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java +++ b/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java @@ -145,7 +145,7 @@ public class CarFlagEncoder extends AbstractFlagEncoder String highwayValue = way.getTag("highway"); Integer speed = defaultSpeedMap.get(highwayValue); if (speed == null) - throw new IllegalStateException(toString() + ", no speed found for:" + highwayValue); + throw new IllegalStateException(toString() + ", no speed found for: " + highwayValue + ", tags: " + way); if (highwayValue.equals("track")) { diff --git a/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java b/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java +++ b/core/src/main/java/com/graphhopper/routing/util/EncodingManager.java @@ -26,6 +26,7 @@ import com.graphhopper.reader.OSMWay; import com.graphhopper.storage.Directory; import com.graphhopper.storage.RAMDirectory; import com.graphhopper.storage.StorableProperties; +import com.graphhopper.util.BitUtil; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.Helper; import java.util.*; diff --git a/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java b/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java +++ b/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java @@ -481,4 +481,18 @@ public class CarFlagEncoderTest } } + @Test + public void testCombination() + { + OSMWay way = new OSMWay(123); + way.setTag("highway", "cycleway"); + way.setTag("sac_scale", "hiking"); + + long flags = em.acceptWay(way); + long edgeFlags = em.handleWayTags(way, flags, 0); + assertFalse(encoder.isBackward(edgeFlags)); + assertFalse(encoder.isForward(edgeFlags)); + assertTrue(em.getEncoder("bike").isBackward(edgeFlags)); + assertTrue(em.getEncoder("bike").isForward(edgeFlags)); + } }
fixed #<I>, Graph build fail in rare situations with sac_scale due to BikeFlagEncoder bug
graphhopper_graphhopper
train
1f9223a7c2c0e5c04936c56a071830f8792c3dd7
diff --git a/commands.go b/commands.go index <HASH>..<HASH> 100644 --- a/commands.go +++ b/commands.go @@ -1762,10 +1762,11 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co _ = cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)") _ = cmd.String("name", "", "Assign a name to the container") ) + cmd.Var(flAttach, "a", "Attach to stdin, stdout or stderr.") cmd.Var(flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)") - cmd.Var(&flPublish, "p", "Publish a container's port to the host (use 'docker port' to see the actual mapping)") + cmd.Var(&flPublish, "p", fmt.Sprintf("Publish a container's port to the host (format: %s) (use 'docker port' to see the actual mapping)", PortSpecTemplateFormat)) cmd.Var(&flExpose, "expose", "Expose a port from the container without publishing it to your host") cmd.Var(&flEnv, "e", "Set environment variables") cmd.Var(&flDns, "dns", "Set custom dns servers") diff --git a/utils.go b/utils.go index <HASH>..<HASH> 100644 --- a/utils.go +++ b/utils.go @@ -206,6 +206,12 @@ func parseLxcOpt(opt string) (string, string, error) { return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), nil } +// FIXME: network related stuff (including parsing) should be grouped in network file +const ( + PortSpecTemplate = "ip:hostPort:containerPort" + PortSpecTemplateFormat = "ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort" +) + // We will receive port specs in the format of ip:public:private/proto and these need to be // parsed in the internal types func parsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) { @@ -227,7 +233,7 @@ func parsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, rawPort = fmt.Sprintf(":%s", rawPort) } - parts, err := utils.PartParser("ip:hostPort:containerPort", rawPort) + parts, err := utils.PartParser(PortSpecTemplate, rawPort) if err != nil { return nil, nil, err }
Use a constant for PortSpecTemplate + display the template in the CmdRun help
containers_storage
train
84f8bb6be8c42a63f40567c7ebf71120e6329b0c
diff --git a/docs/source/conf.py b/docs/source/conf.py index <HASH>..<HASH> 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -223,3 +223,7 @@ htmlhelp_basename = 'Chalicedoc' primary_domain = 'py' linkcheck_retries = 5 +# The AWS Doc site now uses javascript to dynamically render the content, +# so the anchors aren't going to exist in the static html content. This +# will fail the anchor checker so we have to disable this. +linkcheck_anchors = False
Disable anchor link checker This is failing our builds now. This is due to the AWS Doc site using javascript to render the content now so even though the anchor links are correct, you won't be able to see them in the static HTML.
aws_chalice
train
64b74aecfa950caf83e36ab3afbcd827a4fff955
diff --git a/lib/yard/cli/yardoc.rb b/lib/yard/cli/yardoc.rb index <HASH>..<HASH> 100644 --- a/lib/yard/cli/yardoc.rb +++ b/lib/yard/cli/yardoc.rb @@ -28,7 +28,10 @@ module YARD # @return [Boolean] whether to generate output attr_accessor :generate - + + # @return [Boolean] whether to print a list of objects + attr_accessor :list + # The options file name (defaults to {DEFAULT_YARDOPTS_FILE}) # @return [String] the filename to load extra options from attr_accessor :options_file @@ -85,6 +88,8 @@ module YARD Registry.load_all if use_cache Templates::Engine.generate(all_objects, options) end + elsif list + print_list end true @@ -125,6 +130,17 @@ module YARD end end + # Prints a list of all objects + # @return [void] + def print_list + Registry.load_all + Registry.all. + reject {|item| options[:verifier].call(item).is_a?(FalseClass) }. + sort_by {|item| [item.file, item.line]}.each do |item| + puts "#{item.file}:#{item.line}: #{item}" + end + end + # Reads a .document file in the directory to get source file globs # @return [void] def support_rdoc_document_file! @@ -294,7 +310,12 @@ module YARD opts.on('--query QUERY', "Only show objects that match a specific query") do |query| query_expressions << query.taint end - + + opts.on('--list', 'List objects to standard out (implies -n)') do |format| + self.generate = false + self.list = true + end + opts.on('--title TITLE', 'Add a specific title to HTML documents') do |title| options[:title] = title end
Add a --list option for listing all objects matching the query.
lsegal_yard
train
b6aa87d11685a9784f6f77cb11ecbc68ce7e6278
diff --git a/code/solr/SolrIndex.php b/code/solr/SolrIndex.php index <HASH>..<HASH> 100644 --- a/code/solr/SolrIndex.php +++ b/code/solr/SolrIndex.php @@ -268,9 +268,9 @@ abstract class SolrIndex extends SearchIndex { foreach ($res->response->docs as $doc) { $result = DataObject::get_by_id($doc->ClassName, $doc->ID); - if ($result) $results[] = $result; + if($result) $results->push($result); } - + $ret = array(); $ret['Matches'] = new PaginatedList($results); $ret['Matches']->setLimitItems(false);
Fix results aggregation in SolrIndex (ArrayAccess broken) Needs to use push() explicitly, native operators don't seem to work on ArrayList (see <URL>)
silverstripe_silverstripe-fulltextsearch
train
e8c77b00de470bfba8f34580a06321876b2f9974
diff --git a/cnxarchive/scripts/initializedb.py b/cnxarchive/scripts/initializedb.py index <HASH>..<HASH> 100644 --- a/cnxarchive/scripts/initializedb.py +++ b/cnxarchive/scripts/initializedb.py @@ -8,24 +8,21 @@ """Commandline script used to initialize the SQL database.""" import os import sys +import argparse import psycopg2 from ..database import initdb from ..utils import parse_app_settings -def usage(argv): - cmd = os.path.basename(argv[0]) - print('usage: %s <config_uri>\n' - '(example: "%s development.ini")' % (cmd, cmd)) - sys.exit(1) +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('config_uri', help="Configuration INI file.") -def main(argv=sys.argv): - if len(argv) != 2: - usage(argv) - config_uri = argv[1] - try: - settings = parse_app_settings(config_uri) - except: - usage(argv) + args = parser.parse_args(argv) + settings = parse_app_settings(args.config_uri) initdb(settings) + return 0 + +if __name__ == '__main__': + main()
Use argparse, because other options need added.
openstax_cnx-archive
train
a8c28cae6b7f261398ec2b686a18f3292bf2eff7
diff --git a/tofu/tests/tests01_geom/tests03_core.py b/tofu/tests/tests01_geom/tests03_core.py index <HASH>..<HASH> 100644 --- a/tofu/tests/tests01_geom/tests03_core.py +++ b/tofu/tests/tests01_geom/tests03_core.py @@ -925,6 +925,26 @@ class Test03_Rays(object): # Just to check the loaded version works fine obj2.strip(0, verb=verb) os.remove(pfe) + def test15_get_sample_same_res_unit(self): + dmeths = ['rel', 'abs'] + qmeths = ['simps', 'romb', 'sum'] + + dL = 0.25 + DL = np.array([[1.,10.],[2.,20.]]) + + for dm in dmeths: + for qm in qmeths: + print("============ for: ", dm, " -", qm, "=======") + out = _GG.LOS_get_sample(2, dL, DL, dmethod=dm, method=qm) + k = out[0] + lind = out[2] + print(" k =", k) + print("lind =", lind) + assert np.all(k[:lind[0]] >= DL[0][0]) + assert np.all(k[:lind[0]] <= DL[1][0]) + assert np.all(k[lind[0]:] >= DL[0][1]) + assert np.all(k[lind[0]:] <= DL[1][1]) + print("================= OK =======================") """
[Issue<I>] added unit test
ToFuProject_tofu
train
5f8de2e468b35228676d00d80692932bead4bc27
diff --git a/org.jenetics.prog/src/main/java/org/jenetics/prog/ops/MathOp.java b/org.jenetics.prog/src/main/java/org/jenetics/prog/ops/MathOp.java index <HASH>..<HASH> 100644 --- a/org.jenetics.prog/src/main/java/org/jenetics/prog/ops/MathOp.java +++ b/org.jenetics.prog/src/main/java/org/jenetics/prog/ops/MathOp.java @@ -59,7 +59,7 @@ public final class MathOp { * <p> * <b><em>Terminal operation</em></b> */ - public static final Op<Double> PI = Const.of("π", Math.PI); + public static final Const<Double> PI = Const.of("π", Math.PI); /** * The double value that is closer than any other to e, the base of the @@ -67,7 +67,7 @@ public final class MathOp { * <p> * <b><em>Terminal operation</em></b> */ - public static final Op<Double> E = Const.of("e", Math.E); + public static final Const<Double> E = Const.of("e", Math.E); /* *************************************************************************
#<I>: Class cleanup.
jenetics_jenetics
train
3ca41f907a891e5b121d58cc07155848cf1bb369
diff --git a/tests/system/Helpers/FormHelperTest.php b/tests/system/Helpers/FormHelperTest.php index <HASH>..<HASH> 100644 --- a/tests/system/Helpers/FormHelperTest.php +++ b/tests/system/Helpers/FormHelperTest.php @@ -3,6 +3,7 @@ use CodeIgniter\HTTP\URI; use Config\App; use CodeIgniter\Services; +use Config\Filters; class FormHelperTest extends \CIUnitTestCase { @@ -21,10 +22,25 @@ class FormHelperTest extends \CIUnitTestCase Services::injectMock('request', $request); - $expected = <<<EOH + $before = (new Filters())->globals['before']; + if (in_array('csrf', $before) || array_key_exists('csrf', $before )) + { + $Value = csrf_hash(); + $Name = csrf_token(); + $expected = <<<EOH +<form action="http://example.com/index.php/foo/bar" name="form" id="form" method="POST" accept-charset="utf-8"> +<input type="hidden" name="$Name" value="$Value" style="display: none;" /> + +EOH; + } + else + { + $expected = <<<EOH <form action="http://example.com/index.php/foo/bar" name="form" id="form" method="POST" accept-charset="utf-8"> EOH; + } + $attributes = [ 'name' => 'form', 'id' => 'form', @@ -43,10 +59,24 @@ EOH; Services::injectMock('request', $request); - $expected = <<<EOH + $before = (new Filters())->globals['before']; + if (in_array('csrf', $before) || array_key_exists('csrf', $before )) + { + $Value = csrf_hash(); + $Name = csrf_token(); + $expected = <<<EOH <form action="http://example.com/" name="form" id="form" method="POST" accept-charset="utf-8"> +<input type="hidden" name="$Name" value="$Value" style="display: none;" /> EOH; + } + else + { + $expected = <<<EOH +<form action="http://example.com/" name="form" id="form" method="POST" accept-charset="utf-8"> + +EOH; + } $attributes = [ 'name' => 'form', 'id' => 'form', @@ -65,10 +95,25 @@ EOH; Services::injectMock('request', $request); - $expected = <<<EOH + $before = (new Filters())->globals['before']; + if (in_array('csrf', $before) || array_key_exists('csrf', $before )) + { + $Value = csrf_hash(); + $Name = csrf_token(); + $expected = <<<EOH +<form action="http://example.com/index.php/foo/bar" name="form" id="form" method="post" accept-charset="utf-8"> +<input type="hidden" name="$Name" value="$Value" style="display: none;" /> + +EOH; + } + else + { + $expected = <<<EOH <form action="http://example.com/index.php/foo/bar" name="form" id="form" method="post" accept-charset="utf-8"> EOH; + } + $attributes = [ 'name' => 'form', 'id' => 'form' @@ -86,11 +131,27 @@ EOH; Services::injectMock('request', $request); - $expected = <<<EOH + $before = (new Filters())->globals['before']; + if (in_array('csrf', $before) || array_key_exists('csrf', $before )) + { + $Value = csrf_hash(); + $Name = csrf_token(); + $expected = <<<EOH +<form action="http://example.com/index.php/foo/bar" name="form" id="form" method="POST" accept-charset="utf-8"> +<input type="hidden" name="foo" value="bar" style="display: none;" /> +<input type="hidden" name="$Name" value="$Value" style="display: none;" /> + +EOH; + } + else + { + $expected = <<<EOH <form action="http://example.com/index.php/foo/bar" name="form" id="form" method="POST" accept-charset="utf-8"> <input type="hidden" name="foo" value="bar" style="display: none;" /> EOH; + } + $attributes = [ 'name' => 'form', 'id' => 'form', @@ -112,10 +173,24 @@ EOH; Services::injectMock('request', $request); - $expected = <<<EOH + $before = (new Filters())->globals['before']; + if (in_array('csrf', $before) || array_key_exists('csrf', $before )) + { + $Value = csrf_hash(); + $Name = csrf_token(); + $expected = <<<EOH +<form action="http://example.com/index.php/foo/bar" name="form" id="form" method="POST" enctype="multipart&#x2F;form-data" accept-charset="utf-8"> +<input type="hidden" name="$Name" value="$Value" style="display: none;" /> + +EOH; + } + else + { + $expected = <<<EOH <form action="http://example.com/index.php/foo/bar" name="form" id="form" method="POST" enctype="multipart&#x2F;form-data" accept-charset="utf-8"> EOH; + } $attributes = [ 'name' => 'form', 'id' => 'form',
+ added support for csrf fields
codeigniter4_CodeIgniter4
train
6b72bc9ffa8943d6ad5eee63064bc5fdfbddc9a1
diff --git a/src/Connection.php b/src/Connection.php index <HASH>..<HASH> 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -204,8 +204,7 @@ class Connection public function publish($subject, $payload) { $msg = 'PUB '.$subject.' '.strlen($payload); - $this->send($msg); - $this->send($payload); + $this->send($msg . "\r\n" . $payload); $this->pubs += 1; }
Fixed #<I> msg and payload should be send in one request.
repejota_phpnats
train
aaca5eac7dfb419f6fc6f756f030f13902d9abe1
diff --git a/modules/parser/ext.core.LinkHandler.js b/modules/parser/ext.core.LinkHandler.js index <HASH>..<HASH> 100644 --- a/modules/parser/ext.core.LinkHandler.js +++ b/modules/parser/ext.core.LinkHandler.js @@ -74,6 +74,7 @@ WikiLinkHandler.prototype._simpleImageOptions = { 'left': 'halign', 'right': 'halign', 'center': 'halign', + 'float': 'halign', 'none': 'halign', // valign 'baseline': 'valign', @@ -152,7 +153,7 @@ WikiLinkHandler.prototype.renderFile = function ( token, manager, cb, title ) { if ( bits.length > 1 && key) { oHash[key] = bits[1]; options.push( new KV( key, bits[1] ) ); - console.warn('handle prefix ' + bits ); + //console.warn('handle prefix ' + bits ); } else { // neither simple nor prefix option, add original // tokens to caption. @@ -160,10 +161,10 @@ WikiLinkHandler.prototype.renderFile = function ( token, manager, cb, title ) { } } } + } else { + caption = caption.concat( oContent.v ); } } - //console.warn('caption: ' + JSON.stringify( caption ) ); - //var contentPos = token.dataAttribs.contentPos; //var optionSource = token.source.substr( contentPos[0], contentPos[1] - contentPos[0] ); diff --git a/modules/parser/ext.core.TemplateHandler.js b/modules/parser/ext.core.TemplateHandler.js index <HASH>..<HASH> 100644 --- a/modules/parser/ext.core.TemplateHandler.js +++ b/modules/parser/ext.core.TemplateHandler.js @@ -160,6 +160,10 @@ TemplateHandler.prototype._expandTemplate = function ( tplExpandData ) { this.manager.env.dp( 'argHash: ', args ); + + // XXX: strip subst for now.. + target = target.replace( /^(safe)?subst:/, '' ); + var prefix = target.split(':', 1)[0].toLowerCase().trim(); if ( prefix && 'pf_' + prefix in this.parserFunctions ) { var funcArg = target.substr( prefix.length + 1 ); @@ -310,7 +314,7 @@ TemplateHandler.prototype._stripEOFTk = function ( tokens ) { */ TemplateHandler.prototype._processTemplateAndTitle = function( pipeline, src, title ) { // Feed the pipeline. XXX: Support different formats. - this.manager.env.dp( 'TemplateHandler._processTemplateAndTitle: ', src ); + this.manager.env.dp( 'TemplateHandler._processTemplateAndTitle: ', title, src ); pipeline.process ( src ); }; @@ -372,6 +376,7 @@ TemplateHandler.prototype.onTemplateArg = function ( token, frame, cb ) { token.resultTokens = false; + // XXX: get this from the cache! new AttributeTransformManager ( this.manager, this._returnArgAttributes.bind( this, token, cb, frame ) diff --git a/modules/parser/mediawiki.parser.environment.js b/modules/parser/mediawiki.parser.environment.js index <HASH>..<HASH> 100644 --- a/modules/parser/mediawiki.parser.environment.js +++ b/modules/parser/mediawiki.parser.environment.js @@ -188,9 +188,6 @@ MWParserEnvironment.prototype.normalizeTitle = function( name ) { name = name.trim().replace(/[\s_]+/g, '_'); - // XXX: strip subst for now.. - name = name.replace( /^subst:/, '' ); - // Implement int: as alias for MediaWiki: if ( name.substr( 0, 4 ) === 'int:' ) { name = 'MediaWiki:' + name.substr( 4 ); diff --git a/tests/parser/parserTests-whitelist.js b/tests/parser/parserTests-whitelist.js index <HASH>..<HASH> 100644 --- a/tests/parser/parserTests-whitelist.js +++ b/tests/parser/parserTests-whitelist.js @@ -30,8 +30,6 @@ testWhiteList["A table with no data."] = "<table></table>"; testWhiteList["A table with nothing but a caption"] = "<table><caption> caption</caption></table>"; testWhiteList["Fuzz testing: Parser22"] = "<p><a href=\"http://===r:::https://b\">http://===r:::https://b</a></p><table></table>"; -testWhiteList["Nested table"] = "<table border=\"1\"><tbody><tr><td> α</td><td><table bgcolor=\"#ABCDEF\" border=\"2\"><tbody><tr><td>nested</td></tr><tr><td>table</td></tr></tbody></table></td><td>the original table again</td></tr></tbody></table>"; - // Very minor whitespace difference at end of cell (MediaWiki inserts a // newline before the close tag even if there was no trailing space in the cell) testWhiteList["Table rowspan"] = "<table border=\"1\"><tbody><tr><td> Cell 1, row 1 </td><td rowspan=\"2\"> Cell 2, row 1 (and 2) </td><td> Cell 3, row 1 </td></tr><tr><td> Cell 1, row 2 </td><td> Cell 3, row 2 </td></tr></tbody></table>";
More tweaks: safesubst and image options * Ignore safesubst for now * Remove an unneeded whitelist entry * Make sure the caption is not lost for thumbs (fix to last commit) and remove debug print Change-Id: I<I>ed<I>cf7c3b<I>fe9cdf<I>
wikimedia_parsoid
train
115db6721ca79dcabacba47867e3bbba1c78bdbd
diff --git a/SecureHeaders.php b/SecureHeaders.php index <HASH>..<HASH> 100644 --- a/SecureHeaders.php +++ b/SecureHeaders.php @@ -675,7 +675,7 @@ class SecureHeaders{ } } - if (preg_match_all('/(?:[ ]\Khttps?[:](?:\/\/)?[*]?|[ ]\K[*])(?=[ ;]|$)/', $value, $matches)) + if (preg_match_all('/(?:[ ]|^)\K(?:https?[:](?:\/\/)?[*]?|[*])(?=[ ;]|$)/', $value, $matches)) { $this->add_error( $friendly_header.' '.(count($matches[0]) > 1 ? @@ -687,7 +687,7 @@ class SecureHeaders{ ); } - if (preg_match_all('/[ ]\Khttp[:][^ ]*/', $value, $matches)) + if (preg_match_all('/(?:[ ]|^)\Khttp[:][^ ]*/', $value, $matches)) { $this->add_error( $friendly_header.' contains the insecure protocol HTTP in '.
optimise regex and allow wildcard to start at begining of string with no space
aidantwoods_SecureHeaders
train
5e11e414208608b7e43372154493b3e0a184e580
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -632,12 +632,14 @@ class RequestProtocol < BaseRequestTest end class RequestMethod < BaseRequestTest - test "request methods" do - [:post, :get, :patch, :put, :delete].each do |method| - request = stub_request('REQUEST_METHOD' => method.to_s.upcase) + test "method returns environment's request method when it has not been + overriden by middleware".squish do - assert_equal method.to_s.upcase, request.method - assert_equal method, request.method_symbol + ActionDispatch::Request::HTTP_METHODS.each do |method| + request = stub_request('REQUEST_METHOD' => method) + + assert_equal method, request.method + assert_equal method.underscore.to_sym, request.method_symbol end end
Update test to clearly reflect what it is testing for.
rails_rails
train
e2ac1448514f824b1e37e730a5d597285d6bc2ed
diff --git a/Gemfile b/Gemfile index <HASH>..<HASH> 100644 --- a/Gemfile +++ b/Gemfile @@ -5,9 +5,6 @@ source "https://rubygems.org" # development dependencies will be added by default to the :development group. gemspec -# jquery-rails is used by the dummy application -gem "jquery-rails" - # Declare any dependencies that are still in development here instead of in # your gemspec. These might include edge Rails or gems from your path or # Git. Remember to move these dependencies to your gemspec before releasing diff --git a/app/models/user_import_file.rb b/app/models/user_import_file.rb index <HASH>..<HASH> 100644 --- a/app/models/user_import_file.rb +++ b/app/models/user_import_file.rb @@ -47,7 +47,7 @@ class UserImportFile < ActiveRecord::Base end def import - sm_start! + transition_to!(:started) reload num = {:user_imported => 0, :user_found => 0, :failed => 0} rows = open_import_file @@ -101,12 +101,12 @@ class UserImportFile < ActiveRecord::Base end def modify - sm_start! - sm_complete! + transition_to!(:started) + transition_to!(:completed) end def remove - sm_start! + transition_to!(:started) reload rows = open_import_file @@ -120,7 +120,7 @@ class UserImportFile < ActiveRecord::Base user = User.where(:username => username).first user.destroy if user end - sm_complete! + transition_to!(:completed) end private diff --git a/lib/enju_leaf/engine.rb b/lib/enju_leaf/engine.rb index <HASH>..<HASH> 100644 --- a/lib/enju_leaf/engine.rb +++ b/lib/enju_leaf/engine.rb @@ -8,7 +8,6 @@ require 'rails_autolink' require 'devise-encryptable' require 'sitemap_generator' #require 'redis-rails' -require 'jquery-rails' require 'jquery-ui-rails' require 'resque_scheduler/server' require 'bcrypt/password'
removed jquery-rails from Gemfile
next-l_enju_leaf
train
e6570cadc4eee13b450810b26d24bb52944829d0
diff --git a/core/src/main/java/org/apache/druid/guice/LifecycleModule.java b/core/src/main/java/org/apache/druid/guice/LifecycleModule.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/apache/druid/guice/LifecycleModule.java +++ b/core/src/main/java/org/apache/druid/guice/LifecycleModule.java @@ -57,8 +57,11 @@ public class LifecycleModule implements Module * * This mechanism exists to allow the {@link Lifecycle} to be the primary entry point from the injector, not to * auto-register things with the {@link Lifecycle}. It is also possible to just bind things eagerly with Guice, - * it is not clear which is actually the best approach. This is more explicit, but eager bindings inside of modules - * is less error-prone. + * but that is almost never the correct option. Guice eager bindings are pre-instantiated before the object graph + * is materialized and injected, meaning that objects are not actually instantiated in dependency order. + * Registering with the LifecyceModule, on the other hand, will instantiate the objects after the normal object + * graph has already been instantiated, meaning that objects will be created in dependency order and this will + * only actually instantiate something that wasn't actually dependend upon. * * @param clazz the class to instantiate * @return this, for chaining. @@ -78,8 +81,11 @@ public class LifecycleModule implements Module * * This mechanism exists to allow the {@link Lifecycle} to be the primary entry point from the injector, not to * auto-register things with the {@link Lifecycle}. It is also possible to just bind things eagerly with Guice, - * it is not clear which is actually the best approach. This is more explicit, but eager bindings inside of modules - * is less error-prone. + * but that is almost never the correct option. Guice eager bindings are pre-instantiated before the object graph + * is materialized and injected, meaning that objects are not actually instantiated in dependency order. + * Registering with the LifecyceModule, on the other hand, will instantiate the objects after the normal object + * graph has already been instantiated, meaning that objects will be created in dependency order and this will + * only actually instantiate something that wasn't actually dependend upon. * * @param clazz the class to instantiate * @param annotation The annotation class to register with Guice @@ -98,10 +104,13 @@ public class LifecycleModule implements Module * scope. That is, they are generally eagerly loaded because the loading operation will produce some beneficial * side-effect even if nothing actually directly depends on the instance. * - * This mechanism exists to allow the {@link Lifecycle} to be the primary entry point - * from the injector, not to auto-register things with the {@link Lifecycle}. It is - * also possible to just bind things eagerly with Guice, it is not clear which is actually the best approach. - * This is more explicit, but eager bindings inside of modules is less error-prone. + * This mechanism exists to allow the {@link Lifecycle} to be the primary entry point from the injector, not to + * auto-register things with the {@link Lifecycle}. It is also possible to just bind things eagerly with Guice, + * but that is almost never the correct option. Guice eager bindings are pre-instantiated before the object graph + * is materialized and injected, meaning that objects are not actually instantiated in dependency order. + * Registering with the LifecyceModule, on the other hand, will instantiate the objects after the normal object + * graph has already been instantiated, meaning that objects will be created in dependency order and this will + * only actually instantiate something that wasn't actually dependend upon. * * @param key The key to use in finding the DruidNode instance */
Update LifecycleModule.java (#<I>) Update the javadoc on LifecycleModule to be more clear about why the register methods exist and why they should always be used instead of Guice's eager instantiation.
apache_incubator-druid
train
072de8ebff48db0ee3cab0f74a1d9f8d4373bbc5
diff --git a/rapidoid-u/src/main/java/org/rapidoid/util/U.java b/rapidoid-u/src/main/java/org/rapidoid/util/U.java index <HASH>..<HASH> 100644 --- a/rapidoid-u/src/main/java/org/rapidoid/util/U.java +++ b/rapidoid-u/src/main/java/org/rapidoid/util/U.java @@ -2235,4 +2235,21 @@ public class U { return CALENDAR.get(Calendar.YEAR); } + public static short bytesToShort(String s) { + ByteBuffer buf = buf(s); + ensure(buf.limit() == 2); + return buf.getShort(); + } + + public static int bytesToInt(String s) { + ByteBuffer buf = buf(s); + ensure(buf.limit() == 4); + return buf.getInt(); + } + + public static long bytesToLong(String s) { + ByteBuffer buf = buf(s); + ensure(buf.limit() == 8); + return buf.getLong(); + } }
Added utils that construct number from a provided string.
rapidoid_rapidoid
train
7e936877b32d8aa0932081b20b2f75270086ba6b
diff --git a/packages/service/src/serverless/util/configureEnvironment.js b/packages/service/src/serverless/util/configureEnvironment.js index <HASH>..<HASH> 100644 --- a/packages/service/src/serverless/util/configureEnvironment.js +++ b/packages/service/src/serverless/util/configureEnvironment.js @@ -3,7 +3,7 @@ import logger, {configureLogger} from "../../lib/logger"; import {XRayedAwsSdk} from "../../lib/util"; import loadServerlessSecrets from "./loadServerlessSecrets"; -dynamoose.setDDB(new XRayedAwsSdk.DynamoDB()); +dynamoose.AWS = XRayedAwsSdk; if (process.env.IS_OFFLINE || process.env.NODE_ENV === "test") { dynamoose.local();
fix(service): Just set `dynamoose.AWS` instead of `dynamoose.setDDB` for X-Ray support.
randytarampi_me
train
74645193241c4bdf0d82b25800fdc3bfb206261e
diff --git a/Bundle/TwigBundle/Controller/ExceptionController.php b/Bundle/TwigBundle/Controller/ExceptionController.php index <HASH>..<HASH> 100644 --- a/Bundle/TwigBundle/Controller/ExceptionController.php +++ b/Bundle/TwigBundle/Controller/ExceptionController.php @@ -3,7 +3,7 @@ namespace Victoire\Bundle\TwigBundle\Controller; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; -use Symfony\Component\Debug\Exception\FlattenException; +use Symfony\Component\HttpKernel\Exception\FlattenException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface;
rollback FlattenException use because of parent class which still use FlattenException in <I>
Victoire_victoire
train
938dd757293a9b00ae5f9dc7343fc24456e33bfc
diff --git a/libkbfs/tlf_handle_resolve.go b/libkbfs/tlf_handle_resolve.go index <HASH>..<HASH> 100644 --- a/libkbfs/tlf_handle_resolve.go +++ b/libkbfs/tlf_handle_resolve.go @@ -627,19 +627,23 @@ func parseTlfHandleLoose( return nil, err } - // First try resolving this full name as an implicit team. If - // that doesn't work, fall through to individual name resolution. - rit := resolvableImplicitTeam{kbpki, name, t} - iteamHandle, err := makeTlfHandleHelper( - ctx, t, []resolvableUser{rit}, nil, nil, idGetter) - if err == nil && iteamHandle.tlfID != tlf.NullID { - // The iteam already has a TLF ID, let's use it. - return iteamHandle, nil - } - // This is not an implicit team, so continue on to check for a - // normal team. TODO: return non-nil errors immediately if they - // don't simply indicate the implicit team doesn't exist yet - // (i.e., when we start creating them by default). + /** + * COMMENTED OUT FOR PERFORMANCE REASONS FOR NOW + * + // First try resolving this full name as an implicit team. If + // that doesn't work, fall through to individual name resolution. + rit := resolvableImplicitTeam{kbpki, name, t} + iteamHandle, err := makeTlfHandleHelper( + ctx, t, []resolvableUser{rit}, nil, nil, idGetter) + if err == nil && iteamHandle.tlfID != tlf.NullID { + // The iteam already has a TLF ID, let's use it. + return iteamHandle, nil + } + // This is not an implicit team, so continue on to check for a + // normal team. TODO: return non-nil errors immediately if they + // don't simply indicate the implicit team doesn't exist yet + // (i.e., when we start creating them by default). + */ // Before parsing the tlf handle (which results in identify // calls that cause tracker popups), first see if there's any diff --git a/libkbfs/tlf_handle_test.go b/libkbfs/tlf_handle_test.go index <HASH>..<HASH> 100644 --- a/libkbfs/tlf_handle_test.go +++ b/libkbfs/tlf_handle_test.go @@ -1012,6 +1012,8 @@ func TestParseTlfHandleNoncanonicalExtensions(t *testing.T) { } func TestParseTlfHandleImplicitTeams(t *testing.T) { + t.Skip("Performance issues") + ctx := context.Background() localUsers := MakeLocalUsers([]libkb.NormalizedUsername{"u1", "u2", "u3"})
tlf_handle: don't call resolve implicit teams for now It has bad performance.
keybase_client
train
7705d10d1bc8d43fb519fbaf02beff769cbca3ee
diff --git a/st_reg/states/ba.py b/st_reg/states/ba.py index <HASH>..<HASH> 100644 --- a/st_reg/states/ba.py +++ b/st_reg/states/ba.py @@ -18,8 +18,10 @@ def check(st_reg_number): sum_second_digit = sum_second_digit + i*int(st_reg_number[-i-1]) - second_digits_check = 10 - (sum_second_digit % 10) - + second_digits_check = 10 - (sum_second_digit % 10) + + if sum_second_digit % 10 == 0 or sum_second_digit % 11 == 1: + second_digits_check = '0' if str(second_digits_check) !=second_digits: return False @@ -27,10 +29,15 @@ def check(st_reg_number): digit_two = number_state_registration + str(second_digits_check) for i in weights_first_digit: + sum_first_digit = sum_first_digit + i*int(digit_two[-i+1]) first_digits_check = 10 - (sum_first_digit % 10) + if sum_first_digit % 10 == 0 or sum_first_digit % 10 == 1: + first_digits_check = '0' + + return str(first_digits_check) + str(second_digits_check) == digits_state_registration elif st_reg_number[-8] in ['6' , '7' , '9']: @@ -40,7 +47,10 @@ def check(st_reg_number): sum_second_digit = sum_second_digit + i*int(st_reg_number[-i-1]) second_digits_check = 11 - (sum_second_digit % 11) - + + if sum_second_digit % 11 == 0 or sum_second_digit % 11 == 1: + second_digits_check = '0' + if str(second_digits_check) !=second_digits: return False @@ -48,10 +58,14 @@ def check(st_reg_number): digit_two = number_state_registration + str(second_digits_check) for i in weights_first_digit: - sum_first_digit = sum_first_digit + i*int(digit_two[-i+1]) + sum_first_digit = sum_first_digit + i*int(digit_two[-i+1]) + print sum_first_digit first_digits_check = 11 - (sum_first_digit % 11) - + + if sum_first_digit % 11 == 0 or sum_first_digit % 11 == 1: + first_digits_check = '0' + return str(first_digits_check) + str(second_digits_check) == digits_state_registration diff --git a/st_reg/tests/test_states.py b/st_reg/tests/test_states.py index <HASH>..<HASH> 100644 --- a/st_reg/tests/test_states.py +++ b/st_reg/tests/test_states.py @@ -160,7 +160,8 @@ def test_ba_validation_right_size_invalid_number_8_digits_and_second_digit_diffe def test_ba_validation_right_size_valid_number_8_digits_and_second_digit_different_6_7_9(): """Test if a valid number is really valid with 8 digits""" - valid_number = '12345663' + valid_number = '74694200' + print ba.check(valid_number) assert ba.check(valid_number) == True def test_ba_validation_right_size_invalid_number_8_digits_and_second_digit_equal_6_7_9():
Fix bug in validating the state registration of the Bahia
matheuscas_pyIE
train
7d0f0f7e11823765b00fb90818be5ae0bc0a8e10
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -79,14 +79,18 @@ module.exports = function(grunt) { } }; - // Determine which files we should package + /** + * Determine which components we should package. + * + * The --components= parameter can be used to filter down components. + * The --effects= parameter can be used to include component effects. + */ var toPackage = grunt.option('components') ? grunt.option('components').split(',') : _.keys(manifest), - useEffects = grunt.option('effects') ? grunt.option('effects').split(',') : toPackage, + useEffects = grunt.option('effects') ? grunt.option('effects').split(',') : [], dependencies = {}; toPackage.forEach(addDependency); - // Helper functions function addDependency(name) { if (!manifest[name]) { log.error('Invalid component: ' + name); @@ -121,22 +125,39 @@ module.exports = function(grunt) { toPackage = _.union([name], toPackage); } - function mapSass(css) { - var map = {}; + /** + * Map all the available source files for each task. + * We need to map tons of different paths since each task accepts a different format -.- + */ + var cssPaths = { + build: dependencies.css, + buildSass: {} + }, + jsPaths = { + build: [], + buildUglify: {} + }; - css.forEach(function(path) { - map[path] = path.replace(/css/g, 'scss'); - }); + dependencies.css.forEach(function(path) { + cssPaths.buildSass[path] = path.replace(/css/g, 'scss'); + }); - return map; - } + dependencies.js.forEach(function(path) { + var buildPath = path.replace(/src/g, 'build'); + + jsPaths.build.push(buildPath); + jsPaths.buildUglify[buildPath] = path; + }); + /** + * Configure grunt and all its tasks. + */ function createBanner() { return "/*!\n" + " * Titon Toolkit v<%= pkg.version %>\n" + " * <%= pkg.copyright %> - <%= pkg.homepage %>\n" + " * <%= pkg.licenses[0].type %> - <%= pkg.licenses[0].url %>\n" + - " * Components: " + toPackage.join(', ') + "\n" + + " * Components: " + toPackage.sort().join(', ') + "\n" + " */\n"; } @@ -185,36 +206,34 @@ module.exports = function(grunt) { compass: 'src/config.rb' }, build: { - files: mapSass(dependencies.css) + files: cssPaths.buildSass } }, - // 3) Combine the JS and CSS components into a single file - // https://npmjs.org/package/grunt-contrib-concat - concat: { + // 3) Minify Javascript (CSS was minified in step 2) + // http://lisperator.net/uglifyjs/ + uglify: { options: { - banner: createBanner(), - separator: "" + report: 'min' }, build: { - files: [ - { src: dependencies.css, dest: '<%= buildFile %>.min.css' }, - { src: dependencies.js, dest: '<%= buildFile %>.min.js' } - ] + files: jsPaths.buildUglify } }, - // 4) Minify Javascript (CSS was minified in step 2) - // http://lisperator.net/uglifyjs/ - uglify: { + // 4) Combine the JS and CSS components into a single file + // https://npmjs.org/package/grunt-contrib-concat + concat: { options: { - report: 'min', - banner: createBanner() + stripBanners: true, + banner: createBanner(), + separator: "\n" }, build: { - files: { - '<%= buildFile %>.min.js': '<%= buildFile %>.min.js' - } + files: [ + { src: cssPaths.build, dest: '<%= buildFile %>.min.css' }, + { src: jsPaths.build, dest: '<%= buildFile %>.min.js' } + ] } }, @@ -245,5 +264,5 @@ module.exports = function(grunt) { // Register tasks grunt.registerTask('validate', ['jshint']); - grunt.registerTask('default', ['jshint', 'concat', 'uglify', 'compress']); + grunt.registerTask('default', ['jshint', 'uglify', 'concat', 'compress']); }; \ No newline at end of file
Swapped concat and uglify grunt order
titon_toolkit
train
fb1644fa4db606154ebd9d51a341f6d71a704e8d
diff --git a/fastlane/lib/fastlane/actions/import_from_git.rb b/fastlane/lib/fastlane/actions/import_from_git.rb index <HASH>..<HASH> 100644 --- a/fastlane/lib/fastlane/actions/import_from_git.rb +++ b/fastlane/lib/fastlane/actions/import_from_git.rb @@ -26,6 +26,10 @@ module Fastlane description: "The branch or tag to check-out on the repository", default_value: 'HEAD', optional: true), + FastlaneCore::ConfigItem.new(key: :dependencies, + description: "The array of additional Fastfiles in the repository", + default_value: [], + optional: true), FastlaneCore::ConfigItem.new(key: :path, description: "The path of the Fastfile in the repository", default_value: 'fastlane/Fastfile', diff --git a/fastlane/lib/fastlane/fast_file.rb b/fastlane/lib/fastlane/fast_file.rb index <HASH>..<HASH> 100644 --- a/fastlane/lib/fastlane/fast_file.rb +++ b/fastlane/lib/fastlane/fast_file.rb @@ -263,7 +263,7 @@ module Fastlane # @param branch [String] The branch to checkout in the repository # @param path [String] The path to the Fastfile # @param version [String, Array] Version requirement for repo tags - def import_from_git(url: nil, branch: 'HEAD', path: 'fastlane/Fastfile', version: nil) + def import_from_git(url: nil, branch: 'HEAD', path: 'fastlane/Fastfile', version: nil, dependencies: []) UI.user_error!("Please pass a path to the `import_from_git` action") if url.to_s.length == 0 Actions.execute_action('import_from_git') do @@ -280,6 +280,10 @@ module Fastlane branch_option = "--branch #{branch}" if branch != 'HEAD' + checkout_dependencies = dependencies.map(&:shellescape).join(" ") + + checkout_path = "#{path.shellescape} #{checkout_dependencies}" + UI.message("Cloning remote git repo...") Helper.with_env_values('GIT_TERMINAL_PROMPT' => '0') do Actions.sh("git clone #{url.shellescape} #{clone_folder.shellescape} --depth 1 -n #{branch_option}") @@ -292,7 +296,7 @@ module Fastlane UI.user_error!("No tag found matching #{version.inspect}") if checkout_param.nil? end - Actions.sh("cd #{clone_folder.shellescape} && git checkout #{checkout_param.shellescape} #{path.shellescape}") + Actions.sh("cd #{clone_folder.shellescape} && git checkout #{checkout_param.shellescape} #{checkout_path}") # We also want to check out all the local actions of this fastlane setup containing = path.split(File::SEPARATOR)[0..-2] @@ -304,7 +308,13 @@ module Fastlane # We don't care about a failure here, as local actions are optional end - return_value = import(File.join(clone_folder, path)) + return_value = nil + if dependencies.any? + return_value = [import(File.join(clone_folder, path))] + return_value += dependencies.map { |file_path| import(File.join(clone_folder, file_path)) } + else + return_value = import(File.join(clone_folder, path)) + end action_completed('import_from_git', status: FastlaneCore::ActionCompletionStatus::SUCCESS)
Import multiple files from git (#<I>)
fastlane_fastlane
train
6d2a0ab0dfcbdc90284848da30bdfee5d5286005
diff --git a/helper/communicator/config.go b/helper/communicator/config.go index <HASH>..<HASH> 100644 --- a/helper/communicator/config.go +++ b/helper/communicator/config.go @@ -13,6 +13,7 @@ import ( helperssh "github.com/hashicorp/packer/helper/ssh" "github.com/hashicorp/packer/template/interpolate" "github.com/masterzen/winrm" + "github.com/mitchellh/go-homedir" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" ) @@ -109,12 +110,11 @@ func (c *Config) SSHConfigFunc() func(multistep.StateBag) (*ssh.ClientConfig, er var privateKeys [][]byte if c.SSHPrivateKeyFile != "" { - // key based auth - bytes, err := ioutil.ReadFile(c.SSHPrivateKeyFile) + privateKey, err := c.ReadSSHPrivateKeyFile() if err != nil { - return nil, fmt.Errorf("Error setting up SSH config: %s", err) + return nil, err } - privateKeys = append(privateKeys, bytes) + privateKeys = append(privateKeys, privateKey) } // aws,alicloud,cloudstack,digitalOcean,oneAndOne,openstack,oracle & profitbricks key @@ -260,10 +260,14 @@ func (c *Config) prepareSSH(ctx *interpolate.Context) []error { } if c.SSHPrivateKeyFile != "" { - if _, err := os.Stat(c.SSHPrivateKeyFile); err != nil { + path, err := homedir.Expand(c.SSHPrivateKeyFile) + if err != nil { + errs = append(errs, fmt.Errorf( + "ssh_private_key_file is invalid: %s", err)) + } else if _, err := os.Stat(path); err != nil { errs = append(errs, fmt.Errorf( "ssh_private_key_file is invalid: %s", err)) - } else if _, err := helperssh.FileSigner(c.SSHPrivateKeyFile); err != nil { + } else if _, err := helperssh.FileSigner(path); err != nil { errs = append(errs, fmt.Errorf( "ssh_private_key_file is invalid: %s", err)) }
communicator/ssh: expand user path for private key
hashicorp_packer
train
c8f2e2be77bdd6fda2ae4123e3d2690d99a805d1
diff --git a/SlevomatCodingStandard/Sniffs/TypeHints/PropertyTypeHintSniff.php b/SlevomatCodingStandard/Sniffs/TypeHints/PropertyTypeHintSniff.php index <HASH>..<HASH> 100644 --- a/SlevomatCodingStandard/Sniffs/TypeHints/PropertyTypeHintSniff.php +++ b/SlevomatCodingStandard/Sniffs/TypeHints/PropertyTypeHintSniff.php @@ -170,10 +170,16 @@ class PropertyTypeHintSniff implements Sniff continue; } + $isTraversable = TypeHintHelper::isTraversableType(TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $propertyPointer, $typeHint), $this->getTraversableTypeHints()); + + if (!$isTraversable && count($traversableTypeHints) > 0) { + return; + } + if ( !$innerTypeNode instanceof ArrayTypeNode && !$innerTypeNode instanceof ArrayShapeNode - && TypeHintHelper::isTraversableType(TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $propertyPointer, $typeHint), $this->getTraversableTypeHints()) + && $isTraversable ) { $traversableTypeHints[] = $typeHint; } diff --git a/tests/Sniffs/TypeHints/data/propertyTypeHintEnabledNativeNoErrors.php b/tests/Sniffs/TypeHints/data/propertyTypeHintEnabledNativeNoErrors.php index <HASH>..<HASH> 100644 --- a/tests/Sniffs/TypeHints/data/propertyTypeHintEnabledNativeNoErrors.php +++ b/tests/Sniffs/TypeHints/data/propertyTypeHintEnabledNativeNoErrors.php @@ -121,4 +121,9 @@ class Whatever /** @var mixed[]|array|Traversable */ public $moreTraverasableTypes; + /** + * @var mixed[]|array|SomethingThatLooksAsArray + */ + public $moreDifferentTypes; + }
PropertyTypeHintSniff: Fixed false positive
slevomat_coding-standard
train
aa890bb857da004adde0d226945e3111b14c5e48
diff --git a/airflow/contrib/hooks/bigquery_hook.py b/airflow/contrib/hooks/bigquery_hook.py index <HASH>..<HASH> 100644 --- a/airflow/contrib/hooks/bigquery_hook.py +++ b/airflow/contrib/hooks/bigquery_hook.py @@ -495,6 +495,93 @@ class BigQueryBaseCursor(object): .execute() ) + def run_table_upsert(self, dataset_id, table_resource, project_id=None): + """ + creates a new, empty table in the dataset; + If the table already exists, update the existing table. + Since BigQuery does not natively allow table upserts, this is not an + atomic operation. + :param dataset_id: the dataset to upsert the table into. + :type dataset_id: str + :param table_resource: a table resource. see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource + :type table_resource: dict + :param project_id: the project to upsert the table into. If None, + project will be self.project_id. + :return: + """ + # check to see if the table exists + table_id = table_resource['tableReference']['tableId'] + table_exists = False + project_id = project_id if project_id is not None else self.project_id + tables_list_resp = self.service.tables().list(projectId=project_id, + datasetId=dataset_id).execute() + if 'tables' in tables_list_resp: + for table in tables_list_resp['tables']: + if table['tableReference']['tableId'] == table_id: + table_exists = True + break + + # do update if table exists + if table_exists: + logging.info('table %s:%s.%s exists, updating.', project_id, dataset_id, table_id) + return self.service.tables().update(projectId=project_id, + datasetId=dataset_id, + tableId=table_id, + body=table_resource).execute() + # do insert if table does not exist + else: + logging.info('table %s:%s.%s does not exist. creating.', project_id, dataset_id, table_id) + return self.service.tables().insert(projectId=project_id, + datasetId=dataset_id, + body=table_resource).execute() + + def run_grant_dataset_view_access(self, + source_project, + source_dataset, + view_project, + view_dataset, + view_table): + """ + Grant authorized view access of a dataset to a view table. + If this view has already been granted access to the dataset, do nothing. + This method is not atomic. Running it may clobber a simultaneous update. + :param source_project: the project of the source dataset + :type source_project: str + :param source_dataset: the source dataset + :type source_dataset: str + :param view_project: the project that the view is in + :type view_project: str + :param view_dataset: the dataset that the view is in + :type view_dataset: str + :param view_table: the table of the view + :type view_table: str + :return: the datasets resource of the source dataset. + """ + + # we don't want to clobber any existing accesses, so we have to get + # info on the dataset before we can add view access + source_dataset_resource = self.service.datasets().get(projectId=source_project, + datasetId=source_dataset).execute() + access = source_dataset_resource['access'] if 'access' in source_dataset_resource else [] + view_access = {'view': {'projectId': view_project, + 'datasetId': view_dataset, + 'tableId': view_table}} + # check to see if the view we want to add already exists. + if view_access not in access: + logging.info('granting table %s:%s.%s authorized view access to %s:%s dataset.', + view_project, view_dataset, view_table, + source_project, source_dataset) + access.append(view_access) + return self.service.datasets().patch(projectId=source_project, + datasetId=source_dataset, + body={'access': access}).execute() + else: + # if view is already in access, do nothing. + logging.info('table %s:%s.%s already has authorized view access to %s:%s dataset.', + view_project, view_dataset, view_table, + source_project, source_dataset) + return source_dataset_resource + class BigQueryCursor(BigQueryBaseCursor): """
Add two methods to bigquery hook's base cursor: run_table_upsert, which adds a table or updates an existing table; and run_grant_dataset_view_access, which grants view access to a given dataset for a given table.
apache_airflow
train
4bcc3719dae8d2a3540784b51630faab0e9c90e4
diff --git a/lib/riddle/query/select.rb b/lib/riddle/query/select.rb index <HASH>..<HASH> 100644 --- a/lib/riddle/query/select.rb +++ b/lib/riddle/query/select.rb @@ -66,7 +66,7 @@ class Riddle::Query::Select end sql << " #{limit_clause}" unless @limit.nil? && @offset.nil? sql << " #{options_clause}" unless @options.empty? - + sql end @@ -88,10 +88,21 @@ class Riddle::Query::Select def wheres_to_s @wheres.keys.collect { |key| - "#{key} = #{@wheres[key]}" + "#{key} = #{filter_value @wheres[key]}" }.join(' AND ') end + def filter_value(value) + case value + when TrueClass + 1 + when FalseClass + 0 + else + value + end + end + def limit_clause if @offset.nil? "LIMIT #{@limit}" diff --git a/spec/riddle/query/select_spec.rb b/spec/riddle/query/select_spec.rb index <HASH>..<HASH> 100644 --- a/spec/riddle/query/select_spec.rb +++ b/spec/riddle/query/select_spec.rb @@ -2,61 +2,71 @@ require 'spec_helper' describe Riddle::Query::Select do let(:query) { Riddle::Query::Select.new } - + it 'handles basic queries on a specific index' do query.from('foo_core').to_sql.should == 'SELECT * FROM foo_core' end - + it 'handles queries on multiple indices' do query.from('foo_core').from('foo_delta').to_sql. should == 'SELECT * FROM foo_core, foo_delta' end - + it 'accepts multiple arguments for indices' do query.from('foo_core', 'foo_delta').to_sql. should == 'SELECT * FROM foo_core, foo_delta' end - + it 'handles basic queries with a search term' do query.from('foo_core').matching('foo').to_sql. should == "SELECT * FROM foo_core WHERE MATCH('foo')" end - + it 'handles filters with integers' do query.from('foo_core').matching('foo').where(:bar_id => 10).to_sql. should == "SELECT * FROM foo_core WHERE MATCH('foo') AND bar_id = 10" end - + + it "handles filters with true" do + query.from('foo_core').matching('foo').where(:bar => true).to_sql. + should == "SELECT * FROM foo_core WHERE MATCH('foo') AND bar = 1" + end + + it "handles filters with false" do + query.from('foo_core').matching('foo').where(:bar => false).to_sql. + should == "SELECT * FROM foo_core WHERE MATCH('foo') AND bar = 0" + end + it 'handles grouping' do query.from('foo_core').group_by('bar_id').to_sql. should == "SELECT * FROM foo_core GROUP BY bar_id" end - + it 'handles ordering' do query.from('foo_core').order_by('bar_id ASC').to_sql. should == 'SELECT * FROM foo_core ORDER BY bar_id ASC' end - + it 'handles group ordering' do query.from('foo_core').order_within_group_by('bar_id ASC').to_sql. should == 'SELECT * FROM foo_core WITHIN GROUP ORDER BY bar_id ASC' end - + it 'handles a limit' do query.from('foo_core').limit(10).to_sql. should == 'SELECT * FROM foo_core LIMIT 10' end - + it 'handles an offset' do query.from('foo_core').offset(20).to_sql. should == 'SELECT * FROM foo_core LIMIT 20, 20' end - + it 'handles an option' do query.from('foo_core').with_options(:bar => :baz).to_sql. should == 'SELECT * FROM foo_core OPTION bar=baz' end - + it 'handles multiple options' do sql = query.from('foo_core').with_options(:bar => :baz, :qux => :quux). to_sql
Handle boolean values for filters in SphinxQL queries.
pat_riddle
train
502944d054c2ad3d758b88b1a3c1816a3b3402d5
diff --git a/java/server/src/org/openqa/selenium/grid/security/RequiresSecretFilter.java b/java/server/src/org/openqa/selenium/grid/security/RequiresSecretFilter.java index <HASH>..<HASH> 100644 --- a/java/server/src/org/openqa/selenium/grid/security/RequiresSecretFilter.java +++ b/java/server/src/org/openqa/selenium/grid/security/RequiresSecretFilter.java @@ -24,11 +24,12 @@ import org.openqa.selenium.remote.http.HttpHandler; import org.openqa.selenium.remote.http.HttpRequest; import org.openqa.selenium.remote.http.HttpResponse; -import java.util.Objects; +import java.util.TreeMap; import java.util.logging.Logger; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; import static org.openqa.selenium.grid.security.AddSecretFilter.HEADER_NAME; +import static org.openqa.selenium.json.Json.JSON_UTF_8; public class RequiresSecretFilter implements Filter { @@ -47,8 +48,14 @@ public class RequiresSecretFilter implements Filter { if (!isSecretMatch(secret, req)) { return new HttpResponse() .setStatus(HTTP_UNAUTHORIZED) - .addHeader("Content-Type", "text/plain; charset=UTF-8") - .setContent(Contents.utf8String("Unauthorized access attempted to " + req.getUri())); + .addHeader("Content-Type", JSON_UTF_8) + .setContent(Contents.asJson(new TreeMap<String, Object>() {{ + put("value", new TreeMap<String, Object>() {{ + put("error", "unknown error"); + put("message", "Unauthorized access attempted to " + req); + put("stacktrace", ""); + }}); + }})); } return httpHandler.execute(req); @@ -59,7 +66,7 @@ public class RequiresSecretFilter implements Filter { String header = request.getHeader(HEADER_NAME); if (header == null) { if (secret != null) { - LOG.warning("Unexpected secret sent!"); + LOG.warning("Unexpectedly received registration secret to " + request); return false; } return true; @@ -68,7 +75,7 @@ public class RequiresSecretFilter implements Filter { Secret requestSecret = new Secret(header); if (!secret.matches(requestSecret)) { - LOG.warning("Secrets did not match!"); + LOG.warning("Unauthorized access attempted to " + request); return false; }
[grid] RequiresSecretFilter now returns a regular webdriver response
SeleniumHQ_selenium
train
7b1502b93e365e22f0ed5a1f4ae191e5a8f15b83
diff --git a/_config.php b/_config.php index <HASH>..<HASH> 100644 --- a/_config.php +++ b/_config.php @@ -1,3 +1,3 @@ <?php -define('RESPONSIVE_IMAGES_DIR', basename(dirname(__FILE__))); +define('RESPONSIVE_IMAGES_DIR', dirname(__FILE__));
Removed basename call, to enable vendor path reference
heyday_silverstripe-responsive-images
train
ec30a2616ce6230e673ad0f3d0afdbd860d53971
diff --git a/src/main/java/gwt/material/design/client/ui/table/cell/Column.java b/src/main/java/gwt/material/design/client/ui/table/cell/Column.java index <HASH>..<HASH> 100644 --- a/src/main/java/gwt/material/design/client/ui/table/cell/Column.java +++ b/src/main/java/gwt/material/design/client/ui/table/cell/Column.java @@ -281,9 +281,7 @@ public abstract class Column<T, C> implements HasCell<T, C> { public final Comparator<? super RowComponent<T>> sortComparator() { if (sortComparator == null) { - sortComparator = (o1, o2) -> { - return o1.compareTo(o2.getData()); - }; + sortComparator = Comparator.comparing(o -> getValue(o.getData()).toString()); } return sortComparator; }
BUG: DataTable default sort is not using the value to sort by correctly
GwtMaterialDesign_gwt-material-table
train
5acffb9fa30286912e7170caa6cc73ac8f15f344
diff --git a/dfply/transform.py b/dfply/transform.py index <HASH>..<HASH> 100644 --- a/dfply/transform.py +++ b/dfply/transform.py @@ -17,7 +17,7 @@ def transmute(df, *keep_columns, **kwargs): # ------------------------------------------------------------------------------ -# Series operation helper functions +# Window functions # ------------------------------------------------------------------------------ def lead(series, i=1): @@ -30,9 +30,9 @@ def lag(series, i=1): return shifted -def row_number(series): - row_numbers = np.arange(len(series)) - return row_numbers +# def row_number(series): +# row_numbers = np.arange(len(series)) +# return row_numbers def between(series, a, b, inclusive=False):
commented out row_number (incorrect functionality compared to dplyr)
kieferk_dfply
train
547ada2e104dbe035a05c9ee2fb82582d2a1e916
diff --git a/spec/mongoid/contextual/atomic_spec.rb b/spec/mongoid/contextual/atomic_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mongoid/contextual/atomic_spec.rb +++ b/spec/mongoid/contextual/atomic_spec.rb @@ -496,7 +496,7 @@ describe Mongoid::Contextual::Atomic do end end - describe "#push_each" do + describe "#push_all" do context 'when the criteria does not have a collation' do @@ -517,7 +517,7 @@ describe Mongoid::Contextual::Atomic do end before do - context.push_each(members: [ "Alan", "Fletch" ]) + context.push_all(members: [ "Alan", "Fletch" ]) end it "pushes the values to existing arrays" do @@ -548,7 +548,7 @@ describe Mongoid::Contextual::Atomic do end before do - context.push_each(members: [ "Alan", "Fletch" ]) + context.push_all(members: [ "Alan", "Fletch" ]) end it "pushes the values to existing arrays" do
MONGOID-<I> Update spec after method name change
mongodb_mongoid
train
1f9f941b3502eb717ca04b213403b3f8c311ee60
diff --git a/scripts/emulator.js b/scripts/emulator.js index <HASH>..<HASH> 100644 --- a/scripts/emulator.js +++ b/scripts/emulator.js @@ -8,6 +8,9 @@ const inquirer = require('inquirer') const { execSync } = require('child_process') const emulators = execSync(`$ANDROID_HOME/emulator/emulator -list-avds`).toString() +const sdks = execSync( + `$ANDROID_HOME/tools/bin/sdkmanager --list | grep "system-images/" `, +).toString() const askForEmu = [ { @@ -24,16 +27,37 @@ const askForEmu = [ .concat([ new inquirer.Separator(), { - name: 'New Emu', + name: 'New Emulator', value: null, }, new inquirer.Separator(), ]), }, { - type: 'input', + type: 'list', name: 'sdk', when: answers => !answers.name, + message: 'Sdk Version:', + choices: sdks + .split('\n') + .filter(value => value.length > 0) + .map(sdk => ({ + name: sdk.split(' ')[2].slice(14), + value: sdk.split(' ')[2], + })) + .concat([ + new inquirer.Separator(), + { + name: 'Other Sdk', + value: null, + }, + new inquirer.Separator(), + ]), + }, + { + type: 'input', + name: 'sdk', + when: answers => !answers.sdk && !answers.name, message: 'Sdk Version (21-28):', validate: input => input > 20 && input < 29, }, @@ -48,6 +72,8 @@ const askForEmu = [ const openEmu = options => { const { name, sdk } = options if (sdk !== undefined) { + const sdkPath = + sdk.length === 2 ? `system-images;android-${sdk.replace(/\s/g, '')};google_apis;x86` : sdk return [ { title: 'Downloading Emulator Image', @@ -55,25 +81,15 @@ const openEmu = options => { console.log('Downloading Emulator Image\nIt may take a while') execSync('touch ~/.android/repositories.cfg') execSync('export JAVA_OPTS="-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee"') - execSync( - `$ANDROID_HOME/tools/bin/sdkmanager "system-images;android-${sdk.replace( - /\s/g, - '', - )};google_apis;x86"`, - ) + execSync(`$ANDROID_HOME/tools/bin/sdkmanager "${sdkPath}"`) }, }, { title: `Creating Emulator ${name}`, task: () => { execSync( - `echo no | $ANDROID_HOME/tools/bin/avdmanager create avd -n ${name.replace( - /\s/g, - '', - )} -k "system-images;android-${sdk.replace( - /\s/g, - '', - )};google_apis;x86" --device "Nexus 6P"`, + `echo no | $ANDROID_HOME/tools/bin/avdmanager \ + create avd -n ${name.replace(/\s/g, '')} -k "${sdkPath}" --device "Nexus 6P"`, ) }, },
[Script][Emulator] Better Sdk management, cleaner code
Nozbe_WatermelonDB
train
3c26ff2003ef6a44ffd15ebb641d91405681db44
diff --git a/lib/amber/i18n.rb b/lib/amber/i18n.rb index <HASH>..<HASH> 100644 --- a/lib/amber/i18n.rb +++ b/lib/amber/i18n.rb @@ -1,4 +1,4 @@ - +# encoding: utf-8 require 'i18n' require 'i18n/backend/fallbacks' diff --git a/lib/amber/version.rb b/lib/amber/version.rb index <HASH>..<HASH> 100644 --- a/lib/amber/version.rb +++ b/lib/amber/version.rb @@ -1,5 +1,5 @@ module Amber unless defined?(Amber::VERSION) - VERSION = '0.3.5' + VERSION = '0.3.6' end end \ No newline at end of file
fix missing encoding in i<I>n.rb
leapcode_amber
train
1696bbc6ca60461a52dd8382929c2cd5be2803eb
diff --git a/test/extractFields.js b/test/extractFields.js index <HASH>..<HASH> 100644 --- a/test/extractFields.js +++ b/test/extractFields.js @@ -61,6 +61,10 @@ describe('extractFields', function () { 0: 'this Saturday', 1: 'next Saturday', '-1': 'last Saturday' + }, + relativeTime: { + future: { one: 'in {0} Saturday', other: 'in {0} Saturdays' }, + past: { one: '{0} Saturday ago', other: '{0} Saturdays ago' } } }); diff --git a/test/extractListPatterns.js b/test/extractListPatterns.js index <HASH>..<HASH> 100644 --- a/test/extractListPatterns.js +++ b/test/extractListPatterns.js @@ -4,7 +4,7 @@ var expect = require('unexpected'), describe('extractListPatterns', function () { it('should extract the British English list patterns correctly', function () { var britishListPatterns = cldr.extractListPatterns('en_GB'); - expect(britishListPatterns, 'to only have keys', ['default', 'unit', 'unitNarrow', 'unitShort']); + expect(britishListPatterns, 'to only have keys', ['default', 'unit', 'unitNarrow', 'unitShort', 'standardShort']); expect(britishListPatterns.default, 'to equal', { 2: '{0} and {1}', start: '{0}, {1}',
Fix failing tests that expect less data to be present :)
papandreou_node-cldr
train
6afefddb4433bd85e31c4c6a16be3e20bae1bb93
diff --git a/src/Intervention/Image/Gd/Commands/LimitColorsCommand.php b/src/Intervention/Image/Gd/Commands/LimitColorsCommand.php index <HASH>..<HASH> 100644 --- a/src/Intervention/Image/Gd/Commands/LimitColorsCommand.php +++ b/src/Intervention/Image/Gd/Commands/LimitColorsCommand.php @@ -25,7 +25,7 @@ class LimitColorsCommand extends \Intervention\Image\Commands\AbstractCommand // define matte if (is_null($matte)) { - $matte = imagecolorallocatealpha($resource, 0, 0, 0, 127); + $matte = imagecolorallocatealpha($resource, 255, 255, 255, 127); } else { $matte = $image->getDriver()->parseColor($matte)->getInt(); } diff --git a/src/Intervention/Image/Gd/Commands/ResizeCanvasCommand.php b/src/Intervention/Image/Gd/Commands/ResizeCanvasCommand.php index <HASH>..<HASH> 100644 --- a/src/Intervention/Image/Gd/Commands/ResizeCanvasCommand.php +++ b/src/Intervention/Image/Gd/Commands/ResizeCanvasCommand.php @@ -69,7 +69,7 @@ class ResizeCanvasCommand extends \Intervention\Image\Commands\AbstractCommand // make image area transparent to keep transparency // even if background-color is set - $transparent = imagecolorallocatealpha($canvas->getCore(), 0, 0, 0, 127); + $transparent = imagecolorallocatealpha($canvas->getCore(), 255, 255, 255, 127); imagealphablending($canvas->getCore(), false); // do not blend / just overwrite imagefilledrectangle($canvas->getCore(), $dst_x, $dst_y, $dst_x + $src_w - 1, $dst_y + $src_h - 1, $transparent); diff --git a/src/Intervention/Image/Gd/Source.php b/src/Intervention/Image/Gd/Source.php index <HASH>..<HASH> 100644 --- a/src/Intervention/Image/Gd/Source.php +++ b/src/Intervention/Image/Gd/Source.php @@ -110,10 +110,6 @@ class Source extends \Intervention\Image\AbstractSource */ public function gdResourceToTruecolor(&$resource) { - if (imageistruecolor($resource)) { - return true; - } - $width = imagesx($resource); $height = imagesy($resource); @@ -122,7 +118,7 @@ class Source extends \Intervention\Image\AbstractSource // fill with transparent color imagealphablending($canvas, false); - $transparent = imagecolorallocatealpha($canvas, 0, 0, 0, 127); + $transparent = imagecolorallocatealpha($canvas, 255, 255, 255, 127); imagefilledrectangle($canvas, 0, 0, $width, $height, $transparent); imagealphablending($canvas, true); diff --git a/src/Intervention/Image/Imagick/Encoder.php b/src/Intervention/Image/Imagick/Encoder.php index <HASH>..<HASH> 100644 --- a/src/Intervention/Image/Imagick/Encoder.php +++ b/src/Intervention/Image/Imagick/Encoder.php @@ -15,6 +15,9 @@ class Encoder extends \Intervention\Image\AbstractEncoder $compression = \Imagick::COMPRESSION_JPEG; $imagick = $this->image->getCore(); + $imagick->setImageBackgroundColor('white'); + $imagick->setBackgroundColor('white'); + $imagick = $imagick->flattenImages(); $imagick->setFormat($format); $imagick->setImageFormat($format); $imagick->setCompression($compression); diff --git a/tests/EncoderTest.php b/tests/EncoderTest.php index <HASH>..<HASH> 100644 --- a/tests/EncoderTest.php +++ b/tests/EncoderTest.php @@ -140,6 +140,9 @@ class EncoderTest extends PHPUnit_Framework_TestCase $imagick->shouldReceive('setimagecompression')->once(); $imagick->shouldReceive('setcompressionquality'); $imagick->shouldReceive('setimagecompressionquality'); + $imagick->shouldReceive('setimagebackgroundcolor'); + $imagick->shouldReceive('setbackgroundcolor'); + $imagick->shouldReceive('flattenimages')->andReturn($imagick); $imagick->shouldReceive('__toString')->once()->andReturn(sprintf('mock-%s', $type)); return $imagick; } diff --git a/tests/GdSystemTest.php b/tests/GdSystemTest.php index <HASH>..<HASH> 100644 --- a/tests/GdSystemTest.php +++ b/tests/GdSystemTest.php @@ -1113,9 +1113,9 @@ class GdSystemTest extends PHPUnit_Framework_TestCase $this->assertEquals(1, $c[3]); $c = $img->pickColor(0, 15); - $this->assertEquals(0, $c[0]); - $this->assertEquals(0, $c[1]); - $this->assertEquals(0, $c[2]); + $this->assertEquals(255, $c[0]); + $this->assertEquals(255, $c[1]); + $this->assertEquals(255, $c[2]); $this->assertEquals(0, $c[3]); } @@ -1137,9 +1137,9 @@ class GdSystemTest extends PHPUnit_Framework_TestCase $this->assertEquals(1, $c[3]); $c = $img->pickColor(0, 15); - $this->assertEquals(0, $c[0]); - $this->assertEquals(0, $c[1]); - $this->assertEquals(0, $c[2]); + $this->assertEquals(255, $c[0]); + $this->assertEquals(255, $c[1]); + $this->assertEquals(255, $c[2]); $this->assertEquals(0, $c[3]); }
fixed issue when converting transparent images to non-transparent formats
Intervention_image
train
5d48f6c87ab58557a40e0b377826b21ab57dbfb5
diff --git a/lib/cri.rb b/lib/cri.rb index <HASH>..<HASH> 100644 --- a/lib/cri.rb +++ b/lib/cri.rb @@ -3,10 +3,10 @@ module Cri # The current Cri version. VERSION = '1.1' + autoload 'Base', 'cri/base' + autoload 'Command', 'cri/command' + autoload 'OptionParser', 'cri/option_parser' + end -# Load Cri -require 'cri/base' -require 'cri/command' require 'cri/core_ext' -require 'cri/option_parser'
switched to autoload for easiness
ddfreyne_cri
train
1d2788457fd84bff10e921f439927e9304f70842
diff --git a/linux_backend/linux_container.go b/linux_backend/linux_container.go index <HASH>..<HASH> 100644 --- a/linux_backend/linux_container.go +++ b/linux_backend/linux_container.go @@ -30,8 +30,7 @@ type LinuxContainer struct { graceTime time.Duration - state State - stateMutex sync.RWMutex + state State events []string eventsMutex sync.RWMutex @@ -156,9 +155,6 @@ func (c *LinuxContainer) GraceTime() time.Duration { } func (c *LinuxContainer) State() State { - c.stateMutex.RLock() - defer c.stateMutex.RUnlock() - return c.state } @@ -233,7 +229,7 @@ func (c *LinuxContainer) Snapshot(out io.Writer) error { } func (c *LinuxContainer) Restore(snapshot ContainerSnapshot) error { - c.setState(State(snapshot.State)) + c.state = State(snapshot.State) for _, ev := range snapshot.Events { c.registerEvent(ev) @@ -294,7 +290,7 @@ func (c *LinuxContainer) Start() error { return err } - c.setState(StateActive) + c.state = StateActive return nil } @@ -317,7 +313,7 @@ func (c *LinuxContainer) Stop(kill bool) error { c.stopOomNotifier() - c.setState(StateStopped) + c.state = StateStopped return nil } @@ -673,13 +669,6 @@ func (c *LinuxContainer) NetOut(network string, port uint32) error { return nil } -func (c *LinuxContainer) setState(state State) { - c.stateMutex.Lock() - defer c.stateMutex.Unlock() - - c.state = state -} - func (c *LinuxContainer) registerEvent(event string) { c.eventsMutex.Lock() defer c.eventsMutex.Unlock()
remove overly-defensive state transition mutex
cloudfoundry_garden
train
2654b74e0d6e2d5b8e1cc6a36f99b14481fe06d0
diff --git a/nats.go b/nats.go index <HASH>..<HASH> 100644 --- a/nats.go +++ b/nats.go @@ -2424,3 +2424,17 @@ func (nc *Conn) MaxPayload() int64 { defer nc.mu.Unlock() return nc.info.MaxPayload } + +// AuthRequired will return if the connected server requires authorization. +func (nc *Conn) AuthRequired() bool { + nc.mu.Lock() + defer nc.mu.Unlock() + return nc.info.AuthRequired +} + +// TLSRequired will return if the connected server requires TLS connections. +func (nc *Conn) TLSRequired() bool { + nc.mu.Lock() + defer nc.mu.Unlock() + return nc.info.TLSRequired +}
Added in checks for auth and tls requirements
nats-io_go-nats
train
be52eaf3ef4c984116b610d5f6b7fffa0dd4d091
diff --git a/phoebe/frontend/bundle.py b/phoebe/frontend/bundle.py index <HASH>..<HASH> 100644 --- a/phoebe/frontend/bundle.py +++ b/phoebe/frontend/bundle.py @@ -1310,29 +1310,29 @@ class Bundle(ParameterSet): for component in self.hierarchy.get_stars(): # first check ld_coeffs_bol vs ld_func_bol - ld_func = self.get_value(qualifier='ld_func_bol', component=component, context='component', check_visible=False, **kwargs) - ld_coeffs = self.get_value(qualifier='ld_coeffs_bol', component=component, context='component', check_visible=False, **kwargs) + ld_func = str(self.get_value(qualifier='ld_func_bol', component=component, context='component', check_visible=False, **kwargs)) + ld_coeffs = np.asarray(self.get_value(qualifier='ld_coeffs_bol', component=component, context='component', check_visible=False, **kwargs)) check = ld_coeffs_len(ld_func, ld_coeffs) if not check[0]: return check - if ld_func is not 'interp': - check = libphoebe.ld_check(ld_func, np.asarray(ld_coeffs)) + if ld_func != 'interp': + check = libphoebe.ld_check(ld_func, ld_coeffs) if not check: return False, 'ld_coeffs_bol={} not compatible for ld_func_bol=\'{}\'.'.format(ld_coeffs, ld_func) for dataset in self.datasets: if dataset=='_default' or self.get_dataset(dataset=dataset, kind='*dep').kind not in ['lc_dep', 'rv_dep']: continue - ld_func = self.get_value(qualifier='ld_func', dataset=dataset, component=component, context='dataset', **kwargs) - ld_coeffs = self.get_value(qualifier='ld_coeffs', dataset=dataset, component=component, context='dataset', check_visible=False, **kwargs) + ld_func = str(self.get_value(qualifier='ld_func', dataset=dataset, component=component, context='dataset', **kwargs)) + ld_coeffs = np.asarray(self.get_value(qualifier='ld_coeffs', dataset=dataset, component=component, context='dataset', check_visible=False, **kwargs)) if ld_coeffs is not None: check = ld_coeffs_len(ld_func, ld_coeffs) if not check[0]: return check - if ld_func is not 'interp': - check = libphoebe.ld_check(ld_func, np.asarray(ld_coeffs)) + if ld_func != 'interp': + check = libphoebe.ld_check(ld_func, ld_coeffs) if not check: return False, 'ld_coeffs={} not compatible for ld_func=\'{}\'.'.format(ld_coeffs, ld_func)
make sure to cast ld_func and ld_coeffs so libphoebe doesn't complain
phoebe-project_phoebe2
train
92731c521d5d242e3a1d2350ea3dd71db1d989a4
diff --git a/src/ossos-pipeline/pymop/pymop/io/workload.py b/src/ossos-pipeline/pymop/pymop/io/workload.py index <HASH>..<HASH> 100644 --- a/src/ossos-pipeline/pymop/pymop/io/workload.py +++ b/src/ossos-pipeline/pymop/pymop/io/workload.py @@ -52,7 +52,7 @@ class WorkUnit(object): return self.work_items -class WorkUnitFactory(object): +class WorkUnitProvider(object): def __init__(self, taskid, directory_manager, @@ -63,7 +63,7 @@ class WorkUnitFactory(object): self.progress_manager = progress_manager self.builder = builder - def create_workunit(self): + def get_workunit(self): potential_files = self.directory_manager.get_listing(self.taskid) while len(potential_files) > 0: diff --git a/src/ossos-pipeline/pymop/test/test_pymop/test_io/test_workload.py b/src/ossos-pipeline/pymop/test/test_pymop/test_io/test_workload.py index <HASH>..<HASH> 100644 --- a/src/ossos-pipeline/pymop/test/test_pymop/test_io/test_workload.py +++ b/src/ossos-pipeline/pymop/test/test_pymop/test_io/test_workload.py @@ -10,7 +10,7 @@ from test.base_tests import FileReadingTestCase from pymop import tasks from pymop.io import workload from pymop.io.persistence import InMemoryProgressManager -from pymop.io.workload import (WorkUnitFactory, DirectoryManager, +from pymop.io.workload import (WorkUnitProvider, DirectoryManager, WorkUnit, NoAvailableWorkException) @@ -48,7 +48,7 @@ class WorkUnitFactoryTest(unittest.TestCase): progress_manager = InMemoryProgressManager(directory_manager) builder = TestWorkUnitBuilder() - self.undertest = WorkUnitFactory(self.taskid, directory_manager, + self.undertest = WorkUnitProvider(self.taskid, directory_manager, progress_manager, builder) self.directory_manager = directory_manager self.progress_manager = progress_manager @@ -56,40 +56,40 @@ class WorkUnitFactoryTest(unittest.TestCase): def test_create_workload_acquires_lock(self): self.directory_manager.set_listing(self.taskid, self.test_files) - workunit1 = self.undertest.create_workunit() + workunit1 = self.undertest.get_workunit() assert_that(self.progress_manager.owns_lock(workunit1.get_filename()), equal_to(True)) def test_create_workload_fresh_directory(self): - workunit1 = self.undertest.create_workunit() + workunit1 = self.undertest.get_workunit() assert_that(workunit1.get_filename(), is_in(self.test_files)) self.progress_manager.record_done(workunit1.get_filename()) - workunit2 = self.undertest.create_workunit() + workunit2 = self.undertest.get_workunit() assert_that(workunit2.get_filename(), is_in(self.test_files)) assert_that(workunit2.get_filename(), is_not(equal_to(workunit1.get_filename()))) self.progress_manager.record_done(workunit2.get_filename()) - self.assertRaises(NoAvailableWorkException, self.undertest.create_workunit) + self.assertRaises(NoAvailableWorkException, self.undertest.get_workunit) def test_create_workload_one_file_already_done(self): self.progress_manager.done.append(self.file1) - workunit = self.undertest.create_workunit() + workunit = self.undertest.get_workunit() assert_that(workunit.get_filename(), equal_to(self.file2)) self.progress_manager.record_done(self.file2) - self.assertRaises(NoAvailableWorkException, self.undertest.create_workunit) + self.assertRaises(NoAvailableWorkException, self.undertest.get_workunit) def test_create_workload_locked_files(self): self.progress_manager.add_external_lock(self.file2) - workunit = self.undertest.create_workunit() + workunit = self.undertest.get_workunit() assert_that(workunit.get_filename(), equal_to(self.file1)) self.progress_manager.record_done(self.file1) - self.assertRaises(NoAvailableWorkException, self.undertest.create_workunit) + self.assertRaises(NoAvailableWorkException, self.undertest.get_workunit) class DirectoryManagerTest(FileReadingTestCase):
Renamed WorkUnitFactory to WorkUnitProvider and renamed create_workunit to get_workunit.
OSSOS_MOP
train
0be8ec1893d39c27a01259cbb832a1a693f5831b
diff --git a/eeweather/mappings.py b/eeweather/mappings.py index <HASH>..<HASH> 100644 --- a/eeweather/mappings.py +++ b/eeweather/mappings.py @@ -165,7 +165,12 @@ class ISDStationMapping(MappingResult): target_longitude, target_latitude, self.isd_station.longitude, self.isd_station.latitude)[2]) - if distance_meters > 50000: + if distance_meters > 200000: + # CalTrack 2.4.2 + self.warnings.append( + 'Distance from target to weather station is greater than 200km.' + ) + elif distance_meters > 50000: self.warnings.append( 'Distance from target to weather station is greater than 50km.' ) diff --git a/tests/test_mappings.py b/tests/test_mappings.py index <HASH>..<HASH> 100644 --- a/tests/test_mappings.py +++ b/tests/test_mappings.py @@ -24,7 +24,7 @@ def test_empty_mapping(): assert repr(mapping) == "EmptyMapping(warnings=['No mapping result was found.'])" -def test_mapping_result_blank_default_kwargs(): +def test_mapping_result_blank_default_kwargs_200km_away(): mapping = ISDStationMapping('720446', 40, -110) assert mapping.target_latitude == 40 assert mapping.target_longitude == -110 @@ -32,13 +32,28 @@ def test_mapping_result_blank_default_kwargs(): assert mapping.distance_meters == 2132142 assert mapping.isd_station.usaf_id == '720446' assert mapping.warnings == [ - 'Distance from target to weather station is greater than 50km.' + 'Distance from target to weather station is greater than 200km.' ] assert str(mapping) == '720446' assert repr(mapping) == "ISDStationMapping('720446', distance_meters=2132142)" assert mapping.is_empty() is False +def test_mapping_result_blank_default_kwargs_50km_away(): + mapping = ISDStationMapping('720446', 38, -87) + assert mapping.target_latitude == 38 + assert mapping.target_longitude == -87 + assert mapping.target_coords == (38, -87) + assert mapping.distance_meters == 133519 + assert mapping.isd_station.usaf_id == '720446' + assert mapping.warnings == [ + 'Distance from target to weather station is greater than 50km.' + ] + assert str(mapping) == '720446' + assert repr(mapping) == "ISDStationMapping('720446', distance_meters=133519)" + assert mapping.is_empty() is False + + def test_mapping_with_kwargs(): mapping = ISDStationMapping( '720446', 40, -110, distance_meters=100, warnings=['a', 'b'])
added additional warning for <I>km distance matching to go along with CalTrack warning
openeemeter_eeweather
train
a8eeee135e84b77287ea5ce62b153badccf91ec4
diff --git a/addon-mirage-support/get-all.js b/addon-mirage-support/get-all.js index <HASH>..<HASH> 100644 --- a/addon-mirage-support/get-all.js +++ b/addon-mirage-support/get-all.js @@ -5,7 +5,10 @@ import { Collection, Model } from 'ember-cli-mirage'; const getAll = function (schema, request) { //turn /api/programyears?limit=1 into 'programYears' const modelRegex = /\/api\/([a-z]+).*/i; - const modelName = getName(request.url.match(modelRegex)[1]); + let modelName = getName(request.url.match(modelRegex)[1]); + if ('aamcpcrses' === modelName.toLowerCase()) { + modelName = 'aamcPcrs'; + } if (!schema[modelName]) { console.error( 'Mirage: The route handler for ' +
kludges in a solution for retrieving all PCRS
ilios_common
train
f8de8032e5de7a574d8fc7a9f2487d0f1a94da45
diff --git a/src/Service/Provider.php b/src/Service/Provider.php index <HASH>..<HASH> 100644 --- a/src/Service/Provider.php +++ b/src/Service/Provider.php @@ -39,7 +39,9 @@ class Provider implements \Pimple\ServiceProviderInterface // Define view class loader $container["loadView.service"] = $container->protect( function (string $view) use ($container) { - $class = rtrim($container["config.service"]["view.classNamespace"], "\\") . "\\" . $view; + $class = rtrim($container["config.service"]["view.classNamespace"], "\\") + . "\\" + . str_replace("/", "\\", $view); return new $class( $container["config.service"], $container["tplLoader.service"],
replace forward slashes with backward slashes in view class name
SlaxWeb_View
train
7408a281073dc073356992dc370918397689a1b1
diff --git a/src/ORM/FieldType/MultiValueField.php b/src/ORM/FieldType/MultiValueField.php index <HASH>..<HASH> 100755 --- a/src/ORM/FieldType/MultiValueField.php +++ b/src/ORM/FieldType/MultiValueField.php @@ -167,12 +167,12 @@ class MultiValueField extends DBComposite return ''; } - public function ItemsByKey() + public function ItemByKey() { - $value = $this->getValue(); - if(array_keys($value) == range(0, count($value) - 1)) - $value = []; - return new ArrayData($value); + $values = $this->getValue(); + if(array_keys($values) == range(0, count($values) - 1)) + $values = []; + return new ArrayData($values); } public function Items()
Update MultiValueField.php
symbiote_silverstripe-multivaluefield
train
a8277204a2a92508c07c21e7d744ab2ce973e238
diff --git a/salt/modules/x509.py b/salt/modules/x509.py index <HASH>..<HASH> 100644 --- a/salt/modules/x509.py +++ b/salt/modules/x509.py @@ -1129,7 +1129,7 @@ def create_certificate(path=None, text=False, ca_server=None, **kwargs): cert.set_issuer(signing_cert.get_subject()) for extname, extlongname in EXT_NAME_MAPPINGS.iteritems(): - if extname not in kwargs or extlongname not in kwargs or extname not in csrexts or extlongname not in csrexts: + if (extname in kwargs or extlongname in kwargs or extname in csrexts or extlongname in csrexts) is False: continue # Use explicitly set values first, fall back to CSR values.
bad logic in checking for x<I> extensions
saltstack_salt
train
dcd9984d253707fe9899e6361e0676ce4de0d0a7
diff --git a/source/application/views/admin/de/lang.php b/source/application/views/admin/de/lang.php index <HASH>..<HASH> 100755 --- a/source/application/views/admin/de/lang.php +++ b/source/application/views/admin/de/lang.php @@ -1984,8 +1984,7 @@ $aLang = array( 'PAYMENT_RDFA_VISA' => 'VISA', 'DELIVERY_RDFA_ASIGN_DELIVERY' => 'Versandarten zuordnen', -'DELIVERY_RDFA_ADVICE_START' => '<b>Hinweis:</b> Bitte w�hlen Sie nur die in GoodRelations vordefinierten Versandarten aus, die Ihrer Versandart ', -'DELIVERY_RDFA_ADVICE_END' => 'entsprechen', +'DELIVERY_RDFA_ADVICE' => '<b>Hinweis:</b> Bitte w�hlen Sie nur die in GoodRelations vordefinierten Versandarten aus, die Ihrer Versandart %s entsprechen', 'DELIVERY_RDFA_GENERAL' => 'Allgemeine Versandarten', 'DELIVERY_RDFA_DELIVERYMODEDIRECTDOWNLOAD' => 'Download', 'DELIVERY_RDFA_DELIVERYMODEOWNFLEET' => 'Eigener Fuhrpark', diff --git a/source/application/views/admin/en/lang.php b/source/application/views/admin/en/lang.php index <HASH>..<HASH> 100755 --- a/source/application/views/admin/en/lang.php +++ b/source/application/views/admin/en/lang.php @@ -1983,8 +1983,7 @@ $aLang = array( 'PAYMENT_RDFA_VISA' => 'VISA', 'DELIVERY_RDFA_ASIGN_DELIVERY' => 'Assign delivery method', -'DELIVERY_RDFA_ADVICE_START' => '<b>Hint:</b> Please choose only those delivery methods, pre-defined in GoodRelations, that comply with your shipping method', -'DELIVERY_RDFA_ADVICE_END' => '', +'DELIVERY_RDFA_ADVICE' => '<b>Hint:</b> Please choose only those delivery methods, pre-defined in GoodRelations, that comply with your shipping method', 'DELIVERY_RDFA_GENERAL' => 'General delivery methods', 'DELIVERY_RDFA_DELIVERYMODEDIRECTDOWNLOAD' => 'Download', 'DELIVERY_RDFA_DELIVERYMODEOWNFLEET' => 'Own fleet', diff --git a/source/application/views/admin/tpl/deliveryset_rdfa.tpl b/source/application/views/admin/tpl/deliveryset_rdfa.tpl index <HASH>..<HASH> 100644 --- a/source/application/views/admin/tpl/deliveryset_rdfa.tpl +++ b/source/application/views/admin/tpl/deliveryset_rdfa.tpl @@ -25,7 +25,7 @@ <strong>[{ oxmultilang ident="DELIVERY_RDFA_ASIGN_DELIVERY" }]</strong><br> -[{ oxmultilang ident="DELIVERY_RDFA_ADVICE_START" }] <b>[{$edit->oxdeliveryset__oxtitle->value}]</b> [{ oxmultilang ident="DELIVERY_RDFA_ADVICE_END" }]. + [{ assign var='oxDeliverySet' value=$edit->oxpayments__oxdesc->value }][{ oxmultilang ident="DELIVERY_RDFA_ADVICE" args=$oxDeliverySet }]. <table cellspacing="0" cellpadding="0" border="0" width="98%"> <tr> <td valign="top" class="edittext">
fixed #<I>, removed DELIVERY_RDFA_ADVICE_END, introduced %s
OXID-eSales_oxideshop_ce
train
125a3667f912eb47521e8953e89a1f8db9cd7212
diff --git a/helpers/TbHtml.php b/helpers/TbHtml.php index <HASH>..<HASH> 100755 --- a/helpers/TbHtml.php +++ b/helpers/TbHtml.php @@ -1349,8 +1349,7 @@ EOD; } if (in_array($type, array(self::INPUT_TYPE_CHECKBOX, self::INPUT_TYPE_RADIOBUTTON))) { - $htmlOptions['label'] = $label; - $htmlOptions['labelOptions'] = $labelOptions; + $htmlOptions['label'] = parent::label($label, $name); $label = false; } @@ -2059,8 +2058,7 @@ EOD; } if (in_array($type, array(self::INPUT_TYPE_CHECKBOX, self::INPUT_TYPE_RADIOBUTTON))) { - $htmlOptions['label'] = $label; - $htmlOptions['labelOptions'] = $labelOptions; + $htmlOptions['label'] = parent::activeLabelEx($model, $attribute); $label = false; }
Fix selecting checkboxes by clicking on the label
crisu83_yiistrap
train
5430487d85de3e6ac0d886e384ef039f15e64a88
diff --git a/actionview/lib/action_view/helpers/sanitize_helper/sanitizers.rb b/actionview/lib/action_view/helpers/sanitize_helper/sanitizers.rb index <HASH>..<HASH> 100644 --- a/actionview/lib/action_view/helpers/sanitize_helper/sanitizers.rb +++ b/actionview/lib/action_view/helpers/sanitize_helper/sanitizers.rb @@ -5,12 +5,13 @@ require 'action_view/helpers/sanitize_helper/scrubbers' module ActionView XPATHS_TO_REMOVE = %w{.//script .//form comment()} - class Sanitizer - # :nodoc: + class Sanitizer # :nodoc: def sanitize(html, options = {}) raise NotImplementedError, "subclasses must implement" end + # call +remove_xpaths+ with string and get a string back + # call it with a node or nodeset and get back a node/nodeset def remove_xpaths(html, xpaths) if html.respond_to?(:xpath) html.xpath(*xpaths).remove @@ -23,7 +24,7 @@ module ActionView class FullSanitizer < Sanitizer def sanitize(html, options = {}) - return nil unless html + return unless html return html if html.empty? Loofah.fragment(html).tap do |fragment| @@ -44,15 +45,15 @@ module ActionView end class WhiteListSanitizer < Sanitizer - def initialize @permit_scrubber = PermitScrubber.new end def sanitize(html, options = {}) - return nil unless html + return unless html loofah_fragment = Loofah.fragment(html) + if scrubber = options[:scrubber] # No duck typing, Loofah ensures subclass of Loofah::Scrubber loofah_fragment.scrub!(scrubber) @@ -64,11 +65,12 @@ module ActionView remove_xpaths(loofah_fragment, XPATHS_TO_REMOVE) loofah_fragment.scrub!(:strip) end + loofah_fragment.to_s end def sanitize_css(style_string) - Loofah::HTML5::Scrub.scrub_css style_string + Loofah::HTML5::Scrub.scrub_css(style_string) end def protocol_separator
Stylistic improvements. Some light documentation for remove_xpaths.
rails_rails
train
22baa19c513ec77b65e511f4a75a9e0f7dca057c
diff --git a/pymatgen/analysis/surface_analysis.py b/pymatgen/analysis/surface_analysis.py index <HASH>..<HASH> 100644 --- a/pymatgen/analysis/surface_analysis.py +++ b/pymatgen/analysis/surface_analysis.py @@ -1363,7 +1363,7 @@ class WorkFunctionAnalyzer: The average locpot of the slab region along the c direction """ - def __init__(self, structure, locpot_along_c, efermi, shift=0, blength=3): + def __init__(self, structure, locpot_along_c, efermi, shift=0, blength=3.5): """ Initializes the WorkFunctionAnalyzer class. @@ -1572,7 +1572,7 @@ class WorkFunctionAnalyzer: return all(all_flat) @staticmethod - def from_files(poscar_filename, locpot_filename, outcar_filename, shift=0, blength=3): + def from_files(poscar_filename, locpot_filename, outcar_filename, shift=0, blength=3.5): p = Poscar.from_file(poscar_filename) l = Locpot.from_file(locpot_filename) o = Outcar(outcar_filename) diff --git a/pymatgen/core/surface.py b/pymatgen/core/surface.py index <HASH>..<HASH> 100644 --- a/pymatgen/core/surface.py +++ b/pymatgen/core/surface.py @@ -1734,14 +1734,15 @@ def generate_all_slabs(structure, max_index, min_slab_size, min_vacuum_size, return all_slabs -def get_slab_regions(slab, blength=3): +def get_slab_regions(slab, blength=3.5): """ Function to get the ranges of the slab regions. Useful for discerning where the slab ends and vacuum begins if the slab is not fully within the cell - Args: slab (Structure): Structure object modelling the surface - blength (float, Ang): The bondlength between atoms. + blength (float, Ang): The bondlength between atoms. You generally + want this value to be larger than the actual bondlengths in + order to find atoms that are part of the slab """ fcoords, indices, all_indices = [], [], [] diff --git a/pymatgen/core/tests/test_surface.py b/pymatgen/core/tests/test_surface.py index <HASH>..<HASH> 100644 --- a/pymatgen/core/tests/test_surface.py +++ b/pymatgen/core/tests/test_surface.py @@ -227,16 +227,16 @@ class SlabTest(PymatgenTest): s = self.get_structure("LiFePO4") slabgen = SlabGenerator(s, (0, 0, 1), 15, 15) slab = slabgen.get_slabs()[0] - s.translate_sites([i for i, site in enumerate(slab)], [0, 0, -0.25]) + slab.translate_sites([i for i, site in enumerate(slab)], [0, 0, -0.25]) bottom_c, top_c = [], [] - for site in s: + for site in slab: if site.frac_coords[2] < 0.5: bottom_c.append(site.frac_coords[2]) else: top_c.append(site.frac_coords[2]) - ranges = get_slab_regions(s) - self.assertArrayEqual(tuple(ranges[0]) == (0, max(bottom_c))) - self.assertArrayEqual(tuple(ranges[1]) == (min(top_c), 1)) + ranges = get_slab_regions(slab) + self.assertEqual(tuple(ranges[0]), (0, max(bottom_c))) + self.assertEqual(tuple(ranges[1]), (min(top_c), 1)) class SlabGeneratorTest(PymatgenTest):
better default bondlength for finding sites in get_slab_region
materialsproject_pymatgen
train
151e0ba0ce743081a276886b2dc94f54f03e4a8b
diff --git a/bench/serializing.rb b/bench/serializing.rb index <HASH>..<HASH> 100644 --- a/bench/serializing.rb +++ b/bench/serializing.rb @@ -10,7 +10,7 @@ module Models end end - class ClassRoom + class ClassRoom attr_reader :students attr_accessor :teacher def initialize(opts = {}) @@ -51,7 +51,7 @@ module Entities class ClassRoom < Grape::Entity expose :teacher, using: 'Entities::Teacher' expose :students, using: 'Entities::Student' - expose :size do |model, opts| + expose :size do |model, _opts| model.students.count end end @@ -62,7 +62,7 @@ module Entities class Student < Entities::Person expose :grade - expose :failing do |model, opts| + expose :failing do |model, _opts| model.grade == 'F' end end @@ -72,18 +72,17 @@ module Entities end end +teacher1 = Models::Teacher.new(name: 'John Smith', tenure: 2) +classroom1 = Models::ClassRoom.new(teacher: teacher1) +classroom1.students << Models::Student.new(name: 'Bobby', grade: 'A') +classroom1.students << Models::Student.new(name: 'Billy', grade: 'B') -teacher1 = Models::Teacher.new(:name => "John Smith", :tenure => 2) -classroom1 = Models::ClassRoom.new(:teacher => teacher1) -classroom1.students << Models::Student.new(:name => "Bobby", :grade => 'A' ) -classroom1.students << Models::Student.new(:name => "Billy", :grade => 'B' ) - -teacher2 = Models::Teacher.new(:name => "Lisa Barns") -classroom2 = Models::ClassRoom.new(:teacher => teacher2, :tenure => 15) -classroom2.students << Models::Student.new(:name => "Eric", :grade => 'A' ) -classroom2.students << Models::Student.new(:name => "Eddie", :grade => 'C' ) -classroom2.students << Models::Student.new(:name => "Arnie", :grade => 'C' ) -classroom2.students << Models::Student.new(:name => "Alvin", :grade => 'F' ) +teacher2 = Models::Teacher.new(name: 'Lisa Barns') +classroom2 = Models::ClassRoom.new(teacher: teacher2, tenure: 15) +classroom2.students << Models::Student.new(name: 'Eric', grade: 'A') +classroom2.students << Models::Student.new(name: 'Eddie', grade: 'C') +classroom2.students << Models::Student.new(name: 'Arnie', grade: 'C') +classroom2.students << Models::Student.new(name: 'Alvin', grade: 'F') school = Models::School.new school.classrooms << classroom1 school.classrooms << classroom2 @@ -91,9 +90,9 @@ school.classrooms << classroom2 iters = 5000 Benchmark.bm do |bm| - bm.report("serializing") do + bm.report('serializing') do iters.times do - Entities::School.represent(school, :serializable => true) + Entities::School.represent(school, serializable: true) end end end diff --git a/lib/grape_entity/entity.rb b/lib/grape_entity/entity.rb index <HASH>..<HASH> 100644 --- a/lib/grape_entity/entity.rb +++ b/lib/grape_entity/entity.rb @@ -501,7 +501,7 @@ module Grape def conditions_met?(exposure_options, options) if_conditions = [] unless exposure_options[:if_extras].nil? - if_conditions.concat(exposure_options[:if_extras]) + if_conditions.concat(exposure_options[:if_extras]) end if_conditions << exposure_options[:if] unless exposure_options[:if].nil?
Clean up code to satisfy RuboCop
ruby-grape_grape-entity
train
7492a8dcab06d10f338c6a9df4dac697d58efecb
diff --git a/src/Collection.php b/src/Collection.php index <HASH>..<HASH> 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -39,6 +39,68 @@ class Collection return empty($this->_data); } + /** + * Get a value of an entry in the collection + * Useful to get deep array elements without manually dealing with errors + * During the process + * + * @example + * // If the 'two' is not defined this code will trigger a PHP notice + * $list->one->two->three->four->five + * + * // This method will never trigger a PHP notice, safe to use at any depth + * $list->get('one.two.three.four.five') + * + * @param string $keyPath - the period delimited location + * + * @return mixed|null|Collection|LinkedCollection + */ + public function get($keyPath) + { + $stops = explode('.', $keyPath); + + $value = $this; + foreach($stops as $key){ + if ($value instanceof Collection){ + // Move one step deeper into the collection + $value = $value->$key; + } else { + /* + * One more stops still pending and the current + * value is not a collection, terminate iteration + * and set value to null + */ + $value = null; + break; + } + } + + return $value; + } + + public function set($keyPath, $value) + { + $stops = explode('.', $keyPath); + + $currentLocation = $previousLocation = $this; + foreach($stops as $key){ + if ($currentLocation instanceof Collection){ + // Move one step deeper into the collection + if ( ! ($currentLocation->$key instanceof Collection) ) { + $currentLocation->$key = array(); + } + } else { + $currentLocation = array(); + $currentLocation->$key = array(); + } + $previousLocation = $currentLocation; + $currentLocation = $currentLocation->$key; + } + + // Set the value + $previousLocation->$key = $value; + } + public function __set($name, $value) { $this->_data[$name] = $value; diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index <HASH>..<HASH> 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -64,6 +64,91 @@ class CollectionTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($expectation, $list->toArray()); } + public function testExistence() + { + $list = new Collection(array( + 'one' => 1, + 'two' => 2, + 'three' => 3, + 'four' => 4, + )); + + $this->assertTrue(isset($list->one)); + $this->assertFalse(isset($list->five)); + + $this->assertNull($list->five); + $this->assertNull($list->get('two.one')); + } + + public function testUnsetter() + { + $list = new Collection(array( + 'one' => array( + 'two' => 2 + ), + 'two' => 2, + 'three' => 3, + 'four' => 4, + )); + + $this->assertTrue(isset($list->two)); + unset($list->two); + $this->assertFalse(isset($list->two)); + $list->two = 2; + $this->assertTrue(isset($list->two)); + $list->two = null; + $this->assertFalse(isset($list->two)); + + $this->assertTrue(isset($list->one->two)); + unset($list->one->two); + $this->assertFalse(isset($list->one->two)); + $list->one->two = 2; + $this->assertTrue(isset($list->one->two)); + $list->one->two = null; + $this->assertFalse(isset($list->one->two)); + } + + public function testStringGetter() + { + $list = new Collection(array( + 'one' => array( + 'two' => 2 + ), + 'two' => 2, + 'three' => 3, + 'four' => 4, + )); + + error_reporting(E_ALL); + + $this->assertEquals(array('two'=>2), $list->get('one')->toArray()); + $this->assertEquals(2, $list->get('one.two')); + $this->assertEquals(null, $list->get('one.two.three')); + + } + + public function testStringSetter() + { + $list = new Collection(array( + 'one' => array( + 'two' => 2 + ), + 'two' => 2, + 'three' => 3, + 'four' => 4, + )); + + error_reporting(E_ALL); + + $list->set('five',5); + $this->assertEquals(5, $list->five); + + $list->set('one.two.three',3); + $this->assertEquals(3, $list->one->two->three); + + $list->set('two.three.four.five', array(1,1,1,1,1)); + $this->assertEquals(array(1,1,1,1,1), $list->two->three->four->five->toArray()); + } } \ No newline at end of file
Improved the magic collection object to include a deep string base lookup function
ptejada_uFlex
train
219836a6d85503ee72c5ab8d47e5b475b25b130a
diff --git a/ocelot-web/src/main/java/fr/hhdev/ocelot/core/CacheManager.java b/ocelot-web/src/main/java/fr/hhdev/ocelot/core/CacheManager.java index <HASH>..<HASH> 100644 --- a/ocelot-web/src/main/java/fr/hhdev/ocelot/core/CacheManager.java +++ b/ocelot-web/src/main/java/fr/hhdev/ocelot/core/CacheManager.java @@ -51,19 +51,23 @@ public class CacheManager { } /** * Get deadline for cache - * if 0 : is infinite + * if 0 : is 1 year cache * @param jcr * @return */ public long getJsCacheResultDeadline(JsCacheResult jcr) { Calendar deadline = Calendar.getInstance(); - deadline.add(Calendar.YEAR, jcr.year()); - deadline.add(Calendar.MONTH, jcr.month()); - deadline.add(Calendar.DATE, jcr.day()); - deadline.add(Calendar.HOUR, jcr.hour()); - deadline.add(Calendar.MINUTE, jcr.minute()); - deadline.add(Calendar.SECOND, jcr.second()); - deadline.add(Calendar.MILLISECOND, jcr.millisecond()); + if((jcr.year() + jcr.month() + jcr.day() + jcr.hour() + jcr.minute() + jcr.second() + jcr.millisecond()) == 0) { + deadline.add(Calendar.YEAR, 1); + } else { + deadline.add(Calendar.YEAR, jcr.year()); + deadline.add(Calendar.MONTH, jcr.month()); + deadline.add(Calendar.DATE, jcr.day()); + deadline.add(Calendar.HOUR, jcr.hour()); + deadline.add(Calendar.MINUTE, jcr.minute()); + deadline.add(Calendar.SECOND, jcr.second()); + deadline.add(Calendar.MILLISECOND, jcr.millisecond()); + } return deadline.getTime().getTime(); }
Add store notion. Store NONE, BROWSER, SESSION if cache deadline is not define by annotation so cache deadline 1 year
ocelotds_ocelot
train
79d3033b6064176081233fe4f753469a5f4ff2bd
diff --git a/spec/amq/protocol/exchange_spec.rb b/spec/amq/protocol/exchange_spec.rb index <HASH>..<HASH> 100644 --- a/spec/amq/protocol/exchange_spec.rb +++ b/spec/amq/protocol/exchange_spec.rb @@ -9,20 +9,18 @@ module AMQ describe Declare do describe '.encode' do it 'encodes the parameters into a MethodFrame' do - pending 'encoding issues when using Fixnum#chr' do - channel = 1 - exchange = 'amqclient.adapters.em.exchange1' - type = 'fanout' - passive = false, - durable = false - auto_delete = false - internal = false - nowait = false - arguments = nil - method_frame = Declare.encode(channel, exchange, type, passive, durable, auto_delete, internal, nowait, arguments) - method_frame.payload.should == "\x00(\x00\n\x00\x00\x1Famqclient.adapters.em.exchange1\x06fanout\x00\x00\x00\x00\x00" - method_frame.channel.should == 1 - end + channel = 1 + exchange = 'amqclient.adapters.em.exchange1' + type = 'fanout' + passive = false + durable = false + auto_delete = false + internal = false + nowait = false + arguments = nil + method_frame = Declare.encode(channel, exchange, type, passive, durable, auto_delete, internal, nowait, arguments) + method_frame.payload.should == "\x00(\x00\n\x00\x00\x1Famqclient.adapters.em.exchange1\x06fanout\x00\x00\x00\x00\x00" + method_frame.channel.should == 1 end end end
Fixed a test It wasn't the encoding that caused the problem, but a trailing comma...
ruby-amqp_amq-protocol
train
fad002c11ee3b6f106c4a2c47652cbad1dac1e59
diff --git a/internal/pkg/gateway/api.go b/internal/pkg/gateway/api.go index <HASH>..<HASH> 100644 --- a/internal/pkg/gateway/api.go +++ b/internal/pkg/gateway/api.go @@ -101,17 +101,15 @@ func (gs *Server) Endorse(ctx context.Context, request *gp.EndorseRequest) (*gp. go func(e *endorser) { defer wg.Done() response, err := e.client.ProcessProposal(ctx, signedProposal) - var detail *gp.EndpointError - if err != nil { - detail = &gp.EndpointError{Address: e.address, MspId: e.mspid, Message: err.Error()} - responseCh <- &endorserResponse{err: detail} - return - } - if response.Response.Status < 200 || response.Response.Status >= 400 { + switch { + case err != nil: + responseCh <- &endorserResponse{err: endpointError(e, err)} + case response.Response.Status < 200 || response.Response.Status >= 400: // this is an error case and will be returned in the error details to the client - detail = &gp.EndpointError{Address: e.address, MspId: e.mspid, Message: fmt.Sprintf("error %d, %s", response.Response.Status, response.Response.Message)} + responseCh <- &endorserResponse{err: endpointError(e, fmt.Errorf("error %d, %s", response.Response.Status, response.Response.Message))} + default: + responseCh <- &endorserResponse{pr: response} } - responseCh <- &endorserResponse{pr: response, err: detail} }(e) } wg.Wait() @@ -200,3 +198,7 @@ func (gs *Server) CommitStatus(ctx context.Context, request *gp.CommitStatusRequ } return nil, status.Error(codes.Unimplemented, "Not implemented") } + +func endpointError(e *endorser, err error) *gp.EndpointError { + return &gp.EndpointError{Address: e.address, MspId: e.mspid, Message: err.Error()} +}
Gateway error logic refactor Implements the suggested improvement as per previous review comment: <URL>
hyperledger_fabric
train