hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
917a4b6472b93db429e59a39da56b5d90feb53e6
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -173,7 +173,7 @@ function addAttribute(props, name, value, ctx) { * `selector`. */ function react(h) { var node = h && h('div'); - return Boolean(node && '_owner' in node && node.key === null); + return Boolean(node && ('_owner' in node || '_store' in node) && node.key === null); } /* Check if `h` is `hyperscript`. It doesn’t accept
Check for either `_store` or `_owner` in React
syntax-tree_hast-to-hyperscript
train
e8a00392e837e26bcde4712eb1c73e0bdcbf212d
diff --git a/js/preprocessor.js b/js/preprocessor.js index <HASH>..<HASH> 100644 --- a/js/preprocessor.js +++ b/js/preprocessor.js @@ -50,8 +50,11 @@ YoastSEO.PreProcessor.prototype.countStore = function() { 0 : this.__store.cleanText.split( " " ).length; } - this.__store.wordcountNoTags = this.__store.cleanTextNoTags.split( " " ).length; - + if ( this.__store.cleanTextNoTags === "." ){ + this.__store.wordcountNoTags = 0; + } else { + this.__store.wordcountNoTags = this.__store.cleanTextNoTags.split(" ").length; + } /*sentencecounters*/ this.__store.sentenceCount = this.sentenceCount( this.__store.cleanText ); this.__store.sentenceCountNoTags = this.sentenceCount( this.__store.cleanTextNoTags );
Fixed issue with word counts, no longer reports 1 word on empty strings.
Yoast_YoastSEO.js
train
4c83ffb14774e91b54308b8e66beff4d38c31fc5
diff --git a/sqlx.go b/sqlx.go index <HASH>..<HASH> 100644 --- a/sqlx.go +++ b/sqlx.go @@ -308,6 +308,7 @@ func (db *DB) Select(dest interface{}, query string, args ...interface{}) error // Get using this DB. // Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. func (db *DB) Get(dest interface{}, query string, args ...interface{}) error { return Get(db, dest, query, args...) } @@ -430,6 +431,7 @@ func (tx *Tx) QueryRowx(query string, args ...interface{}) *Row { // Get within a transaction. // Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. func (tx *Tx) Get(dest interface{}, query string, args ...interface{}) error { return Get(tx, dest, query, args...) } @@ -499,6 +501,7 @@ func (s *Stmt) Select(dest interface{}, args ...interface{}) error { // Get using the prepared statement. // Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. func (s *Stmt) Get(dest interface{}, args ...interface{}) error { return Get(&qStmt{s}, dest, "", args...) } @@ -660,6 +663,7 @@ func Select(q Queryer, dest interface{}, query string, args ...interface{}) erro // to dest. If dest is scannable, the result must only have one column. Otherwise, // StructScan is used. Get will return sql.ErrNoRows like row.Scan would. // Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. func Get(q Queryer, dest interface{}, query string, args ...interface{}) error { r := q.QueryRowx(query, args...) return r.scanAny(dest, false)
Information about the errors included in the godoc
jmoiron_sqlx
train
cdc4274931c2d6bafdf2b97f7e4ecedf89a8202e
diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/core_ext/class/attribute.rb +++ b/activesupport/lib/active_support/core_ext/class/attribute.rb @@ -110,12 +110,6 @@ class Class private def singleton_class? - # in case somebody is crazy enough to overwrite allocate - allocate = Class.instance_method(:allocate) - # object.class always points to a real (non-singleton) class - allocate.bind(self).call.class != self - rescue TypeError - # MRI/YARV/JRuby all disallow creating new instances of a singleton class - true + !name || '' == name end end
simplify singleton_class? method
rails_rails
train
84216a034a977bef8ee78639fafbcb7fe2894b57
diff --git a/securitycenter/synth.py b/securitycenter/synth.py index <HASH>..<HASH> 100644 --- a/securitycenter/synth.py +++ b/securitycenter/synth.py @@ -29,22 +29,9 @@ s.move( ] ) -# Fix security_center_client.py docstrings. +# Add encoding header to protoc-generated files. +# See: https://github.com/googleapis/gapic-generator/issues/2097 s.replace( - "google/cloud/securitycenter_v1beta1/gapic/security_center_client.py", - "::\n\n\s+(compare_duration, but present at [a-z]+_time.)", - " \g<1>" -) - -s.replace( - "google/cloud/securitycenter_v1beta1/gapic/security_center_client.py", - "::\n\n\s+(compare_duration, but not present at [a-z]+_time.)", - " \g<1>" -) - -s.replace( - "google/cloud/securitycenter_v1beta1/gapic/security_center_client.py", - "(^\s+)::\n\n\s+(start and the end of the time period defined by\n)" - "\s+(compare_duration and [a-z]+_time.)", - "\g<1> \g<2>\g<1> \g<3>" -) + '**/proto/*_pb2.py', + r"(^.*$\n)*", + r"# -*- coding: utf-8 -*-\n\g<0>")
Securitycenter: overlooked synth changes. (#<I>) The *effects* were merged in #<I>, but not the synth changes themselves.
googleapis_google-cloud-python
train
e95276c2d5d67e59922b05ad82ac9fca1ff0647c
diff --git a/lib/erector/rails.rb b/lib/erector/rails.rb index <HASH>..<HASH> 100644 --- a/lib/erector/rails.rb +++ b/lib/erector/rails.rb @@ -1,5 +1,6 @@ dir = File.dirname(__FILE__) require "action_controller" +require "#{dir}/rails/rails_version" require "#{dir}/rails/extensions/rails_widget" require "#{dir}/rails/extensions/action_controller" require "#{dir}/rails/extensions/action_view" diff --git a/spec/rails_root/config/boot.rb b/spec/rails_root/config/boot.rb index <HASH>..<HASH> 100644 --- a/spec/rails_root/config/boot.rb +++ b/spec/rails_root/config/boot.rb @@ -13,9 +13,6 @@ end unless defined?(Rails::Initializer) rails_dir = "#{RAILS_ROOT}/vendor/rails" - system("rm -rf #{RAILS_ROOT}/vendor/plugins/erector") - - system("cd #{RAILS_ROOT}/../.. && rake switch_to_rails_version_tag") Dir["#{rails_dir}/*"].each do |path| $:.unshift("#{path}/lib") if File.directory?("#{path}/lib") diff --git a/spec/rails_root/spec/rails_spec_helper.rb b/spec/rails_root/spec/rails_spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/rails_root/spec/rails_spec_helper.rb +++ b/spec/rails_root/spec/rails_spec_helper.rb @@ -11,8 +11,10 @@ require "hpricot" require "rr" require "rr/adapters/rspec" require 'treetop' +require "erector" require "erector/erect" require "erector/erected" +system("cd #{RAILS_ROOT}/../.. && rake switch_to_rails_version_tag") Spec::Runner.configure do |config| config.mock_with RR::Adapters::Rspec
Moved git checkout call into rails_spec_helper.
erector_erector
train
d63a7010d965b0ecf16424b4f4b67beb7df167ac
diff --git a/plugins/inputs/x509_cert/x509_cert.go b/plugins/inputs/x509_cert/x509_cert.go index <HASH>..<HASH> 100644 --- a/plugins/inputs/x509_cert/x509_cert.go +++ b/plugins/inputs/x509_cert/x509_cert.go @@ -102,14 +102,15 @@ func (c *X509Cert) serverName(u *url.URL) (string, error) { } func (c *X509Cert) getCert(u *url.URL, timeout time.Duration) ([]*x509.Certificate, error) { + protocol := u.Scheme switch u.Scheme { case "https": - u.Scheme = "tcp" + protocol = "tcp" fallthrough case "udp", "udp4", "udp6": fallthrough case "tcp", "tcp4", "tcp6": - ipConn, err := net.DialTimeout(u.Scheme, u.Host, timeout) + ipConn, err := net.DialTimeout(protocol, u.Host, timeout) if err != nil { return nil, err }
Fix messing up the 'source' tag for https sources. (#<I>)
influxdata_telegraf
train
54e61aa78aab4b49a1ba17bbba4a606111cd4274
diff --git a/plugins/aggregators/basicstats/basicstats.go b/plugins/aggregators/basicstats/basicstats.go index <HASH>..<HASH> 100644 --- a/plugins/aggregators/basicstats/basicstats.go +++ b/plugins/aggregators/basicstats/basicstats.go @@ -72,9 +72,9 @@ func (m *BasicStats) Add(in telegraf.Metric) { tags: in.Tags(), fields: make(map[string]basicstats), } - for k, v := range in.Fields() { - if fv, ok := convert(v); ok { - a.fields[k] = basicstats{ + for _, field := range in.FieldList() { + if fv, ok := convert(field.Value); ok { + a.fields[field.Key] = basicstats{ count: 1, min: fv, max: fv, @@ -86,11 +86,11 @@ func (m *BasicStats) Add(in telegraf.Metric) { } m.cache[id] = a } else { - for k, v := range in.Fields() { - if fv, ok := convert(v); ok { - if _, ok := m.cache[id].fields[k]; !ok { + for _, field := range in.FieldList() { + if fv, ok := convert(field.Value); ok { + if _, ok := m.cache[id].fields[field.Key]; !ok { // hit an uncached field of a cached metric - m.cache[id].fields[k] = basicstats{ + m.cache[id].fields[field.Key] = basicstats{ count: 1, min: fv, max: fv, @@ -101,7 +101,7 @@ func (m *BasicStats) Add(in telegraf.Metric) { continue } - tmp := m.cache[id].fields[k] + tmp := m.cache[id].fields[field.Key] //https://en.m.wikipedia.org/wiki/Algorithms_for_calculating_variance //variable initialization x := fv @@ -126,7 +126,7 @@ func (m *BasicStats) Add(in telegraf.Metric) { //sum compute tmp.sum += fv //store final data - m.cache[id].fields[k] = tmp + m.cache[id].fields[field.Key] = tmp } } }
Use FieldList in basicstats to improve performance (#<I>)
influxdata_telegraf
train
01d030ce56539f83d0733b9232714632f5187de2
diff --git a/state/apiserver/backup.go b/state/apiserver/backup.go index <HASH>..<HASH> 100644 --- a/state/apiserver/backup.go +++ b/state/apiserver/backup.go @@ -37,7 +37,15 @@ func (h *backupHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } defer os.RemoveAll(tempDir) - filename, sha, err := Backup(tempDir) + + config, err := h.state.EnvironConfig() + if err != nil { + h.sendError(w, http.StatusInternalServerError, fmt.Sprintf("backup failed: %v", err)) + return + } + adminPassword := config.AdminSecret() + mongoPort := config.StatePort() + filename, sha, err := Backup(adminPassword, tempDir, mongoPort) if err != nil { h.sendError(w, http.StatusInternalServerError, fmt.Sprintf("backup failed: %v", err)) return
Use EnvironConfig for mongo details required by Backup
juju_juju
train
a2d55973f4e19f0ef9213148570e6d44d3267133
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,4 @@ -from setuptools import setup, find_packages +from setuptools import setup import simple_history setup( @@ -13,7 +13,7 @@ setup( author_email='[email protected]', maintainer='Trey Hunner', url='https://github.com/treyhunner/django-simple-history', - packages=find_packages(), + packages=["simple_history"], classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Django",
Removed usage of 'find_packages'
treyhunner_django-simple-history
train
320f4880e2fe7a40c66ad70f7aea10f7811bfb9e
diff --git a/src/org/jgroups/protocols/FD_HOST.java b/src/org/jgroups/protocols/FD_HOST.java index <HASH>..<HASH> 100644 --- a/src/org/jgroups/protocols/FD_HOST.java +++ b/src/org/jgroups/protocols/FD_HOST.java @@ -381,30 +381,27 @@ public class FD_HOST extends Protocol { } targets.remove(local_host); - // 1. Ping each host for(InetAddress target: targets) { try { + // Ping each host boolean is_alive=ping_command.isAlive(target, check_timeout); num_liveness_checks++; if(is_alive) updateTimestampFor(target); else log.trace("%s: %s is not alive (age=%d secs)", local_addr, target, getAgeOf(target)); + + // Check timestamp + long current_time=getTimestamp(); + long timestamp=timestamps.get(target); + long diff=TimeUnit.MILLISECONDS.convert(current_time - timestamp, TimeUnit.NANOSECONDS); + if(diff >= timeout) + suspect(target); } catch(Exception e) { log.error("%s: ping command failed: %s", local_addr, e); } } - - // 2. Check timestamps - long current_time=getTimestamp(); - for(Map.Entry<InetAddress,Long> entry: timestamps.entrySet()) { - InetAddress host=entry.getKey(); - long timestamp=entry.getValue(); - long diff=TimeUnit.MILLISECONDS.convert(current_time - timestamp, TimeUnit.NANOSECONDS); - if(diff >= timeout) - suspect(host); - } } }
JGRP-<I> FD_HOST many false suspect with Full GC
belaban_JGroups
train
e38716f8bb7640503b0f4a1863fd2726a5beb451
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapper.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapper.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapper.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapper.java @@ -31,6 +31,10 @@ import org.apache.flink.runtime.io.network.buffer.NetworkBuffer; import org.apache.flink.util.CloseableIterator; import org.apache.flink.util.StringUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -57,9 +61,11 @@ final class SpanningWrapper { private static final int DEFAULT_THRESHOLD_FOR_SPILLING = 5 * 1024 * 1024; // 5 MiBytes private static final int DEFAULT_FILE_BUFFER_SIZE = 2 * 1024 * 1024; + private static final Logger LOG = LoggerFactory.getLogger(SpanningWrapper.class); + private final byte[] initialBuffer = new byte[1024]; - private final String[] tempDirs; + private String[] tempDirs; private final Random rnd = new Random(); @@ -285,12 +291,23 @@ final class SpanningWrapper { // try to find a unique file name for the spilling channel int maxAttempts = 10; + int initialDirIndex = rnd.nextInt(tempDirs.length); for (int attempt = 0; attempt < maxAttempts; attempt++) { - String directory = tempDirs[rnd.nextInt(tempDirs.length)]; + int dirIndex = (initialDirIndex + attempt) % tempDirs.length; + String directory = tempDirs[dirIndex]; File file = new File(directory, randomString(rnd) + ".inputchannel"); - if (file.createNewFile()) { - spillFile = new RefCountedFile(file); - return new RandomAccessFile(file, "rw").getChannel(); + try { + if (file.createNewFile()) { + spillFile = new RefCountedFile(file); + return new RandomAccessFile(file, "rw").getChannel(); + } + } catch (IOException e) { + // if there is no tempDir left to try + if (tempDirs.length <= 1) { + throw e; + } + LOG.warn("Caught an IOException when creating spill file: " + directory + ". Attempt " + attempt, e); + tempDirs = (String[]) ArrayUtils.remove(tempDirs, dirIndex); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapperTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapperTest.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapperTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/io/network/api/serialization/SpanningWrapperTest.java @@ -25,6 +25,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -52,7 +53,10 @@ public class SpanningWrapperTest { byte[] record1 = recordBytes(recordLen); byte[] record2 = recordBytes(recordLen * 2); - SpanningWrapper spanningWrapper = new SpanningWrapper(new String[]{folder.newFolder().getAbsolutePath()}, spillingThreshold, recordLen); + File canNotEecutableFile = folder.newFolder(); + canNotEecutableFile.setExecutable(false); + // Always pick 'canNotEecutableFile' first as the Spilling Channel TmpDir. Thus trigger an IOException. + SpanningWrapper spanningWrapper = new SpanningWrapper(new String[]{folder.newFolder().getAbsolutePath(), canNotEecutableFile.getAbsolutePath() + File.separator + "pathdonotexit"}, spillingThreshold, recordLen); spanningWrapper.transferFrom(wrapNonSpanning(record1, firstChunk), recordLen); spanningWrapper.addNextChunkFromMemorySegment(wrap(record1), firstChunk, recordLen - firstChunk + LENGTH_BYTES); spanningWrapper.addNextChunkFromMemorySegment(wrap(record2), 0, record2.length); @@ -63,6 +67,8 @@ public class SpanningWrapperTest { spanningWrapper.transferLeftOverTo(new NonSpanningWrapper()); // clear any leftover spanningWrapper.transferFrom(wrapNonSpanning(recordBytes(recordLen), recordLen), recordLen); // overwrite with new data + canNotEecutableFile.setExecutable(true); + assertArrayEquals(concat(record1, record2), toByteArray(unconsumedSegment)); }
[FLINK-<I>][network] Pick another tmpDir if an IOException occurs when creating spill file
apache_flink
train
e62fbadc3dd39e1663f5b680ee064751975d1882
diff --git a/lib/src/main/java/ru/noties/debug/Debug.java b/lib/src/main/java/ru/noties/debug/Debug.java index <HASH>..<HASH> 100644 --- a/lib/src/main/java/ru/noties/debug/Debug.java +++ b/lib/src/main/java/ru/noties/debug/Debug.java @@ -90,16 +90,15 @@ public class Debug { } public static void e(String message, Object... args) { - e(null, message, args); + log(Level.E, null, message, args); } public static void e() { - e(null); + log(Level.E, null, null); } public static void e(Throwable throwable) { - if (!isDebug) return; - e(throwable, EXCEPTION_PATTERN, throwable); + log(Level.E, throwable, EXCEPTION_PATTERN, throwable); } public static void w(Throwable throwable, String message, Object... args) { @@ -107,11 +106,11 @@ public class Debug { } public static void w(String message, Object... args) { - w(null, message, args); + log(Level.W, null, message, args); } public static void w() { - w(null); + log(Level.W, null, null); } public static void i(Throwable throwable, String message, Object... args) { @@ -119,11 +118,11 @@ public class Debug { } public static void i(String message, Object... args) { - i(null, message, args); + log(Level.I, null, message, args); } public static void i() { - i(null); + log(Level.I, null, null); } public static void d(Throwable throwable, String message, Object... args) { @@ -131,11 +130,11 @@ public class Debug { } public static void d(String message, Object... args) { - d(null, message, args); + log(Level.D, null, message, args); } public static void d() { - d(null); + log(Level.D, null, null); } public static void v(Throwable throwable, String message, Object... args) { @@ -143,11 +142,11 @@ public class Debug { } public static void v(String message, Object... args) { - v(null, message, args); + log(Level.V, null, message, args); } public static void v() { - v(null); + log(Level.V, null, null); } public static void wtf() {
Decreased number of method calls inside Debug.java
noties_Debug
train
5c0a955925062cb25bd0f2a20b6803b7b3512d54
diff --git a/src/main/java/rx/internal/operators/OperatorDoOnSubscribe.java b/src/main/java/rx/internal/operators/OperatorDoOnSubscribe.java index <HASH>..<HASH> 100644 --- a/src/main/java/rx/internal/operators/OperatorDoOnSubscribe.java +++ b/src/main/java/rx/internal/operators/OperatorDoOnSubscribe.java @@ -28,7 +28,7 @@ public class OperatorDoOnSubscribe<T> implements Operator<T, T> { /** * Constructs an instance of the operator with the callback that gets invoked when the modified Observable is subscribed - * @param unsubscribe The action that gets invoked when the modified {@link rx.Observable} is subscribed + * @param subscribe the action that gets invoked when the modified {@link rx.Observable} is subscribed */ public OperatorDoOnSubscribe(Action0 subscribe) { this.subscribe = subscribe; diff --git a/src/main/java/rx/subjects/SerializedSubject.java b/src/main/java/rx/subjects/SerializedSubject.java index <HASH>..<HASH> 100644 --- a/src/main/java/rx/subjects/SerializedSubject.java +++ b/src/main/java/rx/subjects/SerializedSubject.java @@ -18,6 +18,20 @@ package rx.subjects; import rx.Subscriber; import rx.observers.SerializedObserver; +/** + * Wraps a {@link Subject} so that it is safe to call its various {@code on} methods from different threads. + * <p> + * When you use an ordinary {@link Subject} as a {@link Subscriber}, you must take care not to call its + * {@link Subscriber#onNext} method (or its other {@code on} methods) from multiple threads, as this could lead + * to non-serialized calls, which violates the Observable contract and creates an ambiguity in the resulting + * Subject. + * <p> + * To protect a {@code Subject} from this danger, you can convert it into a {@code SerializedSubject} with code + * like the following: + * <p><pre>{@code + * mySafeSubject = new SerializedSubject( myUnsafeSubject ); + * }</pre> + */ public class SerializedSubject<T, R> extends Subject<T, R> { private final SerializedObserver<T> observer;
add javadocs to describe SerializedSubject class (also correct error in javadoc comments for OperatorDoOnSubscribe, for what it's worth)
ReactiveX_RxJava
train
cdd8a6b54a35e83a5f9aebb419ada476593ab144
diff --git a/src/main/java/hex/glm/GLM2.java b/src/main/java/hex/glm/GLM2.java index <HASH>..<HASH> 100644 --- a/src/main/java/hex/glm/GLM2.java +++ b/src/main/java/hex/glm/GLM2.java @@ -68,7 +68,7 @@ public class GLM2 extends Job.ModelJobWithoutClassificationField { @API(help="disable line search in all cases.",filter=Default.class, importance = ParamImportance.EXPERT, hide = true) protected boolean disable_line_search = false; // -1 is magic value for default value which is mean(y) computed on the current dataset - private double _iceptAdjust; // adjustment due to the prior + private double _iceptAdjust = 0; // adjustment due to the prior @API(help = "validation folds", filter = Default.class, lmin=0, lmax=100, json=true, importance = ParamImportance.CRITICAL) protected int n_folds; @@ -765,6 +765,8 @@ public class GLM2 extends Job.ModelJobWithoutClassificationField { int intercept = (this.intercept ?1:0); double [] fullBeta = (_activeCols == null || newBeta == null)?newBeta:expandVec(newBeta,_activeCols); if(val != null) val.null_deviance = _nullDeviance; + if(this.intercept) + fullBeta[fullBeta.length-1] += _iceptAdjust; if(_noffsets > 0){ fullBeta = Arrays.copyOf(fullBeta,fullBeta.length + _noffsets); if(this.intercept) @@ -1164,14 +1166,7 @@ public class GLM2 extends Job.ModelJobWithoutClassificationField { _ymu = ymut.ymu(); _nobs = ymut.nobs(); if(_glm.family == Family.binomial && prior != -1 && prior != _ymu && !Double.isNaN(prior)) { - double ratio = prior / _ymu; - double pi0 = 1, pi1 = 1; - if (ratio > 1) { - pi1 = 1.0 / ratio; - } else if (ratio < 1) { - pi0 = ratio; - } - _iceptAdjust = Math.log(pi0 / pi1); + _iceptAdjust = -Math.log(_ymu * (1-prior)/(prior * (1-_ymu))); } else prior = _ymu; H2OCountedCompleter cmp = (H2OCountedCompleter)getCompleter(); cmp.addToPendingCount(1);
Fixed intercept adjustment by prior probability in logistic regression.
h2oai_h2o-2
train
1e8723d64e34b5e381e08a02f864d701381863f0
diff --git a/drf_dynamic_fields/__init__.py b/drf_dynamic_fields/__init__.py index <HASH>..<HASH> 100644 --- a/drf_dynamic_fields/__init__.py +++ b/drf_dynamic_fields/__init__.py @@ -29,7 +29,7 @@ class DynamicFieldsMixin(object): params = getattr( request, 'query_params', getattr(request, 'GET', None) ) - if not params: + if params is None: warnings.warn('Request object does not contain query paramters') try:
Warn only if the params are missing from `request` Previously it would warn if they were present but empty.
dbrgn_drf-dynamic-fields
train
7806505ab4ea8c46ad94eb7741e827a77ed0b4dc
diff --git a/hmtk/seismicity/max_magnitude/cumulative_moment_release.py b/hmtk/seismicity/max_magnitude/cumulative_moment_release.py index <HASH>..<HASH> 100644 --- a/hmtk/seismicity/max_magnitude/cumulative_moment_release.py +++ b/hmtk/seismicity/max_magnitude/cumulative_moment_release.py @@ -50,7 +50,7 @@ from hmtk.seismicity.max_magnitude.base import ( BaseMaximumMagnitude, MAX_MAGNITUDE_METHODS) -@MAX_MAGNITUDE_METHODS.add("get_mmax", number_bootstraps=np.float) +@MAX_MAGNITUDE_METHODS.add("get_mmax", number_bootstraps=np.int) class CumulativeMoment(BaseMaximumMagnitude): '''Class to implement the bootstrapped cumulative moment estimator of maximum magnitude. Adapted by G. Weatherill from the Cumulative Strain
fixed type of number_bootstraps
gem_oq-engine
train
5b91e55e96fbf5a187ac9bad5e4a52f4debcbc57
diff --git a/gpiozero/pins/data.py b/gpiozero/pins/data.py index <HASH>..<HASH> 100644 --- a/gpiozero/pins/data.py +++ b/gpiozero/pins/data.py @@ -288,6 +288,7 @@ PI_REVISIONS = { 0x9000c1: ('Zero W', '1.1', '2017Q1', 'BCM2835', 'Sony', 512, 'MicroSD', 1, 0, True, True, 1, 0, {'P1': PLUS_P1}, ), 0xa22042: ('2B', '1.2', '2016Q3', 'BCM2837', 'Embest', 1024, 'MicroSD', 4, 1, False, False, 1, 1, {'P1': PLUS_P1}, ), 0x900021: ('A+', '1.1', '2016Q3', 'BCM2835', 'Sony', 512, 'MicroSD', 1, 0, False, False, 1, 1, {'P1': PLUS_P1}, ), + 0x920093: ('Zero', '1.3', '2016Q2', 'BCM2835', 'Embest', 512, 'MicroSD', 1, 0, False, False, 1, 0, {'P1': PLUS_P1}, ), }
Add details for Chinese Pi Zero (on top of <I>.post1)
RPi-Distro_python-gpiozero
train
9e76b5319ef9790d8bce27eacbc2aff4ba312cac
diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java index <HASH>..<HASH> 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java @@ -499,7 +499,7 @@ public class DnsNameResolverTest { try { InetAddress address = resolver.resolve("10.0.0.1").syncUninterruptibly().getNow(); - assertEquals("10.0.0.1", address.getHostName()); + assertEquals("10.0.0.1", address.getHostAddress()); } finally { resolver.close(); }
Fix testResolveIp to make it work in some special environment Motivation: As "getHostName" may do a reverse name lookup and return a host name based on the system configured name lookup service, testResolveIp may fail in some special environment. See #<I> Modifications: Use getHostAddress instead of getHostName Result: testResolveIp works in all environments
netty_netty
train
852ce3c4715957a7426c2d7d824d4819e2f37831
diff --git a/tortoise/contrib/test/__init__.py b/tortoise/contrib/test/__init__.py index <HASH>..<HASH> 100644 --- a/tortoise/contrib/test/__init__.py +++ b/tortoise/contrib/test/__init__.py @@ -37,8 +37,8 @@ class TestCase(asynctest.TestCase): await generate_schema(self.db) async def _tearDownDB(self) -> None: - await self.db.db_delete() await self.db.close() + await self.db.db_delete() def _setUp(self) -> None: self._init_loop() diff --git a/tortoise/tests/test_two_databases.py b/tortoise/tests/test_two_databases.py index <HASH>..<HASH> 100644 --- a/tortoise/tests/test_two_databases.py +++ b/tortoise/tests/test_two_databases.py @@ -18,8 +18,8 @@ class TestTwoDatabases(TestCase): await generate_schema(self.second_db) async def tearDown(self): - await self.second_db.db_delete() await self.second_db.close() + await self.second_db.db_delete() async def test_two_databases(self): tournament = await Tournament.create(name='Tournament')
Fix order of db close/delete
tortoise_tortoise-orm
train
499343ab1873faf997f738d3c6b6f4e2c6ae0315
diff --git a/packages/react-static/src/browser/components/RouteData.js b/packages/react-static/src/browser/components/RouteData.js index <HASH>..<HASH> 100644 --- a/packages/react-static/src/browser/components/RouteData.js +++ b/packages/react-static/src/browser/components/RouteData.js @@ -33,8 +33,14 @@ const RouteData = withStaticInfo( render() { const { children, Loader, routePath } = this.props + const routeError = routeErrorByPath[routePath] + const routeInfo = routeError + ? routeInfoByPath['404'] + : routeInfoByPath[routePath] + // If there was an error reported for this path, throw an error - if (routeErrorByPath[routePath]) { + // unless there is data for the 404 page + if (routeError && (!routeInfo || !routeInfo.data)) { throw new Error( `React-Static: <RouteData> could not find any data for this route: ${routePath}. If this is a dynamic route, please remove any reliance on RouteData or withRouteData from this routes components` ) @@ -43,7 +49,7 @@ const RouteData = withStaticInfo( // If we haven't requested the routeInfo yet, or it's loading // Show a spinner and prefetch the data // TODO:suspense - This will become a suspense resource - if (!routeInfoByPath[routePath] || !routeInfoByPath[routePath].data) { + if (!routeInfo || !routeInfo.data) { ;(async () => { await Promise.all([ prefetch(routePath, { priority: true }), @@ -57,7 +63,7 @@ const RouteData = withStaticInfo( } // Otherwise, get it from the routeInfoByPath (subsequent client side) - return children(routeInfoByPath[routePath].data) + return children(routeInfo.data) } } ) diff --git a/packages/react-static/src/browser/index.js b/packages/react-static/src/browser/index.js index <HASH>..<HASH> 100644 --- a/packages/react-static/src/browser/index.js +++ b/packages/react-static/src/browser/index.js @@ -179,6 +179,9 @@ export async function getRouteInfo(path, { priority } = {}) { } catch (err) { // If there was an error, mark the path as errored routeErrorByPath[path] = true + // Unless we already failed to find info for the 404 page, + // try to load info for the 404 page + if (path !== '404') return getRouteInfo('404', { priority }) return } if (!priority) {
Enable routeData for the <I> page (#<I>) * Enable routeData for <I> pages * Throw error if info but not data found for route
nozzle_react-static
train
87213c4cc8fd18b2a977880bf81047d9ca6323f4
diff --git a/src/wyil/transforms/LiveVariablesAnalysis.java b/src/wyil/transforms/LiveVariablesAnalysis.java index <HASH>..<HASH> 100755 --- a/src/wyil/transforms/LiveVariablesAnalysis.java +++ b/src/wyil/transforms/LiveVariablesAnalysis.java @@ -69,8 +69,7 @@ public class LiveVariablesAnalysis extends BackwardFlowAnalysis<LiveVariablesAna @Override public Module.Case propagate(Module.Case mcase) { - // TODO: back propagate through pre- and post-conditions - + // TODO: back propagate through pre- and post-conditions methodCase = mcase; stores = new HashMap<String,Env>(); afterInserts.clear(); @@ -107,7 +106,7 @@ public class LiveVariablesAnalysis extends BackwardFlowAnalysis<LiveVariablesAna @Override public Env propagate(int index, Entry entry, Env environment) { - Code code = entry.code; + Code code = entry.code; if(code instanceof Code.Load) { Code.Load load = (Code.Load) code; if(!environment.contains(load.slot)) { diff --git a/src/wyil/util/dfa/BackwardFlowAnalysis.java b/src/wyil/util/dfa/BackwardFlowAnalysis.java index <HASH>..<HASH> 100755 --- a/src/wyil/util/dfa/BackwardFlowAnalysis.java +++ b/src/wyil/util/dfa/BackwardFlowAnalysis.java @@ -166,7 +166,12 @@ public abstract class BackwardFlowAnalysis<T> implements Transform { Code.Goto gto = (Code.Goto) stmt.code; store = stores.get(gto.target); } else { - // This indicates a sequential statement was encountered. + // This indicates a sequential statement was encountered. + if (code instanceof Code.Fail + || code instanceof Code.Return + || code instanceof Code.Throw) { + store = lastStore(); + } store = propagate(i, stmt, store); }
Bug fix for backwards flow analysis.
Whiley_WhileyCompiler
train
04f5c75239cba156db70523bcd90657e5c7b5ddb
diff --git a/pkg/namesgenerator/names-generator.go b/pkg/namesgenerator/names-generator.go index <HASH>..<HASH> 100644 --- a/pkg/namesgenerator/names-generator.go +++ b/pkg/namesgenerator/names-generator.go @@ -56,7 +56,7 @@ func GenerateRandomName(checker NameChecker) (string, error) { retry := 5 rand.Seed(time.Now().UnixNano()) name := fmt.Sprintf("%s_%s", left[rand.Intn(len(left))], right[rand.Intn(len(right))]) - for checker != nil && checker.Exists(name) && retry > 0 { + for checker != nil && checker.Exists(name) && retry > 0 || name == "boring_wozniak" /* Steve Wozniak is not boring */ { name = fmt.Sprintf("%s%d", name, rand.Intn(10)) retry = retry - 1 }
Steve Wozniak is not boring. Docker-DCO-<I>-
containers_storage
train
1926999bfecc8d36e4449881ebf771d2147b6fdb
diff --git a/tests/core/test_accounts.py b/tests/core/test_accounts.py index <HASH>..<HASH> 100644 --- a/tests/core/test_accounts.py +++ b/tests/core/test_accounts.py @@ -54,17 +54,17 @@ ETH_TEST_TRANSACTIONS = [ ] -PRIVATE_KEY_AS_HEXSTR = '0x33e95ade1eb6453d5b1412414925d59c3fa1c10d3935fa680234ad1e74ced197' -PRIVATE_KEY_AS_BYTES = to_bytes(hexstr=PRIVATE_KEY_AS_HEXSTR) +PRIVATE_KEY_AS_BYTES = b'unicorns' * 4 +PRIVATE_KEY_AS_HEXSTR = '0x756e69636f726e73756e69636f726e73756e69636f726e73756e69636f726e73' PRIVATE_KEY_AS_INT = int(PRIVATE_KEY_AS_HEXSTR, 16) PRIVATE_KEY_AS_OBJ = keys.PrivateKey(PRIVATE_KEY_AS_BYTES) -ACCT_ADDRESS = '0x6c9d7169d6602f560C68E505Dc4379DdA19ff929' +ACCT_ADDRESS = '0xa79F6f349C853F9Ea0B29636779ae3Cb4E3BA729' -PRIVATE_KEY_AS_HEXSTR_ALT = '0x9377abaa20bb2b6ffcbe8e4413a1f2a600a6ad4bbe270385c4f15782ab012955' -PRIVATE_KEY_AS_BYTES_ALT = to_bytes(hexstr=PRIVATE_KEY_AS_HEXSTR_ALT) +PRIVATE_KEY_AS_BYTES_ALT = b'rainbows' * 4 +PRIVATE_KEY_AS_HEXSTR_ALT = '0x7261696e626f77737261696e626f77737261696e626f77737261696e626f7773' PRIVATE_KEY_AS_INT_ALT = int(PRIVATE_KEY_AS_HEXSTR_ALT, 16) PRIVATE_KEY_AS_OBJ_ALT = keys.PrivateKey(PRIVATE_KEY_AS_BYTES_ALT) -ACCT_ADDRESS_ALT = '0x54d6391B972fcf451C201E99ed8b495479967eDC' +ACCT_ADDRESS_ALT = '0xafd7f0E16A1814B854b45f551AFD493BE5F039F9' @pytest.fixture(params=[PRIVATE_KEY_AS_INT, PRIVATE_KEY_AS_HEXSTR, PRIVATE_KEY_AS_BYTES, PRIVATE_KEY_AS_OBJ]) # noqa: 501
Unicorns and rainbows are back!
ethereum_eth-account
train
18cba747cc061b09ef24a39fd2672077b6ca14d7
diff --git a/vendor/TraceKit/tracekit.js b/vendor/TraceKit/tracekit.js index <HASH>..<HASH> 100644 --- a/vendor/TraceKit/tracekit.js +++ b/vendor/TraceKit/tracekit.js @@ -441,6 +441,47 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() { element.func = UNKNOWN_FUNCTION; } + if (element.url && element.url.substr(0, 5) === 'blob:') { + // Special case for handling JavaScript loaded into a blob. + // We use a synchronous AJAX request here as a blob is already in + // memory - it's not making a network request. This will generate a warning + // in the browser console, but there has already been an error so that's not + // that much of an issue. + var xhr = new XMLHttpRequest(); + xhr.open('GET', element.url, false); + xhr.send(null); + + // If we failed to download the source, skip the element. + if (xhr.status === 200) { + var source = xhr.responseText; + + // We trim the source down to the last 300 characters here as + // sourceMappingURL is usually at the end of the file. + source = source.substr(source.length - 300); + + // Now we dig out the source map URL + var sourceMaps = source.match(/\/\/# {0,1}sourceMappingURL=(.*) {0,1}/); + + // If we don't find a source map comment or we find more than one, + // continue on to the next element. We check for a length of 2 as the + // first result is always the entire match, subsequent indices are + // the group matches. + if (sourceMaps.length === 2) { + var sourceMapAddress = sourceMaps[1]; + + // Now we check to see if it's a relative URL. If it is, convert it + // to an absolute one. + if (sourceMapAddress.substr(0, 1) === '~') { + sourceMapAddress = window.location.origin + sourceMapAddress.substr(1); + } + + // Now we strip the '.map' off of the end of the URL and update the + // element so that Sentry can match the map to the blob. + element.url = sourceMapAddress.substr(0, sourceMapAddress.length - 4); + } + } + } + stack.push(element); }
feat: Handle JavaScript loaded in the browser inside a blob
getsentry_sentry-javascript
train
36701c41d5ec5e499f286673045cd7d7fcbcd24f
diff --git a/nodeconductor/iaas/backup/instance_backup.py b/nodeconductor/iaas/backup/instance_backup.py index <HASH>..<HASH> 100644 --- a/nodeconductor/iaas/backup/instance_backup.py +++ b/nodeconductor/iaas/backup/instance_backup.py @@ -50,6 +50,7 @@ class InstanceBackupStrategy(BackupStrategy): metadata['system_snapshot_size'] = instance.system_volume_size metadata['data_snapshot_size'] = instance.data_volume_size + return metadata @classmethod @@ -154,5 +155,7 @@ class InstanceBackupStrategy(BackupStrategy): 'key_name': instance.key_name, 'key_fingerprint': instance.key_fingerprint, 'agreed_sla': instance.agreed_sla, + 'user_data': instance.user_data, + 'type': instance.type, } return metadata diff --git a/nodeconductor/iaas/tests/factories.py b/nodeconductor/iaas/tests/factories.py index <HASH>..<HASH> 100644 --- a/nodeconductor/iaas/tests/factories.py +++ b/nodeconductor/iaas/tests/factories.py @@ -255,6 +255,7 @@ class InstanceFactory(factory.DjangoModelFactory): backend_id = factory.Sequence(lambda n: 'instance-id%s' % n) agreed_sla = Decimal('99.9') + type = factory.Iterator([models.Instance.Services.IAAS, models.Instance.Services.PAAS]) @classmethod def get_url(self, instance=None, action=None):
Persist instance type on backup/restoration - ITACLOUD-<I>
opennode_waldur-core
train
523e35d9735bf5b4aa205a2f8ccdf1a73d66a665
diff --git a/pywb/warcserver/index/fuzzymatcher.py b/pywb/warcserver/index/fuzzymatcher.py index <HASH>..<HASH> 100644 --- a/pywb/warcserver/index/fuzzymatcher.py +++ b/pywb/warcserver/index/fuzzymatcher.py @@ -84,7 +84,7 @@ class FuzzyMatcher(object): m = rule.regex.search(urlkey) groups = m and m.groups() - if not groups: + if groups is None: continue matched_rule = rule @@ -99,7 +99,7 @@ class FuzzyMatcher(object): # support matching w/o query if no additional filters # don't include trailing '?' if no filters and replace_after '?' - no_filters = (filters == {'urlkey:'}) and (matched_rule.replace_after == '?') + no_filters = (not filters or filters == {'urlkey:'}) and (matched_rule.replace_after == '?') inx = url.find(matched_rule.replace_after) if inx > 0:
fuzzy matching: apply fuzzy match if url prefix and regex match, even if no groups are captured by the regex (#<I>)
webrecorder_pywb
train
8ec490daca978e077726d41a7cb8a4f57d04be01
diff --git a/src/org/zaproxy/zap/extension/forceduser/ExtensionForcedUser.java b/src/org/zaproxy/zap/extension/forceduser/ExtensionForcedUser.java index <HASH>..<HASH> 100644 --- a/src/org/zaproxy/zap/extension/forceduser/ExtensionForcedUser.java +++ b/src/org/zaproxy/zap/extension/forceduser/ExtensionForcedUser.java @@ -354,10 +354,8 @@ public class ExtensionForcedUser extends ExtensionAdaptor implements ContextPane // Note: Do not persist whether the 'Forced User Mode' is enabled as there's no need // for this and the mode can be easily enabled/disabled directly } else { - // If we don't have a forced user, set an 'empty' list to force deletion of any - // previous values - session.setContextData(context.getIndex(), RecordContext.TYPE_FORCED_USER_ID, - Collections.<String> emptyList()); + // If we don't have a forced user, force deletion of any previous values + session.clearContextDataForType(context.getIndex(), RecordContext.TYPE_FORCED_USER_ID); } } catch (Exception e) { log.error("Unable to persist forced user.", e);
Proper deletion of existing context data for ForcedUserExtension.
zaproxy_zaproxy
train
8a1cc5e80dc7806bc996efa67b7c11fc0885acab
diff --git a/_raw/lib/picker.js b/_raw/lib/picker.js index <HASH>..<HASH> 100644 --- a/_raw/lib/picker.js +++ b/_raw/lib/picker.js @@ -238,7 +238,10 @@ function PickerConstructor( ELEMENT, NAME, COMPONENT, OPTIONS ) { // * Don’t worry about clicks or focusins on the root because those don’t bubble up. // Also, for Firefox, a click on an `option` element bubbles up directly // to the doc. So make sure the target wasn't the doc. - if ( target != ELEMENT && target != document ) { + // * In Firefox stopPropagation() doesn’t prevent right-click events from bubbling, + // which causes the picker to unexpectedly close when right-clicking it. So make + // sure the event wasn’t a right-click. + if ( target != ELEMENT && target != document && event.which != 3 ) { // If the target was the holder that covers the screen, // keep the element focused to maintain tabindex.
Ignore right-click events to prevent picker from closing when it is right-clicked in Firefox
amsul_pickadate.js
train
d76905aaaf410d4c306c2c599797b3b825b522bb
diff --git a/lib/howitzer/blank_page.rb b/lib/howitzer/blank_page.rb index <HASH>..<HASH> 100644 --- a/lib/howitzer/blank_page.rb +++ b/lib/howitzer/blank_page.rb @@ -2,5 +2,5 @@ require 'howitzer/web_page' class BlankPage < WebPage URL = 'about:blank' - validates :url, pattern: /about:blank/ + validates :url, pattern: /^about:blank$/ end \ No newline at end of file diff --git a/lib/howitzer/web_page.rb b/lib/howitzer/web_page.rb index <HASH>..<HASH> 100644 --- a/lib/howitzer/web_page.rb +++ b/lib/howitzer/web_page.rb @@ -33,7 +33,7 @@ class WebPage # * +WebPage+ - New instance of current class # - def self.open(url="#{app_url}#{self::URL}") + def self.open(url = "#{self::URL.to_s == BlankPage::URL.to_s ? '' : app_url}#{self::URL}") log.info "Open #{self.name} page by '#{url}' url" retryable(tries: 2, logger: log, trace: true, on: Exception) do |retries| log.info "Retry..." unless retries.zero?
fixed problem with blank page 'about:blank' it should not start with app url
strongqa_howitzer
train
7aae8c9489f5b7d4308c63799ed3e9caca6f920f
diff --git a/spec/support/rails_template_with_data.rb b/spec/support/rails_template_with_data.rb index <HASH>..<HASH> 100644 --- a/spec/support/rails_template_with_data.rb +++ b/spec/support/rails_template_with_data.rb @@ -189,6 +189,15 @@ inject_into_file 'app/admin/post.rb', <<-RUBY, after: "ActiveAdmin.register Post end end + member_action :toggle_starred, method: :put do + resource.update(starred: !resource.starred) + redirect_to resource_path, notice: "Post updated." + end + + action_item :toggle_starred, only: :show do + link_to 'Toggle Starred', toggle_starred_admin_post_path(post), method: :put + end + show do |post| attributes_table do row :id
Add custom action item and member action Simple action here to toggle the starred attribute on post.
activeadmin_activeadmin
train
9e9d3684a1e97e9b8f300c09934ecd0230a3dd86
diff --git a/python/ccxt/binance.py b/python/ccxt/binance.py index <HASH>..<HASH> 100644 --- a/python/ccxt/binance.py +++ b/python/ccxt/binance.py @@ -498,7 +498,8 @@ class binance (Exchange): 'interval': self.timeframes[timeframe], } request['limit'] = limit if (limit) else 500 # default == max == 500 - if since: + # Set since = 0 to traverse records from the beginning. + if not (since is None) and (since >= 0): request['startTime'] = since response = self.publicGetKlines(self.extend(request, params)) return self.parse_ohlcvs(response, market, timeframe, since, limit) diff --git a/python/ccxt/bitfinex.py b/python/ccxt/bitfinex.py index <HASH>..<HASH> 100644 --- a/python/ccxt/bitfinex.py +++ b/python/ccxt/bitfinex.py @@ -518,7 +518,8 @@ class bitfinex (Exchange): } if limit: request['limit'] = limit - if since: + # Set since = 0 to traverse records from the beginning. + if not (since is None) and since >= 0: request['start'] = since request = self.extend(request, params) response = self.v2GetCandlesTradeTimeframeSymbolHist(request) diff --git a/python/ccxt/kraken.py b/python/ccxt/kraken.py index <HASH>..<HASH> 100644 --- a/python/ccxt/kraken.py +++ b/python/ccxt/kraken.py @@ -426,7 +426,8 @@ class kraken (Exchange): 'pair': market['id'], 'interval': self.timeframes[timeframe], } - if since: + # Set since = 0 to traverse records from the beginning. + if not (since is None) and (since >= 0): request['since'] = int(since / 1000) response = self.publicGetOHLC(self.extend(request, params)) ohlcvs = response['result'][market['id']]
fetch_ohlcv(): Now you can set since = 0 to traverse records from the beginning.
ccxt_ccxt
train
9999ab55fa10e89e128e86f6b27fbc6e63b44f8f
diff --git a/src/Entities/Products/ProductExtra.php b/src/Entities/Products/ProductExtra.php index <HASH>..<HASH> 100644 --- a/src/Entities/Products/ProductExtra.php +++ b/src/Entities/Products/ProductExtra.php @@ -16,12 +16,8 @@ class ProductExtra private $enabled; /** @var OrganisationShort */ private $organisation; - /** - * @var ProductTag - */ - private $tag; - public function __construct($id, $name, $description, $price, $enabled, OrganisationShort $organisation, ProductTag $tag) + public function __construct($id, $name, $description, $price, $enabled, OrganisationShort $organisation) { $this->id = $id; $this->name = $name; @@ -29,7 +25,6 @@ class ProductExtra $this->price = $price; $this->enabled = $enabled; $this->organisation = $organisation; - $this->tag = $tag; } /** @@ -79,12 +74,4 @@ class ProductExtra { return $this->organisation; } - - /** - * @return ProductTag - */ - public function getTag() - { - return $this->tag; - } } diff --git a/src/Entities/Products/ProductOption.php b/src/Entities/Products/ProductOption.php index <HASH>..<HASH> 100644 --- a/src/Entities/Products/ProductOption.php +++ b/src/Entities/Products/ProductOption.php @@ -16,12 +16,8 @@ class ProductOption private $enabled; /** @var OrganisationShort */ private $organisation; - /** - * @var ProductTag - */ - private $tag; - public function __construct($id, $name, $description, $price, $enabled, OrganisationShort $organisation, ProductTag $tag) + public function __construct($id, $name, $description, $price, $enabled, OrganisationShort $organisation) { $this->id = $id; $this->name = $name; @@ -29,7 +25,6 @@ class ProductOption $this->price = $price; $this->enabled = $enabled; $this->organisation = $organisation; - $this->tag = $tag; } /** @@ -79,12 +74,4 @@ class ProductOption { return $this->organisation; } - - /** - * @return ProductTag - */ - public function getTag() - { - return $this->tag; - } }
Removed product tag from product extras & options
ordercloud_ordercloud-php
train
655e61bf5b86e029a657a97f733b72a9f5ed2fec
diff --git a/src/internal/_isArrayLike.js b/src/internal/_isArrayLike.js index <HASH>..<HASH> 100644 --- a/src/internal/_isArrayLike.js +++ b/src/internal/_isArrayLike.js @@ -6,22 +6,19 @@ var _isString = require('./_isString'); /** * Tests whether or not an object is similar to an array. * - * @func - * @memberOf R - * @since v0.5.0 + * @private * @category Type * @category List * @sig * -> Boolean * @param {*} x The object to test. * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise. - * @deprecated since v0.23.0 * @example * - * R.isArrayLike([]); //=> true - * R.isArrayLike(true); //=> false - * R.isArrayLike({}); //=> false - * R.isArrayLike({length: 10}); //=> false - * R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true + * _isArrayLike([]); //=> true + * _isArrayLike(true); //=> false + * _isArrayLike({}); //=> false + * _isArrayLike({length: 10}); //=> false + * _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true */ module.exports = _curry1(function isArrayLike(x) { if (_isArray(x)) { return true; }
fix _isArrayLike jsdoc now that it is internal
ramda_ramda
train
1d9b51c8af29a3ad8a30c72e78f5422d14e1ef2e
diff --git a/src/main/java/org/aesh/parser/ParsedLineIterator.java b/src/main/java/org/aesh/parser/ParsedLineIterator.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/aesh/parser/ParsedLineIterator.java +++ b/src/main/java/org/aesh/parser/ParsedLineIterator.java @@ -165,6 +165,8 @@ public class ParsedLineIterator { character = length + character; } + else + throw new IllegalArgumentException("The length given must be > 0 and not exceed the boundary of the line (including the current position)"); } }
throw an exception if the given value is not valid
aeshell_aesh-readline
train
dcd81173edb8a3841ca740dafb39fed0037987fe
diff --git a/src/ContaoCommunityAlliance/DcGeneral/Contao/View/Contao2BackendView/ListView.php b/src/ContaoCommunityAlliance/DcGeneral/Contao/View/Contao2BackendView/ListView.php index <HASH>..<HASH> 100644 --- a/src/ContaoCommunityAlliance/DcGeneral/Contao/View/Contao2BackendView/ListView.php +++ b/src/ContaoCommunityAlliance/DcGeneral/Contao/View/Contao2BackendView/ListView.php @@ -55,23 +55,6 @@ class ListView extends BaseView $objCollection = $objCurrentDataProvider->fetchAll($objConfig); - // If we want to group the elements, do so now. - if (isset($objCondition) - && ($this->getViewSection()->getListingConfig()->getGroupingMode() == ListingConfigInterface::GROUP_CHAR) - ) - { - foreach ($objCollection as $objModel) - { - /** @var ModelInterface $objModel */ - $arrFilter = $objCondition->getInverseFilter($objModel); - $objConfig = $objParentDataProvider->getEmptyConfig()->setFilter($arrFilter); - $objParent = $objParentDataProvider->fetch($objConfig); - - $objModel->setMeta($objModel::PARENT_ID, $objParent->getId()); - $objModel->setMeta($objModel::PARENT_PROVIDER_NAME, $objParent->getProviderName()); - } - } - return $objCollection; }
Drop dead code from ListView. I have really no clue where this chunk originated from and can not make neither heads nor tails out of it's original purpose. Therefore I dropped it as it was always skipped.
contao-community-alliance_dc-general
train
bfbe95ccc12d339bbf1691d0ed8107acaa7880f6
diff --git a/liquibase-core/src/main/java/liquibase/change/core/AddPrimaryKeyChange.java b/liquibase-core/src/main/java/liquibase/change/core/AddPrimaryKeyChange.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/change/core/AddPrimaryKeyChange.java +++ b/liquibase-core/src/main/java/liquibase/change/core/AddPrimaryKeyChange.java @@ -205,6 +205,10 @@ public class AddPrimaryKeyChange extends AbstractChange { inverse.setTableName(getTableName()); inverse.setConstraintName(getConstraintName()); + if (this.getForIndexName() != null) { + inverse.setDropIndex(false); + } + return new Change[]{ inverse, }; diff --git a/liquibase-core/src/main/java/liquibase/change/core/DropPrimaryKeyChange.java b/liquibase-core/src/main/java/liquibase/change/core/DropPrimaryKeyChange.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/change/core/DropPrimaryKeyChange.java +++ b/liquibase-core/src/main/java/liquibase/change/core/DropPrimaryKeyChange.java @@ -24,6 +24,7 @@ public class DropPrimaryKeyChange extends AbstractChange { private String schemaName; private String tableName; private String constraintName; + private Boolean dropIndex; @Override public boolean generateStatementsVolatile(Database database) { @@ -69,6 +70,14 @@ public class DropPrimaryKeyChange extends AbstractChange { this.constraintName = constraintName; } + public Boolean getDropIndex() { + return dropIndex; + } + + public void setDropIndex(Boolean dropIndex) { + this.dropIndex = dropIndex; + } + @Override public SqlStatement[] generateStatements(Database database) { @@ -76,9 +85,11 @@ public class DropPrimaryKeyChange extends AbstractChange { // return special statements for SQLite databases return generateStatementsForSQLiteDatabase(database); } - + + DropPrimaryKeyStatement statement = new DropPrimaryKeyStatement(getCatalogName(), getSchemaName(), getTableName(), getConstraintName()); + statement.setDropIndex(this.dropIndex); return new SqlStatement[]{ - new DropPrimaryKeyStatement(getCatalogName(), getSchemaName(), getTableName(), getConstraintName()), + statement, }; } diff --git a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/DropPrimaryKeyGenerator.java b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/DropPrimaryKeyGenerator.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/DropPrimaryKeyGenerator.java +++ b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/DropPrimaryKeyGenerator.java @@ -87,7 +87,10 @@ public class DropPrimaryKeyGenerator extends AbstractSqlGenerator<DropPrimaryKey } else if (database instanceof FirebirdDatabase) { sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " DROP CONSTRAINT "+database.escapeConstraintName(statement.getConstraintName()); } else if (database instanceof OracleDatabase) { - sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " DROP PRIMARY KEY DROP INDEX"; + sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " DROP PRIMARY KEY"; + if (statement.getDropIndex() == null || statement.getDropIndex()) { + sql += " DROP INDEX"; + } } else if (database instanceof InformixDatabase) { sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " DROP CONSTRAINT " + database.escapeConstraintName(statement.getConstraintName()); } else { diff --git a/liquibase-core/src/main/java/liquibase/statement/core/DropPrimaryKeyStatement.java b/liquibase-core/src/main/java/liquibase/statement/core/DropPrimaryKeyStatement.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/statement/core/DropPrimaryKeyStatement.java +++ b/liquibase-core/src/main/java/liquibase/statement/core/DropPrimaryKeyStatement.java @@ -8,6 +8,7 @@ public class DropPrimaryKeyStatement extends AbstractSqlStatement { private String schemaName; private String tableName; private String constraintName; + private Boolean dropIndex; public DropPrimaryKeyStatement(String catalogName, String schemaName, String tableName, String constraintName) { this.catalogName = catalogName; @@ -32,4 +33,11 @@ public class DropPrimaryKeyStatement extends AbstractSqlStatement { return constraintName; } + public Boolean getDropIndex() { + return dropIndex; + } + + public void setDropIndex(Boolean dropIndex) { + this.dropIndex = dropIndex; + } }
CORE-<I> Oracle: primary keys that use a pre-existing index drop the index along with the primary key on rollback
liquibase_liquibase
train
594a8badc95f5a77900ce6852f5e3819f3f6a419
diff --git a/client/my-sites/checkout/controller.jsx b/client/my-sites/checkout/controller.jsx index <HASH>..<HASH> 100644 --- a/client/my-sites/checkout/controller.jsx +++ b/client/my-sites/checkout/controller.jsx @@ -35,8 +35,10 @@ export function checkout( context, next ) { const selectedSite = getSelectedSite( state ); const currentUser = getCurrentUser( state ); const hasSite = currentUser && currentUser.visible_site_count >= 1; + const isDomainOnlyFlow = context.query?.isDomainOnly === '1'; const isDisallowedForSitePicker = - context.pathname.includes( '/checkout/no-site' ) && ( isLoggedOut || ! hasSite ); + context.pathname.includes( '/checkout/no-site' ) && + ( isLoggedOut || ! hasSite || isDomainOnlyFlow ); if ( ! selectedSite && ! isDisallowedForSitePicker ) { sites( context, next ); diff --git a/client/my-sites/controller.js b/client/my-sites/controller.js index <HASH>..<HASH> 100644 --- a/client/my-sites/controller.js +++ b/client/my-sites/controller.js @@ -324,8 +324,9 @@ export function noSite( context, next ) { const { getState } = getStore( context ); const currentUser = getCurrentUser( getState() ); const hasSite = currentUser && currentUser.visible_site_count >= 1; + const isDomainOnlyFlow = context.query?.isDomainOnly === '1'; - if ( hasSite ) { + if ( ! isDomainOnlyFlow && hasSite ) { siteSelection( context, next ); } else { context.store.dispatch( setSelectedSiteId( null ) ); diff --git a/client/signup/config/flows.js b/client/signup/config/flows.js index <HASH>..<HASH> 100644 --- a/client/signup/config/flows.js +++ b/client/signup/config/flows.js @@ -13,7 +13,7 @@ import { isEcommercePlan } from 'lib/plans'; import { generateFlows } from 'signup/config/flows-pure'; import { addQueryArgs } from 'lib/url'; -function getCheckoutUrl( dependencies, localeSlug ) { +function getCheckoutUrl( dependencies, localeSlug, flowName ) { let checkoutURL = `/checkout/${ dependencies.siteSlug }`; // Append the locale slug for the userless checkout page. @@ -32,6 +32,7 @@ function getCheckoutUrl( dependencies, localeSlug ) { redirect_to: `/home/${ dependencies.siteSlug }`, } ), ...( dependencies.isGutenboardingCreate && { isGutenboardingCreate: 1 } ), + ...( 'domain' === flowName && { isDomainOnly: 1 } ), }, checkoutURL ); @@ -123,7 +124,7 @@ function removeP2DetailsStepFromFlow( flow ) { function filterDestination( destination, dependencies, flowName, localeSlug ) { if ( dependenciesContainCartItem( dependencies ) ) { - return getCheckoutUrl( dependencies, localeSlug ); + return getCheckoutUrl( dependencies, localeSlug, flowName ); } return destination;
In the domain only flow, neither redirect to /checkout/SITE_SLUG nor show site picker. We will keep the checkout page slug as /checkout/no-site and let create_new_blog flag in the backend handle the site creation. (#<I>)
Automattic_wp-calypso
train
668d625ae73d5c1f9fecf59235a1ccc84fec7523
diff --git a/src/Illuminate/View/Component.php b/src/Illuminate/View/Component.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/View/Component.php +++ b/src/Illuminate/View/Component.php @@ -214,7 +214,7 @@ abstract class Component { $this->attributes = $this->attributes ?: new ComponentAttributeBag; - $this->attributes->setAttributes($attributes); + $this->attributes = $this->attributes->merge($attributes); return $this; } diff --git a/tests/View/ViewComponentTest.php b/tests/View/ViewComponentTest.php index <HASH>..<HASH> 100644 --- a/tests/View/ViewComponentTest.php +++ b/tests/View/ViewComponentTest.php @@ -45,6 +45,17 @@ class ViewComponentTest extends TestCase $component->data(); $this->assertEquals(3, $component->counter); } + + public function testAttributesAreMergedNotOverwritten() + { + $component = new TestDefaultAttributesComponent; + + $this->assertEquals('text-red-500', $component->attributes->get('class')); + + $component->withAttributes(['class' => 'bg-blue-100']); + + $this->assertEquals('bg-blue-100 text-red-500', $component->attributes->get('class')); + } } class TestViewComponent extends Component @@ -99,3 +110,16 @@ class TestSampleViewComponent extends Component $this->counter++; } } + +class TestDefaultAttributesComponent extends Component +{ + public function __construct() + { + $this->withAttributes(['class' => 'text-red-500']); + } + + public function render() + { + return $this->attributes->get('id'); + } +}
[7.x] Fix not being able to set component attributes from inside class (#<I>) * Made attributes merge instead of overwrite * Added test for attribute merging
laravel_framework
train
39ca9979a6c1fbaa4a36380c2ebd7970d86eaf86
diff --git a/lib/mongo_profiler/extensions/mongo/cursor.rb b/lib/mongo_profiler/extensions/mongo/cursor.rb index <HASH>..<HASH> 100644 --- a/lib/mongo_profiler/extensions/mongo/cursor.rb +++ b/lib/mongo_profiler/extensions/mongo/cursor.rb @@ -4,7 +4,7 @@ Mongo::Cursor.class_eval do def send_initial_query beginning_time = Time.now original_send_initial_query - time_spent = Time.now - beginning_time + total_time = Time.now - beginning_time begin profiler = MongoProfiler::Profiler.new(@db) @@ -12,7 +12,7 @@ Mongo::Cursor.class_eval do result = {} - result[:time_spent] = time_spent + result[:total_time] = total_time # the payload sent to mongo result[:instrument_payload] = JSON.dump(instrument_payload) @@ -31,7 +31,7 @@ Mongo::Cursor.class_eval do profiler.log(result) if statsd_client = MongoProfiler.statsd_client - statsd_client.populate(_caller, time_spent) + statsd_client.populate(_caller, total_time) end rescue => e p "MongoProfiler: #{e.message}" diff --git a/lib/mongo_profiler/stats.rb b/lib/mongo_profiler/stats.rb index <HASH>..<HASH> 100644 --- a/lib/mongo_profiler/stats.rb +++ b/lib/mongo_profiler/stats.rb @@ -4,16 +4,16 @@ module MongoProfiler @statsd_client = statsd_client end - def populate(_caller, time_spent) + def populate(_caller, total_time) file = sanitaze_stat_key _caller.file.split('/').last method = sanitaze_stat_key _caller.method stat_name = "mongo_profiler.#{MongoProfiler.application_name}.#{file}.#{method}" - time_spent_ms = time_spent * 1000 + total_time_ms = total_time * 1000 @statsd_client.increment stat_name - @statsd_client.timing stat_name, time_spent_ms + @statsd_client.timing stat_name, total_time_ms end private
s/time_spent/total_time/
phstc_mongo_profiler
train
eeac222e41ebb8b2c24f6a1e56aeac7d322eeaee
diff --git a/impl/src/main/java/org/apache/camel/cdi/CdiSpiHelper.java b/impl/src/main/java/org/apache/camel/cdi/CdiSpiHelper.java index <HASH>..<HASH> 100644 --- a/impl/src/main/java/org/apache/camel/cdi/CdiSpiHelper.java +++ b/impl/src/main/java/org/apache/camel/cdi/CdiSpiHelper.java @@ -45,6 +45,11 @@ import static java.util.stream.Collectors.joining; @Vetoed final class CdiSpiHelper { + static Predicate<Annotation> isAnnotationType(Class<? extends Annotation> clazz) { + requireNonNull(clazz); + return annotation -> clazz.equals(annotation.annotationType()); + } + static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { return Class.class.cast(type); @@ -73,11 +78,6 @@ final class CdiSpiHelper { return getRawType(bounds[0]); } - static Predicate<Annotation> isAnnotationType(Class<? extends Annotation> clazz) { - requireNonNull(clazz); - return annotation -> clazz.equals(annotation.annotationType()); - } - /** * Generates a unique signature for {@link BeanAttributes}. */ @@ -93,7 +93,7 @@ final class CdiSpiHelper { /** * Generates a unique signature of a collection of types. */ - private static String createTypeCollectionId(Collection<? extends Type> types) { + private static String createTypeCollectionId(Collection<Type> types) { return types.stream() .sorted(comparing(CdiSpiHelper::createTypeId)) .map(CdiSpiHelper::createTypeId)
Fix type inference compilation error on older JDK versions
astefanutti_camel-cdi
train
b11a95a06e7ee5c96cddfc0ad54aae45478a75bb
diff --git a/CurlWrapper.php b/CurlWrapper.php index <HASH>..<HASH> 100644 --- a/CurlWrapper.php +++ b/CurlWrapper.php @@ -70,7 +70,7 @@ class CurlWrapper $this->ch = curl_init(); if (!$this->ch) { - throw new CurlWrapperException($this->ch); + throw new CurlWrapperCurlException($this->ch); } $this->setDefaults(); @@ -399,7 +399,7 @@ class CurlWrapper $this->response = curl_exec($this->ch); if ($this->response === false) { - throw new CurlWrapperException($this->ch); + throw new CurlWrapperCurlException($this->ch); } $this->transferInfo = curl_getinfo($this->ch); @@ -594,7 +594,7 @@ class CurlWrapper } if (!curl_setopt_array($this->ch, $this->options)) { - throw new CurlWrapperException($this->ch); + throw new CurlWrapperCurlException($this->ch); } } @@ -695,15 +695,25 @@ class CurlWrapper class CurlWrapperException extends Exception { /** - * @param string|resource $messageOrCurlHandler + * @param string $message */ - public function __construct($messageOrCurlHandler) + public function __construct($message) { - if (is_string($messageOrCurlHandler)) { - $this->message = $messageOrCurlHandler; - } else { - $this->message = curl_error($messageOrCurlHandler); - $this->code = curl_errno($messageOrCurlHandler); - } + $this->message = $message; + } +} + +/** + * CurlWrapper cURL Exceptions class + */ +class CurlWrapperCurlException extends CurlWrapperException +{ + /** + * @param resource $curlHandler + */ + public function __construct($curlHandler) + { + $this->message = curl_error($curlHandler); + $this->code = curl_errno($curlHandler); } } \ No newline at end of file
New exception class specifically for cURL exceptions added
svyatov_CurlWrapper
train
edc200e6d14c67e6b8973efa7cb37453c3c5fb7a
diff --git a/api/opentrons/drivers/rpi_drivers/gpio.py b/api/opentrons/drivers/rpi_drivers/gpio.py index <HASH>..<HASH> 100755 --- a/api/opentrons/drivers/rpi_drivers/gpio.py +++ b/api/opentrons/drivers/rpi_drivers/gpio.py @@ -129,9 +129,9 @@ def set_low(pin): def read(pin): """ - Reads a pin's value. This pin must have been previously initialized - and set up as with direction of IN, otherwise this operation will not - behave as expected. + Reads a pin's value. If the pin has been previously initialized with + a direction of IN, the value will be the input signal. If pin is configured + as OUT, the value will be the current output state. :param pin: An integer corresponding to the GPIO number of the pin in RPi GPIO board numbering (not physical pin numbering) diff --git a/api/opentrons/drivers/smoothie_drivers/driver_3_0.py b/api/opentrons/drivers/smoothie_drivers/driver_3_0.py index <HASH>..<HASH> 100755 --- a/api/opentrons/drivers/smoothie_drivers/driver_3_0.py +++ b/api/opentrons/drivers/smoothie_drivers/driver_3_0.py @@ -1265,6 +1265,10 @@ class SmoothieDriver_3_0_0: def turn_off_rail_lights(self): gpio.set_low(gpio.OUTPUT_PINS['FRAME_LEDS']) + def get_rail_lights_on(self): + value = gpio.read(gpio.OUTPUT_PINS['FRAME_LEDS']) + return True if value == 1 else False + def read_button(self): # button is normal-HIGH, so invert return not bool(gpio.read(gpio.INPUT_PINS['BUTTON_INPUT'])) diff --git a/api/opentrons/robot/robot.py b/api/opentrons/robot/robot.py index <HASH>..<HASH> 100755 --- a/api/opentrons/robot/robot.py +++ b/api/opentrons/robot/robot.py @@ -312,6 +312,9 @@ class Robot(object): def turn_off_rail_lights(self): self._driver.turn_off_rail_lights() + def get_rail_lights_on(self): + return self._driver.get_rail_lights_on() + def identify(self, seconds): """ Identify a robot by flashing the light around the frame button for 10s diff --git a/api/opentrons/server/endpoints/control.py b/api/opentrons/server/endpoints/control.py index <HASH>..<HASH> 100644 --- a/api/opentrons/server/endpoints/control.py +++ b/api/opentrons/server/endpoints/control.py @@ -283,14 +283,21 @@ async def identify(request): return web.json_response({"message": "identifying"}) -async def turn_on_rail_lights(request): - robot.turn_on_rail_lights() - return web.json_response({"lights": "on"}) +async def get_rail_lights(request): + return web.json_response({'on': robot.get_rail_lights_on()}) -async def turn_off_rail_lights(request): - robot.turn_off_rail_lights() - return web.json_response({"lights": "off"}) +async def set_rail_lights(request): + data = await request.json() + on = data.get('on') + + if on is None: + return web.json_response( + {'message': '"on" must be true or false, got {}'.format(on)}, + status=400) + + robot.turn_on_rail_lights() if on else robot.turn_off_rail_lights() + return web.json_response({'on': on}) async def take_picture(request): diff --git a/api/opentrons/server/main.py b/api/opentrons/server/main.py index <HASH>..<HASH> 100755 --- a/api/opentrons/server/main.py +++ b/api/opentrons/server/main.py @@ -153,10 +153,6 @@ def init(loop=None): server.app.router.add_post( '/identify', control.identify) server.app.router.add_post( - '/lights/on', control.turn_on_rail_lights) - server.app.router.add_post( - '/lights/off', control.turn_off_rail_lights) - server.app.router.add_post( '/camera/picture', control.take_picture) server.app.router.add_post( '/server/update', endpoints.update_api) @@ -185,6 +181,10 @@ def init(loop=None): server.app.router.add_post( '/robot/home', control.home) server.app.router.add_get( + '/robot/lights', control.get_rail_lights) + server.app.router.add_post( + '/robot/lights', control.set_rail_lights) + server.app.router.add_get( '/settings', update.get_feature_flag) server.app.router.add_get( '/settings/environment', update.environment)
refactor(api): Move lights endpoints to /robot/lights and provide getter (#<I>)
Opentrons_opentrons
train
116c91e29337da0cee57bf65da85f4d05869d4c4
diff --git a/tests/unit/states/file_test.py b/tests/unit/states/file_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/states/file_test.py +++ b/tests/unit/states/file_test.py @@ -4,6 +4,7 @@ from __future__ import absolute_import import json import pprint +import tempfile # Import Salt Testing libs from salttesting import skipIf, TestCase @@ -138,13 +139,16 @@ class FileTestCase(TestCase): ''' # 'symlink' function tests: 1 + @destructiveTest def test_symlink(self): ''' Test to create a symlink. ''' - name = '/etc/grub.conf' - target = '/boot/grub/grub.conf' + name = '/tmp/testfile.txt' + target = tempfile.mkstemp()[1] + test_dir = '/tmp' user = 'salt' + if salt.utils.is_windows(): group = 'salt' else: @@ -200,10 +204,10 @@ class FileTestCase(TestCase): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_f): with patch.object(os.path, 'exists', mock_f): - comt = ('Directory /etc for symlink is not present') + comt = ('Directory {0} for symlink is not present').format(test_dir) ret.update({'comment': comt, 'result': False, - 'pchanges': {'new': '/etc/grub.conf'}}) + 'pchanges': {'new': name}}) self.assertDictEqual(filestate.symlink(name, target, user=user, group=group), ret) @@ -232,16 +236,17 @@ class FileTestCase(TestCase): 'file.readlink': mock_target}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_t): - with patch.object(os.path, 'lexists', mock_t): - comt = ('File exists where the backup target SALT' - ' should go') - ret.update({'comment': comt, - 'result': False, - 'pchanges': {'new': name}}) - self.assertDictEqual(filestate.symlink - (name, target, user=user, - group=group, backupname='SALT'), - ret) + with patch.object(os.path, 'exists', mock_f): + with patch.object(os.path, 'lexists', mock_t): + comt = ('File exists where the backup target SALT' + ' should go') + ret.update({'comment': comt, + 'result': False, + 'pchanges': {'new': name}}) + self.assertDictEqual(filestate.symlink + (name, target, user=user, + group=group, backupname='SALT'), + ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid, @@ -250,13 +255,16 @@ class FileTestCase(TestCase): 'file.readlink': mock_target}): with patch.dict(filestate.__opts__, {'test': False}): with patch.object(os.path, 'isdir', mock_t): - with patch.object(os.path, 'isfile', mock_t): - comt = ('File exists where the symlink {0} should be' - .format(name)) - ret.update({'comment': comt, 'result': False}) - self.assertDictEqual(filestate.symlink - (name, target, user=user, - group=group), ret) + with patch.object(os.path, 'exists', mock_f): + with patch.object(os.path, 'isfile', mock_t): + comt = ('File exists where the symlink {0} should be' + .format(name)) + ret.update({'comment': comt, + 'pchanges': {'new': name}, + 'result': False}) + self.assertDictEqual(filestate.symlink + (name, target, user=user, + group=group), ret) with patch.dict(filestate.__salt__, {'config.manage_mode': mock_t, 'file.user_to_uid': mock_uid,
Changed the target file in file.symlink test (#<I>)
saltstack_salt
train
18ca0362b8963bedd85ad5262a33e7d0a3c9b742
diff --git a/bootstrapnavtags/templatetags/bootstrapnavtags.py b/bootstrapnavtags/templatetags/bootstrapnavtags.py index <HASH>..<HASH> 100644 --- a/bootstrapnavtags/templatetags/bootstrapnavtags.py +++ b/bootstrapnavtags/templatetags/bootstrapnavtags.py @@ -13,7 +13,7 @@ def navitem(parser, token): template_tag = bits[0] if len(bits) < 3: - raise template.TemplateSyntaxError, "%r tag requires at least two argument" % template_tag + raise TemplateSyntaxError("%r tag requires at least two argument" % template_tag) try: label = parser.compile_filter(bits[1])
fix python3 issue with raising of template synax error
noxan_django-bootstrap-navtags
train
4352be9e1c27b9893ba48509aea1882565817108
diff --git a/py/dynesty/dynamicsampler.py b/py/dynesty/dynamicsampler.py index <HASH>..<HASH> 100644 --- a/py/dynesty/dynamicsampler.py +++ b/py/dynesty/dynamicsampler.py @@ -938,6 +938,13 @@ class DynamicSampler: bounditer=results.bounditer, eff=self.eff, delta_logz=results.delta_logz) + new_vals = {} + (new_vals['logwt'], new_vals['logz'], new_vals['logzvar'], + new_vals['h']) = compute_integrals(logl=self.saved_run.D['logl'], + logvol=self.saved_run.D['logvol']) + for curk in ['logwt', 'logz', 'logzvar', 'h']: + self.saved_run.D[curk] = new_vals[curk].tolist() + self.base_run.D[curk] = new_vals[curk].tolist() self.base = True # baseline run complete self.saved_run.D['batch'] = np.zeros(len(self.saved_run.D['id']), @@ -1683,7 +1690,6 @@ class DynamicSampler: dlogz=dlogz_init, logl_max=logl_max_init) - # Add points in batches. for n in range(self.batch, maxbatch): # Update stopping criteria. res = self.results
run compute_integrals after the initial run of the dynamic run to ensure that the logz errors are correct. That's needed only if no batches will be added.
joshspeagle_dynesty
train
594337189e5d5a0794ffbc2ee006e877ddd5b19b
diff --git a/edisgo/grid/network.py b/edisgo/grid/network.py index <HASH>..<HASH> 100644 --- a/edisgo/grid/network.py +++ b/edisgo/grid/network.py @@ -1779,18 +1779,11 @@ class Results: Attributes ---------- - measures: list - A stack that details the history of measures to increase grid's hosting - capacity. The last item refers to the latest measure. The key - `original` refers to the state of the grid topology as it was initially - imported. network : :class:`~.grid.network.Network` The network is a container object holding all data. """ - # ToDo: maybe add setter to alter list of measures - def __init__(self, network): self.network = network self._measures = ['original'] @@ -1806,6 +1799,32 @@ class Results: self._unresolved_issues = {} @property + def measures(self): + """ + List with the history of measures to increase grid's hosting capacity. + + Parameters + ---------- + measure : :obj:`str` + Measure to increase grid's hosting capacity. Possible options are + 'grid_expansion', 'storage_integration', 'curtailment'. + + Returns + ------- + measures : :obj:`list` + A stack that details the history of measures to increase grid's + hosting capacity. The last item refers to the latest measure. The + key `original` refers to the state of the grid topology as it was + initially imported. + + """ + return self._measures + + @measures.setter + def measures(self, measure): + self._measures.append(measure) + + @property def pfa_p(self): """ Active power results from power flow analysis in kW.
Add getter and setter for measures
openego_eDisGo
train
08c8d36fc9e27a413fa7a3f4b85e51378d85dccd
diff --git a/src/js/me-shim.js b/src/js/me-shim.js index <HASH>..<HASH> 100644 --- a/src/js/me-shim.js +++ b/src/js/me-shim.js @@ -325,7 +325,6 @@ mejs.HtmlMediaElementShim = { // flash/silverlight vars initVars = [ 'id=' + pluginid, - 'poster=' + poster, 'isvideo=' + ((isVideo) ? "true" : "false"), 'autoplay=' + ((autoplay) ? "true" : "false"), 'preload=' + preload,
- remove poster from plugins (HTML handles this)
mediaelement_mediaelement
train
eb4930e3c724cf71d6ce5bb2aec4af82b2025b03
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb index <HASH>..<HASH> 100644 --- a/actionmailer/lib/action_mailer/test_case.rb +++ b/actionmailer/lib/action_mailer/test_case.rb @@ -10,13 +10,6 @@ module ActionMailer end class TestCase < ActiveSupport::TestCase - - # Use AM::TestCase for the base class when describing a mailer - register_spec_type(self) do |desc| - Class === desc && desc < ActionMailer::Base - end - register_spec_type(/Mailer( ?Test)?\z/i, self) - module Behavior extend ActiveSupport::Concern diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index <HASH>..<HASH> 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -360,13 +360,6 @@ module ActionController # # assert_redirected_to page_url(title: 'foo') class TestCase < ActiveSupport::TestCase - - # Use AC::TestCase for the base class when describing a controller - register_spec_type(self) do |desc| - Class === desc && desc < ActionController::Metal - end - register_spec_type(/Controller( ?Test)?\z/i, self) - module Behavior extend ActiveSupport::Concern include ActionDispatch::TestProcess diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index <HASH>..<HASH> 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -491,9 +491,6 @@ module ActionDispatch include ActionController::TemplateAssertions include ActionDispatch::Routing::UrlFor - # Use AD::IntegrationTest for acceptance tests - register_spec_type(/(Acceptance|Integration) ?Test\z/i, self) - @@app = nil def self.app diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index <HASH>..<HASH> 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -30,9 +30,6 @@ module ActionView end end - # Use AV::TestCase for the base class for helpers and views - register_spec_type(/(Helper|View)( ?Test)?\z/i, self) - module Behavior extend ActiveSupport::Concern diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -1,5 +1,5 @@ gem 'minitest' # make sure we get the gem, not stdlib -require 'minitest/spec' +require 'minitest/unit' require 'active_support/testing/tagged_logging' require 'active_support/testing/setup_and_teardown' require 'active_support/testing/assertions' @@ -17,13 +17,7 @@ rescue LoadError end module ActiveSupport - class TestCase < ::MiniTest::Spec - - # Use AS::TestCase for the base class when describing a model - register_spec_type(self) do |desc| - Class === desc && desc < ActiveRecord::Base - end - + class TestCase < ::MiniTest::Unit::TestCase Assertion = MiniTest::Assertion alias_method :method_name, :__name__ diff --git a/railties/test/engine_test.rb b/railties/test/engine_test.rb index <HASH>..<HASH> 100644 --- a/railties/test/engine_test.rb +++ b/railties/test/engine_test.rb @@ -1,7 +1,7 @@ require 'abstract_unit' class EngineTest < ActiveSupport::TestCase - it "reports routes as available only if they're actually present" do + test "reports routes as available only if they're actually present" do engine = Class.new(Rails::Engine) do def initialize(*args) @routes = nil
Inherit from MiniTest::Unit::TestCase instead of MiniTest::Spec
rails_rails
train
c942da1cc957c5b0677b3c36d918617121ed6173
diff --git a/www/src/py_utils.js b/www/src/py_utils.js index <HASH>..<HASH> 100644 --- a/www/src/py_utils.js +++ b/www/src/py_utils.js @@ -126,7 +126,7 @@ $B.wrong_nb_args = function(name, received, expected, positional){ } -$B.get_class = function(obj, from){ +$B.get_class = function(obj){ // generally we get the attribute __class__ of an object by obj.__class__ // but Javascript builtins used by Brython (functions, numbers, strings...) // don't have this attribute so we must return it @@ -161,6 +161,8 @@ $B.get_class = function(obj, from){ }else if(obj.constructor===Number) return _b_.float.$dict break } + }else if(klass.__class__===$B.$factory){ + klass = klass.$dict } return klass } @@ -717,6 +719,29 @@ $B.$is_member = function(item,_set){ } } +$B.$call = function(callable){ + if(callable.__class__ === $B.$MethodDict){ + return callable + } + else if(callable.$is_func || typeof callable=="function"){return callable} + else if(callable.$factory){ + return callable.$factory + } + else if(callable.$is_class){ + // Use metaclass __call__, cache result in callable.$factory + return callable.$factory = $B.$instance_creator(callable) + } + else if(callable.__class__===$B.$factory){return callable} // XXX old style + try{ + return $B.$getattr(callable, "__call__") + }catch(err){ + console.log(err) + console.log(callable) + throw _b_.TypeError("'" + $B.get_class(callable).__name__ + + "' object is not callable") + } +} + // default standard output and error // can be reset by sys.stdout or sys.stderr var $io = {__class__:$B.$type,__name__:'io'} @@ -1355,50 +1380,46 @@ $B.rich_comp = function(op, x, y){ return x1 > y1 } } - var res, rev_op, compared = false, x1, y1 - x1 = x.__class__===$B.$factory ? x.$dict : x - y1 = y.__class__===$B.$factory ? y.$dict : y + var res, rev_op, compared = false + x = x.__class__===$B.$factory ? x.$dict : x + y = y.__class__===$B.$factory ? y.$dict : y - if(x1.$factory) { + if(x.$is_class || x.$factory) { if ( op == '__eq__') { - //console.log("compare classes", x, y, x===y) - return (x1 === y1) + return (x === y) } else if ( op == '__ne__') { - return !(x1 === y1) + return !(x === y) } else { throw _b_.TypeError("'"+op+"' not supported between types") } } - if(x1.__class__ && y1.__class__){ + if(x.__class__ && y.__class__){ // cf issue #600 and // https://docs.python.org/3/reference/datamodel.html : // "If the operands are of different types, and right operand’s type // is a direct or indirect subclass of the left operand’s type, the // reflected method of the right operand has priority, otherwise the // left operand’s method has priority." - if(y1.__class__.__mro__.indexOf(x1.__class__)>-1){ + if(y.__class__.__mro__.indexOf(x.__class__)>-1){ rev_op = reversed_op[op] || op - res = _b_.getattr(y1, rev_op)(x1) + res = _b_.getattr(y, rev_op)(x) if ( res !== _b_.NotImplemented ) return res compared = true } } - - res = _b_.getattr(x1, op)(y1) - + res = $B.$call(_b_.getattr(x, op))(y) + if ( res !== _b_.NotImplemented ) return res; if (compared) return false; rev_op = reversed_op[op] || op - res = _b_.getattr(y1, rev_op)(x1) + res = _b_.getattr(y, rev_op)(x) if ( res !== _b_.NotImplemented ) return res // If both operands return NotImplemented, return False if the operand is // __eq__, True if it is __ne__, raise TypeError otherwise if(op=='__eq__'){return _b_.False} else if(op=='__ne__'){return _b_.True} - //if(x.__class__===$B.$factory){x=x.__class__} - //if(y.__class__===$B.$factory){y=y.__class__} throw _b_.TypeError("'"+method2comp[op]+"' not supported between " + "instances of '" + $B.get_class(x).__name__+ "' and '" + $B.get_class(y).__name__+"'")
Add $B.$call, used to translate Python calls : Python "f(args)" is translated to Javascript "$B.$call(f)(args)". If f is a class, $B.$call(f) is the class factory ; if it is a function or a method, returns f unchanged ; otherwise use getattr(f, "__call__"). Adapt several function to support both old-style and new-style classes (temporary).
brython-dev_brython
train
a3d9930831fb032f51d22911961254ccdb638995
diff --git a/auto_ml/utils_models.py b/auto_ml/utils_models.py index <HASH>..<HASH> 100644 --- a/auto_ml/utils_models.py +++ b/auto_ml/utils_models.py @@ -50,6 +50,11 @@ except ImportError: def get_model_from_name(model_name, training_params=None): + # For Keras + nb_epoch = 250 + if 'is_test_suite' in sys.argv: + nb_epoch = 10 + all_model_params = { 'LogisticRegression': {'n_jobs': -2}, 'RandomForestClassifier': {'n_jobs': -2}, @@ -69,8 +74,9 @@ def get_model_from_name(model_name, training_params=None): 'XGBRegressor': {'nthread':-1, 'n_estimators': 200}, 'XGBClassifier': {'nthread':-1, 'n_estimators': 200}, 'LGBMRegressor': {}, - 'LGBMClassifier': {} - + 'LGBMClassifier': {}, + 'DeepLearningRegressor': {'nb_epoch': nb_epoch, 'batch_size': 50, 'verbose': 2}, + 'DeepLearningClassifier': {'nb_epoch': nb_epoch, 'batch_size': 50, 'verbose': 2} } model_params = all_model_params.get(model_name, None) @@ -132,12 +138,9 @@ def get_model_from_name(model_name, training_params=None): model_map['LGBMClassifier'] = lgb.LGBMClassifier() if keras_installed: - nb_epoch = 250 - if 'is_test_suite' in sys.argv: - nb_epoch = 10 - model_map['DeepLearningClassifier'] = KerasClassifier(build_fn=make_deep_learning_classifier, nb_epoch=nb_epoch, batch_size=50, verbose=2) - model_map['DeepLearningRegressor'] = KerasRegressor(build_fn=make_deep_learning_model, nb_epoch=nb_epoch, batch_size=50, verbose=2) + model_map['DeepLearningClassifier'] = KerasClassifier(build_fn=make_deep_learning_classifier) + model_map['DeepLearningRegressor'] = KerasRegressor(build_fn=make_deep_learning_model) model_without_params = model_map[model_name] model_with_params = model_without_params.set_params(**model_params)
updates deep learning models to use the training_params structure the rest of our algos use
ClimbsRocks_auto_ml
train
4b23d5e43f7d3b3dc063b61a74016e7c1b3c4897
diff --git a/lib/neo4j-server/cypher_transaction.rb b/lib/neo4j-server/cypher_transaction.rb index <HASH>..<HASH> 100644 --- a/lib/neo4j-server/cypher_transaction.rb +++ b/lib/neo4j-server/cypher_transaction.rb @@ -73,13 +73,17 @@ module Neo4j cypher_response.set_data(first_result) else first_error = response.body[:errors].first - autoclosed! - mark_expired if first_error[:message].match(/Unrecognized transaction id/) + tx_cleanup!(first_error) cypher_response.set_error(first_error) end end end + def tx_cleanup!(first_error) + autoclosed! + mark_expired if first_error[:message].match(/Unrecognized transaction id/) + end + def empty_response OpenStruct.new(status: 200, body: '') end
split tx cleanup stuff into separate method to appease rubocop
neo4jrb_neo4j-core
train
7a5ab95089fc67149513eb956b8a28fe89c25a52
diff --git a/agent/lib/kontena/workers/container_health_check_worker.rb b/agent/lib/kontena/workers/container_health_check_worker.rb index <HASH>..<HASH> 100644 --- a/agent/lib/kontena/workers/container_health_check_worker.rb +++ b/agent/lib/kontena/workers/container_health_check_worker.rb @@ -61,7 +61,7 @@ module Kontena::Workers } } begin - response = Excon.get(url, :connect_timeout => timeout) + response = Excon.get(url, :connect_timeout => timeout, :headers => {"User-Agent" => "Kontena-Agent/#{Kontena::Agent::VERSION}"}) debug "got status: #{response.status}" msg[:data]['status'] = HEALTHY_STATUSES.include?(response.status) ? 'healthy' : 'unhealthy' msg[:data]['status_code'] = response.status diff --git a/agent/spec/lib/kontena/workers/container_health_check_worker_spec.rb b/agent/spec/lib/kontena/workers/container_health_check_worker_spec.rb index <HASH>..<HASH> 100644 --- a/agent/spec/lib/kontena/workers/container_health_check_worker_spec.rb +++ b/agent/spec/lib/kontena/workers/container_health_check_worker_spec.rb @@ -51,11 +51,15 @@ describe Kontena::Workers::ContainerHealthCheckWorker do end describe '#check_http_status' do + + let(:headers) { + {"User-Agent"=>"Kontena-Agent/#{Kontena::Agent::VERSION}"} + } it 'returns healthy status' do response = double allow(response).to receive(:status).and_return(200) - expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', connect_timeout: 10).and_return(response) + expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', {:connect_timeout=>10, :headers=>headers}).and_return(response) health_status = subject.check_http_status('1.2.3.4', 8080, '/health', 10) expect(health_status[:data]['status']).to eq('healthy') expect(health_status[:data]['status_code']).to eq(200) @@ -64,20 +68,20 @@ describe Kontena::Workers::ContainerHealthCheckWorker do it 'returns unhealthy status when response status not 200' do response = double allow(response).to receive(:status).and_return(500) - expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', connect_timeout: 10).and_return(response) + expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', {:connect_timeout=>10, :headers=>headers}).and_return(response) health_status = subject.check_http_status('1.2.3.4', 8080, '/health', 10) expect(health_status[:data]['status']).to eq('unhealthy') expect(health_status[:data]['status_code']).to eq(500) end it 'returns unhealthy status when connection timeouts' do - expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', connect_timeout: 10).and_raise(Excon::Errors::Timeout) + expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', {:connect_timeout=>10, :headers=>headers}).and_raise(Excon::Errors::Timeout) health_status = subject.check_http_status('1.2.3.4', 8080, '/health', 10) expect(health_status[:data]['status']).to eq('unhealthy') end it 'returns unhealthy status when connection fails with weird error' do - expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', connect_timeout: 10).and_raise(Excon::Errors::Error) + expect(Excon).to receive(:get).with('http://1.2.3.4:8080/health', {:connect_timeout=>10, :headers=>headers}).and_raise(Excon::Errors::Error) health_status = subject.check_http_status('1.2.3.4', 8080, '/health', 10) expect(health_status[:data]['status']).to eq('unhealthy') end
Add user-agent for http healthcheck (#<I>)
kontena_kontena
train
5a42097013fcd106f367a3fbe30058c8102ae6a3
diff --git a/tests/test_mocks.py b/tests/test_mocks.py index <HASH>..<HASH> 100644 --- a/tests/test_mocks.py +++ b/tests/test_mocks.py @@ -360,7 +360,7 @@ class MockedRelationsTest(TestCase): @mocked_relations(Manufacturer, Car) def test_mocked_relations_create_foreign_key_with_kwargs(self): make = Manufacturer.objects.create(name='foo') - _ = Car.objects.create(make=make) + Car.objects.create(make=make) class TestMockers(TestCase):
Update test_mocks.py flake8 is whining about unused underscore variables.
stphivos_django-mock-queries
train
539784b64095f2befc3f6d5d4ca87a59a8b44028
diff --git a/src/babel/transformation/transformers/es6/block-scoping.js b/src/babel/transformation/transformers/es6/block-scoping.js index <HASH>..<HASH> 100644 --- a/src/babel/transformation/transformers/es6/block-scoping.js +++ b/src/babel/transformation/transformers/es6/block-scoping.js @@ -32,8 +32,8 @@ function isVar(node, parent) { } function standardizeLets(declars) { - for (var i = 0; i < declars.length; i++) { - delete declars[i]._let; + for (var declar of (declars: Array)) { + delete declar._let; } } @@ -109,19 +109,14 @@ function traverseReplace(node, parent, scope, remaps) { } var letReferenceBlockVisitor = { - enter(node, parent, scope, state) { - if (this.isFunction()) { - this.traverse(letReferenceFunctionVisitor, state); - return this.skip(); - } + Function(node, parent, scope, state) { + this.traverse(letReferenceFunctionVisitor, state); + return this.skip(); } }; var letReferenceFunctionVisitor = { - enter(node, parent, scope, state) { - // not a direct reference - if (!this.isReferencedIdentifier()) return; - + ReferencedIdentifier(node, parent, scope, state) { var ref = state.letReferences[node.name]; // not a part of our scope @@ -159,10 +154,8 @@ var hoistVarDeclarationsVisitor = { }; var loopLabelVisitor = { - enter(node, parent, scope, state) { - if (this.isLabeledStatement()) { - state.innerLabels.push(node.label.name); - } + LabeledStatement(node, parent, scope, state) { + state.innerLabels.push(node.label.name); } }; diff --git a/src/babel/traversal/scope.js b/src/babel/traversal/scope.js index <HASH>..<HASH> 100644 --- a/src/babel/traversal/scope.js +++ b/src/babel/traversal/scope.js @@ -430,8 +430,8 @@ export default class Scope { this.registerBinding("hoisted", path); } else if (t.isVariableDeclaration(node)) { var declarations = path.get("declarations"); - for (var i = 0; i < declarations.length; i++) { - this.registerBinding(node.kind, declarations[i]); + for (var declar of (declarations: Array)) { + this.registerBinding(node.kind, declar); } } else if (t.isClassDeclaration(node)) { this.registerBinding("let", path); @@ -548,8 +548,8 @@ export default class Scope { // ForStatement - left, init if (path.isLoop()) { - for (let i = 0; i < t.FOR_INIT_KEYS.length; i++) { - var node = path.get(t.FOR_INIT_KEYS[i]); + for (let key of (t.FOR_INIT_KEYS: Array)) { + var node = path.get(key); if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); } } @@ -572,8 +572,8 @@ export default class Scope { if (path.isFunction()) { var params = path.get("params"); - for (let i = 0; i < params.length; i++) { - this.registerBinding("param", params[i]); + for (let param of (params: Array)) { + this.registerBinding("param", param); } this.traverse(path.get("body").node, blockVariableVisitor, this); } @@ -697,8 +697,7 @@ export default class Scope { getAllBindingsOfKind(): Object { var ids = object(); - for (let i = 0; i < arguments.length; i++) { - var kind = arguments[i]; + for (let kind of (arguments: Array)) { var scope = this; do { for (var name in scope.bindings) { @@ -790,6 +789,19 @@ export default class Scope { } /** + * Move a binding of `name` to another `scope`. + */ + + moveBindingTo(name, scope) { + var info = this.getBinding(name); + if (info) { + info.scope.removeOwnBinding(name); + info.scope = scope; + scope.bindings[name] = info; + } + } + + /** * Description */
add Scope#moveBindingTo method and change more for array loops to for...of
babel_babel
train
eec2ac50e006a857d9aca7ca3d438ce38b46361a
diff --git a/languagetool-core/src/main/java/org/languagetool/languagemodel/BaseLanguageModel.java b/languagetool-core/src/main/java/org/languagetool/languagemodel/BaseLanguageModel.java index <HASH>..<HASH> 100644 --- a/languagetool-core/src/main/java/org/languagetool/languagemodel/BaseLanguageModel.java +++ b/languagetool-core/src/main/java/org/languagetool/languagemodel/BaseLanguageModel.java @@ -63,6 +63,10 @@ public abstract class BaseLanguageModel implements LanguageModel { totalCount = phraseCount; } double thisP = (double) (phraseCount + 1) / (firstWordCount + 1); + /* boosting 4grams seems to improve f-measure a tiny bit: + if (subList.size() == 4 && phraseCount > 0) { + thisP = 100; + }*/ maxCoverage++; debug(" P for " + subList + ": %.20f (%d)\n", thisP, phraseCount); if (phraseCount > 0) {
add comment about boosting 4grams
languagetool-org_languagetool
train
55e93184d269140366a5f5117d1384a97ba91561
diff --git a/test/matrix_tests.js b/test/matrix_tests.js index <HASH>..<HASH> 100644 --- a/test/matrix_tests.js +++ b/test/matrix_tests.js @@ -5,3 +5,83 @@ exports.newMatrix = function(beforeExit, assert) { assert.equal(m.toString(), "matrix(1,0,0,1,0,0)"); }; + +exports.IDENTITY = function(beforeExit, assert) { + +}; + +exports.multiply = function(beforeExit, assert) { + +}; + +exports.inverse = function(beforeExit, assert) { + +}; + +exports.translate = function(beforeExit, assert) { + +}; + +exports.scale = function(beforeExit, assert) { + +}; + +exports.scaleAt = function(beforeExit, assert) { + +}; + +exports.scaleNonUniform = function(beforeExit, assert) { + +}; + +exports.scaleNonUniformAt = function(beforeExit, assert) { + +}; + +exports.rotate = function(beforeExit, assert) { + +}; + +exports.rotateAt = function(beforeExit, assert) { + +}; + +exports.rotateFromVector = function(beforeExit, assert) { + +}; + +exports.flipX = function(beforeExit, assert) { + +}; + +exports.flipY = function(beforeExit, assert) { + +}; + +exports.skewX = function(beforeExit, assert) { + +}; + +exports.skewY = function(beforeExit, assert) { + +}; + +exports.isIdentity = function(beforeExit, assert) { + +}; + +exports.isInvertible = function(beforeExit, assert) { + +}; + +exports.getScale = function(beforeExit, assert) { + +}; + +exports.equals = function(beforeExit, assert) { + +}; + +exports.toString = function(beforeExit, assert) { + +};
Set up skeleton tests for Matrix2D
thelonious_kld-affine
train
667820efd0652df8ed61420cd0dec8df1b3ecdd2
diff --git a/src/Exceptions/LaravelModuleInstallerException.php b/src/Exceptions/LaravelModuleInstallerException.php index <HASH>..<HASH> 100644 --- a/src/Exceptions/LaravelModuleInstallerException.php +++ b/src/Exceptions/LaravelModuleInstallerException.php @@ -6,5 +6,10 @@ use Exception; class LaravelModuleInstallerException extends Exception { - protected $message = "Ensure your package's name is in the format <vendor>/<name>-<module>"; -} \ No newline at end of file + public static function fromInvalidPackage(string $invalidPackageName): self + { + return new self( + "Ensure your package's name ({$invalidPackageName}) is in the format <vendor>/<name>-<module>" + ); + } +} diff --git a/src/LaravelModuleInstaller.php b/src/LaravelModuleInstaller.php index <HASH>..<HASH> 100644 --- a/src/LaravelModuleInstaller.php +++ b/src/LaravelModuleInstaller.php @@ -21,7 +21,7 @@ class LaravelModuleInstaller extends LibraryInstaller /** * Get the base path that the module should be installed into. * Defaults to Modules/ and can be overridden in the module's composer.json. - * + * * @return string */ protected function getBaseInstallationPath() @@ -41,11 +41,11 @@ class LaravelModuleInstaller extends LibraryInstaller /** * Get the module name, i.e. "joshbrw/something-module" will be transformed into "Something" - * + * * @param PackageInterface $package Compose Package Interface - * + * * @return string Module Name - * + * * @throws LaravelModuleInstallerException */ protected function getModuleName(PackageInterface $package) @@ -54,17 +54,17 @@ class LaravelModuleInstaller extends LibraryInstaller $split = explode("/", $name); if (count($split) !== 2) { - throw new LaravelModuleInstallerException(); + throw LaravelModuleInstallerException::fromInvalidPackage($name); } $splitNameToUse = explode("-", $split[1]); if (count($splitNameToUse) < 2) { - throw new LaravelModuleInstallerException(); + throw LaravelModuleInstallerException::fromInvalidPackage($name); } if (array_pop($splitNameToUse) !== 'module') { - throw new LaravelModuleInstallerException(); + throw LaravelModuleInstallerException::fromInvalidPackage($name); } return implode('', array_map('ucfirst', $splitNameToUse));
Include failed package name in error message (closes PR #6)
joshbrw_laravel-module-installer
train
2dee6a394f42e26e87ce00e4f458a4c7a4097c9c
diff --git a/bypy.py b/bypy.py index <HASH>..<HASH> 100755 --- a/bypy.py +++ b/bypy.py @@ -143,7 +143,7 @@ elif sys.version_info[0] == 3: basestring = str long = int raw_input = input - pickleload = partial(pickle.load(encoding="bytes")) + pickleload = partial(pickle.load, encoding="bytes") import json import hashlib import base64 @@ -422,10 +422,11 @@ rb = remove_backslash # http://stackoverflow.com/questions/9403986/python-3-traceback-fails-when-no-exception-is-active def format_exc(**kwargs): - if sys.exc_info() == (None, None, None): - return [] - else: - return traceback.format_stack(**kwargs) + if sys.version_info[0] == 3: + if sys.exc_info() == (None, None, None): + return [] + + return traceback.format_stack(**kwargs) def format_exc_str(**kwargs): return ''.join(format_exc(**kwargs)) @@ -3742,7 +3743,10 @@ def main(argv=None): # IGNORE:C0111 verbose = args.verbose, debug = args.debug) uargs = [] for arg in args.command[1:]: - uargs.append(unicode(arg, SystemEncoding)) + if sys.version_info[0] < 3: + uargs.append(unicode(arg, SystemEncoding)) + else: + uargs.append(arg) result = getattr(by, args.command[0])(*uargs) else: pr("Error: Command '{}' not available.".format(args.command[0])) @@ -3753,8 +3757,9 @@ def main(argv=None): # IGNORE:C0111 # handle keyboard interrupt pr("KeyboardInterrupt") pr("Abort") - except Exception: + except Exception as ex: perr("Exception occurred:") + pr("Exception: {}".format(ex)) pr(format_exc_str()) pr("Abort") # raise
Fix Python 3 command line param passing and stack printing (#<I>)
houtianze_bypy
train
4942faaeaa7c18805c3425dff90ccb9191f951e7
diff --git a/test/sass/less_conversion_test.rb b/test/sass/less_conversion_test.rb index <HASH>..<HASH> 100755 --- a/test/sass/less_conversion_test.rb +++ b/test/sass/less_conversion_test.rb @@ -1,5 +1,7 @@ #!/usr/bin/env ruby require File.dirname(__FILE__) + '/../test_helper' + +begin require 'sass/less' class LessConversionTest < Test::Unit::TestCase @@ -210,3 +212,7 @@ LESS assert_equal(scss, Less::Engine.new(less).to_tree.to_sass_tree.to_scss) end end + +rescue LoadError => e +puts "\nCouldn't require less, skipping some tests." +end
[Sass] [Less] Don't die when testing if Less isn't available.
sass_ruby-sass
train
88833d9ded6949e03de3a98ccff67c67b2c6e551
diff --git a/src/main/java/org/jboss/netty/buffer/ChannelBufferInputStream.java b/src/main/java/org/jboss/netty/buffer/ChannelBufferInputStream.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jboss/netty/buffer/ChannelBufferInputStream.java +++ b/src/main/java/org/jboss/netty/buffer/ChannelBufferInputStream.java @@ -232,7 +232,7 @@ public class ChannelBufferInputStream extends InputStream implements DataInput { private void checkAvailable(int fieldSize) throws IOException { if (fieldSize < 0) { - throw new IllegalArgumentException(); + throw new IndexOutOfBoundsException(); } if (fieldSize > available()) { throw new EOFException();
Fixed issue: NETTY-<I> (ChannelBufferInputStream.readFully(byte[], int, int) should throw IndexOutOfBoundsException.) * ChannelBufferInputstream.checkAvailable() throws IndexOutOfBoundsException instead of IllegalArgumentException now.
netty_netty
train
64e5518c2f1c779e44cd40fddd519d498725817e
diff --git a/src/org/zaproxy/zap/extension/ascan/ActiveScanAPI.java b/src/org/zaproxy/zap/extension/ascan/ActiveScanAPI.java index <HASH>..<HASH> 100644 --- a/src/org/zaproxy/zap/extension/ascan/ActiveScanAPI.java +++ b/src/org/zaproxy/zap/extension/ascan/ActiveScanAPI.java @@ -753,11 +753,11 @@ public class ActiveScanAPI extends ApiImplementor { try { startURI = new URI(url, true); } catch (URIException e) { - throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL); + throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL, e); } String scheme = startURI.getScheme(); if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) { - throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL); + throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_URL + " does not have a scheme."); } try {
Provide more details on ascan API URL errors Include the exception when failed to parse the start URL and indicate that the scheme is missing in the exception message.
zaproxy_zaproxy
train
85e1281b68252484a78c99a46d72bc88f5e31cd6
diff --git a/src/Kris/LaravelFormBuilder/Fields/FormField.php b/src/Kris/LaravelFormBuilder/Fields/FormField.php index <HASH>..<HASH> 100644 --- a/src/Kris/LaravelFormBuilder/Fields/FormField.php +++ b/src/Kris/LaravelFormBuilder/Fields/FormField.php @@ -220,6 +220,19 @@ abstract class FormField $this->options = $helper->mergeOptions($this->options, $options); + foreach (['attr', 'label_attr', 'wrapper'] as $appendable) { + // Append values to the 'class' attribute + if ($this->getOption("{$appendable}.class_append")) { + // Combine the current class attribute with the appends + $append = $this->getOption("{$appendable}.class_append"); + $classAttribute = $this->getOption("{$appendable}.class", '').' '.$append; + $this->setOption("{$appendable}.class", $classAttribute); + + // Then remove the class_append option to prevent it from showing up as an attribute in the HTML + $this->setOption("{$appendable}.class_append", null); + } + } + if ($this->getOption('attr.multiple') && !$this->getOption('tmp.multipleBracesSet')) { $this->name = $this->name.'[]'; $this->setOption('tmp.multipleBracesSet', true);
add the ability to append to wrapper, label and field class attribute
kristijanhusak_laravel-form-builder
train
5f801ebbe3886649ea1620e6f9386cde31a10a96
diff --git a/Paradox/pod/Document.php b/Paradox/pod/Document.php index <HASH>..<HASH> 100644 --- a/Paradox/pod/Document.php +++ b/Paradox/pod/Document.php @@ -269,7 +269,7 @@ class Document implements IObserver } else { $info = $this->_toolbox->parseId($this->_referencePodId); - return $this->_toolbox->getPodManager()->load($info['collection'], $info['id']); + return $this->_toolbox->getPodManager()->load($info['collection'], $info['key']); } } @@ -282,20 +282,20 @@ class Document implements IObserver $fields = $this->_toolbox->getCollectionManager()->getGeoFieldsForAQL($this->getType()); //A geo1 index (field is an array with the coordinates). - if($fields){ - if (count($fields) == 1) { - - $field = $this->get($fields[0]); - - return array('latitude' => $field[0], 'longitude' => $field[1]); - - //A geo2 index (2 fields each representing latitue and longitude). - } else { - $latitude = $this->get($fields[0]); - $longitude = $this->get($fields[1]); - - return array('latitude' => $latitude, 'longitude' => $longitude); - } + if ($fields) { + if (count($fields) == 1) { + + $field = $this->get($fields[0]); + + return array('latitude' => $field[0], 'longitude' => $field[1]); + + //A geo2 index (2 fields each representing latitue and longitude). + } else { + $latitude = $this->get($fields[0]); + $longitude = $this->get($fields[1]); + + return array('latitude' => $latitude, 'longitude' => $longitude); + } } return null;
Fixed small bug in document and formatted everything.
F21_Paradox
train
a8a807e9d90649bf5f8c7744b7ce36b967339911
diff --git a/src/Traits/FactoryTrait.php b/src/Traits/FactoryTrait.php index <HASH>..<HASH> 100644 --- a/src/Traits/FactoryTrait.php +++ b/src/Traits/FactoryTrait.php @@ -273,7 +273,7 @@ trait FactoryTrait */ public static function createFromArray(array $values): ChronosInterface { - $values += ['hour' => 0, 'minute' => 0, 'second' => 0, 'microsecond' => 0]; + $values += ['hour' => 0, 'minute' => 0, 'second' => 0, 'microsecond' => 0, 'timezone' => null]; $formatted = ''; if ( @@ -300,9 +300,8 @@ trait FactoryTrait $values['second'], $values['microsecond'] ); - $tz = $values['timezone'] ?? null; - return static::parse($formatted, $tz); + return static::parse($formatted, $values['timezone']); } /**
Updated use of ?? to match <I>
cakephp_chronos
train
3b208b263d971d3699ae0f5d7c30820be197eae4
diff --git a/tpot/tpot.py b/tpot/tpot.py index <HASH>..<HASH> 100644 --- a/tpot/tpot.py +++ b/tpot/tpot.py @@ -308,25 +308,22 @@ class TPOT(object): return self._evaluate_individual(self.optimized_pipeline_, training_testing_data)[0] - def export(self, output_file_name): - """Exports the current optimized pipeline as Python code. + + def _replace_mathematical_operators(self, exported_pipeline): + """Replace all of the mathematical operators with their results in export(). Parameters ---------- - output_file_name: string - String containing the path and file name of the desired output file + exported_pipeline: + The current optimized pipeline Returns ------- - None + exported_pipeline: + The current optimized pipeline after replacing the mathematical operators """ - if self.optimized_pipeline_ is None: - raise ValueError('A pipeline has not yet been optimized. Please call fit() first.') - - exported_pipeline = self.optimized_pipeline_ - - # Replace all of the mathematical operators with their results + while True: for i in range(len(exported_pipeline) - 1, -1, -1): node = exported_pipeline[i] @@ -348,7 +345,25 @@ class TPOT(object): else: break - # Unroll the nested function calls into serial code + return exported_pipeline + + def _unroll_nested_fuctions_calls(self, exported_pipeline): + """Unroll the nested function calls into serial code in export() + + Parameters + ---------- + exported_pipeline: + The current optimized pipeline + + Returns + ------- + exported_pipeline: + The current optimized pipeline after unrolling the nested function calls + pipeline_list: + List of operators in the current optimized pipeline + + """ + pipeline_list = [] result_num = 1 while True: @@ -369,6 +384,31 @@ class TPOT(object): break else: break + return exported_pipeline, pipeline_list + + + def export(self, output_file_name): + """Exports the current optimized pipeline as Python code. + + Parameters + ---------- + output_file_name: string + String containing the path and file name of the desired output file + + Returns + ------- + None + + """ + if self.optimized_pipeline_ is None: + raise ValueError('A pipeline has not yet been optimized. Please call fit() first.') + + exported_pipeline = self.optimized_pipeline_ + + exported_pipeline = self._replace_mathematical_operators(exported_pipeline) + + exported_pipeline, pipeline_list = self._unroll_nested_fuctions_calls(exported_pipeline) + # Have the code import all of the necessary modules and functions # operator[1] is the name of the operator
Break Export into separate functions Build separate functions for: -Replace all of the mathematical operators with their results -Unroll the nested function calls into serial code
EpistasisLab_tpot
train
6fecec6dfd7d6c839cbefbdc1ed0a5ea63980957
diff --git a/modules/component/component.js b/modules/component/component.js index <HASH>..<HASH> 100644 --- a/modules/component/component.js +++ b/modules/component/component.js @@ -14,7 +14,6 @@ export default class Component extends Container { */ constructor (position, options) { super(position, options); - this.options.alpha = this.options.opacity || this.options.alpha; /** * @type {Boolean} @@ -34,7 +33,6 @@ export default class Component extends Container { render (ctx) { return super.render(ctx, () => { ctx.beginPath(); - ctx.globalAlpha = this.options.alpha; ctx.moveTo(0, 0); this.trace(ctx); @@ -96,7 +94,6 @@ export default class Component extends Container { */ static get defaultOptions () { return Object.assign(super.defaultOptions, { - alpha: 1, fill: "#000", stroke: null, strokeWidth: 2, diff --git a/modules/container/container.js b/modules/container/container.js index <HASH>..<HASH> 100644 --- a/modules/container/container.js +++ b/modules/container/container.js @@ -220,6 +220,10 @@ export default class Container extends EventEmitter { stableSort.inplace(this.children, (a, b) => a.options.zIndex - b.options.zIndex); + if (this.options.opacity !== null) { + ctx.globalAlpha = this.options.opacity; + } + const pivotIndex = this.children.filter(child => child.options.zIndex < 0).length; this.children.slice(0, pivotIndex).forEach(child => child.render(ctx)); @@ -237,9 +241,10 @@ export default class Container extends EventEmitter { /** * @typedef {Object} ContainerOptions * @prop {Boolean} [shown=true] - Is shown - * @prop {Number} [rotation=0] - Rotation in degree (clockwise) + * @prop {Number} [opacity=null] - Opacity level from 0 to 1 (null mean inherited from parent) + * @prop {Number} [rotation=0] - Rotation ratio from 0 to 1 (clockwise) * @prop {Position} [rotationAnchor=new Position(0, 0)] - Center of rotation relative to this position - * @prop {Number} [zIndex=0] - + * @prop {Number} [zIndex=1] - Depth ordering */ /** * @return {ContainerOptions} @@ -247,6 +252,7 @@ export default class Container extends EventEmitter { static get defaultOptions () { return { shown: true, + opacity: null, rotation: 0, rotationAnchor: new Position(), zIndex: 1, diff --git a/modules/scene/scene.js b/modules/scene/scene.js index <HASH>..<HASH> 100644 --- a/modules/scene/scene.js +++ b/modules/scene/scene.js @@ -235,6 +235,7 @@ export default class Scene extends Container { static get defaultOptions () { return Object.assign(super.defaultOptions, { fill: null, + opacity: 1, cursor: Component.cursors.defaultOptions, }); }
Make opacity inherit from parent
pencil-js_pencil.js
train
2a4ef098d65939d436e2a5efbb518fb807b6b1b6
diff --git a/examples/run_squad.py b/examples/run_squad.py index <HASH>..<HASH> 100644 --- a/examples/run_squad.py +++ b/examples/run_squad.py @@ -44,7 +44,9 @@ from transformers import (WEIGHTS_NAME, BertConfig, XLNetForQuestionAnswering, XLNetTokenizer, DistilBertConfig, DistilBertForQuestionAnswering, DistilBertTokenizer, - AlbertConfig, AlbertForQuestionAnswering, AlbertTokenizer) + AlbertConfig, AlbertForQuestionAnswering, AlbertTokenizer, + XLMConfig, XLMForQuestionAnswering, XLMTokenizer, + ) from transformers import AdamW, get_linear_schedule_with_warmup, squad_convert_examples_to_features @@ -58,7 +60,8 @@ MODEL_CLASSES = { 'xlnet': (XLNetConfig, XLNetForQuestionAnswering, XLNetTokenizer), 'xlm': (XLMConfig, XLMForQuestionAnswering, XLMTokenizer), 'distilbert': (DistilBertConfig, DistilBertForQuestionAnswering, DistilBertTokenizer), - 'albert': (AlbertConfig, AlbertForQuestionAnswering, AlbertTokenizer) + 'albert': (AlbertConfig, AlbertForQuestionAnswering, AlbertTokenizer), + 'xlm': (XLMConfig, XLMForQuestionAnswering, XLMTokenizer) } def set_seed(args):
Add ALBERT and XLM to SQuAD script
huggingface_pytorch-pretrained-BERT
train
22312fd8d4e6d086d82e28ffcfcccf5993fc7cd1
diff --git a/lib/puppet/provider/nameservice.rb b/lib/puppet/provider/nameservice.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/provider/nameservice.rb +++ b/lib/puppet/provider/nameservice.rb @@ -261,7 +261,12 @@ class Puppet::Provider::NameService < Puppet::Provider # reading of the file. Puppet::Etc.endgrent - groups.join(",") + uniq_groups = groups.uniq + if groups != uniq_groups + debug("Removing any duplicate group entries") + end + # remove any double listed groups + uniq_groups.join(",") end # Convert the Etc struct into a hash.
(PUP-<I>) Remove duplicate entries when listing user resource's groups With some configurations of nsswitch, groups end up double listed. We now remove the duplicate entries since there isn't much we can do to disambiguate things to show where the entries came from by the time we get the information.
puppetlabs_puppet
train
781c5bf6967473701e4812d72ace4f675f5b5c94
diff --git a/airflow/models.py b/airflow/models.py index <HASH>..<HASH> 100755 --- a/airflow/models.py +++ b/airflow/models.py @@ -2286,8 +2286,8 @@ class BaseOperator(LoggingMixin): self.task_concurrency = task_concurrency # Private attributes - self._upstream_task_ids = [] - self._downstream_task_ids = [] + self._upstream_task_ids = set() + self._downstream_task_ids = set() if not dag and _CONTEXT_MANAGER_DAG: dag = _CONTEXT_MANAGER_DAG @@ -2771,13 +2771,13 @@ class BaseOperator(LoggingMixin): def task_type(self): return self.__class__.__name__ - def append_only_new(self, l, item): - if any([item is t for t in l]): + def add_only_new(self, item_set, item): + if item in item_set: raise AirflowException( 'Dependency {self}, {item} already registered' ''.format(**locals())) else: - l.append(item) + item_set.add(item) def _set_relatives(self, task_or_task_list, upstream=False): try: @@ -2793,7 +2793,7 @@ class BaseOperator(LoggingMixin): # relationships can only be set if the tasks share a single DAG. Tasks # without a DAG are assigned to that DAG. - dags = {t._dag.dag_id: t.dag for t in [self] + task_list if t.has_dag()} + dags = {t._dag.dag_id: t._dag for t in [self] + task_list if t.has_dag()} if len(dags) > 1: raise AirflowException( @@ -2814,13 +2814,11 @@ class BaseOperator(LoggingMixin): if dag and not task.has_dag(): task.dag = dag if upstream: - task.append_only_new(task._downstream_task_ids, self.task_id) - self.append_only_new(self._upstream_task_ids, task.task_id) + task.add_only_new(task._downstream_task_ids, self.task_id) + self.add_only_new(self._upstream_task_ids, task.task_id) else: - self.append_only_new(self._downstream_task_ids, task.task_id) - task.append_only_new(task._upstream_task_ids, self.task_id) - - self.detect_downstream_cycle() + self.add_only_new(self._downstream_task_ids, task.task_id) + task.add_only_new(task._upstream_task_ids, self.task_id) def set_downstream(self, task_or_task_list): """ @@ -3729,10 +3727,9 @@ class DAG(BaseDag, LoggingMixin): for t in dag.tasks: # Removing upstream/downstream references to tasks that did not # made the cut - t._upstream_task_ids = [ - tid for tid in t._upstream_task_ids if tid in dag.task_ids] - t._downstream_task_ids = [ - tid for tid in t._downstream_task_ids if tid in dag.task_ids] + t._upstream_task_ids = t._upstream_task_ids.intersection(dag.task_dict.keys()) + t._downstream_task_ids = t._downstream_task_ids.intersection( + dag.task_dict.keys()) if len(dag.tasks) < len(self.tasks): dag.partial = True diff --git a/tests/ti_deps/deps/test_trigger_rule_dep.py b/tests/ti_deps/deps/test_trigger_rule_dep.py index <HASH>..<HASH> 100644 --- a/tests/ti_deps/deps/test_trigger_rule_dep.py +++ b/tests/ti_deps/deps/test_trigger_rule_dep.py @@ -28,7 +28,7 @@ class TriggerRuleDepTest(unittest.TestCase): task = BaseOperator(task_id='test_task', trigger_rule=trigger_rule, start_date=datetime(2015, 1, 1)) if upstream_task_ids: - task._upstream_task_ids.extend(upstream_task_ids) + task._upstream_task_ids.update(upstream_task_ids) return TaskInstance(task=task, state=state, execution_date=None) def test_no_upstream_tasks(self):
[AIRFLOW-<I>] Store task ids as sets not lists Massively improve performance by using sets to represent a task's upstream and downstream task ids.
apache_airflow
train
d97a5043948b5d58d6f7068f74ebf906f7f5c6cc
diff --git a/IpInfoDb.php b/IpInfoDb.php index <HASH>..<HASH> 100644 --- a/IpInfoDb.php +++ b/IpInfoDb.php @@ -57,7 +57,7 @@ final class IpInfoDb extends AbstractHttpProvider implements Provider, IpAddress * * @throws \Geocoder\Exception\InvalidArgument */ - public function __construct(HttpClient $client, $apiKey, $precision = 'city') + public function __construct(HttpClient $client, string $apiKey, string $precision = 'city') { parent::__construct($client); @@ -128,7 +128,7 @@ final class IpInfoDb extends AbstractHttpProvider implements Provider, IpAddress * * @return Collection */ - private function executeQuery($url) + private function executeQuery(string $url): AddressCollection { $content = $this->getUrlContents($url); $data = json_decode($content, true); diff --git a/Tests/IpInfoDbTest.php b/Tests/IpInfoDbTest.php index <HASH>..<HASH> 100644 --- a/Tests/IpInfoDbTest.php +++ b/Tests/IpInfoDbTest.php @@ -41,15 +41,6 @@ class IpInfoDbTest extends BaseTestCase } /** - * @expectedException \Geocoder\Exception\InvalidCredentials - */ - public function testGetDataWithNullApiKey() - { - $provider = new IpInfoDb($this->getMockedHttpClient(), null); - $provider->geocodeQuery(GeocodeQuery::create('foo')); - } - - /** * @expectedException \Geocoder\Exception\UnsupportedOperation * @expectedExceptionMessage The IpInfoDb provider does not support street addresses, only IPv4 addresses. */
Added more PHP7 type hints. (#<I>) * Adding type hints * Added more type hints * Added PHP7 type hints * style fixes * Added type hints
geocoder-php_ip-info-db-provider
train
14bc62281894c90102e8a8a714b485e606c6a6f6
diff --git a/lib/emir/recipes/bias_image.py b/lib/emir/recipes/bias_image.py index <HASH>..<HASH> 100644 --- a/lib/emir/recipes/bias_image.py +++ b/lib/emir/recipes/bias_image.py @@ -40,8 +40,6 @@ sigma-clipping algorithm. ''' -from __future__ import with_statement - __version__ = "$Revision$" @@ -53,7 +51,6 @@ from emir.recipes import pipeline_parameters from emir.instrument.headers import EmirImage from numina.recipes import RecipeBase, RecipeResult from numina.recipes import ParametersDescription, systemwide_parameters -from numina.image.storage import FITSCreator from numina.image.combine import mean import numina.qa as qa @@ -136,8 +133,11 @@ if __name__ == '__main__': os.chdir('/home/inferis/spr/IR/apr21') - with open('config.txt', 'w+') as f: + f = open('config.txt', 'w+') + try: json.dump(p, f, default=to_json, encoding='utf-8',indent=2) + finally: + f.close() # main(['--list']) main(['-d', '--run', 'bias_image','config.txt']) diff --git a/lib/emir/recipes/simulate_image.py b/lib/emir/recipes/simulate_image.py index <HASH>..<HASH> 100644 --- a/lib/emir/recipes/simulate_image.py +++ b/lib/emir/recipes/simulate_image.py @@ -29,9 +29,8 @@ import numpy from numina.recipes import RecipeBase from numina.simulation import RunCounter -from numina.image.storage import FITSCreator from emir.instrument.detector import EmirDetector -from emir.instrument.headers import default_fits_headers +from emir.instrument.headers import EmirImage from dark_image import Result @@ -93,7 +92,7 @@ class Recipe(RecipeBase): self.detector.exposure(readout_opt['exposure']) _logger.info('FITS builder created') - self.creator = FITSCreator(default_fits_headers) + self.creator = EmirImage() _logger.info('Run counter created') self.runcounter = RunCounter("r%05d")
Renamed FITSCreator
guaix-ucm_pyemir
train
f51153c11b25e12075e2f7377f202d6edd5229ac
diff --git a/impl/src/main/java/org/jboss/weld/interceptor/reader/ClassMetadataInterceptorFactory.java b/impl/src/main/java/org/jboss/weld/interceptor/reader/ClassMetadataInterceptorFactory.java index <HASH>..<HASH> 100644 --- a/impl/src/main/java/org/jboss/weld/interceptor/reader/ClassMetadataInterceptorFactory.java +++ b/impl/src/main/java/org/jboss/weld/interceptor/reader/ClassMetadataInterceptorFactory.java @@ -17,20 +17,19 @@ package org.jboss.weld.interceptor.reader; -import static org.jboss.weld.logging.messages.UtilMessage.UNABLE_TO_FIND_CONSTRUCTOR; - -import java.lang.reflect.Constructor; - import javax.enterprise.context.spi.CreationalContext; -import javax.enterprise.inject.CreationException; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.InjectionTarget; +import javax.enterprise.inject.spi.Interceptor; +import javax.interceptor.Interceptors; -import org.jboss.weld.exceptions.DefinitionException; +import org.jboss.weld.annotated.enhanced.EnhancedAnnotatedType; +import org.jboss.weld.injection.producer.BasicInjectionTarget; +import org.jboss.weld.injection.producer.LifecycleCallbackInvoker; +import org.jboss.weld.injection.producer.NoopLifecycleCallbackInvoker; import org.jboss.weld.interceptor.spi.metadata.ClassMetadata; import org.jboss.weld.interceptor.spi.metadata.InterceptorFactory; import org.jboss.weld.manager.BeanManagerImpl; -import org.jboss.weld.util.reflection.SecureReflections; public class ClassMetadataInterceptorFactory<T> implements InterceptorFactory<T> { @@ -40,16 +39,10 @@ public class ClassMetadataInterceptorFactory<T> implements InterceptorFactory<T> private final ClassMetadata<T> classMetadata; private final InjectionTarget<T> injectionTarget; - private final Constructor<T> constructor; private ClassMetadataInterceptorFactory(ClassMetadata<T> classMetadata, BeanManagerImpl manager) { this.classMetadata = classMetadata; - this.injectionTarget = manager.createInjectionTarget(manager.createAnnotatedType(classMetadata.getJavaClass())); - try { - this.constructor = SecureReflections.ensureAccessible(SecureReflections.getDeclaredConstructor(classMetadata.getJavaClass())); - } catch (NoSuchMethodException e) { - throw new DefinitionException(UNABLE_TO_FIND_CONSTRUCTOR, e); - } + this.injectionTarget = new InterceptorInjectionTarget<T>(manager.createEnhancedAnnotatedType(classMetadata.getJavaClass()), manager); } @Override @@ -58,13 +51,9 @@ public class ClassMetadataInterceptorFactory<T> implements InterceptorFactory<T> } public T create(CreationalContext<T> ctx, BeanManager manager) { - try { - T instance = constructor.newInstance(); // TODO: use special InjectionTarget (that does not apply interceptors) to instantiate the class - injectionTarget.inject(instance, ctx); - return instance; - } catch (Exception e) { - throw new CreationException(e); - } + T instance = injectionTarget.produce(ctx); + injectionTarget.inject(instance, ctx); + return instance; } @Override @@ -88,4 +77,24 @@ public class ClassMetadataInterceptorFactory<T> implements InterceptorFactory<T> public String toString() { return "ClassMetadataInterceptorFactory [class=" + classMetadata.getJavaClass().getName() + "]"; } + + /** + * {@link InjectionTarget} for interceptors which do not have associated {@link Interceptor}. These interceptors are a + * result of using {@link Interceptors} annotation directly on the target class. + * + * @author Jozef Hartinger + * + * @param <T> + */ + private static class InterceptorInjectionTarget<T> extends BasicInjectionTarget<T> { + + public InterceptorInjectionTarget(EnhancedAnnotatedType<T> type, BeanManagerImpl beanManager) { + super(type, null, beanManager); + } + + @Override + protected LifecycleCallbackInvoker<T> initInvoker(EnhancedAnnotatedType<T> type) { + return NoopLifecycleCallbackInvoker.getInstance(); + } + } }
Use InjectionTarget for creating interceptor instances in ClassMetadataInterceptorFactory
weld_core
train
a85d6a19fc82ea86f137483a773aa0f1a0e15366
diff --git a/packages/ember-htmlbars/lib/node-managers/component-node-manager.js b/packages/ember-htmlbars/lib/node-managers/component-node-manager.js index <HASH>..<HASH> 100644 --- a/packages/ember-htmlbars/lib/node-managers/component-node-manager.js +++ b/packages/ember-htmlbars/lib/node-managers/component-node-manager.js @@ -87,7 +87,6 @@ function configureCreateOptions(attrs, createOptions) { // they are still streams. if (attrs.id) { createOptions.elementId = getValue(attrs.id); } if (attrs._defaultTagName) { createOptions._defaultTagName = getValue(attrs._defaultTagName); } - if (attrs.viewName) { createOptions.viewName = getValue(attrs.viewName); } } ComponentNodeManager.prototype.render = function ComponentNodeManager_render(_env, visitor) { diff --git a/packages/ember-htmlbars/lib/node-managers/view-node-manager.js b/packages/ember-htmlbars/lib/node-managers/view-node-manager.js index <HASH>..<HASH> 100644 --- a/packages/ember-htmlbars/lib/node-managers/view-node-manager.js +++ b/packages/ember-htmlbars/lib/node-managers/view-node-manager.js @@ -43,7 +43,6 @@ ViewNodeManager.create = function ViewNodeManager_create(renderNode, env, attrs, if (attrs && attrs.id) { options.elementId = getValue(attrs.id); } if (attrs && attrs.tagName) { options.tagName = getValue(attrs.tagName); } if (attrs && attrs._defaultTagName) { options._defaultTagName = getValue(attrs._defaultTagName); } - if (attrs && attrs.viewName) { options.viewName = getValue(attrs.viewName); } if (found.component.create && contentScope) { let _self = contentScope.getSelf(); @@ -211,10 +210,6 @@ export function createOrUpdateComponent(component, options, createOptions, rende if (options.parentView) { options.parentView.appendChild(component); - - if (options.viewName) { - set(options.parentView, options.viewName, component); - } } component._renderNode = renderNode; diff --git a/packages/ember-views/lib/mixins/view_support.js b/packages/ember-views/lib/mixins/view_support.js index <HASH>..<HASH> 100644 --- a/packages/ember-views/lib/mixins/view_support.js +++ b/packages/ember-views/lib/mixins/view_support.js @@ -585,17 +585,8 @@ export default Mixin.create({ @private */ destroy() { - // get parentView before calling super because it'll be destroyed - let parentView = this.parentView; - let viewName = this.viewName; - if (!this._super(...arguments)) { return; } - // remove from non-virtual parent view if viewName was specified - if (viewName && parentView) { - parentView.set(viewName, null); - } - // Destroy HTMLbars template if (this.lastResult) { this.lastResult.destroy();
Remove legacy addon `viewName` support.
emberjs_ember.js
train
7464b159711bd982b80acf120cd42e8809ce0d2f
diff --git a/cli/src/main/java/org/jboss/as/cli/gui/metacommand/DownloadServerLogDialog.java b/cli/src/main/java/org/jboss/as/cli/gui/metacommand/DownloadServerLogDialog.java index <HASH>..<HASH> 100644 --- a/cli/src/main/java/org/jboss/as/cli/gui/metacommand/DownloadServerLogDialog.java +++ b/cli/src/main/java/org/jboss/as/cli/gui/metacommand/DownloadServerLogDialog.java @@ -20,6 +20,7 @@ package org.jboss.as.cli.gui.metacommand; import java.awt.BorderLayout; import java.awt.Container; +import java.awt.Desktop; import java.awt.Dialog; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -37,6 +38,7 @@ import java.io.PrintStream; import java.util.List; import javax.swing.Box; import javax.swing.JButton; +import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; @@ -56,14 +58,19 @@ import org.jboss.dmr.ModelNode; * @author Stan Silvert [email protected] (C) 2014 Red Hat Inc. */ public class DownloadServerLogDialog extends JDialog implements ActionListener, PropertyChangeListener { - // make this static so that it always retains the last directory chosen + // make these static so that they always retains the last value chosen private static JFileChooser fileChooser = new JFileChooser(new File(".")); + private static JCheckBox viewInLogViewer = new JCheckBox("View in default log viewer"); + static { + viewInLogViewer.setSelected(true); + } private CliGuiContext cliGuiCtx; private String fileName; private Long fileSize; private JPanel inputPanel = new JPanel(new GridBagLayout()); private JTextField pathField = new JTextField(40); + private ProgressMonitor progressMonitor; private DownloadLogTask downloadTask; @@ -72,6 +79,7 @@ public class DownloadServerLogDialog extends JDialog implements ActionListener, this.cliGuiCtx = cliGuiCtx; this.fileName = fileName; this.fileSize = fileSize; + fileChooser.setSelectedFile(new File(fileChooser.getCurrentDirectory(), fileName)); setPathField(); @@ -120,6 +128,15 @@ public class DownloadServerLogDialog extends JDialog implements ActionListener, gbConst.gridwidth = GridBagConstraints.REMAINDER; inputPanel.add(browse, gbConst); + if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) { + JLabel emptyLabel = new JLabel(""); + gbConst.gridwidth = 1; + inputPanel.add(emptyLabel, gbConst); + addStrut(); + gbConst.gridwidth = GridBagConstraints.REMAINDER; + inputPanel.add(viewInLogViewer, gbConst); + } + return inputPanel; } @@ -174,6 +191,7 @@ public class DownloadServerLogDialog extends JDialog implements ActionListener, downloadTask.execute(); } + @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())){ int percentRead = (Integer) evt.getNewValue(); @@ -250,8 +268,23 @@ public class DownloadServerLogDialog extends JDialog implements ActionListener, String message = "Download " + fileName + " "; if (isCancelled()) { JOptionPane.showMessageDialog(cliGuiCtx.getMainWindow(), message + "cancelled.", message + "cancelled.", JOptionPane.ERROR_MESSAGE); - } else { + return; + } + + if (!viewInLogViewer.isSelected()) { JOptionPane.showMessageDialog(cliGuiCtx.getMainWindow(), message + "complete."); + return; + } + + try { + Desktop.getDesktop().open(selectedFile); + } catch (IOException ioe) { + // try to open in file manager for destination directory + try { + Desktop.getDesktop().open(fileChooser.getCurrentDirectory()); + } catch (IOException ioe2) { + JOptionPane.showMessageDialog(cliGuiCtx.getMainWindow(), "Download success. No registered application to view " + fileName, "Can't view file.", JOptionPane.ERROR_MESSAGE); + } } } }
After download, view in default log viewer.
wildfly_wildfly
train
596af4075fe1fb4c051e9f60ef7ef7308f05f4c3
diff --git a/tftpy/TftpClient.py b/tftpy/TftpClient.py index <HASH>..<HASH> 100644 --- a/tftpy/TftpClient.py +++ b/tftpy/TftpClient.py @@ -202,15 +202,18 @@ class TftpClient(TftpSession): # end while + outputfile.close() end_time = time.time() duration = end_time - start_time - outputfile.close() - logger.info('') - logger.info("Downloaded %d bytes in %d seconds" % (bytes, duration)) - bps = (bytes * 8.0) / duration - kbps = bps / 1024.0 - logger.info("Average rate: %.2f kbps" % kbps) + if duration == 0: + logger.info("Duration too short, rate undetermined") + else: + logger.info('') + logger.info("Downloaded %d bytes in %d seconds" % (bytes, duration)) + bps = (bytes * 8.0) / duration + kbps = bps / 1024.0 + logger.info("Average rate: %.2f kbps" % kbps) dupcount = 0 for key in dups: dupcount += dups[key]
Fixed division by zero error in rate calculations in download function of client. Thanks to Stefaan Vanheesbeke for the report. git-svn-id: <URL>
msoulier_tftpy
train
b86afb133500f164587f09b48b5f145b77905b77
diff --git a/nodeconductor/structure/serializers.py b/nodeconductor/structure/serializers.py index <HASH>..<HASH> 100644 --- a/nodeconductor/structure/serializers.py +++ b/nodeconductor/structure/serializers.py @@ -350,7 +350,7 @@ class NestedProjectPermissionSerializer(serializers.ModelSerializer): class Meta: model = models.ProjectPermission - fields = ['url', 'uuid', 'name', 'role', 'permission'] + fields = ['url', 'uuid', 'name', 'role', 'permission', 'expiration_time'] class CustomerUserSerializer(serializers.ModelSerializer):
Expose expiration time in nested project permission serializer.
opennode_waldur-core
train
5375817b392b6276bbe0f38c15dd555da5d5ebf2
diff --git a/manual/pages/tiles.html b/manual/pages/tiles.html index <HASH>..<HASH> 100644 --- a/manual/pages/tiles.html +++ b/manual/pages/tiles.html @@ -99,4 +99,37 @@ tileSet.onload = function() { display.draw(1, 1, "#", "white"); display.draw(2, 1, "#", "transparent", "rgba(250, 250, 0, 0.5)"); } -</div> \ No newline at end of file +</div> + +<h2>Colorized tile stacks</h2> + +<p>You can apply colorization to multiple tiles as well. Just make sure you pass foreground/background colors as arrays. + +<div class="example"> +var tileSet = document.createElement("img"); +tileSet.src = "tiles.png"; + +var options = { + layout: "tile", + bg: "transparent", + tileWidth: 64, + tileHeight: 64, + tileSet: tileSet, + tileColorize: true, + tileMap: { + "@": [0, 0], + "#": [0, 64] + }, + width: 1, + height: 1 +} +var display = new ROT.Display(options); +SHOW(display.getContainer()); + +tileSet.onload = function() { + var ch = ["#", "@"]; + var fg = ["rgba(255, 0, 0, 0.5)", "rgba(0, 0, 255, 0.5)"]; + var bg = ["transparent", "transparent"]; + display.draw(0, 0, ch, fg, bg); +} +</div> diff --git a/rot.js b/rot.js index <HASH>..<HASH> 100644 --- a/rot.js +++ b/rot.js @@ -1,6 +1,6 @@ /* This is rot.js, the ROguelike Toolkit in JavaScript. - Version 0.7~dev, generated on Tue Dec 12 13:31:09 CET 2017. + Version 0.7~dev, generated on Thu May 17 14:29:02 CEST 2018. */ (function (root, factory) { if (typeof define === 'function' && define.amd) { @@ -1320,6 +1320,9 @@ ROT.Display.Tile.prototype.draw = function(data, clearBefore) { if (!ch) { return; } var chars = [].concat(ch); + var fgs = [].concat(fg); + var bgs = [].concat(bg); + for (var i=0;i<chars.length;i++) { var tile = this._options.tileMap[chars[i]]; if (!tile) { throw new Error("Char '" + chars[i] + "' not found in tileMap"); } @@ -1327,8 +1330,12 @@ ROT.Display.Tile.prototype.draw = function(data, clearBefore) { if (this._options.tileColorize) { /* apply colorization */ var canvas = this._colorCanvas; var context = canvas.getContext("2d"); + context.globalCompositeOperation = "source-over"; context.clearRect(0, 0, tileWidth, tileHeight); + var fg = fgs[i]; + var bg = bgs[i]; + context.drawImage( this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, @@ -1348,7 +1355,6 @@ ROT.Display.Tile.prototype.draw = function(data, clearBefore) { } this._context.drawImage(canvas, x*tileWidth, y*tileHeight, tileWidth, tileHeight); - } else { /* no colorizing, easy */ this._context.drawImage( this._options.tileSet, diff --git a/src/display/tile.js b/src/display/tile.js index <HASH>..<HASH> 100644 --- a/src/display/tile.js +++ b/src/display/tile.js @@ -40,6 +40,9 @@ ROT.Display.Tile.prototype.draw = function(data, clearBefore) { if (!ch) { return; } var chars = [].concat(ch); + var fgs = [].concat(fg); + var bgs = [].concat(bg); + for (var i=0;i<chars.length;i++) { var tile = this._options.tileMap[chars[i]]; if (!tile) { throw new Error("Char '" + chars[i] + "' not found in tileMap"); } @@ -47,8 +50,12 @@ ROT.Display.Tile.prototype.draw = function(data, clearBefore) { if (this._options.tileColorize) { /* apply colorization */ var canvas = this._colorCanvas; var context = canvas.getContext("2d"); + context.globalCompositeOperation = "source-over"; context.clearRect(0, 0, tileWidth, tileHeight); + var fg = fgs[i]; + var bg = bgs[i]; + context.drawImage( this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, @@ -68,7 +75,6 @@ ROT.Display.Tile.prototype.draw = function(data, clearBefore) { } this._context.drawImage(canvas, x*tileWidth, y*tileHeight, tileWidth, tileHeight); - } else { /* no colorizing, easy */ this._context.drawImage( this._options.tileSet,
colorized tile stacks, fixes #<I>
ondras_rot.js
train
36550f71f4161b0b5c7af872b78dd1e7d96b788a
diff --git a/scripts/patches/dynamodb.py b/scripts/patches/dynamodb.py index <HASH>..<HASH> 100644 --- a/scripts/patches/dynamodb.py +++ b/scripts/patches/dynamodb.py @@ -21,4 +21,15 @@ patches = [ "path": "/ResourceTypes/AWS::DynamoDB::GlobalTable/Properties/SSESpecification/Type", "value": "GlobalTableSSESpecification", }, + # Fix issue in spec 82.0.0 that changed Type to Json + { + "op": "replace", + "path": "/ResourceTypes/AWS::DynamoDB::Table/Properties/KeySchema/Type", + "value": "List", + }, + { + "op": "add", + "path": "/ResourceTypes/AWS::DynamoDB::Table/Properties/KeySchema/ItemType", + "value": "KeySchema", + }, ]
Fix issue in spec <I> with DynamoDB KeySchema Type
cloudtools_troposphere
train
b0f2d5efeeb70387f1fa892afd0411675fcc6ee2
diff --git a/tests/Behat/Mink/Driver/JavascriptDriverTest.php b/tests/Behat/Mink/Driver/JavascriptDriverTest.php index <HASH>..<HASH> 100644 --- a/tests/Behat/Mink/Driver/JavascriptDriverTest.php +++ b/tests/Behat/Mink/Driver/JavascriptDriverTest.php @@ -99,7 +99,7 @@ abstract class JavascriptDriverTest extends GeneralDriverTest { $this->getSession()->visit($this->pathTo('/js_test.php')); - $found = $this->getSession()->wait(5000, '$("#draggable:visible").length == 1'); + $found = $this->getSession()->wait(5000, '$("#draggable").length == 1'); $this->assertTrue($found); }
The `testWaitReturnValue` test was checking element visibility, which failed for Headless drivers
minkphp_Mink
train
6cc208cdbb8d01b5f8feec220bf52c162c5ecbc3
diff --git a/lib/core_extensions.rb b/lib/core_extensions.rb index <HASH>..<HASH> 100644 --- a/lib/core_extensions.rb +++ b/lib/core_extensions.rb @@ -320,7 +320,7 @@ class Hash elsif value.is_a?(Hash) stack << [key,value] else - param << "#{key}=#{URI.encode(value.to_s)}&" + param << "#{key}=#{URI.encode(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}&" end stack.each do |parent, hash|
Made encoding on query parameters treat everything except URI::PATTERN::UNRESERVED as UNSAFE to force encoding of '+' character
jnunemaker_httparty
train
9d984b72fcb4a75200a2743c716e5fa939560a64
diff --git a/lib/client/client.js b/lib/client/client.js index <HASH>..<HASH> 100644 --- a/lib/client/client.js +++ b/lib/client/client.js @@ -703,12 +703,12 @@ Client.prototype._connect = function _connect() { var socket = null; var timer = false; - socket = proto.connect((this.port || this.socketPath), this.host); - - socket.once('connect', function onConnect() { - if (timer) + function onConnect() { + if (timer) clearTimeout(timer); + socket.removeListener('connect', onConnect); + socket.removeListener('secureConnect', onConnect); assert.ok(socket.ldap); socket.ldap.id = nextClientId() + '__' + socket.ldap.id; @@ -718,8 +718,12 @@ Client.prototype._connect = function _connect() { self.socket = socket; self.emit('connect', socket); - }); + } + + socket = proto.connect((this.port || this.socketPath), this.host); + socket.once('connect', onConnect); + socket.once('secureConnect', onConnect); setupSocket(socket, this); if (this.connectTimeout) { diff --git a/lib/client/pool.js b/lib/client/pool.js index <HASH>..<HASH> 100644 --- a/lib/client/pool.js +++ b/lib/client/pool.js @@ -76,11 +76,13 @@ function createPool(options) { return callback(err); res.on('error', function (e) { - return callback(e); + removeAllListeners('end'); + callback(e); }); - return res.on('end', function () { - return callback(null); + res.on('end', function () { + removeAllListeners('error'); + callback(null); }); }); }, diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "name": "ldapjs", "homepage": "http://ldapjs.org", "description": "LDAP client and server APIs", - "version": "0.5.2", + "version": "0.5.3", "repository": { "type": "git", "url": "git://github.com/mcavage/node-ldapjs.git"
<I> broke pooled SSL
joyent_node-ldapjs
train
4479b7d3f287fa3c553fddd6200d942a5be8ab57
diff --git a/derpibooru/image.py b/derpibooru/image.py index <HASH>..<HASH> 100644 --- a/derpibooru/image.py +++ b/derpibooru/image.py @@ -45,6 +45,11 @@ class Image(object): if not hasattr(self, field): setattr(self, field, body) + if self.original_format == "gif": + setattr(self, "webm", self.representations["webm"]) + setattr(self, "mp4", self.representations["mp4"]) + + def __str__(self): return "Image({0})".format(self.id_number)
Add mp4 and webm file representations for gifs
joshua-stone_DerPyBooru
train
aab205f23550ea4752910a472fa7685e6db62b74
diff --git a/securesystemslib/keys.py b/securesystemslib/keys.py index <HASH>..<HASH> 100755 --- a/securesystemslib/keys.py +++ b/securesystemslib/keys.py @@ -1699,7 +1699,7 @@ def create_rsa_encrypted_pem(private_key, passphrase): elif _RSA_CRYPTO_LIBRARY == 'pyca-cryptography': encrypted_pem = \ - securesystemslib.pycrypto_keys.create_rsa_encrypted_pem(private_key, passphrase) + securesystemslib.pyca_crypto_keys.create_rsa_encrypted_pem(private_key, passphrase) # check_crypto_libraries() should have fully verified _RSA_CRYPTO_LIBRARY. else: # pragma: no cover
Call pyca_crypto_keys if the pyca-cryptography library is set
secure-systems-lab_securesystemslib
train
5fbea3b4d15aa903f6b3598e3cf80c0f79af5518
diff --git a/cmd.js b/cmd.js index <HASH>..<HASH> 100755 --- a/cmd.js +++ b/cmd.js @@ -12,6 +12,15 @@ var numeral = require('numeral') var path = require('path') var WebTorrent = require('../') +process.on('exit', function (code) { + if (code !== 0) { + clivas.line('{red:ERROR:} If you think this is a bug in webtorrent, report it!') + console.log('=====> <=====') + console.log('=====> https://github.com/feross/webtorrent/issues <=====') + console.log('=====> <=====') + } +}) + var argv = minimist(process.argv.slice(2), { alias: { p: 'port', @@ -58,7 +67,7 @@ if (argv.help || !torrentId) { Download the torrent, given as: - * magnet uri (string) + * magnet uri * http/https url to .torrent file * filesystem path to .torrent file * info hash (as hex string)
on crash, ask user to report bug
webtorrent_webtorrent-cli
train
2828bc945fd0bf9f95475b5948a63642546698f4
diff --git a/src/autoStart/index.js b/src/autoStart/index.js index <HASH>..<HASH> 100644 --- a/src/autoStart/index.js +++ b/src/autoStart/index.js @@ -17,7 +17,7 @@ const autoStart = { maxInteractions: Infinity, perActionDefaults: { manualStart: false, - max: 0, + max: Infinity, maxPerElement: 1, }, setActionDefaults: function (action) { @@ -367,6 +367,9 @@ function withinInteractionLimit (interactable, element, action) { let targetCount = 0; let targetElementCount = 0; + // no actions if any of these values == 0 + if (!(maxActions && maxPerElement && autoStart.maxInteractions)) { return; } + for (let i = 0, len = scope.interactions.length; i < len; i++) { const interaction = scope.interactions[i]; const otherAction = interaction.prepared.name; diff --git a/src/inertia.js b/src/inertia.js index <HASH>..<HASH> 100644 --- a/src/inertia.js +++ b/src/inertia.js @@ -75,7 +75,7 @@ Interaction.signals.on('down', function ({ interaction, event, pointer, eventTar } }); -Interaction.signals.on('up', function ({ interaction, event }) { +Interaction.signals.on('up', function ({ interaction, pointer, event }) { const status = interaction.inertiaStatus; if (!interaction.interacting() || status.active) { return; } @@ -159,6 +159,8 @@ Interaction.signals.on('up', function ({ interaction, event }) { status.i = animationFrame.request(interaction.boundSmoothEndFrame); } + + interaction.removePointer(pointer); }); Interaction.signals.on('stop-active', function ({ interaction }) { diff --git a/src/utils/interactionFinder.js b/src/utils/interactionFinder.js index <HASH>..<HASH> 100644 --- a/src/utils/interactionFinder.js +++ b/src/utils/interactionFinder.js @@ -46,7 +46,7 @@ const finder = { }, // if it's a mouse interaction - mouse: function ({ mouseEvent, eventType }) { + mouse: function ({ pointerId, mouseEvent, eventType }) { if (!mouseEvent && (browser.supportsTouch || browser.supportsPointerEvent)) { return null; } @@ -56,7 +56,7 @@ const finder = { for (const interaction of scope.interactions) { if (interaction.mouse) { // if it's a down event, skip interactions with running simulations - if (/down/i.test(eventType) && interaction.simulation) { continue; } + if (interaction.simulation && !utils.contains(interaction.pointerIds, pointerId)) { continue; } // if the interaction is active, return it immediately if (interaction.interacting()) {
*: fix issues with multiple pointers and inertia - remove pointer when starting inertia - set default autoStart action max to Infinity - adjust interactionFinder.mouse to handle mouse interactions with simulations better Re: #<I>
taye_interact.js
train
77d89bbd6a338b24a4356aa9ffb5e2fb1a9703e5
diff --git a/app/controllers/confirmations_controller.rb b/app/controllers/confirmations_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/confirmations_controller.rb +++ b/app/controllers/confirmations_controller.rb @@ -34,7 +34,7 @@ module Milia def change_or_confirm_user(tryset=nil) with_unconfirmed_confirmable do # if @confirmable.has_no_password? # milea creates a dummy password when accounts are created - @confirmable.attempt_set_password(user_params) + @confirmable.attempt_set_password(user_params) if tryset if ( @confirmable.skip_confirm_change_password || @confirmable.valid? ) do_confirm # user has a password; use it to sign in else
invite member - <I>
jekuno_milia
train
2b462c8062e4102e102ee7a82dcc4ad7bdbe1d8d
diff --git a/spec/factories/socializer_audiences.rb b/spec/factories/socializer_audiences.rb index <HASH>..<HASH> 100644 --- a/spec/factories/socializer_audiences.rb +++ b/spec/factories/socializer_audiences.rb @@ -4,6 +4,6 @@ FactoryGirl.define do factory :socializer_audience, class: Socializer::Audience do privacy_level 1 activity_id 1 - activity_object_id 1 + association :activity_object, factory: :socializer_activity_object end end
use an association for the activity_object
socializer_socializer
train
06326918a5f2dd85744a54f98dacee41d072fe72
diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php index <HASH>..<HASH> 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php @@ -4,6 +4,8 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Tests\Models\ECommerce\ECommerceCart; use Doctrine\Tests\Models\ECommerce\ECommerceCustomer; +use Doctrine\ORM\Query; +use Doctrine\ORM\Query\AST; require_once __DIR__ . '/../../../TestInit.php'; @@ -18,7 +20,7 @@ class DDC736Test extends \Doctrine\Tests\OrmFunctionalTestCase /** * @group DDC-736 */ - public function testFetchJoinInitializesPreviouslyUninitializedCollectionOfManagedEntity() + public function testReorderEntityFetchJoinForHydration() { $cust = new ECommerceCustomer; $cust->setName('roman'); @@ -43,4 +45,56 @@ class DDC736Test extends \Doctrine\Tests\OrmFunctionalTestCase $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $cart2->getCustomer()); $this->assertEquals(array('name' => 'roman', 'payment' => 'cash'), $result); } + + /** + * @group DDC-736 + * @group DDC-925 + * @group DDC-915 + */ + public function testDqlTreeWalkerReordering() + { + $cust = new ECommerceCustomer; + $cust->setName('roman'); + + $cart = new ECommerceCart; + $cart->setPayment('cash'); + $cart->setCustomer($cust); + + $this->_em->persist($cust); + $this->_em->persist($cart); + $this->_em->flush(); + $this->_em->clear(); + + $dql = "select c, c.name, ca, ca.payment from Doctrine\Tests\Models\ECommerce\ECommerceCart ca join ca.customer c"; + $result = $this->_em->createQuery($dql) + ->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\Tests\ORM\Functional\Ticket\DisableFetchJoinTreeWalker')) + ->getResult(); + + /* @var $cart2 Doctrine\Tests\Models\ECommerce\ECommerceCart */ + $cart2 = $result[0][0]; + $this->assertType('Doctrine\ORM\Proxy\Proxy', $cart2->getCustomer()); + } } + +class DisableFetchJoinTreeWalker extends \Doctrine\ORM\Query\TreeWalkerAdapter +{ + public function walkSelectStatement(AST\SelectStatement $AST) + { + $this->walkSelectClause($AST->selectClause); + } + + /** + * @param \Doctrine\ORM\Query\AST\SelectClause $selectClause + */ + public function walkSelectClause($selectClause) + { + foreach ($selectClause->selectExpressions AS $key => $selectExpr) { + /* @var $selectExpr \Doctrine\ORM\Query\AST\SelectExpression */ + if ($selectExpr->expression == "c") { + unset($selectClause->selectExpressions[$key]); + break; + } + } + } +} +
DDC-<I>, DDC-<I> - Fix Identification Ordering in combination with Tree Walkers.
doctrine_orm
train
9dfd1eb2fcd2d341b7c69c308eb3e4980f99d8ab
diff --git a/tools/astCreatorPlugin/pom.xml b/tools/astCreatorPlugin/pom.xml index <HASH>..<HASH> 100644 --- a/tools/astCreatorPlugin/pom.xml +++ b/tools/astCreatorPlugin/pom.xml @@ -8,7 +8,7 @@ <groupId>org.overturetool.tools</groupId> <artifactId>astcreatorplugin</artifactId> <packaging>maven-plugin</packaging> - <version>1.0.2</version> + <version>1.0.3</version> <name>AST Creator Maven plug-in</name> <build> diff --git a/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/AstCreatorBaseMojo.java b/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/AstCreatorBaseMojo.java index <HASH>..<HASH> 100644 --- a/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/AstCreatorBaseMojo.java +++ b/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/AstCreatorBaseMojo.java @@ -10,7 +10,7 @@ import org.apache.maven.plugin.MojoFailureException; /** * Says "Hi" to the user. * - * @phase process-resources + * @phase generate-sources * @requiresDependencyResolution compile */ public abstract class AstCreatorBaseMojo extends AbstractMojo @@ -44,6 +44,13 @@ public abstract class AstCreatorBaseMojo extends AbstractMojo protected Boolean useSrcOutput; /** + * Name of the directory into which the astCreatorPlugin should dump the ast files. + * + * @parameter expression="${project.build.directory}/generated-sources/astCreator" + */ + protected File outputDirectory; + + /** * Enables generation of vDM source code corresponding to the Java generated tree. * * @parameter diff --git a/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/GenerateTree.java b/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/GenerateTree.java index <HASH>..<HASH> 100644 --- a/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/GenerateTree.java +++ b/tools/astCreatorPlugin/src/main/java/org/overture/tools/plugins/astcreator/GenerateTree.java @@ -13,8 +13,8 @@ import com.lausdahl.ast.creator.env.Environment; /** * Generate Tree * - * @goal astcreate - * @phase process-resources + * @goal generate + * @phase generate-sources * @requiresDependencyResolution compile */ public class GenerateTree extends AstCreatorBaseMojo @@ -23,6 +23,9 @@ public class GenerateTree extends AstCreatorBaseMojo @Override public void execute() throws MojoExecutionException, MojoFailureException { + // Let's make sure that maven knows to look in the output directory + project.addCompileSourceRoot(outputDirectory.getPath()); + File treeName = null; treeName = new File(getResourcesDir(), ast); @@ -85,7 +88,7 @@ public class GenerateTree extends AstCreatorBaseMojo } try { - Main.create(treeName, extendedAstFile, generated, "Interpreter", generateVdm()); + Main.create(treeName, extendedAstFile, generated, "Interpreter", generateVdm); } catch (Exception e) { getLog().error(e); @@ -97,21 +100,16 @@ public class GenerateTree extends AstCreatorBaseMojo + treeName.getAbsolutePath()); } - - } - - public boolean generateVdm() - { - return generateVdm!=null && generateVdm; } public File getGeneratedFolder() { - if (useSrcOutput!=null && useSrcOutput) - { - return getProjectJavaSrcDirectory(); - } - return new File(getProjectOutputDirectory(), "generate-sources"); + // if (useSrcOutput) + // { + // return getProjectJavaSrcDirectory(); + // } + //return new File(getProjectOutputDirectory(), "generated-sources/astCreator".replace('/', File.separatorChar)); + return outputDirectory; } public void generateSingleAst(File treeName, File toStringAstFile, @@ -119,7 +117,7 @@ public class GenerateTree extends AstCreatorBaseMojo { try { - env1 = Main.create(treeName.getAbsolutePath(), generated, true, generateVdm()); + env1 = Main.create(treeName.getAbsolutePath(), generated, true, generateVdm); setCrc(treeName); setCrc(toStringAstFile); } catch (Exception e)
recommit astCreatorPlugin changes from <I>ab<I>e
overturetool_overture
train
ec4c1ff19bc3c967f8c753b0dc40bd0d77aed8ec
diff --git a/core-bundle/src/Resources/contao/library/Contao/Widget.php b/core-bundle/src/Resources/contao/library/Contao/Widget.php index <HASH>..<HASH> 100644 --- a/core-bundle/src/Resources/contao/library/Contao/Widget.php +++ b/core-bundle/src/Resources/contao/library/Contao/Widget.php @@ -754,7 +754,7 @@ abstract class Widget extends \BaseTemplate { return $blnIsXhtml ? ' ' . $strKey . '="' . $varValue . '"' : ' ' . $strKey; } - elseif ($strKey == 'disabled' || $strKey == 'readonly' || $strKey == 'multiple') // see #4131 + else { return ' ' . $strKey; } diff --git a/core-bundle/src/Resources/contao/widgets/CheckBox.php b/core-bundle/src/Resources/contao/widgets/CheckBox.php index <HASH>..<HASH> 100644 --- a/core-bundle/src/Resources/contao/widgets/CheckBox.php +++ b/core-bundle/src/Resources/contao/widgets/CheckBox.php @@ -87,7 +87,7 @@ class CheckBox extends \Widget } // The "required" attribute only makes sense for single checkboxes - if (!$this->multiple && $this->mandatory) + if ($this->mandatory && !$this->multiple) { $this->arrAttributes['required'] = 'required'; } @@ -182,13 +182,15 @@ class CheckBox extends \Widget */ protected function generateCheckbox($arrOption, $i) { - return sprintf('<input type="checkbox" name="%s" id="opt_%s" class="tl_checkbox" value="%s"%s%s onfocus="Backend.getScrollOffset()"> <label for="opt_%s">%s</label>', + return sprintf('<input type="checkbox" name="%s" id="opt_%s" class="tl_checkbox" value="%s"%s%s onfocus="Backend.getScrollOffset()"> <label for="opt_%s">%s%s%s</label>', $this->strName . ($this->multiple ? '[]' : ''), $this->strId.'_'.$i, ($this->multiple ? specialchars($arrOption['value']) : 1), $this->isChecked($arrOption), $this->getAttributes(), $this->strId.'_'.$i, - $arrOption['label']); + ($this->mandatory && !$this->multiple ? '<span class="invisible">'.$GLOBALS['TL_LANG']['MSC']['mandatory'].' </span>' : ''), + $arrOption['label'], + ($this->mandatory && !$this->multiple ? '<span class="mandatory">*</span>' : '')); } }
[Core] Correctly render required single checkboxes in the back end (see #<I>).
contao_contao
train
f3183e78faea1231d9fc83679e2df4b406a4328d
diff --git a/txkoji/task.py b/txkoji/task.py index <HASH>..<HASH> 100644 --- a/txkoji/task.py +++ b/txkoji/task.py @@ -108,6 +108,8 @@ class Task(Munch): # the the past couple of tasks for this tag. defer.returnValue(None) avg_delta = yield self.connection.getAverageBuildDuration(package) + if avg_delta is None: + defer.returnValue(None) est_completion = self.started + avg_delta defer.returnValue(est_completion)
task: return None in estimate_completion() If we cannot estimate this task's package, return None instead of crashing.
ktdreyer_txkoji
train
84855d2587c8d9d06c173375b9a395e8b0bb2f3f
diff --git a/structr-rest/src/main/java/org/structr/rest/auth/AuthHelper.java b/structr-rest/src/main/java/org/structr/rest/auth/AuthHelper.java index <HASH>..<HASH> 100644 --- a/structr-rest/src/main/java/org/structr/rest/auth/AuthHelper.java +++ b/structr-rest/src/main/java/org/structr/rest/auth/AuthHelper.java @@ -29,7 +29,6 @@ import org.structr.common.error.FrameworkException; import org.structr.common.error.UnlicensedScriptException; import org.structr.common.event.RuntimeEventLog; import org.structr.core.app.App; -import org.structr.core.app.Query; import org.structr.core.app.StructrApp; import org.structr.core.auth.exception.*; import org.structr.core.entity.AbstractNode; @@ -50,7 +49,6 @@ import java.nio.charset.StandardCharsets; import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; -import java.time.Instant; import java.util.*; @@ -314,22 +312,24 @@ public class AuthHelper { final PropertyKey<String[]> key = StructrApp.key(Principal.class, "refreshTokens"); final String[] refreshTokens = user.getProperty(key); - try { + if (refreshTokens != null) { - for (final String refreshToken : refreshTokens) { + try { - if (refreshTokenTimedOut(refreshToken)) { + for (final String refreshToken : refreshTokens) { - logger.debug("RefreshToken {} timed out", new Object[]{refreshToken}); + if (refreshTokenTimedOut(refreshToken)) { - user.removeRefreshToken(refreshToken); + logger.debug("RefreshToken {} timed out", new Object[]{refreshToken}); + user.removeRefreshToken(refreshToken); + } } - } - } catch (Exception fex) { + } catch (Exception fex) { - logger.warn("Error while removing refreshToken of user " + user.getUuid(), fex); + logger.warn("Error while removing refreshToken of user " + user.getUuid(), fex); + } } }
Bugfix: Prevent NPE when removing timed out refresh tokens
structr_structr
train
cbbeaf2b594869064b2ec1dc65899bbfb0d455cd
diff --git a/lib/rfd.rb b/lib/rfd.rb index <HASH>..<HASH> 100644 --- a/lib/rfd.rb +++ b/lib/rfd.rb @@ -253,6 +253,7 @@ module Rfd wclear draw_items + wmove 0 move_cursor @row draw_marked_items
move to 0 after drawing when lsing
amatsuda_rfd
train
34ee799ee7d5039f9712db5cec4b6a17e8d3bf48
diff --git a/lib/fog/rackspace/models/dns/callback.rb b/lib/fog/rackspace/models/dns/callback.rb index <HASH>..<HASH> 100644 --- a/lib/fog/rackspace/models/dns/callback.rb +++ b/lib/fog/rackspace/models/dns/callback.rb @@ -11,7 +11,7 @@ module Fog response = nil Fog.wait_for(timeout, interval) do response = connection.callback job_id - if response.status != 202 + if response.body['status'] != 'RUNNING' true elsif retries == 0 raise Fog::Errors::Error.new("Wait on job #{job_id} took too long") diff --git a/lib/fog/rackspace/models/dns/record.rb b/lib/fog/rackspace/models/dns/record.rb index <HASH>..<HASH> 100644 --- a/lib/fog/rackspace/models/dns/record.rb +++ b/lib/fog/rackspace/models/dns/record.rb @@ -51,7 +51,7 @@ module Fog } response = wait_for_job connection.add_records(@zone.identity, [options]).body['jobId'] - merge_attributes(response.body['request']['records'].select {|record| record['name'] == self.name && record['type'] == self.type && record['value'] == self.value}) + merge_attributes(response.body['response']['records'].select {|record| record['name'] == self.name && record['type'] == self.type && record['data'] == self.value}.first) true end diff --git a/lib/fog/rackspace/models/dns/zone.rb b/lib/fog/rackspace/models/dns/zone.rb index <HASH>..<HASH> 100644 --- a/lib/fog/rackspace/models/dns/zone.rb +++ b/lib/fog/rackspace/models/dns/zone.rb @@ -52,7 +52,7 @@ module Fog response = connection.create_domains([data]) response = wait_for_job response.body['jobId'] - merge_attributes(response.body['request']['domains'].select {|domain| domain['name'] == self.domain}) + merge_attributes(response.body['response']['domains'].select {|domain| domain['name'] == self.domain}.first) end def update
[rackspace|dns] Adapted to changes in callback mechanism
fog_fog
train
4991595f64bf2b1c46be4446c5921e7e8f0ecb71
diff --git a/lib/phusion_passenger/platform_info/ruby.rb b/lib/phusion_passenger/platform_info/ruby.rb index <HASH>..<HASH> 100644 --- a/lib/phusion_passenger/platform_info/ruby.rb +++ b/lib/phusion_passenger/platform_info/ruby.rb @@ -68,12 +68,26 @@ module PlatformInfo return filename end end + + # Correctness of these commands are confirmed by mpapis. + case rvm_installation_mode + when :single + repair_command = "rvm get stable && rvm reload && rvm repair all" + wrapper_command = "rvm wrapper #{rvm_ruby_string} --no-prefix --all" + when :multi + repair_command = "rvmsudo rvm get stable && rvm reload && rvmsudo rvm repair all" + wrapper_command = "rvmsudo rvm wrapper #{rvm_ruby_string} --no-prefix --all" + when :mixed + repair_command = "rvmsudo rvm get stable && rvm reload && rvm repair all" + wrapper_command = "rvm wrapper #{rvm_ruby_string} --no-prefix --all" + end + STDERR.puts "Your RVM wrapper scripts are too old, or some " + "wrapper scripts are missing. Please update/regenerate " + "them first by running:\n\n" + - " rvm get stable && rvm reload && rvm repair all\n\n" + + " #{repair_command}\n\n" + "If that doesn't seem to work, please run:\n\n" + - " rvm wrapper #{rvm_ruby_string} --no-prefix --all" + " #{wrapper_command}" exit 1 else # Something's wrong with the user's RVM installation. @@ -241,6 +255,27 @@ module PlatformInfo return nil end memoize :rvm_ruby_string + + # Returns the RVM installation mode: + # :single - RVM is installed in single-user mode. + # :multi - RVM is installed in multi-user mode. + # :mixed - RVM is in a mixed-mode installation. + # nil - The current Ruby interpreter is not using RVM. + def self.rvm_installation_mode + if in_rvm? + if ENV['rvm_path'] =~ /\.rvm/ + return :single + else + if GEM_HOME =~ /\.rvm/ + return :mixed + else + return :multi + end + end + else + return nil + end + end # Returns either 'sudo' or 'rvmsudo' depending on whether the current # Ruby interpreter is managed by RVM.
Output different RVM repair commands based on the RVM installation mode.
phusion_passenger
train
9358496dc4b2fa101ca1365aedd9ec1fb345c876
diff --git a/lib/rr/adapters/test_unit_1.rb b/lib/rr/adapters/test_unit_1.rb index <HASH>..<HASH> 100644 --- a/lib/rr/adapters/test_unit_1.rb +++ b/lib/rr/adapters/test_unit_1.rb @@ -34,7 +34,9 @@ module RR alias_method :teardown_without_rr, :teardown def teardown_with_rr RR.verify + rescue => e teardown_without_rr + raise e end alias_method :teardown, :teardown_with_rr end
Fix Test::Unit adapters to ensure teardown is run if RR.verify borks
rr_rr
train
2d84d01b4246834e2861b244381304e87ebfc169
diff --git a/src/Schemas.js b/src/Schemas.js index <HASH>..<HASH> 100644 --- a/src/Schemas.js +++ b/src/Schemas.js @@ -3,21 +3,8 @@ class Schemas { constructor() { - this.dict = {}; + this.schemaDict = {}; this.templateCache = {}; - this.registeredDefaults = false; - } - - registerDefaults() { - const templates = document.querySelectorAll('a-assets template'); - for (let i = 0; i < templates.length; i++) { - const id = '#' + templates[i].id; - if (id !== '#' && !this.hasTemplate(id)) { - const schema = this.createDefaultSchema(id); - this.add(schema); - } - } - this.registeredDefaults = true; } createDefaultSchema(name) { @@ -32,7 +19,7 @@ class Schemas { add(schema) { if (this.validateSchema(schema)) { - this.dict[schema.template] = schema; + this.schemaDict[schema.template] = schema; var templateEl = document.querySelector(schema.template); if (!templateEl) { NAF.log.error(`Template el not found for ${schema.template}, make sure NAF.schemas.add is called after <a-scene> is defined.`); @@ -48,28 +35,38 @@ class Schemas { } } - hasTemplate(template) { - return this.dict.hasOwnProperty(template); - } - getCachedTemplate(template) { - if (!this.registeredDefaults) { - this.registerDefaults(); - } - if (!this.templateCache.hasOwnProperty(template)) { - NAF.log.error(`template el for ${template} is not cached, register template with NAF.schemas.add.`); + if (!this.templateIsCached(template)) { + if (this.templateExistsInScene(template)) { + this.add(this.createDefaultSchema(template)); + } else { + NAF.log.error(`Template el for ${template} is not in the scene, add the template to <a-assets> and register with NAF.schemas.add.`); + } } return this.templateCache[template].firstElementChild.cloneNode(true); } + templateIsCached(template) { + return this.templateCache.hasOwnProperty(template); + } + getComponents(template) { var components = ['position', 'rotation']; if (this.hasTemplate(template)) { - components = this.dict[template].components; + components = this.schemaDict[template].components; } return components; } + hasTemplate(template) { + return this.schemaDict.hasOwnProperty(template); + } + + templateExistsInScene(templateSelector) { + var el = document.querySelector(templateSelector); + return el && this.isTemplateTag(el); + } + validateSchema(schema) { return schema.hasOwnProperty('template') && schema.hasOwnProperty('components') @@ -97,11 +94,11 @@ class Schemas { } remove(template) { - delete this.dict[template]; + delete this.schemaDict[template]; } clear() { - this.dict = {}; + this.schemaDict = {}; } } diff --git a/tests/unit/Schemas.test.js b/tests/unit/Schemas.test.js index <HASH>..<HASH> 100644 --- a/tests/unit/Schemas.test.js +++ b/tests/unit/Schemas.test.js @@ -79,31 +79,6 @@ suite('Schemas', function() { }) }); - suite('hasTemplate', function() { - - test('does not have templates when empty', function() { - var template = '#template1'; - - var result = schemas.hasTemplate(template); - - assert.isFalse(result); - }); - - test('has template after schema added', function() { - var schema = { - template: '#template4', - components: [ - 'scale' - ] - }; - schemas.dict[schema.template] = schema; - - var result = schemas.hasTemplate(schema.template); - - assert.isTrue(result); - }); - }); - suite('add', function() { test('adds correct schema', function() {
If a template hasn't been registered via schemas.add but in scene, we use default schema
networked-aframe_networked-aframe
train
c69fad002180cfb36d9f859eb2fc93b56977aec6
diff --git a/lib/wechat/access_token.rb b/lib/wechat/access_token.rb index <HASH>..<HASH> 100644 --- a/lib/wechat/access_token.rb +++ b/lib/wechat/access_token.rb @@ -7,6 +7,7 @@ module Wechat @secret = secret @client = client @token_file = token_file + @random_generator = Random.new end def token @@ -14,7 +15,7 @@ module Wechat @token_data ||= JSON.parse(File.read(token_file)) created_at = token_data['created_at'].to_i expires_in = token_data['expires_in'].to_i - fail 'token_data may be expired' if Time.now.to_i - created_at >= expires_in - 3 * 60 + fail 'token_data may be expired' if Time.now.to_i - created_at >= expires_in - @random_generator.rand(30..3 * 60) rescue refresh end diff --git a/lib/wechat/jsapi_base.rb b/lib/wechat/jsapi_base.rb index <HASH>..<HASH> 100644 --- a/lib/wechat/jsapi_base.rb +++ b/lib/wechat/jsapi_base.rb @@ -9,6 +9,7 @@ module Wechat @client = client @access_token = access_token @jsapi_ticket_file = jsapi_ticket_file + @random_generator = Random.new end # Obtain the wechat jssdk signature's ticket and return below hash @@ -23,7 +24,7 @@ module Wechat @jsapi_ticket_data ||= JSON.parse(File.read(jsapi_ticket_file)) created_at = jsapi_ticket_data['created_at'].to_i expires_in = jsapi_ticket_data['expires_in'].to_i - if Time.now.to_i - created_at >= expires_in - 3 * 60 + if Time.now.to_i - created_at >= expires_in - @random_generator.rand(30..3 * 60) fail 'jsapi_ticket may be expired' end rescue
Do not refresh access_token at same time, using random seconds for #<I>
Eric-Guo_wechat
train
9df86ec6ef5b664221eb94efb795abd70ef7420f
diff --git a/wandb/board/ui/src/pages/Run.js b/wandb/board/ui/src/pages/Run.js index <HASH>..<HASH> 100644 --- a/wandb/board/ui/src/pages/Run.js +++ b/wandb/board/ui/src/pages/Run.js @@ -55,7 +55,8 @@ class Run extends React.Component { } // Setup views loaded from server. if ( - nextProps.bucket & (nextProps.views === null || !nextProps.views.run) && + nextProps.bucket && + (nextProps.views === null || !nextProps.views.run) && _.isEmpty(this.props.reduxServerViews.run.views) && // Prevent infinite loop _.isEmpty(this.props.reduxBrowserViews.run.views) &&
Fix bug where views didn't load on run page
wandb_client
train