hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
91f1a00e458c32ab87015c274a72d27fd00aaa01
diff --git a/gifi/feature.py b/gifi/feature.py index <HASH>..<HASH> 100644 --- a/gifi/feature.py +++ b/gifi/feature.py @@ -126,7 +126,7 @@ def _discard(): print 'WARNING: Unable to remove remote feature branch. Maybe it was not yet created?' repo.git.branch('-D', feature_branch) repo.git.rebase('%s/%s' % (config.target_remote, config.target_branch)) - repo.git.fetch('%s --prune' % config.working_remote) + repo.git.fetch('%s' % config.working_remote, '--prune') def configuration(repo=None):
Fix pruning branches on feature-discard
kokosing_git-gifi
train
019701260bb0cba0785c5aacaacbc111fbed4649
diff --git a/java/client/src/org/openqa/selenium/internal/seleniumemulation/Windows.java b/java/client/src/org/openqa/selenium/internal/seleniumemulation/Windows.java index <HASH>..<HASH> 100644 --- a/java/client/src/org/openqa/selenium/internal/seleniumemulation/Windows.java +++ b/java/client/src/org/openqa/selenium/internal/seleniumemulation/Windows.java @@ -39,9 +39,8 @@ public class Windows { } public void selectWindow(WebDriver driver, String windowID) { - if ("null".equals(windowID)) { - driver.switchTo() - .window(originalWindowHandle); + if ("null".equals(windowID) || "".equals(windowID)) { + driver.switchTo().window(originalWindowHandle); } else if ("_blank".equals(windowID)) { selectBlankWindow(driver); } else { diff --git a/java/client/test/com/thoughtworks/selenium/InternalSelenseTestBase.java b/java/client/test/com/thoughtworks/selenium/InternalSelenseTestBase.java index <HASH>..<HASH> 100644 --- a/java/client/test/com/thoughtworks/selenium/InternalSelenseTestBase.java +++ b/java/client/test/com/thoughtworks/selenium/InternalSelenseTestBase.java @@ -50,11 +50,36 @@ public class InternalSelenseTestBase extends SeleneseTestBase { } @Before + public void focusOnMainWindow() { + if (selenium == null) { + return; + } + selenium.windowFocus(); + } + + @Before public void returnFocusToMainWindow() { if (selenium == null) { return; } - selenium.selectWindow(""); + + try { + selenium.selectWindow(""); + } catch (SeleniumException e) { + // TODO(simon): Window switching in Opera is picky. + if (!isOperaDriver(selenium)) { + throw e; + } + } + } + + private boolean isOperaDriver(Selenium selenium) { + if (!(selenium instanceof WrapsDriver)) { + return false; + } + + WebDriver driver = ((WrapsDriver) selenium).getWrappedDriver(); + return "OperaDriver".equals(driver.getClass().getSimpleName()); } @Before
SimonStewart: Edging ever closer to getting the selenium emulation to work with the opera driver r<I>
SeleniumHQ_selenium
train
75da13a4b9650049e07d0ea90a82bd7828cbdb96
diff --git a/lib/connection.js b/lib/connection.js index <HASH>..<HASH> 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -219,7 +219,6 @@ p.parseMessage = function() { var id = this.readChar(); var message = { - id: id, name: messageNames[id], length: this.parseInt32() }; @@ -230,8 +229,8 @@ p.parseMessage = function() { this.lastOffset = this.offset-5; return false; } - - return this["parse"+message.id](message); + + return this["parse"+id](message); }; p.parseR = function(msg) { diff --git a/test/unit/connection/inbound-parser-tests.js b/test/unit/connection/inbound-parser-tests.js index <HASH>..<HASH> 100644 --- a/test/unit/connection/inbound-parser-tests.js +++ b/test/unit/connection/inbound-parser-tests.js @@ -62,13 +62,11 @@ var oneFieldBuf = buffers.dataRow(['test\0']); var expectedAuthenticationOkayMessage = { name: 'authenticationOk', - id: 'R', length: 8 }; var expectedParameterStatusMessage = { name: 'parameterStatus', - id: 'S', length: 25, parameterName: 'client_encoding', parameterValue: 'UTF8' @@ -76,21 +74,18 @@ var expectedParameterStatusMessage = { var expectedBackendKeyDataMessage = { name: 'backendKeyData', - id: 'K', processID: 1, secretKey: 2 }; var expectedReadyForQueryMessage = { name: 'readyForQuery', - id: 'Z', length: 5, status: 'I' }; var expectedCommandCompleteMessage = { length: 13, - id: 'C', text: "SELECT 3" }; var emptyRowDescriptionBuffer = new BufferList() @@ -99,20 +94,17 @@ var emptyRowDescriptionBuffer = new BufferList() var expectedEmptyRowDescriptionMessage = { name: 'rowDescription', - id: 'T', length: 6, fieldCount: 0 }; var expectedOneRowMessage = { name: 'rowDescription', - id: 'T', length: 27, fieldCount: 1 }; var expectedTwoRowMessage = { name: 'rowDescription', - id: 'T', length: 53, fieldCount: 2 }; @@ -144,18 +136,15 @@ var plainPasswordBuffer = buffers.authenticationCleartextPassword(); var md5PasswordBuffer = buffers.authenticationMD5Password(); var expectedPlainPasswordMessage = { - id: 'R', name: 'authenticationCleartextPassword' }; var expectedMD5PasswordMessage = { - id: 'R', name: 'authenticationMD5Password' }; var notificationResponseBuffer = buffers.notification(4, 'hi', 'boom'); var expectedNotificationResponseMessage = { - id: 'A', name: 'notification', processId: 4, channel: 'hi', @@ -183,7 +172,6 @@ test('Connection', function() { test("no data message", function() { testForMessage(Buffer([0x6e, 0, 0, 0, 4]), { - id: 'n', name: 'noData' }); }); @@ -342,14 +330,12 @@ test('Connection', function() { test('parses parse complete command', function() { testForMessage(parseCompleteBuffer, { - id: '1', name: 'parseComplete' }); }); test('parses bind complete command', function() { testForMessage(bindCompleteBuffer, { - id: '2', name: 'bindComplete' }); });
removed id from connection messages (simplify API)
brianc_node-postgres
train
84a555df0dca1566f110a5557a60857bace1c1d9
diff --git a/tests/test_lens.py b/tests/test_lens.py index <HASH>..<HASH> 100644 --- a/tests/test_lens.py +++ b/tests/test_lens.py @@ -1,3 +1,5 @@ +import collections + import pytest from lenses import lens, baselens @@ -101,8 +103,18 @@ def test_lens_getitem(): assert lens([1, 2, 3]).getitem_(1).get() == 2 +def test_lens_getitem_direct(): + assert lens([1, 2, 3])[1].get() == 2 + + def test_lens_getattr(): - assert lens(3).getattr_('denominator').get() == 1 + nt = collections.namedtuple('nt', 'attr') + assert lens(nt(3)).getattr_('attr').get() == 3 + + +def test_lens_getattr_direct(): + nt = collections.namedtuple('nt', 'attr') + assert lens(nt(3)).attr.get() == 3 def test_lens_both():
added test for Lens.__getattr__ and Lens.__getitem__
ingolemo_python-lenses
train
28f46fa32555032cc3f2a02292ebb59a85ea196f
diff --git a/src/View.php b/src/View.php index <HASH>..<HASH> 100644 --- a/src/View.php +++ b/src/View.php @@ -3,7 +3,7 @@ namespace Monolyth\Improse; use DomainException; -use ReflectionClass; +use ReflectionObject; use ReflectionProperty; use Exception; use Closure; @@ -112,25 +112,11 @@ class View */ protected function getVariables() : array { - $reflection = new ReflectionClass($this); - foreach ($reflection->getProperties( - ReflectionProperty::IS_PROTECTED | - ReflectionProperty::IS_PRIVATE | - ReflectionProperty::IS_STATIC - ) as $property) { - $ignore[] = $property->name; - } + $reflection = new ReflectionObject($this); $values = []; - foreach ($this as $prop => $value) { - if (!in_array($prop, $ignore)) { - if (is_object($value)) { - if (method_exists($value, 'jsonSerialize')) { - $value = $value->jsonSerialize(); - } elseif (method_exists($value, 'getArrayCopy')) { - $value = $value->getArrayCopy(); - } - } - $values[$prop] = $value; + foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC & ~ReflectionProperty::IS_STATIC) as $property) { + if (isset($this->{$property->getName()})) { + $values[$property->getName()] = $this->{$property->getName()}; } } return $values;
handle this in a saner way
monolyth-php_improse
train
0671cd021348bde97edafda5c681cf8e5ab832df
diff --git a/src/js/components/RangeInput/RangeInput.js b/src/js/components/RangeInput/RangeInput.js index <HASH>..<HASH> 100644 --- a/src/js/components/RangeInput/RangeInput.js +++ b/src/js/components/RangeInput/RangeInput.js @@ -34,10 +34,12 @@ const RangeInput = forwardRef( if (onBlur) onBlur(event); }} onChange={event => { + const nextValue = event.target.value; if (formContext && name) { - formContext.set(name, event.target.value); + formContext.set(name, nextValue); } if (onChange) onChange(event); + setValue(nextValue); }} type="range" /> diff --git a/src/js/components/Select/Select.js b/src/js/components/Select/Select.js index <HASH>..<HASH> 100644 --- a/src/js/components/Select/Select.js +++ b/src/js/components/Select/Select.js @@ -113,13 +113,15 @@ const Select = forwardRef( }; const onSelectChange = (event, ...args) => { + const nextValue = event.value; if (closeOnChange) { onRequestClose(); } - if (formContext && name) formContext.set(name, event.value); + if (formContext && name) formContext.set(name, nextValue); if (onChange) { onChange({ ...event, target: inputRef.current }, ...args); } + setValue(nextValue); }; let SelectIcon;
Changed Select and RangeInput to fix an issue with setting the value (#<I>)
grommet_grommet
train
0bdbfe77a893520712db1a08f262a6d3f9e0cc21
diff --git a/goatools/go_enrichment.py b/goatools/go_enrichment.py index <HASH>..<HASH> 100755 --- a/goatools/go_enrichment.py +++ b/goatools/go_enrichment.py @@ -13,7 +13,7 @@ from __future__ import print_function from __future__ import absolute_import -__copyright__ = "Copyright (C) 2010-2018, H Tang et al., All rights reserved." +__copyright__ = "Copyright (C) 2010-2019, H Tang et al., All rights reserved." __author__ = "various" import sys @@ -373,13 +373,25 @@ class GOEnrichmentStudy(object): """Print information regarding multitest correction results.""" ntm = ntmt.nt_method attr_mult = "p_{M}".format(M=self.methods.get_fieldname(ntm.source, ntm.method)) - eps = [r.enrichment for r in results if getattr(r, attr_mult) < alpha] + eps = [r for r in results if getattr(r, attr_mult) < alpha] sig_cnt = len(eps) - ctr = cx.Counter(eps) + ctr = cx.Counter([r.enrichment for r in eps]) log.write("{N:8,} GO terms found significant (< {A}=alpha) ".format( N=sig_cnt, A=alpha)) log.write('({E:3} enriched + {P:3} purified): '.format(E=ctr['e'], P=ctr['p'])) log.write("{MSRC} {METHOD}\n".format(MSRC=ntm.source, METHOD=ntm.method)) + log.write("{N:8,} study items associated with significant GO IDs (enriched)\n".format( + N=len(self.get_study_items(r for r in eps if r.enrichment == 'e')))) + log.write("{N:8,} study items associated with significant GO IDs (purified)\n".format( + N=len(self.get_study_items(r for r in eps if r.enrichment == 'p')))) + + @staticmethod + def get_study_items(results): + """Return a list of study items associated with the given results.""" + study_items = set() + for obj in results: + study_items.update(obj.study_items) + return study_items def _run_multitest_statsmodels(self, ntmt): """Use multitest mthods that have been implemented in statsmodels.""" @@ -568,4 +580,4 @@ class GOEnrichmentStudy(object): nts_goea = sorted(nts_goea, key=sortby) wr_py_nts(fout_py, nts_goea, docstring, var_name) -# Copyright (C) 2010-2018, H Tang et al., All rights reserved. +# Copyright (C) 2010-2019, H Tang et al., All rights reserved.
Added info msg upon enrichment; Num. of genes assc w/sig GOs
tanghaibao_goatools
train
6bfae035b7eba69df3566880da6f491dd88c6499
diff --git a/plugin/index.js b/plugin/index.js index <HASH>..<HASH> 100644 --- a/plugin/index.js +++ b/plugin/index.js @@ -18,6 +18,8 @@ function hapiAccount (server, options, next) { var routeOptions = merge({}, options) routeOptions.sessionTimeout = options.sessionTimeout || TIMEOUT_14_DAYS + options.usersDb.constructor.plugin(require('pouchdb-admins')) + var users = getApi({ db: options.usersDb, secret: options.secret,
fix: apply admin-users PouchDB plugin internally * * * This commit was sponsored by &yet. Our friends at &yet have been supporters of Hoodie since its earliest days. <3 And they have availability for new projects! We think they’re some of the best people you can hire anywhere, but you can read what other people have to say about them and their work here: <URL>
hoodiehq_hoodie-account-server
train
ddeed96b4cf0590b4ec785aef3cb9640835b9a36
diff --git a/src/com/google/javascript/jscomp/TranspilationPasses.java b/src/com/google/javascript/jscomp/TranspilationPasses.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/TranspilationPasses.java +++ b/src/com/google/javascript/jscomp/TranspilationPasses.java @@ -21,7 +21,6 @@ import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES2018_MODU import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES6; import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES7; import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8; -import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8_MODULES; import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES_NEXT; import com.google.javascript.jscomp.Es6RewriteDestructuring.ObjectDestructuringRewriteMode; @@ -384,7 +383,7 @@ public class TranspilationPasses { @Override protected FeatureSet featureSet() { - return ES8_MODULES; + return FeatureSet.latest(); } }; @@ -451,7 +450,7 @@ public class TranspilationPasses { @Override protected FeatureSet featureSet() { - return ES8; + return FeatureSet.latest(); } }; diff --git a/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java b/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java +++ b/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java @@ -75,12 +75,7 @@ public final class FeatureSet implements Serializable { public static final FeatureSet TYPESCRIPT = ES_NEXT.with(LangVersion.TYPESCRIPT.features()); public static final FeatureSet TYPE_CHECK_SUPPORTED = - ES8.without(Feature.ARRAY_PATTERN_REST) - .without(Feature.ASYNC_FUNCTIONS) - .without(Feature.DEFAULT_PARAMETERS) - .without(Feature.ARRAY_DESTRUCTURING) - .without(Feature.OBJECT_DESTRUCTURING) - .without(Feature.MODULES); + ES8.without(Feature.ASYNC_FUNCTIONS).without(Feature.MODULES); private enum LangVersion { ES3,
Rollforward: "Change TYPE_CHECK_SUPPORTED to include all ES6 features except modules." The type checker now understands all of these features. ------------- Created by MOE: <URL>
google_closure-compiler
train
aaa5e8732cd240fbb5d1f8c46ed12273c9115c28
diff --git a/Form/Extension/Field/Type/FormTypeFieldExtension.php b/Form/Extension/Field/Type/FormTypeFieldExtension.php index <HASH>..<HASH> 100644 --- a/Form/Extension/Field/Type/FormTypeFieldExtension.php +++ b/Form/Extension/Field/Type/FormTypeFieldExtension.php @@ -90,10 +90,10 @@ class FormTypeFieldExtension extends AbstractTypeExtension */ public function buildView(FormViewInterface $view, FormInterface $form, array $options) { - $sonataAdmin = $form->getAttribute('sonata_admin'); + $sonataAdmin = $form->getConfig()->getAttribute('sonata_admin'); // avoid to add extra information not required by non admin field - if ($form->getAttribute('sonata_admin_enabled', true)) { + if ($form->getConfig()->getAttribute('sonata_admin_enabled', true)) { $sonataAdmin['value'] = $form->getData(); // add a new block types, so the Admin Form element can be tweaked based on the admin code @@ -103,6 +103,7 @@ class FormTypeFieldExtension extends AbstractTypeExtension $types[] = sprintf('%s_%s', $baseName, $baseType); $types[] = sprintf('%s_%s_%s', $baseName, $sonataAdmin['field_description']->getName(), $baseType); + if ($sonataAdmin['block_name']) { $types[] = $sonataAdmin['block_name']; }
#<I> : Fix the bc break calls to get the form attributes
sonata-project_SonataAdminBundle
train
cf1c619ecf5c2d31bb4c9f5f49935d3060f19276
diff --git a/Twig/Extension/Plugin/AbstractMaterialDesignColorPaletteTwigExtension.php b/Twig/Extension/Plugin/AbstractMaterialDesignColorPaletteTwigExtension.php index <HASH>..<HASH> 100644 --- a/Twig/Extension/Plugin/AbstractMaterialDesignColorPaletteTwigExtension.php +++ b/Twig/Extension/Plugin/AbstractMaterialDesignColorPaletteTwigExtension.php @@ -11,12 +11,9 @@ namespace WBW\Bundle\CoreBundle\Twig\Extension\Plugin; -use Twig_Environment; use Twig\Extension\AbstractExtension; -use WBW\Bundle\CoreBundle\Color\AmberColorProvider; -use WBW\Bundle\CoreBundle\Color\BlueColorProvider; -use WBW\Bundle\CoreBundle\Color\BlueGreyColorProvider; -use WBW\Bundle\CoreBundle\Color\BrownColorProvider; +use Twig_Environment; +use WBW\Bundle\CoreBundle\Helper\ColorHelper; use WBW\Bundle\CoreBundle\Provider\ColorProviderInterface; /** @@ -43,36 +40,7 @@ abstract class AbstractMaterialDesignColorPaletteTwigExtension extends AbstractE protected function __construct(Twig_Environment $twigEnvironment) { parent::__construct($twigEnvironment); - $this->addColor(new AmberColorProvider()); - $this->addColor(new BlueColorProvider()); - $this->addColor(new BlueGreyColorProvider()); - $this->addColor(new BrownColorProvider()); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - $this->addColor(new ); - } - - /** - * Add a color. - * - * @param ColorProviderInterface $color The color provider. - * @return AbstractMaterialDesignColorPaletteTwigExtension Returns this Material Design Color Palette Twig extension. - */ - protected function addColor(ColorProviderInterface $color) { - $this->colors[] = $color; - return $this; + $this->setColors(ColorHelper::getMaterialDesignColorPalette()); } /** @@ -95,5 +63,4 @@ abstract class AbstractMaterialDesignColorPaletteTwigExtension extends AbstractE return $this; } - }
Update abstract Material Design Color Palette Twig extension
webeweb_core-bundle
train
22ee85885ed64fd0ada7a8082d2e95843618051f
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -63,18 +63,11 @@ function ESBackend(config, JuttleRuntime) { } }); - var Write = JuttleRuntime.proc.fanin.extend({ + var Write = JuttleRuntime.proc.sink.extend({ procName: 'elastic_write', initialize: function(options) { var self = this; - this.isSink = true; this.eofs = 0; - this.done = new Promise(function(resolve, reject) { - // totally opaque promise that juttle-test-utils.run_juttle depends on - // to wait for the write to finish - self.resolve = resolve; - self.reject = reject; - }); }, process: function(points) { var inserter = electra.get_inserter(); @@ -93,8 +86,8 @@ function ESBackend(config, JuttleRuntime) { eof: function(from) { this.eofs++; if (this.eofs === this.ins.length) { - this.resolve({name: this.procName}); this.emit_eof(); + this.done(); } } });
write: fix implementation to match the new sink contract
juttle_juttle-elastic-adapter
train
7efce4646a9713ee898a48a15a44495d8129be1b
diff --git a/src/follow.js b/src/follow.js index <HASH>..<HASH> 100644 --- a/src/follow.js +++ b/src/follow.js @@ -25,34 +25,39 @@ module.exports = class Follow extends Plugin return } + const center = this.parent.center + let toX = this.target.x, toY = this.target.y if (this.radius) { - const center = this.parent.center const distance = Math.sqrt(Math.pow(this.target.y - center.y, 2) + Math.pow(this.target.x - center.x, 2)) if (distance > this.radius) { const angle = Math.atan2(this.target.y - center.y, this.target.x - center.x) - this.parent.moveCenter(this.target.x - Math.cos(angle) * this.radius, this.target.y - Math.sin(angle) * this.radius) + toX = this.target.x - Math.cos(angle) * this.radius + toY = this.target.y - Math.sin(angle) * this.radius + } + else + { + return } } - else if (this.speed) + if (this.speed) { - const center = this.parent.center - const deltaX = this.target.x - center.x - const deltaY = this.target.y - center.y + const deltaX = toX - center.x + const deltaY = toY - center.y if (deltaX || deltaY) { - const angle = Math.atan2(this.target.y - center.y, this.target.x - center.x) + const angle = Math.atan2(toY - center.y, toX - center.x) const changeX = Math.cos(angle) * this.speed const changeY = Math.sin(angle) * this.speed - const x = Math.abs(changeX) > Math.abs(deltaX) ? this.target.x : center.x + changeX - const y = Math.abs(changeY) > Math.abs(deltaY) ? this.target.y : center.y + changeY + const x = Math.abs(changeX) > Math.abs(deltaX) ? toX : center.x + changeX + const y = Math.abs(changeY) > Math.abs(deltaY) ? toY : center.y + changeY this.parent.moveCenter(x, y) } } else { - this.parent.moveCenter(this.target.x, this.target.y) + this.parent.moveCenter(toX, toY) } } } \ No newline at end of file
follow.radius and follow.speed now work together
davidfig_pixi-viewport
train
4337de7bebafc0a87fff5d8cca2bb0262be06a2a
diff --git a/caas/kubernetes/provider/metadata.go b/caas/kubernetes/provider/metadata.go index <HASH>..<HASH> 100644 --- a/caas/kubernetes/provider/metadata.go +++ b/caas/kubernetes/provider/metadata.go @@ -5,6 +5,7 @@ package provider import ( "os" + "strings" "github.com/juju/collections/set" "github.com/juju/errors" @@ -52,6 +53,7 @@ func getCloudRegionFromNodeMeta(node core.Node) (string, string) { if err != nil { return "", "" } + hostname = strings.ToLower(hostname) hostLabel, _ := node.Labels["kubernetes.io/hostname"] if node.Name == hostname && hostLabel == hostname { return caas.Microk8s, caas.Microk8sRegion
fixed lowercase hostname then compare because k8s Node.Name and label values are all always lowercase.
juju_juju
train
c91e8027a43c5698aaf044380a29cc2371be1ff1
diff --git a/scapy/contrib/automotive/bmw/hsfz.py b/scapy/contrib/automotive/bmw/hsfz.py index <HASH>..<HASH> 100644 --- a/scapy/contrib/automotive/bmw/hsfz.py +++ b/scapy/contrib/automotive/bmw/hsfz.py @@ -11,12 +11,12 @@ import struct import socket import time -from scapy.compat import Optional, Tuple, Type +from scapy.compat import Optional, Tuple, Type, Iterable, List, Union from scapy.packet import Packet, bind_layers, bind_bottom_up from scapy.fields import IntField, ShortEnumField, XByteField from scapy.layers.inet import TCP from scapy.supersocket import StreamSocket -from scapy.contrib.automotive.uds import UDS +from scapy.contrib.automotive.uds import UDS, UDS_TP from scapy.data import MTU from scapy.error import log_interactive @@ -120,3 +120,40 @@ class UDS_HSFZSocket(HSFZSocket): return self.outputcls(bytes(pkt.payload)) else: return pkt + + +def hsfz_scan(ip, # type: str + scan_range=range(0x100), # type: Iterable[int] + src=0xf4, # type: int + timeout=0.1, # type: Union[int, float] + verbose=True # type: bool + ): + # type: (...) -> List[UDS_HSFZSocket] + """ + Helper function to scan for HSFZ endpoints. + + Example: + >>> sockets = hsfz_scan("192.168.0.42") + + :param ip: IPv4 address of target to scan + :param scan_range: Range for HSFZ destination address + :param src: HSFZ source address, used during the scan + :param timeout: Timeout for each request + :param verbose: Show information during scan, if True + :return: A list of open UDS_HSFZSockets + """ + results = list() + for i in scan_range: + with UDS_HSFZSocket(src, i, ip) as sock: + try: + resp = sock.sr1(UDS() / UDS_TP(), + timeout=timeout, + verbose=False) + if resp: + results.append((i, resp)) + if resp and verbose: + print( + "Found endpoint %s, src=0x%x, dst=0x%x" % (ip, src, i)) + except Exception as e: + print("Error %s at destination address 0x%x" % (e, i)) + return [UDS_HSFZSocket(0xf4, dst, ip) for dst, _ in results]
Add utility function to scan for HSFZ endpoints
secdev_scapy
train
6c1732d498a24c133725ea66d4d9330d1f694d52
diff --git a/opal/opal/runtime.js b/opal/opal/runtime.js index <HASH>..<HASH> 100644 --- a/opal/opal/runtime.js +++ b/opal/opal/runtime.js @@ -261,7 +261,7 @@ var prop, block = native_send._p; native_send._p = null; - if (prop = native_methods[mid]) { + if ( (prop = native_methods[mid]) ) { return prop(obj, args, block); }
This is not the comparison you are looking for
opal_opal
train
98e8e58b188336ad49e24cfaa1aaa46ca9de24cc
diff --git a/pyforms/Controls/ControlButton.py b/pyforms/Controls/ControlButton.py index <HASH>..<HASH> 100755 --- a/pyforms/Controls/ControlButton.py +++ b/pyforms/Controls/ControlButton.py @@ -1,44 +1,48 @@ #!/usr/bin/python # -*- coding: utf-8 -*- - -__author__ = "Ricardo Ribeiro" -__credits__ = ["Ricardo Ribeiro"] -__license__ = "MIT" -__version__ = "0.0" -__maintainer__ = "Ricardo Ribeiro" -__email__ = "ricardojvr@gmail.com" -__status__ = "Development" - +''' +@author: Ricardo Ribeiro +@credits: Ricardo Ribeiro +@license: MIT +@version: 0.0 +@maintainer: Ricardo Ribeiro +@email: ricardojvr@gmail.com +@status: Development +@lastEditedBy: Carlos Mão de Ferro (carlos.maodeferro@neuro.fchampalimaud.org) +''' import pyforms.Utils.tools as tools -from PyQt4 import uic, QtGui +from PyQt4 import uic from pyforms.Controls.ControlBase import ControlBase + class ControlButton(ControlBase): def initForm(self): - control_path = tools.getFileInSameDirectory(__file__,"button.ui") - self._form = uic.loadUi( control_path ) + control_path = tools.getFileInSameDirectory(__file__, "button.ui") + self._form = uic.loadUi(control_path) self._form.pushButton.setText(self._label) def load(self, data): pass def save(self, data): pass - ############################################################################ + ########################################################################## @property - def label(self): return ControlBase.lable.fget(self) + def label(self): + return ControlBase.label.fget(self) @label.setter - def label(self, value): + def label(self, value): ControlBase.label.fset(self, value) self._form.pushButton.setText(self._label) - ############################################################################ - + ########################################################################## + @property - def value(self): return None + def value(self): + return None @value.setter def value(self, value):
PEP 8 compliance fixed mistyped variable
UmSenhorQualquer_pyforms
train
2095a6d28ea7ae3ce595a42df5f55c4ad8c7fc11
diff --git a/ide/src/extension/content/treeView.js b/ide/src/extension/content/treeView.js index <HASH>..<HASH> 100644 --- a/ide/src/extension/content/treeView.js +++ b/ide/src/extension/content/treeView.js @@ -604,26 +604,9 @@ objectExtend(TreeView.prototype, { }, drop: function(dropIndex, orientation) { - try{ - var sourceIndex = this.getSourceIndexFromDrag(); - - if (dropIndex > sourceIndex) { - if (orientation == Ci.nsITreeView.DROP_BEFORE) - dropIndex--; - }else{ - if (orientation == Ci.nsITreeView.DROP_AFTER) - dropIndex++; - } - - var removedRow = this.testCase.commands.splice(sourceIndex, 1)[0]; - this.testCase.commands.splice(dropIndex, 0, removedRow); - - this.treebox.invalidate(); - this.selection.clearSelection(); - this.selection.select(dropIndex); - }catch(e){ - new Log("DND").error("drop error : "+e); - } + + var sourceIndex = this.getSourceIndexFromDrag(); + this.executeAction(new TreeView.dndCommandAction(this, sourceIndex, dropIndex, orientation)); } }); @@ -754,3 +737,70 @@ TreeView.PasteCommandAction.prototype = { this.treeView.treebox.ensureRowIsVisible(currentIndex); } } + +//D'n'D action for the undo/redo process +TreeView.dndCommandAction = function(treeView, sourceIndex, dropIndex, orientation){ + + this.treeView = treeView; + this.sourceIndex = sourceIndex; + this.dropIndex = dropIndex; + this.orientation = orientation; + this.sourceIndexU = dropIndex; + this.dropIndexU = sourceIndex; + if (this.dropIndex > this.sourceIndex) { + if (this.orientation == Ci.nsITreeView.DROP_BEFORE) + this.sourceIndexU--; + }else{ + if (this.orientation == Ci.nsITreeView.DROP_AFTER) + this.sourceIndexU++; + } + this.orientationU = this.orientation == Ci.nsITreeView.DROP_BEFORE ? Ci.nsITreeView.DROP_AFTER : Ci.nsITreeView.DROP_BEFORE; +} + +TreeView.dndCommandAction.prototype = { + + execute: function(){ + + try{ + if (this.dropIndex > this.sourceIndex) { + if (this.orientation == Ci.nsITreeView.DROP_BEFORE) + this.dropIndex--; + }else{ + if (this.orientation == Ci.nsITreeView.DROP_AFTER) + this.dropIndex++; + } + + var removedRow = this.treeView.testCase.commands.splice(this.sourceIndex, 1)[0]; + this.treeView.testCase.commands.splice(this.dropIndex, 0, removedRow); + + this.treeView.treebox.invalidate(); + this.treeView.selection.clearSelection(); + this.treeView.selection.select(this.dropIndex); + }catch(e){ + new Log("DND").error("dndCommandAction.execute error : "+e); + } + }, + + undo: function(){ + + try{ + if (this.dropIndexU > this.sourceIndexU) { + if (this.orientationU == Ci.nsITreeView.DROP_BEFORE) + this.dropIndexU--; + }else{ + if (this.orientationU == Ci.nsITreeView.DROP_AFTER) + this.dropIndexU++; + } + + var removedRow = this.treeView.testCase.commands.splice(this.sourceIndexU, 1)[0]; + this.treeView.testCase.commands.splice(this.dropIndexU, 0, removedRow); + + this.treeView.treebox.invalidate(); + this.treeView.selection.clearSelection(); + this.treeView.selection.select(this.dropIndexU); + }catch(e){ + new Log("DND").error("dndCommandAction.undo error : "+e); + } + + } +} \ No newline at end of file
jeremy.herault: it's better when you can undo and redo your Drag'n'Drop r<I>
SeleniumHQ_selenium
train
c484d73bfbdb5b46bbb08f462bb57e65bdf09e0e
diff --git a/ryu/services/protocols/bgp/info_base/base.py b/ryu/services/protocols/bgp/info_base/base.py index <HASH>..<HASH> 100644 --- a/ryu/services/protocols/bgp/info_base/base.py +++ b/ryu/services/protocols/bgp/info_base/base.py @@ -257,6 +257,16 @@ class NonVrfPathProcessingMixin(object): pm = self._core_service.peer_manager pm.comm_new_best_to_bgp_peers(new_best_path) + # withdraw old best path + if old_best_path and self._sent_routes: + for sent_route in self._sent_routes.values(): + sent_path = sent_route.path + withdraw_clone = sent_path.clone(for_withdrawal=True) + outgoing_route = OutgoingRoute(withdraw_clone) + sent_route.sent_peer.enque_outgoing_msg(outgoing_route) + LOG.debug('Sending withdrawal to %s for %s' % + (sent_route.sent_peer, outgoing_route)) + class Destination(object): """State about a particular destination.
bgp: support New best path selecting In case of selecting new best path, Ryu BGPSpeaker send withdraw messages.
osrg_ryu
train
3b160e7737715a50657e0cce2ed58a14f0576220
diff --git a/packages/wxa-core/src/base/app.js b/packages/wxa-core/src/base/app.js index <HASH>..<HASH> 100644 --- a/packages/wxa-core/src/base/app.js +++ b/packages/wxa-core/src/base/app.js @@ -4,7 +4,13 @@ const plugins = []; let launch = function(instance) { let vm = instance; if (typeof instance === 'function') { - vm = new instance(); + let obj = new instance(); + + Object.getOwnPropertyNames(instance.prototype).forEach((key)=>{ + obj[key] = instance.prototype[key]; + }); + + vm = obj; } vm = mixin(vm); diff --git a/packages/wxa-core/src/base/component.js b/packages/wxa-core/src/base/component.js index <HASH>..<HASH> 100644 --- a/packages/wxa-core/src/base/component.js +++ b/packages/wxa-core/src/base/component.js @@ -5,7 +5,13 @@ const notCopy = ['properties', 'data', 'methods', 'behaviors', 'created', 'attac let launch = function(instance) { let vm = instance; if (typeof instance === 'function') { - vm = new instance(); + let obj = new instance(); + + Object.getOwnPropertyNames(instance.prototype).forEach((key)=>{ + obj[key] = instance.prototype[key]; + }); + + vm = obj; } // 微信自定义组件支持使用behaviors,不需要mixins diff --git a/packages/wxa-core/src/base/page.js b/packages/wxa-core/src/base/page.js index <HASH>..<HASH> 100644 --- a/packages/wxa-core/src/base/page.js +++ b/packages/wxa-core/src/base/page.js @@ -5,7 +5,13 @@ const plugins = []; let launch = function(instance) { let vm = instance; if (typeof instance === 'function') { - vm = new instance(); + let obj = new instance(); + + Object.getOwnPropertyNames(instance.prototype).forEach((key)=>{ + obj[key] = instance.prototype[key]; + }); + + vm = obj; } vm.$go = (()=>{ return debounce(function(e) {
feat: support directly write function in class before this commit, wxa only handle function defined in methods property, now, we have just put handle function in to class directly
wxajs_wxa
train
69f75801bf073c69daa204a86ad8ed89df37024a
diff --git a/Entity/Stat.php b/Entity/Stat.php index <HASH>..<HASH> 100644 --- a/Entity/Stat.php +++ b/Entity/Stat.php @@ -26,7 +26,6 @@ class Stat const TYPE_EXCLUSIVE = 'exclusive'; const TYPE_FILTER = 'filter'; const TYPE_LIMITS = 'limits'; - const TYPE_REVENUE = 'revenue'; const TYPE_SCHEDULE = 'schedule'; const TYPE_SUCCESS = 'success'; const TYPE_REJECT = 'reject'; diff --git a/Model/ContactClientModel.php b/Model/ContactClientModel.php index <HASH>..<HASH> 100644 --- a/Model/ContactClientModel.php +++ b/Model/ContactClientModel.php @@ -277,7 +277,27 @@ class ContactClientModel extends FormModel $this->limitQueryToCreator($q); } $data = $query->loadAndBuildTimeData($q); - $chart->setDataset($this->translator->trans('mautic.contactclient.graph.' . $type), $data); + foreach ($data as $val) { + if ($val != 0) { + $chart->setDataset($this->translator->trans('mautic.contactclient.graph.' . $type), $data); + break; + } + } + } + + // Add revenue to the chart. + // @todo - This should really be in it's own chart in the future. + $q = $query->prepareTimeDataQuery('contactclient_stats', 'date_added', ['type' => Stat::TYPE_SUCCESS]); + if (!$canViewOthers) { + $this->limitQueryToCreator($q); + } + $q->select('SUM(t.attribution) AS count'); + $data = $query->loadAndBuildTimeData($q); + foreach ($data as $val) { + if ($val != 0) { + $chart->setDataset($this->translator->trans('mautic.contactclient.graph.revenue'), $data); + break; + } } return $chart->render(); diff --git a/Model/Revenue.php b/Model/Revenue.php index <HASH>..<HASH> 100644 --- a/Model/Revenue.php +++ b/Model/Revenue.php @@ -65,7 +65,7 @@ class Revenue $update = false; $originalAttribution = $this->contact->getFieldValue('attribution'); $originalAttribution = !empty($originalAttribution) ? $originalAttribution : 0; - $newAttribution = $originalAttribution; + $newAttribution = 0; if ($this->payload) { $revenueSettings = $this->jsonDecodeObject($this->contactClient->getRevenueSettings()); @@ -94,9 +94,6 @@ class Revenue } elseif ($math == '*100') { $newAttribution = $newAttribution * 100; } - - // Apply new cost/revenue to the original value. - $newAttribution = $originalAttribution + $newAttribution; $update = true; } } @@ -106,14 +103,14 @@ class Revenue if (!$update) { $revenueDefault = $this->contactClient->getRevenueDefault(); if (!empty($revenueDefault) && is_numeric($revenueDefault)) { - $newAttribution = $originalAttribution + $revenueDefault; + $newAttribution = $revenueDefault; $update = true; } } - if ($update && $originalAttribution != $newAttribution) { + if ($update && $newAttribution) { $this->setNewAttribution($newAttribution); - $this->contact->addUpdatedField('attribution', $newAttribution, $originalAttribution); + $this->contact->addUpdatedField('attribution', $originalAttribution + $newAttribution, $originalAttribution); // Unsure if we should keep this next line for BC. $this->contact->addUpdatedField('attribution_date', (new \DateTime())->format('Y-m-d H:i:s')); }
[ENG-<I>] Initial revenue chart.
TheDMSGroup_mautic-contact-client
train
10429947bedf4dea907ccca8994b3a4180079bcf
diff --git a/consensus/poet/sgx/setup.py b/consensus/poet/sgx/setup.py index <HASH>..<HASH> 100644 --- a/consensus/poet/sgx/setup.py +++ b/consensus/poet/sgx/setup.py @@ -166,6 +166,7 @@ setup(name='sawtooth-poet-sgx', install_requires=[ 'toml', 'ecdsa', + 'sawtooth-ias-client', 'sawtooth-poet-common' ], ext_modules=[enclavemod],
Fix sawtooth-poet-sgx package to be dependent upon sawtooth-ias-client
hyperledger_sawtooth-core
train
61f824798c65b00721bda812228c5357e83bbcd7
diff --git a/karma.conf.js b/karma.conf.js index <HASH>..<HASH> 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -34,7 +34,7 @@ colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG -logLevel = LOG_DEBUG; +logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = true;
test: Use log level of INFO for karma
jtrussell_angular-snap.js
train
e2037d2e8eae04c3541e79cd2908cbe453596328
diff --git a/storage/raster.py b/storage/raster.py index <HASH>..<HASH> 100644 --- a/storage/raster.py +++ b/storage/raster.py @@ -386,10 +386,7 @@ class Raster: # Replace NODATA_VALUE with NaN nodata = self.get_nodata_value() - try: # see issue #174 - NaN = numpy.ones(A.shape, A.dtype) * NAN - except: - pass + NaN = numpy.ones(A.shape, A.dtype) * NAN A = numpy.where(A == nodata, NaN, A) # Take care of possible scaling
Reverted dumb change made while testing win issue with NaN arrays
inasafe_inasafe
train
2a3108501ae5fe9238e74c50fe241c68fe4dc871
diff --git a/__tests__/layer/fully-connected.js b/__tests__/layer/fully-connected.js index <HASH>..<HASH> 100644 --- a/__tests__/layer/fully-connected.js +++ b/__tests__/layer/fully-connected.js @@ -86,8 +86,8 @@ describe('FullyConnected Layer', () => { describe('.compareFilterDeltas (back propagation)', () => { it('can compare a simplge matrix', () => { const inputWeights = [ - [1,3], - [2,4] + [1,2], + [3,4] ] const deltas = [[1,2,3,4]] const filterDeltas = [ @@ -103,16 +103,16 @@ describe('FullyConnected Layer', () => { }, }) assert.deepEqual(kernel(filterDeltas, inputWeights, deltas), [ - [1,3,2,4], - [2,6,4,8], - [3,9,6,12], - [4,12,8,16] + [1,2,3,4], + [2,4,6,8], + [3,6,9,12], + [4,8,12,16] ]) }) it('can add a simplge matrix', () => { const inputWeights = [ - [1,3], - [2,4] + [1,2], + [3,4] ] const deltas = [[1,2,3,4]] const filterDeltas = [ @@ -128,10 +128,10 @@ describe('FullyConnected Layer', () => { }, }) assert.deepEqual(kernel(filterDeltas, inputWeights, deltas), [ - [2, 5, 5, 8], - [7, 12, 11, 16], - [12, 19, 17, 24], - [17, 26, 23, 32] + [2, 4, 6, 8], + [7, 10, 13, 16], + [12, 16, 20, 24], + [17, 22, 27, 32] ]) }) }) @@ -159,8 +159,8 @@ describe('FullyConnected Layer', () => { }) it('can add a simple matrix', () => { const inputDeltas = [ - [1,3], - [2,4] + [1,2], + [3,4] ] const deltas = [[1,2,3,4]] const filters = [ @@ -175,7 +175,7 @@ describe('FullyConnected Layer', () => { connectionCount: 4 }, }) - assert.deepEqual(kernel(inputDeltas, deltas, filters), [[91, 103], [112, 124]]) + assert.deepEqual(kernel(inputDeltas, deltas, filters), [[91, 102], [113, 124]]) }) }) })
Make FullyConnected tests more incremental
BrainJS_brain.js
train
c1844dc1edf338938ebb9d96e8e87116d31c615e
diff --git a/lib/structures/Member.js b/lib/structures/Member.js index <HASH>..<HASH> 100644 --- a/lib/structures/Member.js +++ b/lib/structures/Member.js @@ -69,6 +69,38 @@ class Member { } } + get username() { + return this.user.username; + } + + get discriminator() { + return this.user.discriminator; + } + + get avatar() { + return this.user.avatar; + } + + get bot() { + return this.user.bot; + } + + get createdAt() { + return this.user.createdAt; + } + + get defaultAvatar() { + return this.user.defaultAvatar; + } + + get defaultAvatarURL() { + return this.user.defaultAvatarURL; + } + + get avatarURL() { + return this.user.avatarURL; + } + get mention() { return `<@!${this.id}>`; }
added User getters to Member (#<I>)
abalabahaha_eris
train
d5d1c837708efa1eaea1ebba46bbba0e6fedd34f
diff --git a/src/views/server/_saleModal.php b/src/views/server/_saleModal.php index <HASH>..<HASH> 100644 --- a/src/views/server/_saleModal.php +++ b/src/views/server/_saleModal.php @@ -2,7 +2,7 @@ use hipanel\modules\client\widgets\combo\ClientCombo; use hipanel\modules\finance\widgets\TariffCombo; -use dosamigos\datetimepicker\DateTimePicker; +use hipanel\widgets\DateTimePicker; use yii\widgets\ActiveForm; use yii\helpers\Html; use yii\helpers\Url; @@ -22,7 +22,7 @@ use yii\helpers\Url; 'tariffType' => 'server', ]) ?> <?= $form->field($model, 'sale_time')->widget(DateTimePicker::class, [ - 'clientOptions' => [ + 'pluginOptions' => [ 'autoclose' => true, ], ]) ?>
removed use of 2amigos DateTimePicker
hiqdev_hipanel-module-server
train
78f45edcc17e9c6916c13743b0b0c5487ca4c726
diff --git a/lib/netsuite/actions/add.rb b/lib/netsuite/actions/add.rb index <HASH>..<HASH> 100644 --- a/lib/netsuite/actions/add.rb +++ b/lib/netsuite/actions/add.rb @@ -11,9 +11,11 @@ module NetSuite def request connection.request :platformMsgs, :add do - soap.namespaces['xmlns:platformMsgs'] = 'urn:messages_2011_2.platform.webservices.netsuite.com' - soap.namespaces['xmlns:platformCore'] = 'urn:core_2011_2.platform.webservices.netsuite.com' - soap.namespaces['xmlns:listRel'] = 'urn:relationships_2011_2.lists.webservices.netsuite.com' + soap.namespaces['xmlns:platformMsgs'] = 'urn:messages_2011_2.platform.webservices.netsuite.com' + soap.namespaces['xmlns:platformCore'] = 'urn:core_2011_2.platform.webservices.netsuite.com' + soap.namespaces['xmlns:listRel'] = 'urn:relationships_2011_2.lists.webservices.netsuite.com' + soap.namespaces['xmlns:tranSales'] = 'urn:sales_2011_2.transactions.webservices.netsuite.com' + soap.namespaces['xmlns:platformCommon'] = 'urn:common_2011_2.platform.webservices.netsuite.com' soap.header = auth_header soap.body = request_body end diff --git a/lib/netsuite/records/invoice.rb b/lib/netsuite/records/invoice.rb index <HASH>..<HASH> 100644 --- a/lib/netsuite/records/invoice.rb +++ b/lib/netsuite/records/invoice.rb @@ -77,6 +77,11 @@ module NetSuite response.success? end + def to_record + attributes.delete(:custom_field_list) + super + end + end end end diff --git a/lib/netsuite/support/records.rb b/lib/netsuite/support/records.rb index <HASH>..<HASH> 100644 --- a/lib/netsuite/support/records.rb +++ b/lib/netsuite/support/records.rb @@ -6,7 +6,14 @@ module NetSuite def to_record attributes.inject({}) do |hash, (k,v)| - hash.store("#{record_namespace}:#{k.to_s.lower_camelcase}", v) + kname = "#{record_namespace}:#{k.to_s.lower_camelcase}" + if v.respond_to?(:internal_id) && v.internal_id + hash[:attributes!] ||= {} + hash[:attributes!][kname] ||= {} + hash[:attributes!][kname]['internalId'] = v.internal_id + end + v = v.to_record if v.respond_to?(:to_record) + hash[kname] = v hash end end
adding more stuff to get invoice add to work
NetSweet_netsuite
train
ad7295eec6c4750ec3ce65c0a226815741325632
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -69,6 +69,7 @@ setup( ], keywords='rest client http', packages=find_packages(exclude=['docs', 'tests*']), + setup_requires=['pytest-runner'], install_requires=install_requirements, tests_require=tests_requirements, cmdclass={
Add pytest-runner to setup.py
allisson_python-simple-rest-client
train
63e52abdc39b84f2f32281e4e2bc7ec791a86685
diff --git a/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/squid/check/ClassComplexityCheck.java b/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/squid/check/ClassComplexityCheck.java index <HASH>..<HASH> 100644 --- a/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/squid/check/ClassComplexityCheck.java +++ b/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/squid/check/ClassComplexityCheck.java @@ -21,31 +21,41 @@ package org.sonar.java.squid.check; import org.sonar.check.IsoCategory; +import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.check.RuleProperty; import org.sonar.squid.api.CheckMessage; import org.sonar.squid.api.SourceClass; import org.sonar.squid.measures.Metric; -@Rule(key = "ClassComplexityCheck", name = "ClassComplexityCheck", isoCategory = IsoCategory.Maintainability) +@Rule(key = "ClassCyclomaticComplexity", name = "Avoid too complex class", isoCategory = IsoCategory.Maintainability, + priority = Priority.MAJOR, description = "<p>The Cyclomatic Complexity is measured by the number of (&&, ||) operators " + + "and (if, while, do, for, ?:, catch, switch, case, return, throw) statements in the body of a class plus one for " + + "each constructor, method (but not getter/setter), static initializer, or instance initializer in the class. " + + "The last return stament in method, if exists, is not taken into account.</p>" + + "<p>Even when the Cyclomatic Complexity of a class is very high, this complexity might be well distributed among all methods. " + + "Nevertheless, most of the time, a very complex class is a class which breaks the " + + "<a href='http://en.wikipedia.org/wiki/Single_responsibility_principle'>Single Responsibility Principle</a> " + + "and which should be re-factored to be split in several classes.</p>") public class ClassComplexityCheck extends SquidCheck { - @RuleProperty(description = "Threshold.") - private Integer threshold; + @RuleProperty(description = "Maximum complexity allowed.", defaultValue = "200") + private Integer max; @Override public void visitClass(SourceClass sourceClass) { int complexity = sourceClass.getInt(Metric.COMPLEXITY); - if (complexity > threshold) { - CheckMessage message = new CheckMessage(this, "Class complexity exceeds " + threshold + "."); + if (complexity > max) { + CheckMessage message = new CheckMessage(this, "The Cyclomatic Complexity of this class is " + complexity + " which is greater than " + + max + " authorized."); message.setLine(sourceClass.getStartAtLine()); - message.setCost(complexity - threshold); + message.setCost(complexity - max); getSourceFile(sourceClass).log(message); } } - public void setThreshold(int threshold) { - this.threshold = threshold; + public void setMax(int max) { + this.max = max; } } diff --git a/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/squid/check/ClassComplexityCheckTest.java b/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/squid/check/ClassComplexityCheckTest.java index <HASH>..<HASH> 100644 --- a/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/squid/check/ClassComplexityCheckTest.java +++ b/plugins/sonar-squid-java-plugin/src/test/java/org/sonar/java/squid/check/ClassComplexityCheckTest.java @@ -42,7 +42,7 @@ public class ClassComplexityCheckTest { public void setUp() { squid = new Squid(new JavaSquidConfiguration()); ClassComplexityCheck check = new ClassComplexityCheck(); - check.setThreshold(5); + check.setMax(5); squid.registerVisitor(check); JavaAstScanner scanner = squid.register(JavaAstScanner.class); scanner.scanFile(getFile("/metrics/branches/NoBranches.java"));
SONAR-<I>: Create a SQUID rule : total class complexity should not exceed a pre-defined threshold
SonarSource_sonarqube
train
1e5526d8f05104bc5a1659fbaf4cad08f50e737f
diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -96,10 +96,13 @@ pygments_style = 'sphinx' # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -import sphinx_rtd_theme +try: + import sphinx_rtd_theme + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] +except ImportError: + pass html_theme = "sphinx_rtd_theme" -html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] RTD_NEW_THEME = True
Ignored failed theme import in docs.
openxc_openxc-python
train
72885cc59faa48ea7fcfc462b0dc44dbd01f4f7d
diff --git a/steam_idle_qt/QIdle.py b/steam_idle_qt/QIdle.py index <HASH>..<HASH> 100644 --- a/steam_idle_qt/QIdle.py +++ b/steam_idle_qt/QIdle.py @@ -84,7 +84,8 @@ class Idle(BaseIdle): self.logger.debug('on_steamDataReady with %d apps as parameter', len(apps)) newapp = apps.get(self.app.appid) if newapp: - self.logger.debug('updated app: OLD: %s NEW: %s', self.app, newapp) + self.logger.debug('updated app: OLD: %s', self.app) + self.logger.debug('updated app: NEW: %s', newapp) self.app = newapp self._idle() else: @@ -153,10 +154,8 @@ class MultiIdle(BaseIdle): for appid in list(self.idleChilds): newapp = apps.get(appid) if newapp: - self.logger.debug('updated app: OLD: %s NEW: %s', - self.idleChilds[appid][0].app, - newapp - ) + self.logger.debug('updated app: OLD: %s', self.idleChilds[appid][0].app) + self.logger.debug('updated app: NEW: %s', newapp) if newapp.playTime >= 2.0 or newapp.remainingDrops < 1: self.logger.debug('%s has reached 2h playtime or has no drops remaining', newapp) # Stop this child
improve readability of QIdle debug on data updates
jayme-github_steam_idle
train
a5e814e0f77dbe8fc6dc2ca68e25348cca917e76
diff --git a/lib/Models/WebMapServiceCatalogGroup.js b/lib/Models/WebMapServiceCatalogGroup.js index <HASH>..<HASH> 100644 --- a/lib/Models/WebMapServiceCatalogGroup.js +++ b/lib/Models/WebMapServiceCatalogGroup.js @@ -73,7 +73,15 @@ var WebMapServiceCatalogGroup = function(terria) { */ this.itemProperties = undefined; - knockout.track(this, ['url', 'dataCustodian', 'parameters', 'blacklist', 'titleField', 'itemProperties']); + /** + * Gets or sets a value indicating whether the list of layers queried from GetCapabilities should be + * flattened into a list with no hierarchy. + * @type {Boolean} + * @default false + */ + this.flatten = false; + + knockout.track(this, ['url', 'dataCustodian', 'parameters', 'blacklist', 'titleField', 'itemProperties', 'flatten']); }; inherit(CatalogGroup, WebMapServiceCatalogGroup); @@ -257,6 +265,13 @@ function addLayersRecursively(wmsGroup, layers, items, parent, supportsJsonGetFe layers = [layers]; } + if (layers.length === 1 && (!defined(layers[0].Name) || layers[0].Name.length === 0)) { + layers = layers[0].Layer; + if (!(layers instanceof Array)) { + layers = [layers]; + } + } + for (var i = 0; i < layers.length; ++i) { var layer = layers[i]; @@ -269,12 +284,42 @@ function addLayersRecursively(wmsGroup, layers, items, parent, supportsJsonGetFe } if (defined(layer.Layer)) { + var recurseItems = items; + + var group; + if (!wmsGroup.flatten) { + // Create a group for this layer + group = createWmsSubGroup(wmsGroup, layer); + recurseItems = group.items; + } + // WMS 1.1.1 spec section 7.1.4.5.2 says any layer with a Name property can be used // in the 'layers' parameter of a GetMap request. This is true in 1.0.0 and 1.3.0 as well. + var allName = '(All)'; + var originalNameForAll; if (defined(layer.Name) && layer.Name.length > 0) { - items.push(createWmsDataSource(wmsGroup, layer, supportsJsonGetFeatureInfo, supportsXmlGetFeatureInfo, xmlContentType, dataCustodian)); + var all = createWmsDataSource(wmsGroup, layer, supportsJsonGetFeatureInfo, supportsXmlGetFeatureInfo, xmlContentType, dataCustodian); + + if (!wmsGroup.flatten) { + originalNameForAll = all.name; + all.name = allName + ' ' + all.name; + } + + recurseItems.push(all); + } + + addLayersRecursively(wmsGroup, layer.Layer, recurseItems, layer, supportsJsonGetFeatureInfo, supportsXmlGetFeatureInfo, xmlContentType, dataCustodian); + + if (!wmsGroup.flatten) { + if (recurseItems.length === 1) { + if (recurseItems[0].name.indexOf(allName) === 0) { + recurseItems[0].name = originalNameForAll; + } + items.push(recurseItems[0]); + } else if (recurseItems.length > 0) { + items.push(group); + } } - addLayersRecursively(wmsGroup, layer.Layer, items, layer, supportsJsonGetFeatureInfo, supportsXmlGetFeatureInfo, xmlContentType, dataCustodian); } else { items.push(createWmsDataSource(wmsGroup, layer, supportsJsonGetFeatureInfo, supportsXmlGetFeatureInfo, xmlContentType, dataCustodian)); @@ -365,6 +410,20 @@ function createWmsDataSource(wmsGroup, layer, supportsJsonGetFeatureInfo, suppor return result; } +function createWmsSubGroup(wmsGroup, layer) { + var result = new CatalogGroup(wmsGroup.terria); + + if (wmsGroup.titleField === 'name') { + result.name = layer.Name; + } else if (wmsGroup.titleField === 'abstract') { + result.name = layer.Abstract; + } else { + result.name = layer.Title; + } + + return result; +} + function crsIsMatch(crs, matchValue) { if (crs === matchValue) { return true;
Use layer WMS hierarchy in GetCapabilities. If desired, the old behavior can be restored by setting flatten=true.
TerriaJS_terriajs
train
11864bc2091608eeec2e95d621c81cdb3e51b691
diff --git a/spyder/plugins/explorer/tests/test_explorer.py b/spyder/plugins/explorer/tests/test_explorer.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/explorer/tests/test_explorer.py +++ b/spyder/plugins/explorer/tests/test_explorer.py @@ -140,7 +140,11 @@ def test_single_click_to_open(qtbot, file_explorer): initial_index = treewidget.currentIndex() # To keep a reference def run_test_helper(single_click, initial_index): + # Reset the widget treewidget.setCurrentIndex(initial_index) + file_explorer.label3.setText('') + file_explorer.label1.setText('') + for i in range(4): # 4 items inside `/spyder/plugins/explorer/` qtbot.keyClick(treewidget, Qt.Key_Down) index = treewidget.currentIndex() @@ -149,7 +153,6 @@ def test_single_click_to_open(qtbot, file_explorer): full_path = os.path.join(cwd, path) # Skip folder to avoid changing the view for single click case if os.path.isfile(full_path): - index = treewidget.currentIndex() rect = treewidget.visualRect(index) pos = rect.center() qtbot.mouseClick(treewidget.viewport(), Qt.LeftButton, pos=pos) @@ -159,15 +162,15 @@ def test_single_click_to_open(qtbot, file_explorer): else: assert full_path != file_explorer.label1.text() - # Test double click to open - treewidget.set_single_click_to_open(False) - run_test_helper(single_click=False, initial_index=initial_index) - assert 'False' in file_explorer.label3.text() - # Test single click to open treewidget.set_single_click_to_open(True) - run_test_helper(single_click=True, initial_index=initial_index) assert 'True' in file_explorer.label3.text() + run_test_helper(single_click=True, initial_index=initial_index) + + # Test double click to open + treewidget.set_single_click_to_open(False) + assert 'False' in file_explorer.label3.text() + run_test_helper(single_click=False, initial_index=initial_index) if __name__ == "__main__": diff --git a/spyder/plugins/explorer/widgets.py b/spyder/plugins/explorer/widgets.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/explorer/widgets.py +++ b/spyder/plugins/explorer/widgets.py @@ -189,7 +189,7 @@ class DirView(QTreeView): self.filter_directories() def set_single_click_to_open(self, value): - """Set single click to open files.""" + """Set single click to open items.""" self.single_click_to_open = value self.parent_widget.sig_option_changed.emit('single_click_to_open', value)
Refactor code and fix docstrings and comments
spyder-ide_spyder
train
6ce2e6bcbda4689c4767ef21cc23c6fb4b7b3010
diff --git a/bundle/Controller/MenuController.php b/bundle/Controller/MenuController.php index <HASH>..<HASH> 100644 --- a/bundle/Controller/MenuController.php +++ b/bundle/Controller/MenuController.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace Netgen\Bundle\SiteBundle\Controller; use eZ\Publish\Core\MVC\ConfigResolverInterface; -use FOS\HttpCache\ResponseTagger; +use EzSystems\PlatformHttpCacheBundle\Handler\TagHandler; use Knp\Menu\Provider\MenuProviderInterface; use Knp\Menu\Renderer\RendererProviderInterface; use Symfony\Component\HttpFoundation\Request; @@ -29,20 +29,20 @@ class MenuController extends Controller protected $configResolver; /** - * @var \FOS\HttpCache\ResponseTagger + * @var \EzSystems\PlatformHttpCacheBundle\Handler\TagHandler */ - protected $responseTagger; + protected $tagHandler; public function __construct( MenuProviderInterface $menuProvider, RendererProviderInterface $menuRenderer, ConfigResolverInterface $configResolver, - ResponseTagger $responseTagger + TagHandler $tagHandler ) { $this->menuProvider = $menuProvider; $this->menuRenderer = $menuRenderer; $this->configResolver = $configResolver; - $this->responseTagger = $responseTagger; + $this->tagHandler = $tagHandler; } /** @@ -68,7 +68,7 @@ class MenuController extends Controller $menuLocationId = $menu->getAttribute('location-id'); if (!empty($menuLocationId)) { - $this->responseTagger->addTags(['location-' . $menuLocationId]); + $this->tagHandler->addLocationTags([$menuLocationId]); } $this->processCacheSettings($request, $response);
Typehint eZ Tag Handler to have access to methods from ContentTagInterface
netgen_site-bundle
train
ff9458b7dbf5ccdb3ef34df70a18542d67c4bcce
diff --git a/schedules/index.js b/schedules/index.js index <HASH>..<HASH> 100644 --- a/schedules/index.js +++ b/schedules/index.js @@ -2,6 +2,9 @@ var CronJob = require('cron').CronJob; exports.startJobs = function(options) { + if (options.env && vulpejs.app.env !== options.env) { + return; + } if (options.jobs) { options.jobs.forEach(function(job) { if (!job.timeZone) { @@ -30,4 +33,4 @@ exports.startJobs = function(options) { exports.start = function() { require(root.dir + '/schedules'); -}; \ No newline at end of file +};
add support to schedule only in specific env
activethread_vulpejs
train
b8c695fe887b3fd30accae374e548f25f4151879
diff --git a/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php b/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php index <HASH>..<HASH> 100644 --- a/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php +++ b/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php @@ -541,10 +541,16 @@ class ElasticSearchEngine implements SearchEngineInterface $sort['_score'] = $options->getSortOrder(); } elseif ($options->getSortBy() === SearchEngineOptions::SORT_CREATED_ON) { $sort['created_on'] = $options->getSortOrder(); + } elseif ($options->getSortBy() === 'recordid') { + $sort['recordid'] = $options->getSortOrder(); } else { $sort[sprintf('caption.%s', $options->getSortBy())] = $options->getSortOrder(); } + if (! array_key_exists('recordid', $sort)) { + $sort['recordid'] = $options->getSortOrder(); + } + return $sort; }
Always add recordid as last sort option
alchemy-fr_Phraseanet
train
758d7fcdc71413cf92c048373772bacc40ef387e
diff --git a/benchexec/tablegenerator/__init__.py b/benchexec/tablegenerator/__init__.py index <HASH>..<HASH> 100644 --- a/benchexec/tablegenerator/__init__.py +++ b/benchexec/tablegenerator/__init__.py @@ -240,7 +240,7 @@ def _get_column_type_heur(column, column_values): else: return ColumnType.status, None, None, 1 - column_type = None + column_type = ColumnType.count column_unit = column.unit # May be None column_source_unit = column.source_unit # May be None column_scale_factor = column.scale_factor # May be None @@ -254,8 +254,6 @@ def _get_column_type_heur(column, column_values): explicit_scale_defined = False else: explicit_scale_defined = True - if int(column_scale_factor) != column_scale_factor: - column_type = ColumnMeasureType(0) for value in column_values: @@ -267,36 +265,7 @@ def _get_column_type_heur(column, column_values): # As soon as one row's value is no number, the column type is 'text' if value_match is None: return text_type_tuple - - # If all rows are integers, column type is 'count' - elif not value_match.group(GROUP_DEC_PART) and (not column_type or column_type.type == ColumnType.count): - curr_column_unit = value_match.group(GROUP_UNIT) - - # If the units in two different rows of the same column differ, - # 1. Raise an error if an explicit unit is defined by the displayUnit attribute - # and the unit in the column cell differs from the defined sourceUnit, or - # 2. Handle the column as 'text' type, if no displayUnit was defined for the column's values. - # In that case, a unit different from the definition of sourceUnit does not lead to an error. - if curr_column_unit: - if column_source_unit is None and not explicit_scale_defined: - column_source_unit = curr_column_unit - elif column_source_unit != curr_column_unit: - raise Util.TableDefinitionError("Attribute sourceUnit different from real source unit: {} and {} (in column {})" - .format(column_source_unit, curr_column_unit, column.title)) - if column_unit and curr_column_unit != column_unit: - if explicit_unit_defined: - _check_unit_consistency(curr_column_unit, column_source_unit, column) - else: - return text_type_tuple - else: - column_unit = curr_column_unit - - column_type = ColumnType.count - if column_scale_factor is None: - column_scale_factor = _get_scale_factor(column_unit, column_source_unit, column) - - # If at least one row contains a decimal and all rows are numbers, column type is 'measure' - elif not (column_type and column_type.type == ColumnType.text): + else: curr_column_unit = value_match.group(GROUP_UNIT) # If the units in two different rows of the same column differ, @@ -308,8 +277,9 @@ def _get_column_type_heur(column, column_values): if column_source_unit is None and not explicit_scale_defined: column_source_unit = curr_column_unit elif column_source_unit != curr_column_unit: - raise Util.TableDefinitionError("Attribute sourceUnit different from real source unit: {} and {} (in column {})" - .format(column_source_unit, curr_column_unit, column.title)) + raise Util.TableDefinitionError( + "Attribute sourceUnit different from real source unit: {} and {} (in column {})" + .format(column_source_unit, curr_column_unit, column.title)) if column_unit and curr_column_unit != column_unit: if explicit_unit_defined: _check_unit_consistency(curr_column_unit, column_source_unit, column) @@ -330,10 +300,12 @@ def _get_column_type_heur(column, column_values): # Due to the scaling operation above, floats in the exponent notation may be created. Since this creates # special cases, immediately convert the value back to decimal notation. if value_match.group(GROUP_DEC_PART): - dec_digits_before_scale = len(value_match.group(GROUP_DEC_PART)) - 1 # - 1 since GROUP_DEC_PART includes the point + dec_digits_before_scale = len( + value_match.group(GROUP_DEC_PART)) - 1 # - 1 since GROUP_DEC_PART includes the point else: dec_digits_before_scale = 0 - max_number_of_dec_digits_after_scale = dec_digits_before_scale - math.ceil(math.log10(column_scale_factor)) + max_number_of_dec_digits_after_scale = max(0, dec_digits_before_scale - math.ceil( + math.log10(column_scale_factor))) scaled_value = "{0:.{1}f}".format(scaled_value, max_number_of_dec_digits_after_scale) scaled_value_match = REGEX_MEASURE.match(scaled_value) @@ -348,7 +320,15 @@ def _get_column_type_heur(column, column_values): if curr_dec_digits > max_dec_digits: max_dec_digits = curr_dec_digits - column_type = ColumnMeasureType(max_dec_digits) + if column_type.type == ColumnType.measure or \ + scaled_value_match.group(GROUP_DEC_PART) is not None or\ + value_match.group(GROUP_DEC_PART) is not None: + column_type = ColumnMeasureType(max_dec_digits) + + elif int(column_scale_factor) != column_scale_factor: + column_type = ColumnMeasureType(0) + else: + column_type = ColumnType.count if column_type: return column_type, column_unit, column_source_unit, column_scale_factor
Table generator: Restructure code for column type determination. First check for existing units, then determine scale factor, apply it and perform decision whether column is of type count or measure. Removes redundant code and eliminates special cases for count regarding scaling.
sosy-lab_benchexec
train
1adcd8b345ba555e30ff278e5e8d907113e0bdb3
diff --git a/manual_test/index.js b/manual_test/index.js index <HASH>..<HASH> 100644 --- a/manual_test/index.js +++ b/manual_test/index.js @@ -1,10 +1,10 @@ const dynamoose = require("../lib"); const dynamooseOld = require("dynamoose"); -// const Cat = dynamoose.model("Cat", { "name": String }); +const Cat = dynamoose.model("Cat", { "name": String }); +// console.log(Object.getPrototypeOf(Cat)); +// Cat(); +// console.log(Cat instanceof dynamoose.model); // const kitty = new Cat({ name: 'Zildjian' }); // kitty.save().then(() => console.log('meow')); - -const modelA = dynamooseOld.model("Cat", {"name": String}); -const modelB = new dynamooseOld.model("CatB", {"name": String}); diff --git a/test/Model.js b/test/Model.js index <HASH>..<HASH> 100644 --- a/test/Model.js +++ b/test/Model.js @@ -49,3 +49,15 @@ describe("Model", () => { }); }); }); + +describe("model", () => { + let Cat; + beforeEach(() => { + const schema = new dynamoose.Schema({"name": String}); + Cat = dynamoose.model("Cat", schema); + }); + + it("Should allow creating instance of Model", () => { + expect(() => new Cat({"name": "Bob"})).to.not.throw(); + }); +});
Adding test for creating instance of Model
dynamoosejs_dynamoose
train
7acede1df375d2ef1a2463589f7026d23f4161d5
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ }, "extra": { "branch-alias": { - "dev-master": "3.7.22-dev" + "dev-master": "3.7.23-dev" }, "laravel": { "providers": [ diff --git a/src/Traits/CrudModels.php b/src/Traits/CrudModels.php index <HASH>..<HASH> 100644 --- a/src/Traits/CrudModels.php +++ b/src/Traits/CrudModels.php @@ -1087,6 +1087,7 @@ trait CrudModels { } } $objModelo->save(); + if ($objModelo) { foreach ($config['campos'] as $campo => $detalles) { if (!isset($detalles["nodb"])) { @@ -1166,6 +1167,9 @@ trait CrudModels { } } } + if ($config['tabla']=="articles"){ + \Illuminate\Support\Facades\Artisan::call('view:clear'); + } return $objModelo; } else { return false; diff --git a/src/Views/crudgen/list.blade.php b/src/Views/crudgen/list.blade.php index <HASH>..<HASH> 100644 --- a/src/Views/crudgen/list.blade.php +++ b/src/Views/crudgen/list.blade.php @@ -363,7 +363,11 @@ if (old("__parametros","") != ""){ @else {{ number_format($value->{$columna}) }} @endif - @else + @elseif($datos['tipo']=="html") + <div style="max-height:200px;overflow-y:scroll;"> + {!! $value->{$columna} !!} + </div> + @else {!! $value->{$columna} !!} @endif @if(array_key_exists('enlace',$datos))
Clear View Cache after Article update. Limit html show in list.
sirgrimorum_crudgenerator
train
ad200922477fd90669b3d988a08d655b13550665
diff --git a/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/sequelize_v4.x.x.js b/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/sequelize_v4.x.x.js index <HASH>..<HASH> 100644 --- a/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/sequelize_v4.x.x.js +++ b/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/sequelize_v4.x.x.js @@ -3891,6 +3891,9 @@ declare module "sequelize" { ThroughAttributes, Through >, + static getAssociations<Target: Model<any>>(model: Class<Target>): Array<Association<this, Target>>; + static getAssociationForAlias<Target: Model<any>>(model: Class<Target>, alias: ?string): ?Association<this, Target>; + static associations: {[name: string]: Association<this, any>}, static tableName: string, static rawAttributes: {[name: string]: Attribute}, diff --git a/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/test_sequelize.js b/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/test_sequelize.js index <HASH>..<HASH> 100644 --- a/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/test_sequelize.js +++ b/definitions/npm/sequelize_v4.x.x/flow_v0.42.x-/test_sequelize.js @@ -227,6 +227,9 @@ Customer.belongsToMany(Branch, { through: 'branchCustomer' }); (Warehouse.attributes.blah.type: DataTypeAbstract); (Warehouse.primaryKeys.blah.type: DataTypeAbstract); +Warehouse.getAssociations(WarehouseBranch) +Warehouse.getAssociationForAlias(WarehouseBranch, 'blah') + // hasOne product.getBarcode(); product.getBarcode({ scope: null }).then(b => b && b.code);
fix(sequelize): add missing Model methods (#<I>)
flow-typed_flow-typed
train
bf5df19e4a365f2f79462c2310adcb14b219c648
diff --git a/Lib/fontbakery/specifications/googlefonts.py b/Lib/fontbakery/specifications/googlefonts.py index <HASH>..<HASH> 100644 --- a/Lib/fontbakery/specifications/googlefonts.py +++ b/Lib/fontbakery/specifications/googlefonts.py @@ -4680,7 +4680,7 @@ def com_google_fonts_test_163(ttFont): platformID=plat): if len(familyname_str + stylename_str) > 20: failed = True - yield FAIL, ("The combined length of family and style" + yield WARN, ("The combined length of family and style" " exceeds 20 chars in the following '{}' entries:" " FONT_FAMILY_NAME = '{}' / SUBFAMILY_NAME = '{}'" "").format(PLATID_STR[plat], diff --git a/Lib/fontbakery/specifications/googlefonts_test.py b/Lib/fontbakery/specifications/googlefonts_test.py index <HASH>..<HASH> 100644 --- a/Lib/fontbakery/specifications/googlefonts_test.py +++ b/Lib/fontbakery/specifications/googlefonts_test.py @@ -2187,7 +2187,7 @@ def test_id_163(): status, message = list(test(ttFont))[-1] assert status == PASS - # Then we FAIL with the long family/style names + # Then we emit a WARNing with the long family/style names # that were used as an example on the glyphs tutorial # (at https://glyphsapp.com/tutorials/multiple-masters-part-3-setting-up-instances): for index, name in enumerate(ttFont["name"].names): @@ -2200,9 +2200,9 @@ def test_id_163(): ttFont["name"].names[index].string = "WithAVeryLongStyleName".encode(name.getEncoding()) break - print ("Test FAIL with a bad font...") + print ("Test WARN with a bad font...") status, message = list(test(ttFont))[-1] - assert status == FAIL + assert status == WARN def test_id_164():
emit only a WARNing for bad fonts on test/<I> (issue #<I>)
googlefonts_fontbakery
train
59b3e79c705e2d91b8237e2ed4de956d66063195
diff --git a/server/src/main/java/io/druid/server/coordinator/DruidCoordinator.java b/server/src/main/java/io/druid/server/coordinator/DruidCoordinator.java index <HASH>..<HASH> 100644 --- a/server/src/main/java/io/druid/server/coordinator/DruidCoordinator.java +++ b/server/src/main/java/io/druid/server/coordinator/DruidCoordinator.java @@ -57,7 +57,6 @@ import io.druid.guice.annotations.Self; import io.druid.segment.IndexIO; import io.druid.server.DruidNode; import io.druid.server.coordinator.helper.DruidCoordinatorBalancer; -import io.druid.server.coordinator.helper.DruidCoordinatorCleanup; import io.druid.server.coordinator.helper.DruidCoordinatorCleanupOvershadowed; import io.druid.server.coordinator.helper.DruidCoordinatorCleanupUnneeded; import io.druid.server.coordinator.helper.DruidCoordinatorHelper;
derby seems to be working..?
apache_incubator-druid
train
cd4bca69adafebbf5f6e00fb7a57d3920a85bf83
diff --git a/src/ApiProblemRenderer.php b/src/ApiProblemRenderer.php index <HASH>..<HASH> 100644 --- a/src/ApiProblemRenderer.php +++ b/src/ApiProblemRenderer.php @@ -29,6 +29,10 @@ class ApiProblemRenderer extends Renderer $response = $this->writeBody($response, $output); $response = $response->withHeader('Content-type', $contentType); + + if ($problem->getStatus() >= 100) { + $response = $response->withStatus($problem->getStatus()); + } return $response; } diff --git a/tests/ApiProblemRendererTest.php b/tests/ApiProblemRendererTest.php index <HASH>..<HASH> 100644 --- a/tests/ApiProblemRendererTest.php +++ b/tests/ApiProblemRendererTest.php @@ -15,7 +15,7 @@ class ApiProblemRendererTest extends \PHPUnit_Framework_TestCase * * @dataProvider rendererProvider */ - public function testRenderer($mediaType, $data, $expectedMediaType, $expectedBody, $pretty) + public function testRenderer($mediaType, $problem, $expectedMediaType, $expectedBody, $pretty) { $renderer = new Renderer($pretty); @@ -25,10 +25,14 @@ class ApiProblemRendererTest extends \PHPUnit_Framework_TestCase $response = new Response(); - $response = $renderer->render($request, $response, $data); + $response = $renderer->render($request, $response, $problem); $this->assertSame($expectedMediaType, $response->getHeaderLine('Content-Type')); $this->assertSame($expectedBody, (string)$response->getBody()); + + if ($problem->getStatus()) { + $this->assertSame($problem->getStatus(), $response->getStatusCode()); + } } /** @@ -44,11 +48,13 @@ class ApiProblemRendererTest extends \PHPUnit_Framework_TestCase */ public function rendererProvider() { - $data = new ApiProblem("foo"); + $problem = new ApiProblem("foo"); + $problem->setStatus(400); $outputData = [ 'title' => 'foo', 'type' => 'about:blank', + 'status' => 400, ]; @@ -56,19 +62,19 @@ class ApiProblemRendererTest extends \PHPUnit_Framework_TestCase $expectedPrettyJson = json_encode($outputData, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); $expectedXML = '<?xml version="1.0"?>' . PHP_EOL - . '<problem><title>foo</title><type>about:blank</type></problem>' + . '<problem><title>foo</title><type>about:blank</type><status>400</status></problem>' . PHP_EOL; return [ - ['application/hal+json', $data, 'application/problem+json', $expectedJson, false], - ['application/json', $data, 'application/problem+json', $expectedJson, false], - ['vnd.foo/anything+json', $data, 'application/problem+json', $expectedJson, false], - ['application/json', $data, 'application/problem+json', $expectedPrettyJson, true], - ['application/hal+xml', $data, 'application/problem+xml', $expectedXML, false], - ['application/xml', $data, 'application/problem+xml', $expectedXML, false], - ['text/xml', $data, 'application/problem+xml', $expectedXML, false], - ['vnd.foo/anything+xml', $data, 'application/problem+xml', $expectedXML, false], - ['text/html', $data, 'application/problem+json', $expectedJson, false], + ['application/hal+json', $problem, 'application/problem+json', $expectedJson, false], + ['application/json', $problem, 'application/problem+json', $expectedJson, false], + ['vnd.foo/anything+json', $problem, 'application/problem+json', $expectedJson, false], + ['application/json', $problem, 'application/problem+json', $expectedPrettyJson, true], + ['application/hal+xml', $problem, 'application/problem+xml', $expectedXML, false], + ['application/xml', $problem, 'application/problem+xml', $expectedXML, false], + ['text/xml', $problem, 'application/problem+xml', $expectedXML, false], + ['vnd.foo/anything+xml', $problem, 'application/problem+xml', $expectedXML, false], + ['text/html', $problem, 'application/problem+json', $expectedJson, false], ]; } @@ -77,7 +83,7 @@ class ApiProblemRendererTest extends \PHPUnit_Framework_TestCase */ public function testCaseWhenDataIsNotAnApiProblemObject() { - $data = 'Alex'; + $problem = 'Alex'; $request = (new Request()) ->withUri(new Uri('http://example.com')) @@ -86,6 +92,6 @@ class ApiProblemRendererTest extends \PHPUnit_Framework_TestCase $renderer = new Renderer(); $this->setExpectedException(RuntimeException::class, 'Data is not an ApiProblem object'); - $response = $renderer->render($request, $response, $data); + $response = $renderer->render($request, $response, $problem); } }
Set response status in ApiProblemRenderer If the status is >= <I>, then set the response's status code as they are supposed to be the same thing.
akrabat_rka-content-type-renderer
train
dac0b89f8cd14b4dd64d657db6e35e4c320659ac
diff --git a/src/util/bidi.js b/src/util/bidi.js index <HASH>..<HASH> 100644 --- a/src/util/bidi.js +++ b/src/util/bidi.js @@ -122,7 +122,7 @@ export let bidiOrdering = (function() { // Character types for codepoints 0 to 0xff let lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN" // Character types for codepoints 0x600 to 0x6f9 - let arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmrrmmNmmmmrr1111111111" + let arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111" function charType(code) { if (code <= 0xf7) return lowTypes.charAt(code) else if (0x590 <= code && code <= 0x5f4) return "R"
Correct bidi types for remaining Arabic chars
codemirror_CodeMirror
train
c81f6096b86c6ff4c131854a8f3de418182cc8e9
diff --git a/lib/wireprotocol/get_more.js b/lib/wireprotocol/get_more.js index <HASH>..<HASH> 100644 --- a/lib/wireprotocol/get_more.js +++ b/lib/wireprotocol/get_more.js @@ -37,13 +37,6 @@ function getMore(server, ns, cursorState, batchSize, options, callback) { return; } - // Raw, return all the extracted documents - if (cursorState.raw) { - cursorState.documents = response.documents; - cursorState.cursorId = response.cursorId; - return callback(null, response.documents); - } - // We have an error detected if (response.documents[0].ok === 0) { return callback(new MongoError(response.documents[0]));
fix(get-more): documents are already returned as raw in this case
mongodb-js_mongodb-core
train
bc787e708a0800a95d7d4d2c7aa5aec9bbb2365c
diff --git a/tests/pipeline/test_multidimensional_dataset.py b/tests/pipeline/test_multidimensional_dataset.py index <HASH>..<HASH> 100644 --- a/tests/pipeline/test_multidimensional_dataset.py +++ b/tests/pipeline/test_multidimensional_dataset.py @@ -62,7 +62,7 @@ class TestDataSetFamily(ZiplineTestCase): def test_empty_extra_dims(self): msg = ( "DataSetFamily must be defined with non-empty extra_dims," - " or with `__abstract__ = True`" + " or with `_abstract = True`" ) with assert_raises_str(ValueError, msg): class NoExtraDims(DataSetFamily): @@ -73,7 +73,7 @@ class TestDataSetFamily(ZiplineTestCase): extra_dims = [] class AbstractParent(DataSetFamily): - __abstract__ = True + _abstract = True with assert_raises_str(ValueError, msg): class NoExtraDimsChild(AbstractParent): @@ -84,7 +84,7 @@ class TestDataSetFamily(ZiplineTestCase): extra_dims = [] class AbstractChild(AbstractParent): - __abstract__ = True + _abstract = True class Child(AbstractParent): extra_dims = [ diff --git a/zipline/pipeline/data/dataset.py b/zipline/pipeline/data/dataset.py index <HASH>..<HASH> 100644 --- a/zipline/pipeline/data/dataset.py +++ b/zipline/pipeline/data/dataset.py @@ -608,7 +608,7 @@ class DataSetFamilyMeta(abc.ABCMeta): columns[k] = v dict_[k] = _DataSetFamilyColumn(k) - is_abstract = dict_.pop('__abstract__', False) + is_abstract = dict_.pop('_abstract', False) self = super(DataSetFamilyMeta, cls).__new__( cls, @@ -625,7 +625,7 @@ class DataSetFamilyMeta(abc.ABCMeta): if not extra_dims: raise ValueError( 'DataSetFamily must be defined with non-empty' - ' extra_dims, or with `__abstract__ = True`', + ' extra_dims, or with `_abstract = True`', ) class BaseSlice(self._SliceType): @@ -721,7 +721,7 @@ class DataSetFamily(with_metaclass(DataSetFamilyMeta)): This sliced dataset represents the rows from the higher dimensional dataset where ``(dimension_0 == 'a') & (dimension_1 == 'e')``. """ - __abstract__ = True # Removed by metaclass + _abstract = True # Removed by metaclass domain = GENERIC slice_ndim = 2
MAINT: Don't use system-reserved name pattern > _Any_ use of __*__ names, in any context, that does not follow > explicitly documented use, is subject to breakage without warning. <URL>
quantopian_zipline
train
00c2cf33c15011e63761bb7cc2a8fe735dd423bc
diff --git a/services/TransactionService/src/index.php b/services/TransactionService/src/index.php index <HASH>..<HASH> 100644 --- a/services/TransactionService/src/index.php +++ b/services/TransactionService/src/index.php @@ -4,7 +4,6 @@ namespace Islandora\TransactionService; require_once __DIR__.'/../vendor/autoload.php'; -use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use Islandora\Chullo\Chullo; use Silex\Application; @@ -17,8 +16,7 @@ $app = new Application(); $app['debug'] = true; $app['fedora'] = function () use ($app) { - $client = new Client(['base_uri' => 'http://127.0.0.1:8080/fcrepo/rest']); - return new Chullo($client); + return Chullo::create('http://127.0.0.1:8080/fcrepo/rest'); }; $app->post(
Updating PR to use static factory function for Chullo.
Islandora-CLAW_islandora
train
78b2f91369dcf2a53d81f628bc2ab717abc4ce12
diff --git a/dist/bottom_line.js b/dist/bottom_line.js index <HASH>..<HASH> 100644 --- a/dist/bottom_line.js +++ b/dist/bottom_line.js @@ -664,23 +664,11 @@ * @param {Function} cb - callback function to be called for each element * @param {Object=} ctx_ - optional context */ - // TODO proper implementation for arguments. It will break on phantomJS otherwise each: function(cb, ctx_) { - //if(_.typeOf(this) === 'arguments') {console.log('args!!')} - - //if(this.hasOwnProperty('length')) // we need to distinguish here because for example phantomJS will not let us use for in on arguments - //{ - // for(var key = 0; key < this.length; key++) { - // if (!this.hasOwnProperty(key)) continue; - // if (cb.call(ctx_, this[key], key, this) === false) break; - // } - //} - //else { - for (var key in this) { - if (!this.hasOwnProperty(key)) continue; - if (cb.call(ctx_, this[key], key, this) === false) break; - } - //} + for (var key in this) { + if (!this.hasOwnProperty(key)) continue; + if (cb.call(ctx_, this[key], key, this) === false) break; + } }, /** * Inverse iterator. If the value false is returned, iteration is canceled. This can be used to stop iteration @@ -693,7 +681,7 @@ * @return {Array} - this array for chaining */ eachRight: function(step_, cb, ctx_) { - if(typeof(step_) === 'function') {ctx_ = cb; cb = step_; step_ = 1} + if(typeof(step_) === 'function') {ctx_ = cb; cb = step_} if(this.length) return _.arr.methods.eachRight.apply(this, arguments); // handle arguments. this._.keys()._.eachRight(function(key) { diff --git a/src/obj.js b/src/obj.js index <HASH>..<HASH> 100644 --- a/src/obj.js +++ b/src/obj.js @@ -306,7 +306,7 @@ construct('obj', {native:Object}, { * @return {Array} - this array for chaining */ eachRight: function(step_, cb, ctx_) { - if(typeof(step_) === 'function') {ctx_ = cb; cb = step_; step_ = 1} + if(typeof(step_) === 'function') {ctx_ = cb; cb = step_} if(this.length) return _.arr.methods.eachRight.apply(this, arguments); // handle arguments. this._.keys()._.eachRight(function(key) {
- small optimization for obj.eachRight
unnoon_bottom_line
train
c8f38ac5c4420e97b23e754f971ba014d567002a
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ from distutils.core import setup, Extension ghalton_module = Extension("_ghalton", sources=["src/Halton_wrap.cxx", "src/Halton.cpp"]) setup (name = "ghalton", - version = 0.5, + version = "0.5", author = "Francois-Michel De Rainville", author_email = "f.derainville@gmail.com", license = "LICENSE.txt",
Corrected version number install error.
fmder_ghalton
train
f93de7d86accae9df5738bbbe70322fa152ab5e4
diff --git a/src/chart/sankey/SankeyView.js b/src/chart/sankey/SankeyView.js index <HASH>..<HASH> 100644 --- a/src/chart/sankey/SankeyView.js +++ b/src/chart/sankey/SankeyView.js @@ -286,6 +286,14 @@ export default echarts.extendChartView({ el.cursor = 'move'; } + el.highlight = function () { + this.trigger('emphasis'); + }; + + el.downplay = function () { + this.trigger('normal'); + }; + el.focusNodeAdjHandler && el.off('mouseover', el.focusNodeAdjHandler); el.unfocusNodeAdjHandler && el.off('mouseout', el.unfocusNodeAdjHandler);
add highlight and downplay for every node in sankey
apache_incubator-echarts
train
4c03af6fdbbb7c3b7ac68436138f9783a8981ac3
diff --git a/spec/branch_cover_spec.rb b/spec/branch_cover_spec.rb index <HASH>..<HASH> 100644 --- a/spec/branch_cover_spec.rb +++ b/spec/branch_cover_spec.rb @@ -37,7 +37,10 @@ RSpec::Matchers.define :have_correct_branch_coverage do |filename, lineno| match do |lines| code, answers = parse(lines, lineno) @file_coverage = DeepCover::FileCoverage.new(path: filename, source: code.join("\n"), lineno: lineno) - @file_coverage.execute_file + + # Disable some annoying warning by ruby. We are testing edge cases, so warnings are to be expected. + with_warnings(nil) { @file_coverage.execute_file } + cov = @file_coverage.branch_cover errors = cov.zip(answers, code).each_with_index.reject do |(a, expected, line), i| actual = strip_when_unimportant(line, a) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -29,3 +29,11 @@ if %w(true 1).include?(ENV["WITHOUT_PENDING"]) RSpec::Core::Formatters::DocumentationFormatter.send(:prepend, FormatterOverrides) RSpec::Core::Formatters::ProgressFormatter.send(:prepend, FormatterOverrides) end + + +def with_warnings(flag) + old_verbose, $VERBOSE = $VERBOSE, flag + yield +ensure + $VERBOSE = old_verbose +end
Remove ruby warnings when executing samples
deep-cover_deep-cover
train
394074424a5aec2709c1d0c3afce70727dde0adb
diff --git a/lib/accesslib.php b/lib/accesslib.php index <HASH>..<HASH> 100755 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -399,6 +399,38 @@ function has_capability($capability, $context=NULL, $userid=NULL, $doanything=tr $ACCESS[$userid], $doanything); } +/* + * Uses 1 DB query to answer whether a user is an admin at the sitelevel. + * It depends on DB schema >=1.7 but does not depend on the new datastructures + * in v1.9 (context.path, or $USER->access) + * + * Will return true if the userid has any of + * - moodle/site:config + * - moodle/legacy:admin + * - moodle/site:doanything + * + * @param int $userid + * @returns bool $isadmin + */ +function is_siteadmin($userid) { + global $CFG; + + $sql = "SELECT COUNT(u.id) + FROM mdl_user u + JOIN mdl_role_assignments ra + ON ra.userid=u.id + JOIN mdl_context ctx + ON ctx.id=ra.contextid + JOIN mdl_role_capabilities rc + ON (ra.roleid=rc.roleid AND rc.contextid=ctx.id) + WHERE ctx.contextlevel=10 + AND rc.capability IN ('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything') + AND u.id={$USER->id}"; + + $isadmin = (get_field_sql($sql) == 0); + return $isadmin; +} + function get_course_from_path ($path) { // assume that nothing is more than 1 course deep if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
accesslib: Introducing is_siteadmin() to reliably check for siteadmins is_siteadmin checks a few key capabilities to suss out if the user is an admin. The main virtue of the function is that it does not use the accesslib infrastructure -- it reads directly from the DB, which is useful for the <I> accesslib upgrade.
moodle_moodle
train
fdb7961953ca92864287b590d1301a9a4f28dfec
diff --git a/build/build.go b/build/build.go index <HASH>..<HASH> 100644 --- a/build/build.go +++ b/build/build.go @@ -496,15 +496,13 @@ func (s *Session) BuildPackage(pkg *PackageData) error { return err } - pkg.Archive.JSDecls = []*compiler.Decl{} for _, jsFile := range pkg.JSFiles { code, err := ioutil.ReadFile(filepath.Join(pkg.Dir, jsFile)) if err != nil { return err } - pkg.Archive.JSDecls = append(pkg.Archive.JSDecls, &compiler.Decl{ - DeclCode: append(append([]byte("\t(function() {\n"), code...), []byte("\n\t}).call($global);\n")...), - }) + code = append(append([]byte("\t(function() {\n"), code...), []byte("\n\t}).call($global);\n")...) + pkg.Archive.IncJSCode = append(pkg.Archive.IncJSCode, code...) } if s.options.Verbose { diff --git a/compiler/compiler.go b/compiler/compiler.go index <HASH>..<HASH> 100644 --- a/compiler/compiler.go +++ b/compiler/compiler.go @@ -37,7 +37,7 @@ type Archive struct { Imports []string ExportData []byte Declarations []*Decl - JSDecls []*Decl + IncJSCode []byte FileSet []byte Minified bool @@ -184,8 +184,8 @@ func WritePkgCode(pkg *Archive, dceSelection map[*Decl]struct{}, minify bool, w panic(err) } } - for _, d := range pkg.JSDecls { - if _, err := w.Write(d.DeclCode); err != nil { + if pkg.IncJSCode != nil { + if _, err := w.Write(pkg.IncJSCode); err != nil { return err } }
using []byte and compiler.Archive.IncJSCode to handle *.inc.js files
gopherjs_gopherjs
train
fad52ea2fc34369942a48947ad237345f5421466
diff --git a/gns3server/version.py b/gns3server/version.py index <HASH>..<HASH> 100644 --- a/gns3server/version.py +++ b/gns3server/version.py @@ -23,8 +23,8 @@ # or negative for a release candidate or beta (after the base version # number has been incremented) -__version__ = "2.2.19" -__version_info__ = (2, 2, 19, 0) +__version__ = "2.2.20dev1" +__version_info__ = (2, 2, 20, 99) if "dev" in __version__: try:
Development on <I>dev1
GNS3_gns3-server
train
e3aadf4896812dd18d16651854104243df65558c
diff --git a/raiden/tests/utils/transfer.py b/raiden/tests/utils/transfer.py index <HASH>..<HASH> 100644 --- a/raiden/tests/utils/transfer.py +++ b/raiden/tests/utils/transfer.py @@ -24,7 +24,7 @@ from raiden.transfer.state import ( balanceproof_from_envelope, make_empty_merkle_tree, ) -from raiden.utils import sha3 +from raiden.utils import pex, sha3 from raiden.utils.signer import LocalSigner, Signer from raiden.utils.typing import ( Balance, @@ -104,7 +104,11 @@ def transfer( with Timeout(seconds=timeout): wait_for_unlock.get() - payment_status.payment_done.wait() + msg = ( + f'transfer from {pex(initiator_app.raiden.address)} ' + f'to {pex(target_app.raiden.address)} failed.' + ) + assert payment_status.payment_done.get(), msg def assert_synced_channel_state(
tests: added assert to the transfer util
raiden-network_raiden
train
85edee26f369c6d5b1ac1a99f1bd4b3ff5fa9a41
diff --git a/lib/accesslib.php b/lib/accesslib.php index <HASH>..<HASH> 100755 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -4525,7 +4525,7 @@ function get_users_by_capability($context, $capability, $fields='', $sort='', $sortby = $sort ? " ORDER BY $sort " : ''; // User lastaccess JOIN - if (strpos($sort, 'ul.timeaccess') === FALSE) { // user_lastaccess is not required MDL-13810 + if ((strpos($sort, 'ul.timeaccess') === FALSE) and (strpos($fields, 'ul.timeaccess') === FALSE)) { // user_lastaccess is not required MDL-13810 $uljoin = ''; } else { $uljoin = "LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul
MDL-<I> Merged from <I>
moodle_moodle
train
8744d367a26d4308c6f9d38d63382b2f866265c7
diff --git a/src/Arrayy.php b/src/Arrayy.php index <HASH>..<HASH> 100644 --- a/src/Arrayy.php +++ b/src/Arrayy.php @@ -324,6 +324,28 @@ class Arrayy extends \ArrayObject } /** + * Check if an (case-insensitive) string is in the current array. + * + * @param string $value + * + * @return bool + */ + public function containsCaseInsensitive($value) + { + return in_array( + UTF8::strtolower($value), + array_map( + array( + new UTF8(), + 'strtolower', + ), + $this->array + ), + true + ); + } + + /** * Check if the given key/index exists in the array. * * @param mixed $key Key/index to search for diff --git a/tests/ArrayyTest.php b/tests/ArrayyTest.php index <HASH>..<HASH> 100644 --- a/tests/ArrayyTest.php +++ b/tests/ArrayyTest.php @@ -111,6 +111,28 @@ class ArrayyTest extends PHPUnit_Framework_TestCase /** * @return array */ + public function containsCaseInsensitiveProvider() + { + return array( + array(array(), null, false), + array(array(), false, false), + array(array(0 => false), false, true), + array(array(0 => true), true, true), + array(array(0 => -9), -9, true), + array(array(1.18), 1.18, true), + array(array(1.18), 1.17, false), + array(array('string', '💩'), '💩', true), + array(array(' ', 'É'), 'é', true), + array(array('string', 'foo'), 'foo', true), + array(array('string', 'Foo'), 'foo', true), + array(array('string', 'foo123'), 'foo', false), + array(array('String', 'foo123'), 'foo', false), + ); + } + + /** + * @return array + */ public function containsProvider() { return array( @@ -1535,6 +1557,20 @@ class ArrayyTest extends PHPUnit_Framework_TestCase } /** + * @dataProvider containsCaseInsensitiveProvider() + * + * @param array $array + * @param mixed $value + * @param $expected + */ + public function testContainsCaseInsensitive($array, $value, $expected) + { + $arrayy = new A($array); + + self::assertEquals($expected, $arrayy->containsCaseInsensitive($value)); + } + + /** * @dataProvider containsProvider() * * @param array $array
[+]: added "containsCaseInsensitive()"
voku_Arrayy
train
939a8f58e691c6750d864b1f30f88f4ee7203c33
diff --git a/lib/dynamodb.js b/lib/dynamodb.js index <HASH>..<HASH> 100644 --- a/lib/dynamodb.js +++ b/lib/dynamodb.js @@ -1,7 +1,5 @@ 'use strict'; - // @todo: nice handling of throtteling https://github.com/aws/aws-sdk-js/issues/402 for now let aws take care of it - var Promise = require('promise') var util = require('@awspilot/dynamodb-util') var AWS = require('aws-sdk') @@ -938,12 +936,14 @@ Request.prototype.query = function(callback) { var $this = this - // only build if not not passed as raw if ( this.KeyConditionExpression === undefined ) - this.buildKeyConditionExpression() + this.buildKeyConditionExpression() // will set KeyConditionExpression, ExpressionAttributeNames, ExpressionAttributeValues - this.buildProjectionExpression() // this will set ProjectionExpression and ExpressionAttributeNames - this.buildFilterExpression() + if ( this.ProjectionExpression === undefined ) + this.buildProjectionExpression() // will set ProjectionExpression, ExpressionAttributeNames + + if ( this.FilterExpression === undefined ) + this.buildFilterExpression() // will set FilterExpression, ExpressionAttributeNames, ExpressionAttributeValues var $thisQuery = { TableName: this.tableName, @@ -1003,7 +1003,10 @@ Request.prototype.scan = function( callback ) { var $this = this - this.buildProjectionExpression() // this will set ProjectionExpression and ExpressionAttributeNames + + if ( this.ProjectionExpression === undefined ) + this.buildProjectionExpression() // this will set ProjectionExpression and ExpressionAttributeNames + this.buildFilterExpression() var $thisQuery = { TableName: this.tableName, @@ -1579,7 +1582,7 @@ } - // RAW functions + // RAW functions, used by dynamodb-sql Request.prototype.RawIndexName = function( value ) { this.IndexName = value return this @@ -1608,14 +1611,14 @@ this.ExpressionAttributeValues = value return this } - Request.prototype.RawAttributesToGet = function( value ) { - this.AttributesToGet = value - return this - } Request.prototype.RawProjectionExpression = function( value ) { this.ProjectionExpression = value return this } + Request.prototype.RawFilterExpression = function( value ) { + this.FilterExpression = value + return this + } DynamoDB.Raw = function(data) {
+ Raw functions for FilterExpression and ProjectionExpression
awspilot_dynamodb-oop
train
0fcb74ea4704c98066010695316038903ada02a6
diff --git a/src/Wave/Framework/Application/Controller.php b/src/Wave/Framework/Application/Controller.php index <HASH>..<HASH> 100644 --- a/src/Wave/Framework/Application/Controller.php +++ b/src/Wave/Framework/Application/Controller.php @@ -21,8 +21,15 @@ class Controller implements \Serializable, ControllerInterface protected $conditions = array(); + private $strict = false; + private $arguments = array(); + public function setStrict($strict) + { + $this->strict = $strict; + } + /** * Sets the pattern of the object/controller * @@ -131,7 +138,12 @@ class Controller implements \Serializable, ControllerInterface $pattern .= '?'; } - $regex = '#^' . $pattern . '$#i'; + $regex = '#^' . $pattern . '#i'; + if ($this->strict) { + $regex = '#^' . $pattern . '$#i'; + } + + if (preg_match($regex, urldecode($path), $values)) { $this->arguments = new ArgumentsContext($this, $values);
Strict pattern matching (Beneficial for optional trailing slashes)
DaGhostman_codewave
train
a6250716c9c9f3002474666681cba52debfa5ef5
diff --git a/pyneuroml/pynml.py b/pyneuroml/pynml.py index <HASH>..<HASH> 100644 --- a/pyneuroml/pynml.py +++ b/pyneuroml/pynml.py @@ -1288,19 +1288,25 @@ def evaluate_arguments(args): "number of arguments: %d given, 0-4 required" % num_neuron_args) sys.exit(-1) - post_args = "-neuron %s" % ' '.join(args.neuron[:-1]) - elif args.netpyne is not None: + other_args = [(a if a!='-neuron' else '') for a in args.neuron] + post_args = "-neuron %s" % ' '.join(other_args) + + elif args.netpyne is not None: # Note: either a lems file or nml2 file is allowed here... confirm_file_exists(f) num_netpyne_args = len(args.netpyne) + if num_netpyne_args < 0 or num_netpyne_args > 4: print_comment("ERROR: The \'-netpyne\' option was given an invalid " "number of arguments: %d given, 0-4 required" % num_netpyne_args) sys.exit(-1) - post_args = "-netpyne %s" % ' '.join(args.netpyne[:-1]) + + other_args = [(a if a!='-netpyne' else '') for a in args.netpyne] + post_args = "-netpyne %s" % ' '.join(other_args) + elif args.svg: confirm_neuroml_file(f) post_args = "-svg"
Improved support for -neuron -run and -netpyne -run
NeuroML_pyNeuroML
train
4797aed4823af9adcacbfadef2e5d0c010c82a27
diff --git a/bin/jsx.js b/bin/jsx.js index <HASH>..<HASH> 100644 --- a/bin/jsx.js +++ b/bin/jsx.js @@ -1,5 +1,5 @@ #!/usr/bin/env node if (__filename !== process.argv[1] || process.argv.length < 3) throw new Error('this should only be used to load a jsx file') -process.argv.splice(1, 1) -require('import-jsx')(require('path').resolve(process.argv[1])) +process.argv.splice(1, 1, require('path').resolve(process.argv[2])) +require('import-jsx')(process.argv[1])
Properly set argv[1] for jsx tests Otherwise tap.fullname isn't set to the appropriate path, resulting in potentially conflicting snapshot output files.
tapjs_node-tap
train
46e7bf783580a88a82154f8439998be9f9b56c96
diff --git a/shinken/daemon.py b/shinken/daemon.py index <HASH>..<HASH> 100644 --- a/shinken/daemon.py +++ b/shinken/daemon.py @@ -455,7 +455,8 @@ class Daemon(object): self.debug_output.append("Replacing previous instance %d" % pid) try: - os.kill(pid, signal.SIGQUIT) + pgid = os.getpgid(pid) + os.killpg(pgid, signal.SIGQUIT) except os.error as err: if err.errno != errno.ESRCH: raise
When replacing a daemon kill all processes in the group.
Alignak-monitoring_alignak
train
45230c1b714e1ef9b647c3ae81bdd0792c44ab19
diff --git a/chimp_campaigns.go b/chimp_campaigns.go index <HASH>..<HASH> 100644 --- a/chimp_campaigns.go +++ b/chimp_campaigns.go @@ -21,10 +21,10 @@ const ( campaign_send_endpoint string = "/campaigns/send.json" ) -func (a *ChimpAPI) getContent(apiKey string, cid string, options map[string]interface{}, contentFormat string) ([]SendResponse, error) { +func (a *ChimpAPI) getContent(cid string, options map[string]interface{}, contentFormat string) ([]SendResponse, error) { var response []SendResponse var params map[string]interface{} = make(map[string]interface{}) - params["apikey"] = apiKey + params["apikey"] = a.Key params["cid"] = cid params["options"] = options err := parseChimpJson(a, fmt.Sprintf(get_content_endpoint, contentFormat), params, &response)
remove apikey, get it from chimpapi struct. thanks @kevinburke
mattbaird_gochimp
train
0efcf817b927527bf5af0c5dccd43e1adcbb184f
diff --git a/lib/valid-schema.js b/lib/valid-schema.js index <HASH>..<HASH> 100644 --- a/lib/valid-schema.js +++ b/lib/valid-schema.js @@ -275,10 +275,6 @@ module.exports = function(schema) { if (!isOfType(schema, 'object')) { throw new Error('Schema is ' + prettyType(getType(schema)) + ' when it should be an object'); } - if (schema.type === undefined) { - throw new Error('Schema: \'type\' is required'); - } - assertType(schema, 'type', ['string', 'array'], []); validateSchema(schema, []); }; diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,9 @@ }, { "name": "Nicolas Pelletier" + }, + { + "name": "Damien (feugy)" } ], "repository": { diff --git a/test/schema-basic-test.js b/test/schema-basic-test.js index <HASH>..<HASH> 100644 --- a/test/schema-basic-test.js +++ b/test/schema-basic-test.js @@ -34,9 +34,8 @@ var schemaStringOrNull = { vows.describe('Schema Basic').addBatch({ 'when schema is undefined': schemaShouldBeInvalid(undefined, { errMsg: 'Schema is undefined' }), 'when schema is not an object': schemaShouldBeInvalid(schemaNotAnObject, { errMsg: 'Schema is a string when it should be an object' }), - 'when type attribue is missing': schemaShouldBeInvalid(schemaWithoutType, { errMsg: 'Schema: \'type\' is required' }), - 'when type attribute is not a string': schemaShouldBeInvalid(schemaInvalidType, { errMsg: 'Schema: \'type\' attribute is an integer when it should be either a string or an array' }), + 'when type attribute is neither a string nor an array': schemaShouldBeInvalid(schemaInvalidType, { errMsg: 'Schema: \'type\' attribute is an integer when it should be either a string or an array' }), 'when type attribute is \'object\'': schemaShouldBeValid(schemaEmptyObject), 'when type attribute is \'array\'': schemaShouldBeValid(schemaEmptyArray), - 'when type attribute is [\'string\', \'null\']': schemaShouldBeValid(schemaStringOrNull) + 'when type attribute is a union type with simple types': schemaShouldBeValid(schemaStringOrNull) }).export(module);
removed unncessary code. minor change to tests.
oferei_json-gate
train
fc7003876ad67aa7105d0c4359b5493f5d8ecf0f
diff --git a/pxml/test.py b/pxml/test.py index <HASH>..<HASH> 100644 --- a/pxml/test.py +++ b/pxml/test.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # file: $Id: pxml.py 346 2012-08-12 17:22:39Z griffin $ # desc: pretty-prints xml, nothing more :)
added "utf-8" declaration
metagriffin_pxml
train
09c8c036b471f5183e81f1c70064074d439553da
diff --git a/src/mure.js b/src/mure.js index <HASH>..<HASH> 100644 --- a/src/mure.js +++ b/src/mure.js @@ -131,7 +131,8 @@ class Mure extends Model { .then(dbEntry => { let mureFile = { filename, - metadata: dbEntry.metadata + metadata: dbEntry.metadata, + _rev: dbEntry._rev }; if (dbEntry._attachments[filename].data) { mureFile.base64string = dbEntry._attachments[filename].data;
Include the revision hash with each file request
origraph_origraph.js
train
c025a1194b89841b94aa76d3f9640e9667b2aea2
diff --git a/src/schema/Schema.js b/src/schema/Schema.js index <HASH>..<HASH> 100644 --- a/src/schema/Schema.js +++ b/src/schema/Schema.js @@ -260,7 +260,6 @@ export class Schema { } } } - ctx.tags = this if (item instanceof Pair) return item.toString(ctx, onComment, onChompKeep) if (!tagObj) tagObj = this.getTagObject(item) const props = this.stringifyProps(item, tagObj, ctx) diff --git a/src/stringify/stringifyString.js b/src/stringify/stringifyString.js index <HASH>..<HASH> 100644 --- a/src/stringify/stringifyString.js +++ b/src/stringify/stringifyString.js @@ -203,7 +203,7 @@ function blockString({ comment, type, value }, ctx, onComment, onChompKeep) { function plainString(item, ctx, onComment, onChompKeep) { const { comment, type, value } = item - const { actualString, implicitKey, indent, inFlow, tags } = ctx + const { actualString, doc, implicitKey, indent, inFlow } = ctx if ( (implicitKey && /[\n[\]{},]/.test(value)) || (inFlow && /[[\]{},]/.test(value)) @@ -245,7 +245,7 @@ function plainString(item, ctx, onComment, onChompKeep) { // Verify that output will be parsed as a string, as e.g. plain numbers and // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), // and others in v1.1. - if (actualString && typeof tags.resolveScalar(str).value !== 'string') { + if (actualString && typeof doc.schema.resolveScalar(str).value !== 'string') { return doubleQuotedString(value, ctx) } const body = implicitKey
Drop "tags" from stringifier context
eemeli_yaml
train
1a269d5aab3ce61d18b73e6982db95a1397cfeea
diff --git a/django_ses/__init__.py b/django_ses/__init__.py index <HASH>..<HASH> 100644 --- a/django_ses/__init__.py +++ b/django_ses/__init__.py @@ -91,7 +91,7 @@ class SESBackend(BaseEmailBackend): proxy_user=self._proxy_user, proxy_pass=self._proxy_pass, ) - except: + except Exception: if not self.fail_silently: raise @@ -101,7 +101,7 @@ class SESBackend(BaseEmailBackend): try: self.connection.close() self.connection = None - except: + except Exception: if not self.fail_silently: raise diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -106,7 +106,7 @@ DESCRIPTION = "A Django email backend for Amazon's Simple Email Service" LONG_DESCRIPTION = None try: LONG_DESCRIPTION = open('README.rst').read() -except: +except Exception: pass CLASSIFIERS = [
Don't catch BaseExceptions (#<I>) Exiting exceptions, such as `KeyboardInterrupt`, inherit from `BaseException` rather than `Exception`. The idiomatic way to catch any unexpected exception is to only catch `Exception`, so that `BaseExceptions` still bubble up.
django-ses_django-ses
train
9dbe6c0e02c124ba10d93ad721b7fe37eec9d691
diff --git a/client/driver/java_test.go b/client/driver/java_test.go index <HASH>..<HASH> 100644 --- a/client/driver/java_test.go +++ b/client/driver/java_test.go @@ -98,6 +98,12 @@ func TestJavaDriver_Start_Wait(t *testing.T) { // expect the timeout b/c it's a long lived process break } + + // need to kill long lived process + err = handle.Kill() + if err != nil { + t.Fatalf("Error: %s", err) + } } func TestJavaDriver_Start_Kill_Wait(t *testing.T) { @@ -137,6 +143,12 @@ func TestJavaDriver_Start_Kill_Wait(t *testing.T) { case <-time.After(2 * time.Second): t.Fatalf("timeout") } + + // need to kill long lived process + err = handle.Kill() + if err != nil { + t.Fatalf("Error: %s", err) + } } func cleanupFile(path string) error {
clean up orphaned java processes
hashicorp_nomad
train
d658d3264605d0eda71e916023a3d016e7cda7ff
diff --git a/src/Functions/Polynomial.php b/src/Functions/Polynomial.php index <HASH>..<HASH> 100644 --- a/src/Functions/Polynomial.php +++ b/src/Functions/Polynomial.php @@ -16,11 +16,15 @@ namespace Math\Functions; * Current features: * o Print a human readable representation of a polynomial * o Evaluate a polynomial at any real number + * o Polynomial differentiation (exact) + * o Polynomial integration (indefinite integral) * * Example: - * $polynomial = new Polynomial([1, -8, 12, 3]) - * echo $polynomial; // prints "x³ - 8x² + 12x + 3" - * echo $polynomial(4); // prints -31 + * $polynomial = new Polynomial([1, -8, 12, 3]); + * echo $polynomial; // prints "x³ - 8x² + 12x + 3" + * echo $polynomial(4); // prints -31 + * echo $polynomial->$differentiate() // prints "3x² - 16x + 12" + * echo $polynomial->$integrate() // prints "0.25x⁴ - 2.6666666666667x³ + 6x² + 3x" * * https://en.wikipedia.org/wiki/Polynomial */ @@ -168,6 +172,8 @@ class Polynomial * Example: $polynomial = new Polynomial([3, -16, 12]); // 3x² - 16x + 12 * $integral = $polynomial->integrate(); // x³ - 8x² + 12x * + * Note that this method assumes the constant of integration to be 0. + * * @return object The integral of our polynomial object, also a polynomial object */ public function integrate()
Added integrate and differentiate to class description (with examples)
markrogoyski_math-php
train
328aa14f0a19694d33d88aa97437747ba774a9e2
diff --git a/recipe/exceptions.py b/recipe/exceptions.py index <HASH>..<HASH> 100644 --- a/recipe/exceptions.py +++ b/recipe/exceptions.py @@ -7,8 +7,8 @@ class BadRecipe(Exception): class InvalidColumnError(Exception): - def __init__(self, *args, column_name='', **kwargs): - self.column_name = column_name + def __init__(self, *args, **kwargs): + self.column_name = kwargs.pop('column_name', None) if not args: # default exception message args = ['Invalid column "{}"'.format(column_name)]
argh, get rid of py3-only syntax
juiceinc_recipe
train
de4e08f5445f136056b257b3ee77fe6a3e10152f
diff --git a/ioc_module.js b/ioc_module.js index <HASH>..<HASH> 100644 --- a/ioc_module.js +++ b/ioc_module.js @@ -36,6 +36,7 @@ const { const { CorrelationService, FlowNodeInstanceService, + FlowNodePersistenceFacade, DeleteProcessModelService, ProcessModelService, TimerFacade, @@ -95,6 +96,10 @@ function registerServices(container) { .dependencies('CorrelationService', 'ExternalTaskRepository', 'FlowNodeInstanceService', 'IamService', 'ProcessModelService'); container + .register('FlowNodePersistenceFacade', FlowNodePersistenceFacade) + .dependencies('FlowNodeInstanceService', 'LoggingApiService', 'MetricsApiService'); + + container .register('FlowNodeInstanceService', FlowNodeInstanceService) .dependencies('FlowNodeInstanceRepository', 'IamService');
:sparkles: Add FlowNodePersistenceFacade to ioc
process-engine_process_engine_core
train
b7a2a856b5c7b47f52d5a7c3a624173548bef247
diff --git a/test/test-examples-server-pre-post-functions.js b/test/test-examples-server-pre-post-functions.js index <HASH>..<HASH> 100644 --- a/test/test-examples-server-pre-post-functions.js +++ b/test/test-examples-server-pre-post-functions.js @@ -9,17 +9,27 @@ var alexaAppServer = require("../index"); describe("Alexa App Server with Examples & Pre/Post functions", function() { var testServer; + var fired; var sampleLaunchReq = JSON.parse(fs.readFileSync("test/sample-launch-req.json", 'utf8')); before(function() { + fired = {}; testServer = alexaAppServer.start({ port: 3000, server_root: 'examples', - pre: function(appServer) { console.log("pre function fired!"); }, - post: function(appServer) { console.log("post function fired!"); }, - preRequest: function(json,request,response) { console.log("preRequest function fired!"); }, - postRequest : function(json,request,response) { console.log("postRequest function fired!"); } + pre: function(appServer) { + fired.pre = true; + }, + post: function(appServer) { + fired.post = true; + }, + preRequest: function(json, request, response) { + fired.preRequest = true; + }, + postRequest: function(json, request, response) { + fired.postRequest = true; + } }); }); @@ -28,15 +38,26 @@ describe("Alexa App Server with Examples & Pre/Post functions", function() { }); it("mounts hello world app (GET)", function() { - return request(testServer.express) - .get('/alexa/helloworld') - .expect(200); + return request(testServer.express) + .get('/alexa/helloworld') + .expect(200).then(function(response) { + expect(fired.pre).to.equal(true); + expect(fired.post).to.equal(true); + // only called for actual Alexa requests + expect(fired.preRequest).to.equal(undefined); + expect(fired.postRequest).to.equal(undefined); + }); }); it("mounts hello world app (POST)", function() { - return request(testServer.express) - .post('/alexa/helloworld') - .send(sampleLaunchReq) - .expect(200); + return request(testServer.express) + .post('/alexa/helloworld') + .send(sampleLaunchReq) + .expect(200).then(function(response) { + expect(fired.pre).to.equal(true); + expect(fired.post).to.equal(true); + expect(fired.preRequest).to.equal(true); + expect(fired.postRequest).to.equal(true); + }); }); -}); \ No newline at end of file +});
Added tests of post/pre functions being fired.
alexa-js_alexa-app-server
train
701c0f07b9e03cc7cced48364aa370ad3ba35bed
diff --git a/stage1/init/init.go b/stage1/init/init.go index <HASH>..<HASH> 100644 --- a/stage1/init/init.go +++ b/stage1/init/init.go @@ -383,17 +383,18 @@ func getArgsEnv(p *stage1commontypes.Pod, flavor string, debug bool, n *networki return nil, nil, fmt.Errorf("unrecognized stage1 flavor: %q", flavor) } - // link journal only if the host is running systemd - if util.IsRunningSystemd() { - // we write /etc/machine-id here because systemd-nspawn needs it to link - // the container's journal to the host - mPath := filepath.Join(common.Stage1RootfsPath(p.Root), "etc", "machine-id") - mID := strings.Replace(p.UUID.String(), "-", "", -1) + // systemd-nspawn needs /etc/machine-id to link the container's journal + // to the host. Since systemd-v230, /etc/machine-id is mandatory, see + // https://github.com/systemd/systemd/commit/e01ff70a77e781734e1e73a2238af2e9bf7967a8 + mPath := filepath.Join(common.Stage1RootfsPath(p.Root), "etc", "machine-id") + mID := strings.Replace(p.UUID.String(), "-", "", -1) - if err := ioutil.WriteFile(mPath, []byte(mID), 0644); err != nil { - log.FatalE("error writing /etc/machine-id", err) - } + if err := ioutil.WriteFile(mPath, []byte(mID), 0644); err != nil { + log.FatalE("error writing /etc/machine-id", err) + } + // link journal only if the host is running systemd + if util.IsRunningSystemd() { args = append(args, "--link-journal=try-guest") keepUnit, err := util.RunningFromSystemService() @@ -408,6 +409,8 @@ func getArgsEnv(p *stage1commontypes.Pod, flavor string, debug bool, n *networki if keepUnit { args = append(args, "--keep-unit") } + } else { + args = append(args, "--link-journal=no") } if !debug {
stage1: always write /etc/machine-id Prepare rkt for systemd-<I> in stage1. rkt was previously only writing /etc/machine-id in the stage1 rootfs if systemd was running on the host. However, new versions of systemd always require /etc/machine-id, see: <URL>, but we want rkt to be ready. Fixes <URL>
rkt_rkt
train
d4d3a82514076621936bae127f2b6d917927bb99
diff --git a/src/saml2/cache.py b/src/saml2/cache.py index <HASH>..<HASH> 100644 --- a/src/saml2/cache.py +++ b/src/saml2/cache.py @@ -139,7 +139,7 @@ class Cache(object): :return: A possibly empty list of entity identifiers """ cni = code(name_id) - return self._db[cni].keys() + return list(self._db[cni].keys()) def receivers(self, name_id): """ Another name for entities() just to make it more logic in the IdP diff --git a/src/saml2/client_base.py b/src/saml2/client_base.py index <HASH>..<HASH> 100644 --- a/src/saml2/client_base.py +++ b/src/saml2/client_base.py @@ -149,7 +149,7 @@ class Base(Entity): raise IdpUnspecified("Too many IdPs to choose from: %s" % eids) try: - srvs = self.metadata.single_sign_on_service(eids.keys()[0], binding) + srvs = self.metadata.single_sign_on_service(list(eids.keys())[0], binding) return destinations(srvs)[0] except IndexError: raise IdpUnspecified("No IdP to send to given the premises") diff --git a/tests/test_51_client.py b/tests/test_51_client.py index <HASH>..<HASH> 100644 --- a/tests/test_51_client.py +++ b/tests/test_51_client.py @@ -268,7 +268,7 @@ class TestClient: assert nid_policy.format == saml.NAMEID_FORMAT_TRANSIENT def test_create_auth_request_vo(self): - assert self.client.config.vorg.keys() == [ + assert list(self.client.config.vorg.keys()) == [ "urn:mace:example.com:it:tek"] ar_str = "%s" % self.client.create_authn_request( @@ -1257,7 +1257,7 @@ class TestClientWithDummy(): print(resp) assert resp assert len(resp) == 1 - assert resp.keys() == entity_ids + assert list(resp.keys()) == entity_ids response = resp[entity_ids[0]] assert isinstance(response, LogoutResponse)
Fix python3 .keys() as a view failures
IdentityPython_pysaml2
train
ee2b16c3c0fb31568efba631dd6991cc8e9f0093
diff --git a/buildozer/targets/android.py b/buildozer/targets/android.py index <HASH>..<HASH> 100644 --- a/buildozer/targets/android.py +++ b/buildozer/targets/android.py @@ -474,12 +474,13 @@ class TargetAndroid(Target): ext = 'tar.bz2' else: ext = 'zip' - archive = 'android-ndk-r{0}-' + _platform + '-{1}.' + ext + archive = 'android-ndk-r{0}-' + _platform + '{1}.' + ext is_64 = (os.uname()[4] == 'x86_64') else: raise SystemError('Unsupported platform: {}'.format(platform)) architecture = 'x86_64' if is_64 else 'x86' + architecture = '' if _version >= 23 else f'-{architecture}' unpacked = 'android-ndk-r{0}' archive = archive.format(self.android_ndk_version, architecture) unpacked = unpacked.format(self.android_ndk_version)
Changes for NDK<I> (#<I>) The arch no longer used in url for NDK<I>+
kivy_buildozer
train
2c11bc3234fd2ff6ec7a55826df13fe6e5a8ae4b
diff --git a/microcosm/loaders.py b/microcosm/loaders.py index <HASH>..<HASH> 100644 --- a/microcosm/loaders.py +++ b/microcosm/loaders.py @@ -71,13 +71,15 @@ def load_from_python_file(metadata): return _load_from_file(metadata, load_python_module) -def load_from_environ(metadata): +def _load_from_environ(metadata, value_func=None): """ Load configuration from environment variables. Any environment variable prefixed with the metadata's name will be used to recursively set dictionary keys, splitting on '_'. + :param value_func: a mutator for the envvar's value (if any) + """ # We'll match the ennvar name against the metadata's name. The ennvar # name must be uppercase and hyphens in names converted to underscores. @@ -109,13 +111,26 @@ def load_from_environ(metadata): dct[key_part.lower()] = dict() dct = dct[key_part.lower()] # set the value for the final part - try: - dct[key_parts[-1].lower()] = loads(value) - except ValueError: - dct[key_parts[-1].lower()] = value + dct[key_parts[-1].lower()] = value_func(value) if value_func else value return config +def load_from_environ(metadata): + """ + Load configuration from environment variables. + + """ + return _load_from_environ(metadata) + + +def load_from_environ_as_json(metadata): + """ + Load configuration from environment variables as JSON + + """ + return _load_from_environ(metadata, value_func=loads) + + def load_each(*loaders): """ Loader factory that combines a series of loaders. diff --git a/microcosm/tests/test_loaders.py b/microcosm/tests/test_loaders.py index <HASH>..<HASH> 100644 --- a/microcosm/tests/test_loaders.py +++ b/microcosm/tests/test_loaders.py @@ -16,6 +16,7 @@ from microcosm.loaders import ( get_config_filename, load_each, load_from_environ, + load_from_environ_as_json, load_from_json_file, load_from_python_file, ) @@ -134,7 +135,7 @@ def test_load_from_environ_json(): metadata = Metadata("foo") with envvar("FOO_BAR", '["baz"]'): with envvar("FOO_BAZ", 'true'): - config = load_from_environ(metadata) + config = load_from_environ_as_json(metadata) assert_that(config, is_(equal_to({"bar": ["baz"], "baz": True})))
Separate JSON and non-JSON parsing from envvars. There's too much risk that we'll do the wrong thing for other libraries that read our configuration if we force JSON.
globality-corp_microcosm
train
bcf1bbc636fc4c112112598ab25bc21b5d6e4eb6
diff --git a/filterdb/db.go b/filterdb/db.go index <HASH>..<HASH> 100644 --- a/filterdb/db.go +++ b/filterdb/db.go @@ -51,6 +51,9 @@ type FilterDatabase interface { // target block hash cannot be found, then ErrFilterNotFound is to be // returned. FetchFilter(*chainhash.Hash, FilterType) (*gcs.Filter, error) + + // PurgeFilters purge all filters with a given type from persistent storage. + PurgeFilters(FilterType) error } // FilterStore is an implementation of the FilterDatabase interface which is @@ -107,6 +110,29 @@ func New(db walletdb.DB, params chaincfg.Params) (*FilterStore, error) { }, nil } +// PurgeFilters purge all filters with a given type from persistent storage. +// +// NOTE: This method is a part of the FilterDatabase interface. +func (f *FilterStore) PurgeFilters(fType FilterType) error { + return walletdb.Update(f.db, func(tx walletdb.ReadWriteTx) error { + filters := tx.ReadWriteBucket(filterBucket) + + switch fType { + case RegularFilter: + if err := filters.DeleteNestedBucket(regBucket); err != nil { + return err + } + if _, err := filters.CreateBucket(regBucket); err != nil { + return err + } + default: + return fmt.Errorf("unknown filter type: %v", fType) + } + + return nil + }) +} + // putFilter stores a filter in the database according to the corresponding // block hash. The passed bucket is expected to be the proper bucket for the // passed filter type.
filterdb: Implement PurgeFilters. This commit adds the ability to purge the filters from the db. It is enables mobile apps that use neutrino in the background to implement their own eviction strategy preventing from the db to grow unboundly.
lightninglabs_neutrino
train
0eaee81a13d4d6b17e93fb42192e1b6823c7acb2
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -41,4 +41,5 @@ The project documentation can be found at http://natural.rtfd.org/ url='https://github.com/tehmaze/natural', packages=['natural'], package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']}, + install_requires=['six'], )
Add six to install_requires
tehmaze_natural
train
86f63d9b60e8ea02a3bee301a8ec87e5f77f5f58
diff --git a/UnitySDK/Assets/ML-Agents/Scripts/Academy.cs b/UnitySDK/Assets/ML-Agents/Scripts/Academy.cs index <HASH>..<HASH> 100644 --- a/UnitySDK/Assets/ML-Agents/Scripts/Academy.cs +++ b/UnitySDK/Assets/ML-Agents/Scripts/Academy.cs @@ -92,7 +92,7 @@ namespace MLAgents "docs/Learning-Environment-Design-Academy.md")] public abstract class Academy : MonoBehaviour { - private const string k_ApiVersion = "API-10"; + private const string k_ApiVersion = "API-11"; /// Temporary storage for global gravity value /// Used to restore oringal value when deriving Academy modifies it diff --git a/gym-unity/setup.py b/gym-unity/setup.py index <HASH>..<HASH> 100755 --- a/gym-unity/setup.py +++ b/gym-unity/setup.py @@ -5,7 +5,7 @@ import sys from setuptools import setup, find_packages from setuptools.command.install import install -VERSION = "0.11.0.dev0" +VERSION = "0.11.0" class VerifyVersionCommand(install): diff --git a/ml-agents-envs/mlagents/envs/environment.py b/ml-agents-envs/mlagents/envs/environment.py index <HASH>..<HASH> 100644 --- a/ml-agents-envs/mlagents/envs/environment.py +++ b/ml-agents-envs/mlagents/envs/environment.py @@ -72,7 +72,7 @@ class UnityEnvironment(BaseUnityEnvironment): atexit.register(self._close) self.port = base_port + worker_id self._buffer_size = 12000 - self._version_ = "API-10" + self._version_ = "API-11" self._loaded = ( False ) # If true, this means the environment was successfully loaded diff --git a/ml-agents-envs/setup.py b/ml-agents-envs/setup.py index <HASH>..<HASH> 100644 --- a/ml-agents-envs/setup.py +++ b/ml-agents-envs/setup.py @@ -3,7 +3,7 @@ import sys from setuptools import setup from setuptools.command.install import install -VERSION = "0.11.0.dev0" +VERSION = "0.11.0" here = os.path.abspath(os.path.dirname(__file__)) diff --git a/ml-agents/setup.py b/ml-agents/setup.py index <HASH>..<HASH> 100644 --- a/ml-agents/setup.py +++ b/ml-agents/setup.py @@ -5,7 +5,7 @@ import sys from setuptools import setup, find_namespace_packages from setuptools.command.install import install -VERSION = "0.11.0.dev0" +VERSION = "0.11.0" here = os.path.abspath(os.path.dirname(__file__))
Update package and communicator versions to <I>
Unity-Technologies_ml-agents
train
b43e91a6d6bb0f8efd7b0bd978d64e36c8c2e9d3
diff --git a/src/Drupal/Driver/Cores/CoreInterface.php b/src/Drupal/Driver/Cores/CoreInterface.php index <HASH>..<HASH> 100644 --- a/src/Drupal/Driver/Cores/CoreInterface.php +++ b/src/Drupal/Driver/Cores/CoreInterface.php @@ -42,6 +42,14 @@ interface CoreInterface { public function getModuleList(); /** + * Returns a list of all extension absolute paths. + * + * @return array + * An array of absolute paths to enabled extensions. + */ + public function getExtensionPathList(); + + /** * Clear caches. */ public function clearCache(); diff --git a/src/Drupal/Driver/Cores/Drupal6.php b/src/Drupal/Driver/Cores/Drupal6.php index <HASH>..<HASH> 100644 --- a/src/Drupal/Driver/Cores/Drupal6.php +++ b/src/Drupal/Driver/Cores/Drupal6.php @@ -423,6 +423,21 @@ class Drupal6 extends AbstractCore { /** * {@inheritdoc} */ + public function getExtensionPathList() { + $paths = array(); + + // Get enabled modules. + $modules = $this->getModuleList(); + foreach ($modules as $module) { + $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . \drupal_get_path('module', $module); + } + + return $paths; + } + + /** + * {@inheritdoc} + */ protected function expandEntityFields($entity_type, \stdClass $entity) { return parent::expandEntityFields($entity_type, $entity); } diff --git a/src/Drupal/Driver/Cores/Drupal7.php b/src/Drupal/Driver/Cores/Drupal7.php index <HASH>..<HASH> 100644 --- a/src/Drupal/Driver/Cores/Drupal7.php +++ b/src/Drupal/Driver/Cores/Drupal7.php @@ -433,6 +433,21 @@ class Drupal7 extends AbstractCore { /** * {@inheritdoc} */ + public function getExtensionPathList() { + $paths = array(); + + // Get enabled modules. + $modules = $this->getModuleList(); + foreach ($modules as $module) { + $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . \drupal_get_path('module', $module); + } + + return $paths; + } + + /** + * {@inheritdoc} + */ public function getEntityFieldTypes($entity_type) { $return = array(); $fields = field_info_field_map(); diff --git a/src/Drupal/Driver/Cores/Drupal8.php b/src/Drupal/Driver/Cores/Drupal8.php index <HASH>..<HASH> 100644 --- a/src/Drupal/Driver/Cores/Drupal8.php +++ b/src/Drupal/Driver/Cores/Drupal8.php @@ -328,6 +328,20 @@ class Drupal8 extends AbstractCore { /** * {@inheritdoc} */ + public function getExtensionPathList() { + $paths = array(); + + // Get enabled modules. + foreach (\Drupal::moduleHandler()->getModuleList() as $module) { + $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . $module->getPath(); + } + + return $paths; + } + + /** + * {@inheritdoc} + */ public function getEntityFieldTypes($entity_type) { $return = array(); $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type); diff --git a/src/Drupal/Driver/DrupalDriver.php b/src/Drupal/Driver/DrupalDriver.php index <HASH>..<HASH> 100644 --- a/src/Drupal/Driver/DrupalDriver.php +++ b/src/Drupal/Driver/DrupalDriver.php @@ -146,19 +146,7 @@ class DrupalDriver implements DriverInterface, SubDriverFinderInterface { $this->bootstrap(); } - // Get enabled modules. - $modules = $this->getCore()->getModuleList(); - $paths = array(); - foreach ($modules as $module) { - $paths[] = $this->drupalRoot . DIRECTORY_SEPARATOR . \drupal_get_path('module', $module); - } - - // Themes. - // @todo - // - // Active profile. - // @todo - return $paths; + return $this->getCore()->getExtensionPathList(); } /**
Move more logic into cores for extension handling. - Fixes #<I> - Adds a `getExtensionPathList()` method to the core interface.
jhedstrom_DrupalDriver
train
3d9cf35e1f9c8418715563f7ede4bf9bc362e236
diff --git a/cotyledon/_service_manager.py b/cotyledon/_service_manager.py index <HASH>..<HASH> 100644 --- a/cotyledon/_service_manager.py +++ b/cotyledon/_service_manager.py @@ -200,10 +200,11 @@ class ServiceManager(_utils.SignalManager): self._wait_forever() def _on_wakeup(self): - dead_pid = self._get_last_pid_died() - while dead_pid is not None: - self._restart_dead_worker(dead_pid) - dead_pid = self._get_last_pid_died() + info = self._get_last_worker_died() + while info is not None: + service_id, worker_id = info + self._start_worker(service_id, worker_id) + info = self._get_last_worker_died() self._adjust_workers() def _on_signal_received(self, sig): @@ -265,21 +266,12 @@ class ServiceManager(_utils.SignalManager): for worker_id in range(running_workers, conf.workers): self._stop_worker(service_id, worker_id) - def _restart_dead_worker(self, dead_pid): + def _get_last_worker_died(self): + """Return the last died worker information or None""" for service_id in self._running_services: # We copy the list to clean the orignal one processes = list(self._running_services[service_id].items()) for process, worker_id in processes: - if process.pid == dead_pid: - del self._running_services[service_id][process] - self._start_worker(service_id, worker_id) - return - LOG.error('pid %d not in service known pids list', dead_pid) - - def _get_last_pid_died(self): - """Return the last died service or None""" - for service_id, processes in self._running_services.items(): - for process, worker_id in processes.items(): if not process.is_alive(): if process.exitcode < 0: sig = _utils.signal_to_name(process.exitcode) @@ -288,7 +280,8 @@ class ServiceManager(_utils.SignalManager): else: LOG.info('Child %(pid)d exited with status %(code)d', dict(pid=process.pid, code=process.exitcode)) - return process.pid + del self._running_services[service_id][process] + return service_id, worker_id def _fast_exit(self, signo=None, frame=None, reason='Caught SIGINT signal, instantaneous exiting'):
simplify the dead worker detection/restarting
sileht_cotyledon
train
43d3d671aeeed04d35a057ef453b1b11fa426d3c
diff --git a/src/Action/IndexAction.php b/src/Action/IndexAction.php index <HASH>..<HASH> 100644 --- a/src/Action/IndexAction.php +++ b/src/Action/IndexAction.php @@ -46,10 +46,11 @@ class IndexAction extends BaseAction */ protected function _handle() { - $subject = $this->_subject(['success' => true, 'object' => null]); + $query = $this->_table()->find(); + $subject = $this->_subject(['success' => true, 'query' => $query]); $this->_trigger('beforePaginate', $subject); - $items = $this->_controller()->paginate($subject->object); + $items = $this->_controller()->paginate($subject->query); $subject->set(['entities' => $items]); $this->_trigger('afterPaginate', $subject);
Adding ability to change or swap the query in beforePaginate
FriendsOfCake_crud-json-api
train
7dd8aba597b0e9ce491102bd126bd912944653fd
diff --git a/geomdl/BSpline.py b/geomdl/BSpline.py index <HASH>..<HASH> 100644 --- a/geomdl/BSpline.py +++ b/geomdl/BSpline.py @@ -16,7 +16,7 @@ from . import utilities as utils class Curve(Abstract.Curve): - """ Data storage and evaluation class for 3D B-Spline (NUBS) curves. + """ Data storage and evaluation class for B-Spline (NUBS) curves. **Data Storage** @@ -942,41 +942,43 @@ class Curve(Abstract.Curve): self.ctrlpts = new_ctrlpts + def add_dimension(self): + """ Converts x-D curve to a (x+1)-D curve. -class Curve2D(Curve): - """ Data storage and evaluation class for 2D B-Spline (NUBS) curves. - - **Data Storage** - - The following properties are present in this class: + Useful when converting a 2-D curve to a 3-D curve. - * order - * degree - * knotvector - * delta - * ctrlpts - * curvepts + :return: curve object + :rtype: Curve + """ + dim = self._dimension + if self._rational: + dim -= 1 - The function :func:`.read_ctrlpts_from_txt()` provides an easy way to read weighted control points from a text file. - Additional details on the file formats can be found in the documentation. + # Update control points + new_ctrlpts = [] + for point in self._control_points: + temp = [float(p) for p in point[0:dim]] + temp.append(0.0) + if self._rational: + temp.append(point[-1]) + new_ctrlpts.append(temp) - .. note:: Control points are stored as a list of (x, y) coordinates + # Convert to (x+1)-D curve, where x = self.dimension + ret_val = Curve() + ret_val.degree = self.degree + ret_val.ctrlpts = new_ctrlpts + ret_val.knotvector = self.knotvector + ret_val.delta = self.delta - **Evaluation** + return ret_val - The evaluation methods are: - * :py:meth:`.evaluate()` - * :py:meth:`.derivatives()` - * :py:meth:`.tangent()` - * :py:meth:`.normal()` - * :py:meth:`.binormal()` - * :py:meth:`.insert_knot()` +class Curve2D(Curve): + """ Data storage and evaluation class for 2D B-Spline (NUBS) curves. - .. note:: + .. deprecated:: 3.5 + Use :py:class:`.Curve` instead - If you update any of the data storage elements after the curve evaluation, the surface points stored in - :py:attr:`~curvepts` property will be deleted automatically. """ def __init__(self): diff --git a/geomdl/NURBS.py b/geomdl/NURBS.py index <HASH>..<HASH> 100644 --- a/geomdl/NURBS.py +++ b/geomdl/NURBS.py @@ -14,7 +14,7 @@ from . import utilities as utils class Curve(BSpline.Curve): - """ Data storage and evaluation class for 3D NURBS curves. + """ Data storage and evaluation class for NURBS curves. **Data Storage** @@ -225,38 +225,9 @@ class Curve(BSpline.Curve): class Curve2D(Curve): """ Data storage and evaluation class for 2D NURBS curves. - **Data Storage** - - The following properties are present in this class: - - * order - * degree - * knotvector - * delta - * ctrlpts - * weights - * curvepts - - The function :func:`.read_ctrlpts_from_txt()` provides an easy way to read weighted control points from a text file. - Additional details on the file formats can be found in the documentation. - - .. note:: Control points are stored as a list of (x*w, y*w, w) coordinates + .. deprecated:: 3.5 + Use :py:class:`.Curve` instead - **Evaluation** - - The evaluation methods are: - - * :py:meth:`.evaluate()` - * :py:meth:`.derivatives()` - * :py:meth:`.tangent()` - * :py:meth:`.normal()` - * :py:meth:`.binormal()` - * :py:meth:`.insert_knot()` - - .. note:: - - If you update any of the data storage elements after the curve evaluation, the surface points stored in - :py:attr:`~curvepts` property will be deleted automatically. """ def __init__(self):
Getting rid of Curve2D class
orbingol_NURBS-Python
train
be889bb1cb5893fdf9fda096e0ea611352f13325
diff --git a/.rubocop.yml b/.rubocop.yml index <HASH>..<HASH> 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -3,8 +3,9 @@ AllCops: DisplayStyleGuide: true TargetRubyVersion: 2.4 Exclude: - - 'how_is.gemspec' + - 'okay.gemspec' - 'bin/*' + - 'examples/*' - '**/*~' - 'spec/capture_warnings.rb' diff --git a/Gemfile b/Gemfile index <HASH>..<HASH> 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + source "https://rubygems.org" # Specify your gem's dependencies in okay.gemspec diff --git a/Rakefile b/Rakefile index <HASH>..<HASH> 100644 --- a/Rakefile +++ b/Rakefile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "bundler/gem_tasks" require "rspec/core/rake_task" diff --git a/lib/okay.rb b/lib/okay.rb index <HASH>..<HASH> 100644 --- a/lib/okay.rb +++ b/lib/okay.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "okay/version" module Okay diff --git a/lib/okay/default.rb b/lib/okay/default.rb index <HASH>..<HASH> 100644 --- a/lib/okay/default.rb +++ b/lib/okay/default.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "okay/version" module Okay diff --git a/lib/okay/graphql.rb b/lib/okay/graphql.rb index <HASH>..<HASH> 100644 --- a/lib/okay/graphql.rb +++ b/lib/okay/graphql.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "okay/version" require "okay/http" require "json" diff --git a/lib/okay/http.rb b/lib/okay/http.rb index <HASH>..<HASH> 100644 --- a/lib/okay/http.rb +++ b/lib/okay/http.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "okay/version" require "openssl/better_defaults" require "net/https" diff --git a/lib/okay/version.rb b/lib/okay/version.rb index <HASH>..<HASH> 100644 --- a/lib/okay/version.rb +++ b/lib/okay/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Okay VERSION = "9.0.0" end diff --git a/lib/okay/warning_helpers.rb b/lib/okay/warning_helpers.rb index <HASH>..<HASH> 100644 --- a/lib/okay/warning_helpers.rb +++ b/lib/okay/warning_helpers.rb @@ -19,4 +19,3 @@ module Okay end end end - diff --git a/okay.gemspec b/okay.gemspec index <HASH>..<HASH> 100644 --- a/okay.gemspec +++ b/okay.gemspec @@ -1,4 +1,6 @@ +# frozen_string_literal: true # coding: utf-8 + lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "okay/version" @@ -27,4 +29,5 @@ Gem::Specification.new do |spec| spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rake", "~> 12.3" spec.add_development_dependency "rspec", "~> 3.8" + spec.add_development_dependency "rubocop", "~> 0.49.1" end diff --git a/spec/okay/template_spec.rb b/spec/okay/template_spec.rb index <HASH>..<HASH> 100644 --- a/spec/okay/template_spec.rb +++ b/spec/okay/template_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" require "okay/template" diff --git a/spec/okay_spec.rb b/spec/okay_spec.rb index <HASH>..<HASH> 100644 --- a/spec/okay_spec.rb +++ b/spec/okay_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "spec_helper" RSpec.describe Okay do diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "bundler/setup" require "okay"
add frozen_string_literal comments; misc other RuboCop-suggested fixes.
duckinator_okay
train
2ab5c9f8deaa477ccce406c6558ed5bdc0c6aca4
diff --git a/i3_cycle.py b/i3_cycle.py index <HASH>..<HASH> 100644 --- a/i3_cycle.py +++ b/i3_cycle.py @@ -12,7 +12,7 @@ import i3 def find_focusable(node): """ - Search the first focusable window that is not the focused current one + Search for the first focusable window within the node tree """ if not node.children: @@ -22,27 +22,55 @@ def find_focusable(node): return find_focusable(node.children_dict[node.focus[0]]) -def find_split(node, wanted): +def find_parent_split(node, orientation): """ - Find the appropriate split + Find the first parent split relative to the given node + according to the desired orientation """ - if (node and node.orientation == wanted["orientation"] + if (node and node.orientation == orientation and len(node.children) > 1): + return node + + if not node or node.type == "workspace": + return None + + return find_parent_split(node.parent, orientation) + + +def cycle_windows(tree, direction): + """ + Cycle through windows of the current workspace + """ + wanted = { + "orientation": ("vertical" if direction in ("up", "down") + else "horizontal"), + "direction": (1 if direction in ("down", "right") + else -1), + } + split = find_parent_split(tree.focused.parent, wanted["orientation"]) + + if split: # Get the next child given the direction - child_ids = [child.id for child in node.children] - focus_idx = child_ids.index(node.focused_child.id) + child_ids = [child.id for child in split.children] + focus_idx = child_ids.index(split.focused_child.id) next_idx = (focus_idx + wanted['direction']) % len(child_ids) - next_node = node.children[next_idx] - focusable = find_focusable(next_node) - if focusable: - i3.focus(con_id=focusable.id) - return focusable + next_node = split.children[next_idx] + return find_focusable(next_node) + return None - if not node or node.type == "workspace": - return - return find_split(node.parent, wanted) +def cycle_outputs(tree, direction): + """ + Cycle through directions + """ + direction = 1 if direction == "next" else -1 + outputs = [output for output in tree.root.children + if output.name != "__i3"] + focus_idx = outputs.index(tree.root.focused_child) + next_idx = (focus_idx + direction) % len(outputs) + next_output = outputs[next_idx] + return find_focusable(next_output) def main(): @@ -59,26 +87,15 @@ def main(): args = parser.parse_args() tree = i3Tree() + con = None if args.direction in ("next", "prev"): - direction = 1 if args.direction == "next" else -1 - outputs = [output for output in tree.root.children - if output.name != "__i3"] - focus_idx = outputs.index(tree.root.focused_child) - next_idx = (focus_idx + direction) % len(outputs) - next_output = outputs[next_idx] - con = find_focusable(next_output) - if con: - i3.focus(con_id=con.id) + con = cycle_outputs(tree, args.direction) else: - wanted = { - "orientation": ("vertical" if args.direction in ("up", "down") - else "horizontal"), - "direction": (1 if args.direction in ("down", "right") - else -1), - } - - find_split(tree.focused.parent, wanted) + con = cycle_windows(tree, args.direction) + + if con: + i3.focus(con_id=con.id) if __name__ == '__main__':
Refactoring, testable fuctions, no side effect
mota_i3-cycle
train
e954da5cb1494b2531cec3b78ef88c3bb6b381a7
diff --git a/src/Compiler.php b/src/Compiler.php index <HASH>..<HASH> 100644 --- a/src/Compiler.php +++ b/src/Compiler.php @@ -1668,13 +1668,12 @@ class Compiler $part1 = array_pop($selectors1); $part2 = array_pop($selectors2); - if ($this->isImmediateRelationshipCombinator($part1[0]) && $part1 !== $part2) { + if (! $this->isImmediateRelationshipCombinator($part1[0]) || $part1 !== $part2) { $merged = array_merge($selectors1, [$part1], $selectors2, [$part2], $merged); break; } array_unshift($merged, $part1); - array_unshift($merged, [array_pop($selectors1)[0] . array_pop($selectors2)[0]]); } while (! empty($selectors1) && ! empty($selectors2)); return $merged;
mergeDirectRelationships : 1 bug from refactoring and 1 from initial proposal
leafo_scssphp
train
e532b7784934e2dcab1053d88d562e5f287daf3b
diff --git a/src/main/java/com/bytebybyte/google/geocoding/service/request/GeocodeRequestBuilder.java b/src/main/java/com/bytebybyte/google/geocoding/service/request/GeocodeRequestBuilder.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/bytebybyte/google/geocoding/service/request/GeocodeRequestBuilder.java +++ b/src/main/java/com/bytebybyte/google/geocoding/service/request/GeocodeRequestBuilder.java @@ -59,7 +59,8 @@ public class GeocodeRequestBuilder { * @return GeocodeRequestBuilder */ public GeocodeRequestBuilder address(String address) { - parameters.put("address", address); + parameters.put("address", address != null ? address.replace(' ', '+') + : address); return this; } @@ -100,9 +101,11 @@ public class GeocodeRequestBuilder { */ public GeocodeRequestBuilder componenets(Map<String, String> components) { StringBuffer filters = new StringBuffer(); - for (Iterator<Map.Entry<String, String>> iterator = components.entrySet().iterator(); iterator.hasNext();) { + for (Iterator<Map.Entry<String, String>> iterator = components + .entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, String> entry = iterator.next(); - filters.append(entry.getKey() + ":" + entry.getValue()); + filters.append(entry.getKey() + ":" + entry.getValue() != null ? entry + .getValue().replace(' ', '+') : entry.getValue()); if (iterator.hasNext()) filters.append("|"); }
Added escape for ' ' with '+'.
gjordi_google-geocoding
train
bc8709a31348ba82847c0ebc42e6143311ac0a18
diff --git a/validator/sawtooth_validator/execution/scheduler_serial.py b/validator/sawtooth_validator/execution/scheduler_serial.py index <HASH>..<HASH> 100644 --- a/validator/sawtooth_validator/execution/scheduler_serial.py +++ b/validator/sawtooth_validator/execution/scheduler_serial.py @@ -186,11 +186,14 @@ class SerialScheduler(Scheduler): return state_hash def _calculate_state_root_if_not_already_done(self): - last_txn_signature = self._last_in_batch[-1] - batch_id = self._txn_to_batch[last_txn_signature] - required_state_hash = self._required_state_hashes.get( - batch_id) if not self._already_calculated: + if not self._last_in_batch: + return + last_txn_signature = self._last_in_batch[-1] + batch_id = self._txn_to_batch[last_txn_signature] + required_state_hash = self._required_state_hashes.get( + batch_id) + state_hash = self._compute_merkle_root(required_state_hash) self._already_calculated = True for t_id in self._last_in_batch[::-1]:
Skip state root calculation if no batches Handle the case where there are no batches.
hyperledger_sawtooth-core
train
16635f5902e73183846f1d9a85cdf0546144123d
diff --git a/test/e2e/storage/testsuites/provisioning.go b/test/e2e/storage/testsuites/provisioning.go index <HASH>..<HASH> 100644 --- a/test/e2e/storage/testsuites/provisioning.go +++ b/test/e2e/storage/testsuites/provisioning.go @@ -725,6 +725,28 @@ func StopPodAndDependents(c clientset.Interface, pod *v1.Pod) { } else { framework.Logf("Pod %s has the following logs: %s", pod.Name, body) } + + // We must wait explicitly for removal of the generic ephemeral volume PVs. + // For that we must find them first... + pvs, err := c.CoreV1().PersistentVolumes().List(context.TODO(), metav1.ListOptions{}) + framework.ExpectNoError(err, "list PVs") + var podPVs []v1.PersistentVolume + for _, pv := range pvs.Items { + if pv.Spec.ClaimRef == nil || + pv.Spec.ClaimRef.Namespace != pod.Namespace { + continue + } + pvc, err := c.CoreV1().PersistentVolumeClaims(pod.Namespace).Get(context.TODO(), pv.Spec.ClaimRef.Name, metav1.GetOptions{}) + if err != nil && apierrors.IsNotFound(err) { + // Must have been some unrelated PV, otherwise the PVC should exist. + continue + } + framework.ExpectNoError(err, "get PVC") + if pv.Spec.ClaimRef.UID == pvc.UID && metav1.IsControlledBy(pvc, pod) { + podPVs = append(podPVs, pv) + } + } + framework.Logf("Deleting pod %q in namespace %q", pod.Name, pod.Namespace) deletionPolicy := metav1.DeletePropagationForeground err = c.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, @@ -742,6 +764,14 @@ func StopPodAndDependents(c clientset.Interface, pod *v1.Pod) { } framework.Logf("Wait up to %v for pod %q to be fully deleted", e2epod.PodDeleteTimeout, pod.Name) e2epod.WaitForPodNotFoundInNamespace(c, pod.Name, pod.Namespace, e2epod.PodDeleteTimeout) + if len(podPVs) > 0 { + for _, pv := range podPVs { + // As with CSI inline volumes, we use the pod delete timeout here because conceptually + // the volume deletion needs to be that fast (whatever "that" is). + framework.Logf("Wait up to %v for pod PV %s to be fully deleted", e2epod.PodDeleteTimeout, pv.Name) + e2epv.WaitForPersistentVolumeDeleted(c, pv.Name, 5*time.Second, e2epod.PodDeleteTimeout) + } + } } func verifyPVCsPending(client clientset.Interface, pvcs []*v1.PersistentVolumeClaim) {
storage E2E: explicitly wait for PV deletion after ephemeral test Even with foreground deletion, removal of the PVs that may have been created for a pod with generic ephemeral volumes happens asynchronously, in the worst case after the test has completed and the driver for the volume got removed. Perhaps this can be fixed in Kubernetes itself, but for now we need to deal with it as part of the test.
kubernetes_kubernetes
train
8fcd0aa76fad67276977382dbbb13528036781f6
diff --git a/lib/raca/account.rb b/lib/raca/account.rb index <HASH>..<HASH> 100644 --- a/lib/raca/account.rb +++ b/lib/raca/account.rb @@ -72,7 +72,7 @@ module Raca ) if response.is_a? Net::HTTPSuccess json_data = JSON.load(response.body) - cache_write("cloudfiles-data", { + cache_write(cache_key, { auth_token: extract_value(json_data, "access", "token", "id"), storage_url: ord_cloudfiles_url(json_data), server_url: cloudserver_url(json_data), @@ -193,9 +193,13 @@ module Raca end def cloudfiles_data - refresh_cache unless cache_read("cloudfiles-data") + refresh_cache unless cache_read(cache_key) - cache_read("cloudfiles-data") || {} + cache_read(cache_key) || {} + end + + def cache_key + @cache_key ||= "raca-#{@username}" end end diff --git a/spec/account_spec.rb b/spec/account_spec.rb index <HASH>..<HASH> 100644 --- a/spec/account_spec.rb +++ b/spec/account_spec.rb @@ -21,7 +21,7 @@ describe Raca::Account do describe '#auth_token' do context "when the token is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {auth_token: "foo"}} } + let!(:cache) { {"raca-theuser" => {auth_token: "foo"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do @@ -44,7 +44,7 @@ describe Raca::Account do describe '#storage_host' do context "when the storage url is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {storage_url: "https://example.com/foo"}} } + let!(:cache) { {"raca-theuser" => {storage_url: "https://example.com/foo"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do @@ -67,7 +67,7 @@ describe Raca::Account do describe '#cdn_host' do context "when the cdn url is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {cdn_url: "https://example.com/foo"}} } + let!(:cache) { {"raca-theuser" => {cdn_url: "https://example.com/foo"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do @@ -90,7 +90,7 @@ describe Raca::Account do describe '#path' do context "when the storage url is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {storage_url: "https://example.com/filepath"}} } + let!(:cache) { {"raca-theuser" => {storage_url: "https://example.com/filepath"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do @@ -113,7 +113,7 @@ describe Raca::Account do describe '#server_host' do context "when the server url is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {server_url: "https://example.com/serverpath"}} } + let!(:cache) { {"raca-theuser" => {server_url: "https://example.com/serverpath"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do @@ -136,7 +136,7 @@ describe Raca::Account do describe '#server_path' do context "when the server url is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {server_url: "https://example.com/serverpath"}} } + let!(:cache) { {"raca-theuser" => {server_url: "https://example.com/serverpath"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do @@ -159,7 +159,7 @@ describe Raca::Account do describe '#ngserver_host' do context "when the server url is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {ngserver_url: "https://example.com/ngserverpath"}} } + let!(:cache) { {"raca-theuser" => {ngserver_url: "https://example.com/ngserverpath"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do @@ -182,7 +182,7 @@ describe Raca::Account do describe '#ngserver_path' do context "when the server url is pre-cached" do - let!(:cache) { {"cloudfiles-data" => {ngserver_url: "https://example.com/ngserverpath"}} } + let!(:cache) { {"raca-theuser" => {ngserver_url: "https://example.com/ngserverpath"}} } let!(:info) { Raca::Account.new(username, api_key, cache)} it "should return the cached value" do
scope account caching to usernames * so Accounts for multiple rackspace users don't share data
conversation_raca
train
867da358c52bd75ddc41499ed08ff2f557a685af
diff --git a/examples/test_login.py b/examples/test_login.py index <HASH>..<HASH> 100755 --- a/examples/test_login.py +++ b/examples/test_login.py @@ -12,3 +12,4 @@ class SwagLabsLoginTests(BaseCase): self.login_to_swag_labs() self.assert_element("div.inventory_list") self.assert_element('.inventory_item:contains("Sauce Labs Backpack")') + self.js_click("a#logout_sidebar_link")
Have the login example test also logout
seleniumbase_SeleniumBase
train
eb2c537f72cb9c307ec93ddc56fdaee081223d0e
diff --git a/schema_groups.py b/schema_groups.py index <HASH>..<HASH> 100644 --- a/schema_groups.py +++ b/schema_groups.py @@ -46,10 +46,10 @@ class Group(Base): backref=backref('group'), foreign_keys=[CustomFieldValue.parentkey], primaryjoin='CustomFieldValue.parentkey == Group.encodedkey') - loans = relationship(LoanAccount, - backref=backref('holder_group'), - foreign_keys=[LoanAccount.accountholderkey], - primaryjoin='LoanAccount.accountholderkey == Group.encodedkey') + loans = relationship("LoanAccount", + back_populates = "holder_group", + foreign_keys = [LoanAccount.accountholderkey], + primaryjoin = 'LoanAccount.accountholderkey == Group.encodedkey') def __repr__(self): return "<Group(id={}, groupname={})>".format(self.id, self.groupname) diff --git a/schema_loans.py b/schema_loans.py index <HASH>..<HASH> 100644 --- a/schema_loans.py +++ b/schema_loans.py @@ -108,6 +108,10 @@ class LoanAccount(Base): backref=backref('loan'), foreign_keys=[CustomFieldValue.parentkey], primaryjoin='CustomFieldValue.parentkey == LoanAccount.encodedkey') + holder_group = relationship("Group", + back_populates = "loans", + foreign_keys = "LoanAccount.accountholderkey", + primaryjoin = 'LoanAccount.accountholderkey == Group.encodedkey') def __repr__(self): return "<LoanAccount(id=%s, accountstate=%s)>" % (self.id, self.accountstate)
Changed LoanAccount-Group relationship to a back_populates one. This allows further inheritance strategies to be a easily implemented between loan accounts and groups.
jstitch_MambuPy
train
385e4c3d6b4dcf56ad1bed6a8441159ae00c966f
diff --git a/spec/helpers.rb b/spec/helpers.rb index <HASH>..<HASH> 100644 --- a/spec/helpers.rb +++ b/spec/helpers.rb @@ -1,14 +1,18 @@ # frozen_string_literal: true require 'logger' +require 'method_source' -def wait_for(timeout_milliseconds = 2000) - timeout = (timeout_milliseconds + 0.0) / 1000 +def wait_for(timeout_milliseconds = 2000, &blk) + timeout = timeout_milliseconds / 1000.0 finish = Time.now + timeout + result = nil - Thread.new do - sleep(0.001) while Time.now < finish && !yield - end.join + while Time.now < finish && !(result = blk.call) + sleep(0.001) + end + + flunk("wait_for timed out:\n#{blk.source}") if !result end def test_config_for_backend(backend)
DEV: Fail on wait_for timeout (#<I>)
SamSaffron_message_bus
train
08999cc0cb4323830c52affea8339fdfc21658d6
diff --git a/cli/lib/credentials/credentials.js b/cli/lib/credentials/credentials.js index <HASH>..<HASH> 100644 --- a/cli/lib/credentials/credentials.js +++ b/cli/lib/credentials/credentials.js @@ -128,10 +128,17 @@ credentials.get = function (api, params) { var nameMap = {}; var name; var cred; + var cv; for (var i = 0; i < creds.length; ++i) { cred = creds[i]; name = cred.body.name; + // If cred has been unset then ignore it. + cv = cValue.parse(cred.body.value); + if (cv.type === 'undefined') { + continue; + } + if (!nameMap[name]) { nameMap[name] = cred; continue;
Ignore any credential that has been unset Related arigatomachine/cli#<I>
manifoldco_torus-cli
train
b33c23ef2529c8f6c1537bbd70af47a184ea3f76
diff --git a/superset/migrations/versions/2022-06-19_16-17_f3afaf1f11f0_add_unique_name_desc_rls.py b/superset/migrations/versions/2022-06-19_16-17_f3afaf1f11f0_add_unique_name_desc_rls.py index <HASH>..<HASH> 100644 --- a/superset/migrations/versions/2022-06-19_16-17_f3afaf1f11f0_add_unique_name_desc_rls.py +++ b/superset/migrations/versions/2022-06-19_16-17_f3afaf1f11f0_add_unique_name_desc_rls.py @@ -17,14 +17,14 @@ """add_unique_name_desc_rls Revision ID: f3afaf1f11f0 -Revises: e786798587de +Revises: e09b4ae78457 Create Date: 2022-06-19 16:17:23.318618 """ # revision identifiers, used by Alembic. revision = "f3afaf1f11f0" -down_revision = "e786798587de" +down_revision = "e09b4ae78457" import sqlalchemy as sa from alembic import op
fix: migration revision order (#<I>)
apache_incubator-superset
train
923c02bf2ad0d14dd1e0b7a80e815459453876d6
diff --git a/packages/project-utils/packages/buildPackage.js b/packages/project-utils/packages/buildPackage.js index <HASH>..<HASH> 100644 --- a/packages/project-utils/packages/buildPackage.js +++ b/packages/project-utils/packages/buildPackage.js @@ -25,7 +25,7 @@ module.exports = async params => { } const duration = (new Date() - start) / 1000; - params.options.debug === true && + params.options.logs !== false && log.info(`Done! Build finished in ${log.info.hl(duration + "s")}.`); return { duration }; @@ -34,16 +34,16 @@ module.exports = async params => { const defaults = { prebuild: params => { const { config } = params; - params.options.debug === true && log.info("Deleting existing build files..."); + params.options.logs !== false && log.info("Deleting existing build files..."); rimraf.sync(join(config.cwd, "./dist")); rimraf.sync(join(config.cwd, "*.tsbuildinfo")); }, build: async params => { - params.options.debug === true && log.info("Building..."); + params.options.logs !== false && log.info("Building..."); await Promise.all([tsCompile(params), babelCompile(params)]); }, postbuild: params => { - params.options.debug === true && log.info("Copying meta files..."); + params.options.logs !== false && log.info("Copying meta files..."); copyToDist("package.json", params); copyToDist("LICENSE", params); copyToDist("README.md", params); @@ -128,6 +128,6 @@ const copyToDist = (path, { config, options }) => { const to = join(config.cwd, "dist", path); if (fs.existsSync(from)) { fs.copyFileSync(from, to); - options.debug === true && log.info(`Copied ${log.info.hl(path)}.`); + options.logs !== false && log.info(`Copied ${log.info.hl(path)}.`); } }; diff --git a/scripts/buildWithCache.js b/scripts/buildWithCache.js index <HASH>..<HASH> 100644 --- a/scripts/buildWithCache.js +++ b/scripts/buildWithCache.js @@ -164,9 +164,8 @@ async function build() { const promises = []; for (let j = 0; j < batch.length; j++) { - const currentPackage = workspacesPackages.find(item => item.name === batch[j]); - console.log(`‣ ${currentPackage.packageJson.name}`) + console.log(`‣ ${currentPackage.packageJson.name}`); promises.push( new Promise(async (resolve, reject) => { const configPath = path @@ -174,7 +173,7 @@ async function build() { .replace(/\\/g, "/"); const config = require(configPath); try { - await config.commands.build(); + await config.commands.build({ logs: false }); // Copy and paste built code into the cache folder. const cacheFolderPath = path.join(
feat: turn on logging by default
Webiny_webiny-js
train
957ab9afafde1a438372a2fe2345fe442c770619
diff --git a/test/e2e/apps/rc.go b/test/e2e/apps/rc.go index <HASH>..<HASH> 100644 --- a/test/e2e/apps/rc.go +++ b/test/e2e/apps/rc.go @@ -134,7 +134,7 @@ var _ = SIGDescribe("ReplicationController", func() { framework.ExpectNoError(err, "Failed to create ReplicationController") // setup a watch for the RC - rcWatchTimeoutSeconds := int64(60) + rcWatchTimeoutSeconds := int64(180) rcWatch, err := f.ClientSet.CoreV1().ReplicationControllers(testRcNamespace).Watch(context.TODO(), metav1.ListOptions{LabelSelector: "test-rc-static=true", TimeoutSeconds: &rcWatchTimeoutSeconds}) framework.ExpectNoError(err, "Failed to setup watch on newly created ReplicationController") @@ -259,7 +259,7 @@ var _ = SIGDescribe("ReplicationController", func() { err = f.ClientSet.CoreV1().ReplicationControllers(testRcNamespace).DeleteCollection(context.TODO(), &metav1.DeleteOptions{}, metav1.ListOptions{LabelSelector: "test-rc-static=true"}) framework.ExpectNoError(err, "Failed to delete ReplicationControllers") - ginkgo.By("waiting for ReplicationController is have a DeletionTimestamp") + ginkgo.By("waiting for ReplicationController to have a DELETED event") for event := range rcWatchChan { if event.Type == "DELETED" { break
Adjust RC watch timeout to <I>, update progress log statement
kubernetes_kubernetes
train
ff6ba58d5136e63bd47d510d6db480709a1180d2
diff --git a/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/layer/config/WmsTileConfiguration.java b/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/layer/config/WmsTileConfiguration.java index <HASH>..<HASH> 100644 --- a/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/layer/config/WmsTileConfiguration.java +++ b/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/layer/config/WmsTileConfiguration.java @@ -31,6 +31,8 @@ public class WmsTileConfiguration implements Serializable { private int tileHeight; + private int maximumTileLevel = Integer.MAX_VALUE; + private Coordinate tileOrigin; // ------------------------------------------------------------------------ @@ -117,4 +119,24 @@ public class WmsTileConfiguration implements Serializable { public void setTileOrigin(Coordinate tileOrigin) { this.tileOrigin = tileOrigin; } + + /** + * Get the maximum (map) tile level for this layer. If not set this is unlimited. + * + * @return the maximum tile level + */ + public int getMaximumTileLevel() { + return maximumTileLevel; + } + + /** + * Set the maximum (map) tile level for this layer. If not set this is unlimited. + * + * @param maximumTileLevel + */ + public void setMaximumTileLevel(int maximumTileLevel) { + this.maximumTileLevel = maximumTileLevel; + } + + } \ No newline at end of file diff --git a/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/service/WmsTileServiceImpl.java b/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/service/WmsTileServiceImpl.java index <HASH>..<HASH> 100644 --- a/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/service/WmsTileServiceImpl.java +++ b/plugin/geomajas-plugin-wmsclient/wmsclient/src/main/java/org/geomajas/plugin/wmsclient/client/service/WmsTileServiceImpl.java @@ -38,6 +38,10 @@ public class WmsTileServiceImpl implements WmsTileService { double actualScale = viewPort.getZoomStrategy().checkScale(scale, ZoomOption.LEVEL_CLOSEST); int tileLevel = viewPort.getZoomStrategy().getZoomStepIndex(actualScale); + if (tileLevel > tileConfig.getMaximumTileLevel()) { + tileLevel = tileConfig.getMaximumTileLevel(); + actualScale = viewPort.getZoomStrategy().getZoomStepScale(tileLevel); + } double resolution = 1 / actualScale; double worldTileWidth = tileConfig.getTileWidth() * resolution; double worldTileHeight = tileConfig.getTileHeight() * resolution;
WMSCL-<I> - Allow definition of maximum tile level for wms layers
geomajas_geomajas-project-server
train