hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
16b868b6b00d01a333540a002c127ca35a6ec0ba
diff --git a/addon/components/basic-dropdown.js b/addon/components/basic-dropdown.js index <HASH>..<HASH> 100644 --- a/addon/components/basic-dropdown.js +++ b/addon/components/basic-dropdown.js @@ -180,6 +180,9 @@ export default Component.extend({ } if (e.keyCode === 13) { // Enter this.toggle(e); + } else if (e.keyCode === 32) { // Space + this.toggle(e); + e.preventDefault(); // prevents the space to trigger a scroll page-next } else if (e.keyCode === 27) { this.close(e); } diff --git a/tests/integration/components/basic-dropdown-test.js b/tests/integration/components/basic-dropdown-test.js index <HASH>..<HASH> 100644 --- a/tests/integration/components/basic-dropdown-test.js +++ b/tests/integration/components/basic-dropdown-test.js @@ -268,6 +268,47 @@ test('Pressing Enter while the trigger is focused doesn\'t show the content if t assert.equal($('.ember-basic-dropdown-content').length, 0, 'The content of the dropdown is still not rendered'); }); +test('Pressing Space while the trigger is focused show the content', function(assert) { + assert.expect(3); + + this.didKeydown = function(/* publicAPI, e */) { + assert.ok(true, 'onKeydown action was invoked'); + }; + this.render(hbs` + {{#basic-dropdown onKeydown=didKeydown}} + <h3>Content of the dropdown</h3> + {{else}} + <button>Press me</button> + {{/basic-dropdown}} + `); + + Ember.run(() => this.$('.ember-basic-dropdown-trigger').focus()); + assert.equal($('.ember-basic-dropdown-content').length, 0, 'The content of the dropdown is not rendered'); + Ember.run(() => triggerKeydown(this.$('.ember-basic-dropdown-trigger')[0], 32)); // Space + assert.equal($('.ember-basic-dropdown-content').length, 1, 'The content of the dropdown appeared'); +}); + +test('Pressing Space while the trigger is focused doesn\'t show the content if the onKeydown action returns false', function(assert) { + assert.expect(3); + + this.didKeydown = function() { + assert.ok(true, 'onKeydown action was invoked'); + return false; + }; + this.render(hbs` + {{#basic-dropdown onKeydown=didKeydown}} + <h3>Content of the dropdown</h3> + {{else}} + <button>Press me</button> + {{/basic-dropdown}} + `); + + Ember.run(() => this.$('.ember-basic-dropdown-trigger').focus()); + assert.equal($('.ember-basic-dropdown-content').length, 0, 'The content of the dropdown is not rendered'); + Ember.run(() => triggerKeydown(this.$('.ember-basic-dropdown-trigger')[0], 32)); // Space + assert.equal($('.ember-basic-dropdown-content').length, 0, 'The content of the dropdown is still not rendered'); +}); + test('Pressing ESC while the trigger is focused and the dropdown is opened', function(assert) { assert.expect(3);
Open close with the space bar. Apparently is expected behaviour for all buttons to be triggered with space and enter.
cibernox_ember-basic-dropdown
train
f42ffc2e75fa3f06b3a4d88ec8a6213fe9e3567b
diff --git a/src/graph.js b/src/graph.js index <HASH>..<HASH> 100644 --- a/src/graph.js +++ b/src/graph.js @@ -17,13 +17,6 @@ dagre.graph = {}; */ dagre.graph.create = function() { /* - * Returns graph level attributes. - */ - function attrs() { - return _attrs; - } - - /* * Adds a or updates a node in the graph with the given id. It only makes * sense to use primitive values as ids. This function also optionally takes * an object that will be used as attributes for the node. @@ -235,7 +228,7 @@ dagre.graph.create = function() { // Public API is defined here return { - attrs: attrs, + attrs: _attrs, addNode: addNode, addNodes: addNodes, removeNode: removeNode,
graph.attrs should be an object, not a function
dagrejs_dagre-d3
train
8b36d0952ff48cd6dfcf22ba50ac302c56ea54ee
diff --git a/src/ossos/core/ossos/pipeline/step2.py b/src/ossos/core/ossos/pipeline/step2.py index <HASH>..<HASH> 100755 --- a/src/ossos/core/ossos/pipeline/step2.py +++ b/src/ossos/core/ossos/pipeline/step2.py @@ -67,12 +67,16 @@ def compute_trans(expnums, ccd, version, prefix=None, default="WCS"): (ra0, dec0) = wcs_dict[expnums[0]].xy2sky(x0, y0) result = "" for expnum in expnums: - filename = storage.get_file(expnum, ccd, version, ext='.trans.jmp', prefix=prefix) - jmp_trans = open(filename, 'r').readline().split() (x, y) = wcs_dict[expnum].sky2xy(ra0, dec0) - x1 = float(jmp_trans[0]) + float(jmp_trans[1]) * x + float(jmp_trans[2]) * y - y1 = float(jmp_trans[3]) + float(jmp_trans[4]) * x + float(jmp_trans[5]) * y - dr = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2) + dr = 1000 + try: + filename = storage.get_file(expnum, ccd, version, ext='.trans.jmp', prefix=prefix) + jmp_trans = open(filename, 'r').readline().split() + x1 = float(jmp_trans[0]) + float(jmp_trans[1]) * x + float(jmp_trans[2]) * y + y1 = float(jmp_trans[3]) + float(jmp_trans[4]) * x + float(jmp_trans[5]) * y + dr = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2) + except Exception: + pass if dr > 0.5: result += "WARNING: WCS-JMP transforms mis-matched {} reverting to using {}.\n".format(expnum, default) if default == "WCS": @@ -121,11 +125,14 @@ def run(expnums, ccd, version, prefix=None, dry_run=False, default="WCS", force= ) logging.info("Computing the catalog alignment using sources in catalogs.") - logging.info(util.exec_prog(jmp_trans)) - - logging.info("Comparing computed transform to WCS values") - if default == "WCS": - logging.info(compute_trans(expnums, ccd, version, prefix, default=default)) + try: + logging.info(util.exec_prog(jmp_trans)) + if default == "WCS": + logging.info("Comparing computed transform to WCS values") + logging.info(compute_trans(expnums, ccd, version, prefix, default=default)) + except Exception as ex: + logging.info("JMP Trans failed: {}".format(ex)) + logging.info(compute_trans(expnums, ccd, version, prefix, default="WCS")) logging.info("Using transform to match catalogs for three images.") logging.info(util.exec_prog(jmp_args))
Use the WCS based transform in coord matching fails
OSSOS_MOP
train
ecde2554efccee74773f955e2dde35212278ab57
diff --git a/Classes/IndexQueue/AbstractIndexer.php b/Classes/IndexQueue/AbstractIndexer.php index <HASH>..<HASH> 100644 --- a/Classes/IndexQueue/AbstractIndexer.php +++ b/Classes/IndexQueue/AbstractIndexer.php @@ -91,6 +91,9 @@ abstract class Tx_Solr_IndexQueue_AbstractIndexer { if (isset($indexingConfiguration[$solrFieldName . '.'])) { // configuration found => need to resolve a cObj + // setup locales + $GLOBALS['TSFE']->settingLocale(); + // need to change directory to make IMAGE content objects work in BE context // see http://blog.netzelf.de/lang/de/tipps-und-tricks/tslib_cobj-image-im-backend $backupWorkingDirectory = getcwd();
[BUGFIX] Set up locales before resolving field values Locales were not set up when the object is rendered for indexing, thus leading to incorrect results when using functions like strftime() Resolves: #<I> Releases: <I>
TYPO3-Solr_ext-solr
train
5ff653dad6d846f401089234c301c3a36ba94f3b
diff --git a/code/control/ShoppingCart.php b/code/control/ShoppingCart.php index <HASH>..<HASH> 100644 --- a/code/control/ShoppingCart.php +++ b/code/control/ShoppingCart.php @@ -138,7 +138,7 @@ class ShoppingCart extends Controller { //TODO: is this the right time to delete them??? self::delete_old_carts(); self::$order = new Order(); - self::$order->start(session_id()); + self::$order->init(session_id()); Session::set(self::$cartid_session_name,self::$order->ID.".".session_id()); $hasWritten = true; }
Fixed bug in ShoppingCart::current_order()
silvershop_silvershop-core
train
336aeab6a9ca5fb42ee21fac3bbb5021878408f2
diff --git a/chai/chai.py b/chai/chai.py index <HASH>..<HASH> 100644 --- a/chai/chai.py +++ b/chai/chai.py @@ -51,10 +51,10 @@ class Chai(unittest.TestCase): super(Chai,self).setUp() # Setup stub tracking - self.stubs = deque() + self._stubs = deque() # Setup mock tracking - self.mocks = deque() + self._mocks = deque() # Because cAmElCaSe sucks @@ -66,28 +66,28 @@ class Chai(unittest.TestCase): # Docs insist that this will be called no matter what happens in runTest(), # so this should be a safe spot to unstub everything exception = None - while len(self.stubs): - stub = self.stubs.popleft() - try: - stub.assert_expectations() - except ExpectationNotSatisfied, e: - if not exception: # Store only the first exception - exception = e - - stub.teardown() # Teardown the reset of the stub - - if exception: - raise exception - - + while len(self._stubs): + stub = self._stubs.popleft() + try: + stub.assert_expectations() + except ExpectationNotSatisfied, e: + if not exception: # Store only the first exception + exception = e + + stub.teardown() # Teardown the reset of the stub + # Do the mocks in reverse order in the rare case someone called mock(obj,attr) # twice. - while len(self.mocks): - mock = self.mocks.pop() + while len(self._mocks): + mock = self._mocks.pop() if len(mock)==2: delattr( mock[0], mock[1] ) else: setattr( mock[0], mock[1], mock[2] ) + + # Lastly, if there were any errors, raise them + if exception: + raise exception # Because cAmElCaSe sucks teardown = tearDown @@ -99,8 +99,8 @@ class Chai(unittest.TestCase): can't determine the binding from the object. ''' s = stub(obj, attr) - if s not in self.stubs: - self.stubs.append( s ) + if s not in self._stubs: + self._stubs.append( s ) return s def expect(self, obj, attr=None): @@ -118,9 +118,9 @@ class Chai(unittest.TestCase): if obj!=None and attr!=None: if hasattr(obj,attr): orig = getattr(obj, attr) - self.mocks.append( (obj,attr,orig) ) + self._mocks.append( (obj,attr,orig) ) setattr(obj, attr, rval) else: - self.mocks.append( (obj,attr) ) + self._mocks.append( (obj,attr) ) setattr(obj, attr, rval) return rval diff --git a/tests/chai_test.py b/tests/chai_test.py index <HASH>..<HASH> 100644 --- a/tests/chai_test.py +++ b/tests/chai_test.py @@ -1,10 +1,64 @@ import unittest +from collections import deque + +from chai import Chai +from chai.exception import * + +class CupOf(Chai): + def test_something(self): pass + def runTest(self, *args, **kwargs): pass class ChaiTest(unittest.TestCase): - def test_stub(self): - pass + def test_init(self): + case = CupOf.__new__(CupOf) + self.assertTrue( hasattr(case, 'assertEquals') ) + self.assertFalse( hasattr(case, 'assert_equals') ) + case.__init__() + self.assertTrue( hasattr(case, 'assertEquals') ) + self.assertTrue( hasattr(case, 'assert_equals') ) + + def test_setup(self): + case = CupOf() + case.setup() + self.assertEquals( deque(), case._stubs ) + self.assertEquals( deque(), case._mocks ) + + def test_teardown_closes_out_stubs_and_mocks(self): + class Stub(object): + calls = 0 + def assert_expectations(self): self.calls += 1 + def teardown(self): self.calls += 1 + + obj = type('test',(object,),{})() + setattr(obj, 'mock1', 'foo') + setattr(obj, 'mock2', 'bar') + + case = CupOf() + stub = Stub() + case._stubs = deque([stub]) + case._mocks = deque([(obj,'mock1','fee'), (obj,'mock2')]) + case.teardown() + self.assertEquals( 2, stub.calls ) + self.assertEquals( 'fee', obj.mock1 ) + self.assertFalse( hasattr(obj, 'mock2') ) + + def test_teardown_closes_out_stubs_and_mocks_when_exception(self): + class Stub(object): + calls = 0 + def assert_expectations(self): self.calls += 1; raise ExpectationNotSatisfied('blargh') + def teardown(self): self.calls += 1 - def test_expect(self): - pass + obj = type('test',(object,),{})() + setattr(obj, 'mock1', 'foo') + setattr(obj, 'mock2', 'bar') + + case = CupOf() + stub = Stub() + case._stubs = deque([stub]) + case._mocks = deque([(obj,'mock1','fee'), (obj,'mock2')]) + self.assertRaises( ExpectationNotSatisfied, case.teardown ) + self.assertEquals( 2, stub.calls ) + self.assertEquals( 'fee', obj.mock1 ) + self.assertFalse( hasattr(obj, 'mock2') )
Some tests for Chai class and a couple of bug fixes
agoragames_chai
train
ee0ea41111610ba44bf25e2dd91ce3c7ab5e92c8
diff --git a/src/Command/ClearCacheCommand.php b/src/Command/ClearCacheCommand.php index <HASH>..<HASH> 100644 --- a/src/Command/ClearCacheCommand.php +++ b/src/Command/ClearCacheCommand.php @@ -6,7 +6,7 @@ use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Component\Translation\TranslatorInterface; /** * Class ClearCacheCommand diff --git a/src/Controller/HelpTextController.php b/src/Controller/HelpTextController.php index <HASH>..<HASH> 100644 --- a/src/Controller/HelpTextController.php +++ b/src/Controller/HelpTextController.php @@ -16,7 +16,7 @@ use Sonata\AdminBundle\Admin\Pool; use Sonata\AdminBundle\Templating\MutableTemplateRegistryInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; -use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Component\Translation\TranslatorInterface; /** * Class HelpTextController. * diff --git a/src/Menu/AdminMenuBuilder.php b/src/Menu/AdminMenuBuilder.php index <HASH>..<HASH> 100644 --- a/src/Menu/AdminMenuBuilder.php +++ b/src/Menu/AdminMenuBuilder.php @@ -22,7 +22,7 @@ use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; -use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Component\Translation\TranslatorInterface; /** * Class AdminMenuBuilder. diff --git a/src/Menu/MenuBuilder.php b/src/Menu/MenuBuilder.php index <HASH>..<HASH> 100644 --- a/src/Menu/MenuBuilder.php +++ b/src/Menu/MenuBuilder.php @@ -25,7 +25,7 @@ use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; -use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Component\Translation\TranslatorInterface; /** * Class MenuBuilder. diff --git a/src/Twig/Extension/NetworkingHelperExtension.php b/src/Twig/Extension/NetworkingHelperExtension.php index <HASH>..<HASH> 100644 --- a/src/Twig/Extension/NetworkingHelperExtension.php +++ b/src/Twig/Extension/NetworkingHelperExtension.php @@ -35,7 +35,7 @@ use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormView; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\KernelInterface; -use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Component\Translation\TranslatorInterface; use Twig\Environment; use Twig\Extension\AbstractExtension; use Twig\TwigFilter;
backwards compatiblity with legacy TranslatorInterface
networking_init-cms-bundle
train
24c44e7a8eec0806c25967ba712c8c80828fa853
diff --git a/pkg/cloudprovider/providers/aws/aws.go b/pkg/cloudprovider/providers/aws/aws.go index <HASH>..<HASH> 100644 --- a/pkg/cloudprovider/providers/aws/aws.go +++ b/pkg/cloudprovider/providers/aws/aws.go @@ -2104,22 +2104,48 @@ func (s *AWSCloud) UpdateTCPLoadBalancer(name, region string, hosts []string) er } // Returns the instance with the specified ID -func (a *AWSCloud) getInstanceById(instanceID string) (*ec2.Instance, error) { - request := &ec2.DescribeInstancesInput{ - InstanceIds: []*string{&instanceID}, - } - - instances, err := a.ec2.DescribeInstances(request) +// This function is currently unused, but seems very likely to be needed again +func (a *AWSCloud) getInstanceByID(instanceID string) (*ec2.Instance, error) { + instances, err := a.getInstancesByIDs([]*string{&instanceID}) if err != nil { return nil, err } + if len(instances) == 0 { return nil, fmt.Errorf("no instances found for instance: %s", instanceID) } if len(instances) > 1 { return nil, fmt.Errorf("multiple instances found for instance: %s", instanceID) } - return instances[0], nil + + return instances[instanceID], nil +} + +func (a *AWSCloud) getInstancesByIDs(instanceIDs []*string) (map[string]*ec2.Instance, error) { + instancesByID := make(map[string]*ec2.Instance) + if len(instanceIDs) == 0 { + return instancesByID, nil + } + + request := &ec2.DescribeInstancesInput{ + InstanceIds: instanceIDs, + } + + instances, err := a.ec2.DescribeInstances(request) + if err != nil { + return nil, err + } + + for _, instance := range instances { + instanceID := orEmpty(instance.InstanceId) + if instanceID == "" { + continue + } + + instancesByID[instanceID] = instance + } + + return instancesByID, nil } // TODO: Make efficient diff --git a/pkg/cloudprovider/providers/aws/aws_routes.go b/pkg/cloudprovider/providers/aws/aws_routes.go index <HASH>..<HASH> 100644 --- a/pkg/cloudprovider/providers/aws/aws_routes.go +++ b/pkg/cloudprovider/providers/aws/aws_routes.go @@ -56,6 +56,23 @@ func (s *AWSCloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error } var routes []*cloudprovider.Route + var instanceIDs []*string + + for _, r := range table.Routes { + instanceID := orEmpty(r.InstanceId) + + if instanceID == "" { + continue + } + + instanceIDs = append(instanceIDs, &instanceID) + } + + instances, err := s.getInstancesByIDs(instanceIDs) + if err != nil { + return nil, err + } + for _, r := range table.Routes { instanceID := orEmpty(r.InstanceId) destinationCIDR := orEmpty(r.DestinationCidrBlock) @@ -64,9 +81,10 @@ func (s *AWSCloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error continue } - instance, err := s.getInstanceById(instanceID) - if err != nil { - return nil, err + instance, found := instances[instanceID] + if !found { + glog.Warningf("unable to find instance ID %s in the list of instances being routed to", instanceID) + continue } instanceName := orEmpty(instance.PrivateDnsName) routeName := clusterName + "-" + destinationCIDR
optimize ListRoutes to fetch instances only once per call Issue #<I> - fixes courtesy of @justinsb - thank you
kubernetes_kubernetes
train
af7906fc5c20b1a3850e2902c75555e1c0cc2ce6
diff --git a/src/extensions/default/CodeFolding/foldhelpers/foldcode.js b/src/extensions/default/CodeFolding/foldhelpers/foldcode.js index <HASH>..<HASH> 100644 --- a/src/extensions/default/CodeFolding/foldhelpers/foldcode.js +++ b/src/extensions/default/CodeFolding/foldhelpers/foldcode.js @@ -96,8 +96,9 @@ define(function (require, exports, module) { if (force === "fold") { delete range.cleared; - // in some cases such as in xml style files, the start of line folds can span multiple lines - // render a gutter marker for both the beginning and end of the line + // In some cases such as in xml style files, the start of line folds can span multiple lines. + // For instance the attributes of an element can span multiple lines. In these cases when folding + // we want to render a gutter marker for both the beginning and end of the opening xml tag. if (pos.line < range.from.line) { cm._lineFolds[range.from.line] = range; } else { diff --git a/src/extensions/default/CodeFolding/unittest-files/test.html b/src/extensions/default/CodeFolding/unittest-files/test.html index <HASH>..<HASH> 100644 --- a/src/extensions/default/CodeFolding/unittest-files/test.html +++ b/src/extensions/default/CodeFolding/unittest-files/test.html @@ -35,4 +35,4 @@ </div> </form> </body> -</html> \ No newline at end of file +</html> diff --git a/src/extensions/default/CodeFolding/unittests.js b/src/extensions/default/CodeFolding/unittests.js index <HASH>..<HASH> 100644 --- a/src/extensions/default/CodeFolding/unittests.js +++ b/src/extensions/default/CodeFolding/unittests.js @@ -23,9 +23,6 @@ define(function (require, exports, module) { foldMarkerClosed = gutterName + "-folded"; var extensionPath = FileUtils.getNativeModuleDirectoryPath(module), testDocumentDirectory = extensionPath + "/unittest-files/", - testFiles = ["test.js", "test.hmtml"].map(function (file) { - return testDocumentDirectory + file; - }), // The line numbers referenced below are dependent on the files in /unittest-files directory. // Remember to update the numbers if the files change. testFilesSpec = { @@ -35,7 +32,6 @@ define(function (require, exports, module) { sameLevelFoldableLines: [17, 21], firstSelection: {start: {line: 2, ch: 0}, end: {line: 10, ch: 0}}, secondSelection: {start: {line: 5, ch: 0}, end: {line: 8, ch: 4}} - }, html: { filePath: testDocumentDirectory + "test.html", @@ -44,9 +40,9 @@ define(function (require, exports, module) { firstSelection: {start: {line: 3, ch: 0}, end: {line: 10, ch: 0}}, secondSelection: {start: {line: 6, ch: 0}, end: {line: 17, ch: 4}} } - }; - - var open = "open", folded = "folded"; + }, + open = "open", + folded = "folded"; /** * Utility to temporarily set preference values in the session scope
Addressed CR comments and merged with master.
adobe_brackets
train
252d94fb0c3388dfe49f3d2bd665964804f189c2
diff --git a/src/main/java/com/theisenp/harbor/Harbor.java b/src/main/java/com/theisenp/harbor/Harbor.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/theisenp/harbor/Harbor.java +++ b/src/main/java/com/theisenp/harbor/Harbor.java @@ -10,12 +10,14 @@ import lcm.lcm.LCM; import org.joda.time.Duration; -import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.theisenp.harbor.lcm.Initialize; import com.theisenp.harbor.lcm.Publisher; +import com.theisenp.harbor.lcm.Subscribe; +import com.theisenp.harbor.lcm.Subscriber; +import com.theisenp.harbor.lcm.Unsubscribe; import com.theisenp.harbor.utils.HarborUtils; /** @@ -40,6 +42,7 @@ public class Harbor { private final Set<Listener> listeners = new HashSet<>(); private final ListeningScheduledExecutorService executor; private final ListenableFuture<LCM> lcm; + private final Subscriber subscriber; private ListenableFuture<Object> publisher; /** @@ -67,6 +70,7 @@ public class Harbor { // Initialize the LCM instance on a background thread executor = listeningDecorator(newSingleThreadScheduledExecutor()); lcm = executor.submit(new Initialize(address, port, ttl)); + subscriber = new Subscriber(executor, timeout); } /** @@ -132,18 +136,20 @@ public class Harbor { } /** - * TODO + * Starts the publish and subscribe tasks */ public void open() { - AsyncFunction<LCM, Object> function = new Publisher(executor, period, peer); - publisher = Futures.transform(lcm, function); + Futures.transform(lcm, new Subscribe(subscriber)); + publisher = Futures.transform(lcm, new Publisher(executor, period, peer)); } /** - * TODO + * Stops the publish and subscribe tasks */ public void close() { - + Futures.transform(lcm, new Unsubscribe(subscriber)); + // TODO: Remove all peers + publisher.cancel(true); } /**
Added partial open/close harbor implementations
theisenp_harbor
train
8099338595cefab8d6a416c0457128e6f8ff3e20
diff --git a/tests/column_aggregate_expectations/test_column_aggregate_expectations.py b/tests/column_aggregate_expectations/test_column_aggregate_expectations.py index <HASH>..<HASH> 100644 --- a/tests/column_aggregate_expectations/test_column_aggregate_expectations.py +++ b/tests/column_aggregate_expectations/test_column_aggregate_expectations.py @@ -1,7 +1,7 @@ ### ### # -# This file should not be modified. To adjust test cases, edit the related json file. +# This file should not be modified. To adjust test cases, edit the related json file(s). # ### ### @@ -55,8 +55,9 @@ def pytest_generate_tests(metafunc): def test_case_runner(test_case): - # FIXME: - # test_case["dataset"].remove_all_expectations() + # Note: this should never be done in practice, but we are wiping expectations to reuse datasets during testing. + test_case["dataset"].initialize_expectations() + evaluate_json_test( test_case["dataset"], test_case["expectation_type"], diff --git a/tests/column_map_expectations/test_column_map_expectations.py b/tests/column_map_expectations/test_column_map_expectations.py index <HASH>..<HASH> 100644 --- a/tests/column_map_expectations/test_column_map_expectations.py +++ b/tests/column_map_expectations/test_column_map_expectations.py @@ -1,7 +1,7 @@ ### ### # -# This file should not be modified. To adjust test cases, edit the related json file. +# This file should not be modified. To adjust test cases, edit the related json file(s). # ### ### @@ -54,8 +54,9 @@ def pytest_generate_tests(metafunc): ) def test_case_runner(test_case): - #FIXME: - # test_case["dataset"].remove_all_expectations() + # Note: this should never be done in practice, but we are wiping expectations to reuse datasets during testing. + test_case["dataset"].initialize_expectations() + evaluate_json_test( test_case["dataset"], test_case["expectation_type"], diff --git a/tests/other_expectations/test_other_expectations.py b/tests/other_expectations/test_other_expectations.py index <HASH>..<HASH> 100644 --- a/tests/other_expectations/test_other_expectations.py +++ b/tests/other_expectations/test_other_expectations.py @@ -1,7 +1,7 @@ ### ### # -# This file should not be modified. To adjust test cases, edit the related json file. +# This file should not be modified. To adjust test cases, edit the related json file(s). # ### ### @@ -55,8 +55,9 @@ def pytest_generate_tests(metafunc): def test_case_runner(test_case): - # FIXME: - # test_case["dataset"].remove_all_expectations() + # Note: this should never be done in practice, but we are wiping expectations to reuse datasets during testing. + test_case["dataset"].initialize_expectations() + evaluate_json_test( test_case["dataset"], test_case["expectation_type"],
Update json_test_runner template docs and initialize_expectations in each one.
great-expectations_great_expectations
train
fada2391c351be4c315fa96ea05b9820cb641c63
diff --git a/perceval/backends/core/mbox.py b/perceval/backends/core/mbox.py index <HASH>..<HASH> 100644 --- a/perceval/backends/core/mbox.py +++ b/perceval/backends/core/mbox.py @@ -60,18 +60,19 @@ class MBox(Backend): :param dirpath: directory path where the mboxes are stored :param tag: label used to mark the data :param archive: archive to store/retrieve items + :param ssl_verify: enable/disable SSL verification """ - version = '0.12.0' + version = '0.13.0' CATEGORIES = [CATEGORY_MESSAGE] DATE_FIELD = 'Date' MESSAGE_ID_FIELD = 'Message-ID' - def __init__(self, uri, dirpath, tag=None, archive=None): + def __init__(self, uri, dirpath, tag=None, archive=None, ssl_verify=True): origin = uri - super().__init__(origin, tag=tag, archive=archive) + super().__init__(origin, tag=tag, archive=archive, ssl_verify=ssl_verify) self.uri = uri self.dirpath = dirpath @@ -332,7 +333,8 @@ class MBoxCommand(BackendCommand): """Returns the MBox argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND, - from_date=True) + from_date=True, + ssl_verify=True) # Required arguments parser.parser.add_argument('uri', diff --git a/tests/test_mbox.py b/tests/test_mbox.py index <HASH>..<HASH> 100644 --- a/tests/test_mbox.py +++ b/tests/test_mbox.py @@ -239,6 +239,7 @@ class TestMBoxBackend(TestBaseMBox): self.assertEqual(backend.dirpath, self.tmp_path) self.assertEqual(backend.origin, 'http://example.com/') self.assertEqual(backend.tag, 'test') + self.assertTrue(backend.ssl_verify) # When origin is empty or None it will be set to # the value in uri @@ -246,9 +247,10 @@ class TestMBoxBackend(TestBaseMBox): self.assertEqual(backend.origin, 'http://example.com/') self.assertEqual(backend.tag, 'http://example.com/') - backend = MBox('http://example.com/', self.tmp_path, tag='') + backend = MBox('http://example.com/', self.tmp_path, tag='', ssl_verify=False) self.assertEqual(backend.origin, 'http://example.com/') self.assertEqual(backend.tag, 'http://example.com/') + self.assertFalse(backend.ssl_verify) def test_has_archiving(self): """Test if it returns False when has_archiving is called""" @@ -575,6 +577,19 @@ class TestMBoxCommand(unittest.TestCase): self.assertEqual(parsed_args.dirpath, '/tmp/perceval/') self.assertEqual(parsed_args.tag, 'test') self.assertEqual(parsed_args.from_date, DEFAULT_DATETIME) + self.assertTrue(parsed_args.ssl_verify) + + args = ['http://example.com/', '/tmp/perceval/', + '--tag', 'test', + '--from-date', '1970-01-01', + '--no-ssl-verify'] + + parsed_args = parser.parse(*args) + self.assertEqual(parsed_args.uri, 'http://example.com/') + self.assertEqual(parsed_args.dirpath, '/tmp/perceval/') + self.assertEqual(parsed_args.tag, 'test') + self.assertEqual(parsed_args.from_date, DEFAULT_DATETIME) + self.assertFalse(parsed_args.ssl_verify) if __name__ == "__main__":
[mbox] Support for SSL verification This code enhances the backend with the support to disable SSL verification. Tests have been added accordingly. Backend version is now <I>
chaoss_grimoirelab-perceval
train
1292ce83ea171db59648e2c7c455e8c4cd2f07a2
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,8 @@ setup( packages=find_packages(exclude=["sqlite_framework_test*"]), setup_requires=[ - 'setuptools_scm' + 'setuptools_scm', + 'wheel' ], install_requires=[
Add "wheel" as a build dependency in setup.py, as it is needed for bdist_wheel
alvarogzp_python-sqlite-framework
train
5d5dabc1d2981167569376cf7f932e12cd252002
diff --git a/ocrd/ocrd/cli/workspace.py b/ocrd/ocrd/cli/workspace.py index <HASH>..<HASH> 100644 --- a/ocrd/ocrd/cli/workspace.py +++ b/ocrd/ocrd/cli/workspace.py @@ -154,15 +154,16 @@ def workspace_add_file(ctx, file_grp, file_id, mimetype, page_id, ignore, check_ kwargs = {'fileGrp': file_grp, 'ID': file_id, 'mimetype': mimetype, 'pageId': page_id, 'force': force, 'ignore': ignore} log = getLogger('ocrd.cli.workspace.add') + log.debug("Adding '%s' (%s)", fname, kwargs) if not (fname.startswith('http://') or fname.startswith('https://')): if not fname.startswith(ctx.directory): - if exists(join(ctx.directory, fname)): - fname = join(ctx.directory, fname) + if exists(ctx.directory + '/' + fname): + fname = ctx.directory + '/' + fname else: - log.debug("File '%s' is not in workspace, copying", fname) + log.info("File '%s' is not in workspace, copying", fname) try: fname = ctx.resolver.download_to_directory(ctx.directory, fname, subdir=file_grp) - except FileNotFoundError as e: + except FileNotFoundError: if check_file_exists: log.error("File '%s' does not exist, halt execution!" % fname) sys.exit(1) diff --git a/tests/cli/test_workspace.py b/tests/cli/test_workspace.py index <HASH>..<HASH> 100644 --- a/tests/cli/test_workspace.py +++ b/tests/cli/test_workspace.py @@ -191,6 +191,32 @@ class TestCli(TestCase): self.assertEqual(exit_code, 1) self.assertIn("File 'does-not-exist.xml' does not exist, halt execution!", err) + def test_add_519(self): + """ + https://github.com/OCR-D/core/issues/519 + """ + with TemporaryDirectory() as tempdir: + wsdir = Path(tempdir, "workspace") + wsdir.mkdir() + srcdir = Path(tempdir, "source") + srcdir.mkdir() + srcfile = Path(srcdir, "srcfile.jpg") + srcfile_content = 'foo' + srcfile.write_text(srcfile_content) + with pushd_popd(wsdir): + exit_code, out, err = self.invoke_cli(workspace_cli, ['init']) + exit_code, out, err = self.invoke_cli(workspace_cli, [ + 'add', + '-m', 'image/jpg', + '-G', 'MAX', + '-i', 'IMG_MAX_1818975', + '-C', + str(srcfile) + ]) + self.assertEqual(exit_code, 0) + self.assertTrue(Path(wsdir, 'MAX', 'srcfile.jpg').exists()) + self.assertEquals(Path(wsdir, 'MAX', 'srcfile.jpg').read_text(), srcfile_content) + def test_add_existing_checked(self): ID = 'foo123file' page_id = 'foo123page'
workspace add: os.path.join behavior led to faulty existence check, fix #<I>
OCR-D_core
train
087ba9214593f761156d6092d1532d23324c92b2
diff --git a/lib/pmp/collection_document.rb b/lib/pmp/collection_document.rb index <HASH>..<HASH> 100644 --- a/lib/pmp/collection_document.rb +++ b/lib/pmp/collection_document.rb @@ -138,7 +138,7 @@ module PMP begin raw = connection(current_options.merge({url: url})).send(method) do |request| if [:post, :put].include?(method.to_sym) && !body.blank? - request.body = body.is_a?(String) ? body : body.to_json + request.body = body.is_a?(String) ? body : body.to_put_json end end rescue Faraday::Error::ResourceNotFound=>not_found_ex @@ -153,6 +153,18 @@ module PMP PMP::Response.new(raw, {method: method, url: url, body: body}) end + # blacklist what we PUT back to the server + def as_put_json + obj = self.as_json.select { |k,v| %w(attributes links).include?(k) } + obj['attributes'].reject! { |k,v| %w(created modified).include?(k) } + obj['links'].reject! { |k,v| %w(creator query edit auth).include?(k) } + obj + end + + def to_put_json + as_put_json.to_json + end + def set_guid_if_blank self.guid = SecureRandom.uuid if guid.blank? end
Blacklist what gets PUT back to the PMP The pmp seems to bomb if implicit attributes are explicitly PUT back. This will get fixed sometime in the future, but for now, follow the path of other SDK's and blacklist them.
PRX_pmp
train
d710990e13f2ce430651538f2b746f36aa189347
diff --git a/src/Forms/GridField/GridField.php b/src/Forms/GridField/GridField.php index <HASH>..<HASH> 100644 --- a/src/Forms/GridField/GridField.php +++ b/src/Forms/GridField/GridField.php @@ -438,6 +438,8 @@ class GridField extends FormField */ public function FieldHolder($properties = []) { + $this->extend('onBeforeRenderHolder', $this, $properties); + $columns = $this->getColumns(); $list = $this->getManipulatedList();
ENH Provide onBeforeRenderHolder extension hook. GridField has onBeforeRender in its Field method, but that hardly ever gets called. This commit adds the onBeforeRenderHolder extension hook that is normally available via FormField::FieldHolder().
silverstripe_silverstripe-framework
train
2009ef411dfbc9891ddbe2483e8f5b5e49e2ef3a
diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java index <HASH>..<HASH> 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java @@ -26,6 +26,8 @@ public class DefaultBotOptions implements BotOptions { private ProxyType proxyType; private String proxyHost; private int proxyPort; + private int getUpdatesTimeout; + private int getUpdatesLimit; public enum ProxyType { NO_PROXY, @@ -39,6 +41,8 @@ public class DefaultBotOptions implements BotOptions { baseUrl = ApiConstants.BASE_URL; httpContext = HttpClientContext.create(); proxyType = ProxyType.NO_PROXY; + getUpdatesLimit = ApiConstants.GETUPDATES_TIMEOUT; + getUpdatesLimit = 100; } @Override @@ -129,4 +133,20 @@ public class DefaultBotOptions implements BotOptions { public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } + + public int getGetUpdatesTimeout() { + return getUpdatesTimeout; + } + + public void setGetUpdatesTimeout(int getUpdatesTimeout) { + this.getUpdatesTimeout = getUpdatesTimeout; + } + + public int getGetUpdatesLimit() { + return getUpdatesLimit; + } + + public void setGetUpdatesLimit(int getUpdatesLimit) { + this.getUpdatesLimit = getUpdatesLimit; + } } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java index <HASH>..<HASH> 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java @@ -236,8 +236,8 @@ public class DefaultBotSession implements BotSession { private List<Update> getUpdatesFromServer() throws IOException { GetUpdates request = new GetUpdates() - .setLimit(100) - .setTimeout(ApiConstants.GETUPDATES_TIMEOUT) + .setLimit(options.getGetUpdatesLimit()) + .setTimeout(options.getGetUpdatesTimeout()) .setOffset(lastReceivedUpdate + 1); if (options.getAllowedUpdates() != null) {
Add timeout and update limit for long-polling updates to DefaultBotOptions Just a little commit to make the long-polling timeout and long-polling limit configurable via the BotOptions. Mainly for Testing
rubenlagus_TelegramBots
train
a6fefc86c08aba9e89e982dafd11f5a0387a11ca
diff --git a/spec/cpp_project_spec.rb b/spec/cpp_project_spec.rb index <HASH>..<HASH> 100644 --- a/spec/cpp_project_spec.rb +++ b/spec/cpp_project_spec.rb @@ -119,7 +119,9 @@ describe 'when building a shared library' do before( :each ) do Rake::Task.clear - @project = cpp_task( :shared_library ) + @project = cpp_task( :shared_library ) do |builder| + builder.compilation_options += ['-fPIC'] + end `rm -f #{ @project.target }` end
Shared lib compilation fix for gcc
joeyates_rake-builder
train
49b7903b1a81b8fee107d60295df665596b7920c
diff --git a/spec/system/aws/micro_bosh_spec.rb b/spec/system/aws/micro_bosh_spec.rb index <HASH>..<HASH> 100644 --- a/spec/system/aws/micro_bosh_spec.rb +++ b/spec/system/aws/micro_bosh_spec.rb @@ -49,28 +49,29 @@ describe "AWS" do end end - #Dir.chdir cf_release_path do - # run_bosh "create release" - # run_bosh "upload release #{cf_dev_release_yaml_path}" - #end - - #Dir.chdir deployments_path do - # run_bosh "deployment cf-aws-stub.yml" - # run_bosh "diff ../templates/cf-min-aws-vpc.erb" - #end - end + Dir.chdir cf_release_path do + run_bosh "create release" + run_bosh "upload release" + end - def cf_dev_release_yaml_path - `ls #{cf_release_path}/dev_releases/cf*.yml`.strip + Dir.chdir deployments_path do + run "#{deployments_aws_path}/generators/generator.rb '#{aws_configuration_template_path}' '#{vpc_outfile_path}'" + FileUtils.cp("cf-aws-stub.yml", "cf-aws.yml") + run_bosh "deployment cf-aws.yml" + run_bosh "diff #{deployments_aws_path}/templates/cf-min-aws-vpc.erb" + end end def cf_release_path @cf_release_path ||= begin path = File.join(BOSH_TMP_DIR, "spec", "cf-release") puts "Cloning CF-RELEASE" - run "rm -rf #{path}" - run "git clone git://github.com/cloudfoundry/cf-release.git '#{path}'" - run "cd #{path} && ./update" + if File.exist? path + run "cd '#{path}' && git reset --hard" + else + run "git clone git://github.com/cloudfoundry/cf-release.git '#{path}'" + end + run "cd '#{path}' && ./update" path end end
More work on CF deployment system spec
cloudfoundry_bosh
train
629a76c42741fdbaec0442b15cae620c16d02434
diff --git a/client/state/shortcodes/test/reducer.js b/client/state/shortcodes/test/reducer.js index <HASH>..<HASH> 100644 --- a/client/state/shortcodes/test/reducer.js +++ b/client/state/shortcodes/test/reducer.js @@ -100,6 +100,10 @@ describe( 'reducer', () => { it( 'should set shortcode of that site ID to false if request finishes successfully', () => { const state = requesting( deepFreeze( { 12345678: { + test_shortcode: true, + another_shortcode: true + }, + 87654321: { test_shortcode: true } } ), { @@ -110,14 +114,22 @@ describe( 'reducer', () => { expect( state ).to.eql( { 12345678: { - test_shortcode: false + test_shortcode: false, + another_shortcode: true }, + 87654321: { + test_shortcode: true + } } ); } ); it( 'should set shortcode of that site ID to false if request finishes unsuccessfully', () => { const state = requesting( deepFreeze( { 12345678: { + test_shortcode: true, + another_shortcode: true + }, + 87654321: { test_shortcode: true } } ), { @@ -129,8 +141,12 @@ describe( 'reducer', () => { expect( state ).to.eql( { 12345678: { - test_shortcode: false + test_shortcode: false, + another_shortcode: true }, + 87654321: { + test_shortcode: true + } } ); } );
State: Expand request success/failure reducer tests
Automattic_wp-calypso
train
c76012f550f96af45afd5de1df5ca42f5c223950
diff --git a/ansi2html/ansi2html.py b/ansi2html/ansi2html.py index <HASH>..<HASH> 100755 --- a/ansi2html/ansi2html.py +++ b/ansi2html/ansi2html.py @@ -36,8 +36,8 @@ class Ansi2HTMLConverter(object): """ Load the contents of 'ansi' into this object """ # For now, make heavy use of pixelbeat's amazing script. - cmd = "%s/ansi2html.sh" % self.base - p = sp.Popen([cmd], stdout=sp.PIPE, stdin=sp.PIPE, shell=True) + cmd = ["/bin/sh", "%s/ansi2html.sh" % self.base] + p = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, shell=True) body = HTML(p.communicate(ansi)[0].decode('utf-8')) self._attrs = { diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ except ImportError: setup( name='ansi2html', - version='0.2.4', + version='0.2.5', description="Python Wrapper for pixelbeat.org's ansi2html.sh", long_description=open('README.md').read(), author='Ralph Bean',
permissions get weird once the script travels through pypi/pip
ralphbean_ansi2html
train
cb0a2af6441fbcfed46934a70f834105f01775d8
diff --git a/extensions-core/kafka-extraction-namespace/src/test/java/org/apache/druid/query/lookup/TestKafkaExtractionCluster.java b/extensions-core/kafka-extraction-namespace/src/test/java/org/apache/druid/query/lookup/TestKafkaExtractionCluster.java index <HASH>..<HASH> 100644 --- a/extensions-core/kafka-extraction-namespace/src/test/java/org/apache/druid/query/lookup/TestKafkaExtractionCluster.java +++ b/extensions-core/kafka-extraction-namespace/src/test/java/org/apache/druid/query/lookup/TestKafkaExtractionCluster.java @@ -91,6 +91,9 @@ public class TestKafkaExtractionCluster { zkServer = new TestingCluster(1); zkServer.start(); + closer.register(() -> { + zkServer.stop(); + }); kafkaServer = new KafkaServer( getBrokerProperties(), @@ -99,6 +102,10 @@ public class TestKafkaExtractionCluster false); kafkaServer.startup(); + closer.register(() -> { + kafkaServer.shutdown(); + kafkaServer.awaitShutdown(); + }); log.info("---------------------------Started Kafka Broker ---------------------------"); log.info("---------------------------Publish Messages to topic-----------------------");
TestKafkaExtractionCluster: Shut down Kafka, ZK in @After. (#<I>)
apache_incubator-druid
train
d4e59b963c243c1e37e575a9f4b6cef5861a07d7
diff --git a/org.jenetics/src/main/java/org/jenetics/optimizer/CompositeCodec.java b/org.jenetics/src/main/java/org/jenetics/optimizer/CompositeCodec.java index <HASH>..<HASH> 100644 --- a/org.jenetics/src/main/java/org/jenetics/optimizer/CompositeCodec.java +++ b/org.jenetics/src/main/java/org/jenetics/optimizer/CompositeCodec.java @@ -51,9 +51,8 @@ public class CompositeCodec<T, G extends Gene<?, G>> implements Codec<T, G> { _codecs = requireNonNull(codecs); _decoder = requireNonNull(decoder); - final ISeq<Genotype<G>> genotypes = _codecs.stream() - .map(c -> c.encoding().newInstance()) - .collect(ISeq.toISeq()); + final ISeq<Genotype<G>> genotypes = _codecs + .map(c -> c.encoding().newInstance()); _lengths = genotypes.stream() .mapToInt(Genotype::length)
Implement 'CompositeCodec' class. Do some code cleanup.
jenetics_jenetics
train
37e19aa71296d08f70da6c0ac690c3d6a271b07e
diff --git a/lib/Dependency.js b/lib/Dependency.js index <HASH>..<HASH> 100644 --- a/lib/Dependency.js +++ b/lib/Dependency.js @@ -43,9 +43,9 @@ Dependency.prototype.load = function (realModule, parentDependency) { var artifact var name = this.name + var dashedName = this._dashify(name) try { - var dashedName = this._dashify(name) debug('try require(\'%s\') ', name) // first try naive require @@ -55,7 +55,7 @@ Dependency.prototype.load = function (realModule, parentDependency) { } catch (e) { - if (e.code !== 'MODULE_NOT_FOUND') + if (e.code !== 'MODULE_NOT_FOUND' && !this._isModuleSpecificError(dashedName, e)) throw e debug('fail require(\'%s\')', dashedName) @@ -88,7 +88,7 @@ Dependency.prototype.load = function (realModule, parentDependency) { } catch (e) { - if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf(depPath) > -1) { + if (e.code === 'MODULE_NOT_FOUND' && this._isModuleSpecificError(depPath, e)) { debug('fail require(\'%s\')', depPath) notFoundErrors++ } else { @@ -155,4 +155,9 @@ Dependency.prototype._dashify = function(name) { } return result +} + +//TODO: make this check more robust +Dependency.prototype._isModuleSpecificError = function (module, e) { + return e.toString().indexOf(module) > -1 } \ No newline at end of file
in naive require, make sure that module not found error is specific for the module
kessler_darkmagic
train
dd934b9690ae8f1498bb9aa586863e8d6f092a62
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -162,7 +162,8 @@ class Node extends libp2p { } }, dht: { - kBucketSize: 20 + kBucketSize: 20, + enabledDiscovery: true // Allows to disable discovery (enabled by default) }, // Enable/Disable Experimental features EXPERIMENTAL: { // Experimental features ("behind a flag") diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "dirty-chai": "^2.0.1", "electron-webrtc": "~0.3.0", "libp2p-circuit": "~0.2.1", - "libp2p-kad-dht": "~0.10.3", + "libp2p-kad-dht": "~0.10.5", "libp2p-mdns": "~0.12.0", "libp2p-mplex": "~0.8.2", "libp2p-bootstrap": "~0.9.3", diff --git a/src/config.js b/src/config.js index <HASH>..<HASH> 100644 --- a/src/config.js +++ b/src/config.js @@ -29,7 +29,8 @@ const OptionsSchema = Joi.object({ }) }).default(), dht: Joi.object().keys({ - kBucketSize: Joi.number().allow(null) + kBucketSize: Joi.number().allow(null), + enabledDiscovery: Joi.boolean().default(true) }), EXPERIMENTAL: Joi.object().keys({ dht: Joi.boolean().default(false), diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -85,8 +85,11 @@ class Node extends EventEmitter { // dht provided components (peerRouting, contentRouting, dht) if (this._config.EXPERIMENTAL.dht) { const DHT = this._modules.dht + const enabledDiscovery = this._config.dht.enabledDiscovery !== false + this._dht = new DHT(this._switch, { kBucketSize: this._config.dht.kBucketSize || 20, + enabledDiscovery, // TODO make datastore an option of libp2p itself so // that other things can use it as well datastore: dht.datastore diff --git a/test/create.spec.js b/test/create.spec.js index <HASH>..<HASH> 100644 --- a/test/create.spec.js +++ b/test/create.spec.js @@ -28,10 +28,12 @@ describe('libp2p creation', () => { sinon.spy(sw, 'start') sinon.spy(cm, 'start') sinon.spy(dht, 'start') + sinon.spy(dht.randomWalk, 'start') sinon.spy(pub, 'start') sinon.spy(sw, 'stop') sinon.spy(cm, 'stop') sinon.spy(dht, 'stop') + sinon.spy(dht.randomWalk, 'stop') sinon.spy(pub, 'stop') sinon.spy(node, 'emit') @@ -41,6 +43,7 @@ describe('libp2p creation', () => { expect(sw.start.calledOnce).to.equal(true) expect(cm.start.calledOnce).to.equal(true) expect(dht.start.calledOnce).to.equal(true) + expect(dht.randomWalk.start.calledOnce).to.equal(true) expect(pub.start.calledOnce).to.equal(true) expect(node.emit.calledWith('start')).to.equal(true) @@ -53,6 +56,7 @@ describe('libp2p creation', () => { expect(sw.stop.calledOnce).to.equal(true) expect(cm.stop.calledOnce).to.equal(true) expect(dht.stop.calledOnce).to.equal(true) + expect(dht.randomWalk.stop.called).to.equal(true) expect(pub.stop.calledOnce).to.equal(true) expect(node.emit.calledWith('stop')).to.equal(true) diff --git a/test/utils/bundle-browser.js b/test/utils/bundle-browser.js index <HASH>..<HASH> 100644 --- a/test/utils/bundle-browser.js +++ b/test/utils/bundle-browser.js @@ -79,7 +79,8 @@ class Node extends libp2p { } }, dht: { - kBucketSize: 20 + kBucketSize: 20, + enabledDiscovery: true }, EXPERIMENTAL: { dht: false, diff --git a/test/utils/bundle-nodejs.js b/test/utils/bundle-nodejs.js index <HASH>..<HASH> 100644 --- a/test/utils/bundle-nodejs.js +++ b/test/utils/bundle-nodejs.js @@ -72,7 +72,8 @@ class Node extends libp2p { } }, dht: { - kBucketSize: 20 + kBucketSize: 20, + enabledDiscovery: true }, EXPERIMENTAL: { dht: false,
fix: start kad dht random walk (#<I>) * fix: start kad dht random walk * chore: added tests and stop random walk * chore: allows to disable discovery for dht * chore: upgrade kad-dht version
libp2p_js-libp2p
train
c2d614b0415269606aca4647c04c759725ca5ae0
diff --git a/src/main/java/jcifs/smb/SpnegoContext.java b/src/main/java/jcifs/smb/SpnegoContext.java index <HASH>..<HASH> 100644 --- a/src/main/java/jcifs/smb/SpnegoContext.java +++ b/src/main/java/jcifs/smb/SpnegoContext.java @@ -54,6 +54,7 @@ class SpnegoContext implements SSPContext { private SSPContext mechContext; private Oid[] mechs; + private boolean firstResponse; /** @@ -187,11 +188,12 @@ class SpnegoContext implements SSPContext { try { SpnegoToken spToken = getToken(inputBuf, offset, len); - if ( spToken instanceof NegTokenTarg ) { + if ( this.firstResponse && spToken instanceof NegTokenTarg ) { NegTokenTarg targ = (NegTokenTarg) spToken; if ( !this.mechContext.isSupported(targ.getMechanism()) ) { throw new SmbException("Server chose an unsupported mechanism " + targ.getMechanism()); } + this.firstResponse = false; } Oid currentMech = null;
Only check SPNEGO mechanism on first response token (#<I>)
AgNO3_jcifs-ng
train
3b5359bf51fbd71e89de1c9da68c8953b6eaf40e
diff --git a/classes/Pods.php b/classes/Pods.php index <HASH>..<HASH> 100644 --- a/classes/Pods.php +++ b/classes/Pods.php @@ -1010,7 +1010,7 @@ class Pods implements Iterator { // Default image field handlers. $image_fields = array( 'image_attachment', - 'image_attachment_url' + 'image_attachment_url', ); if ( 'post_type' === $this->pod_data['type'] ) { @@ -1064,7 +1064,7 @@ class Pods implements Iterator { $attachment_id = get_post_thumbnail_id(); break; case 'image_attachment': - if ( isset ( $traverse_names[0] ) ) { + if ( isset( $traverse_names[0] ) ) { $attachment_id = $traverse_names[0]; array_shift( $traverse_names ); } @@ -1087,13 +1087,15 @@ class Pods implements Iterator { } if ( $url ) { - $value = pods_image_url( $attachment_id, $size, 0, true ); + $value = pods_image_url( $attachment_id, $size, 0, true ); + $object_field_found = true; break; } if ( $size ) { $value = pods_image( $attachment_id, $size, 0, null, true ); + $object_field_found = true; break; }
Codestyle (tr1b0t)
pods-framework_pods
train
68bf1a7f4627c0a78df078b1ed7ed4dc4255c450
diff --git a/command/server.go b/command/server.go index <HASH>..<HASH> 100644 --- a/command/server.go +++ b/command/server.go @@ -1100,6 +1100,25 @@ func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig return nil, err } + // Upgrade the default K/V store + req := &logical.Request{ + Operation: logical.UpdateOperation, + ClientToken: init.RootToken, + Path: "sys/mounts/secret/tune", + Data: map[string]interface{}{ + "options": map[string]string{ + "version": "2", + }, + }, + } + resp, err := core.HandleRequest(req) + if err != nil { + return nil, errwrap.Wrapf("error upgrading default K/V store: {{err}}", err) + } + if resp.IsError() { + return nil, errwrap.Wrapf("failed to upgrade default K/V store: {{err}}", resp.Error()) + } + return init, nil } diff --git a/vault/mount.go b/vault/mount.go index <HASH>..<HASH> 100644 --- a/vault/mount.go +++ b/vault/mount.go @@ -959,7 +959,7 @@ func (c *Core) defaultMountTable() *MountTable { Accessor: mountAccessor, BackendAwareUUID: bUUID, Options: map[string]string{ - "version": "2", + "version": "1", }, } table.Entries = append(table.Entries, kvMount)
Make standard secret/ mount version 1, but upgrade to v2 in dev mode.
hashicorp_vault
train
d6f834adf2993ad1236bf8e2dd33781ad41c209d
diff --git a/tests/test_base_optimizer.py b/tests/test_base_optimizer.py index <HASH>..<HASH> 100644 --- a/tests/test_base_optimizer.py +++ b/tests/test_base_optimizer.py @@ -246,6 +246,11 @@ def test_portfolio_performance(): w_dict = dict(zip(range(len(ef.weights)), ef.weights)) assert portfolio_performance(w_dict, ef.expected_returns, ef.cov_matrix) == expected + # Weights must not sum to zero. + w_dict = dict(zip(range(len(ef.weights)), np.zeros(len(ef.weights)))) + with pytest.raises(ValueError): + portfolio_performance(w_dict, ef.expected_returns, ef.cov_matrix) + def test_add_contraint_exception(): ef = setup_efficient_frontier()
Improve test coverage of portfolio_performance fn by adding edge case.
robertmartin8_PyPortfolioOpt
train
c133a594e0d480635004fe9fad3c4f13a6816450
diff --git a/tests/test_connectors/test_ssh.py b/tests/test_connectors/test_ssh.py index <HASH>..<HASH> 100644 --- a/tests/test_connectors/test_ssh.py +++ b/tests/test_connectors/test_ssh.py @@ -25,6 +25,12 @@ from pyinfra.api.exceptions import ConnectError, PyinfraError from ..util import make_inventory +def make_raise_exception_function(cls, *args, **kwargs): + def handler(*a, **kw): + raise cls(*args, **kwargs) + return handler + + @patch('pyinfra.api.connectors.ssh.SSHClient.get_transport', MagicMock()) @patch('pyinfra.api.connectors.ssh.open', mock_open(read_data='test!'), create=True) class TestSSHConnector(TestCase): @@ -225,6 +231,15 @@ class TestSSHConnector(TestCase): 'pyinfra.api.connectors.ssh.path.isfile', lambda *args, **kwargs: True, ), patch( + 'pyinfra.api.connectors.ssh.DSSKey.from_private_key_file', + make_raise_exception_function(SSHException), + ), patch( + 'pyinfra.api.connectors.ssh.ECDSAKey.from_private_key_file', + make_raise_exception_function(SSHException), + ), patch( + 'pyinfra.api.connectors.ssh.Ed25519Key.from_private_key_file', + make_raise_exception_function(SSHException), + ), patch( 'pyinfra.api.connectors.ssh.RSAKey.from_private_key_file', ) as fake_key_open:
Fix test that should fail when looping all SSH key types.
Fizzadar_pyinfra
train
28f5642b2689c761a1817b2ea667673ae4b538cb
diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py index <HASH>..<HASH> 100644 --- a/cherrypy/_cprequest.py +++ b/cherrypy/_cprequest.py @@ -428,11 +428,11 @@ class Request(object): and %(version)s. The set of format mappings can be extended by overriding HTTPError.set_response. - If a callable is provided, it will be called by default with keyword + If a callable is provided, it will be called by default with keyword arguments 'status', 'message', 'traceback', and 'version', as for a - string-formatting template. The callable must return a string which - will be set to response.body. It may also override headers or perform - any other processing. + string-formatting template. The callable must return a string or iterable of + strings which will be set to response.body. It may also override headers or + perform any other processing. If no entry is given for an error code, and no 'default' entry exists, a default template will be used.
correct the docstring for Request.error_page, which claimed that the callable had to return a string. returning an iterable of strings works now with the fix in r<I>.
cherrypy_cheroot
train
14a8a781a67f732e97d0138076af0d260749299e
diff --git a/form-widget/form-widget.js b/form-widget/form-widget.js index <HASH>..<HASH> 100644 --- a/form-widget/form-widget.js +++ b/form-widget/form-widget.js @@ -97,8 +97,8 @@ export const ViewModel = FieldComponentMap.extend('FormWidget', { * An object consisting of validation error strings * ```javascript *{ - * fieldName: 'error message', - * otherFieldName: 'another error message' + * field: 'error message', + * otherfield: 'another error message' *} * ``` * @property {Object} form-widget.ViewModel.props.validationErrors diff --git a/list-table/demo/listTable.js b/list-table/demo/listTable.js index <HASH>..<HASH> 100644 --- a/list-table/demo/listTable.js +++ b/list-table/demo/listTable.js @@ -146,7 +146,7 @@ document.body.appendChild(render({ // sorts the observable list setSort(a, b, c, sortInfo) { - const field = sortInfo.fieldName; + const field = sortInfo.field; this.data.sort((a, b) => { return sortInfo.type === 'asc' diff --git a/list-table/list-table.stache b/list-table/list-table.stache index <HASH>..<HASH> 100644 --- a/list-table/list-table.stache +++ b/list-table/list-table.stache @@ -11,9 +11,9 @@ </div> </th> {{#each fields}} - <th {{#is name currentSort.fieldName}} class="text-bold" {{/is}} ($click)="setSort(name)"> + <th {{#is name currentSort.field}} class="text-bold" {{/is}} ($click)="setSort(name)"> {{alias}} - {{#is name currentSort.fieldName}}<i class="sort-icon fa fa-sort-{{#is currentSort.type 'desc'}}desc{{else}}asc{{/is}}"></i>{{/is}} + {{#is name currentSort.field}}<i class="sort-icon fa fa-sort-{{#is currentSort.type 'desc'}}desc{{else}}asc{{/is}}"></i>{{/is}} </th> {{/each}} </tr> diff --git a/list-table/list-table.test.js b/list-table/list-table.test.js index <HASH>..<HASH> 100644 --- a/list-table/list-table.test.js +++ b/list-table/list-table.test.js @@ -61,24 +61,24 @@ test('fields get() without providing fields', (assert) => { }); test('setSort(field)', (assert) => { - const fieldName = 'name'; + const field = 'name'; const otherField = 'label'; - vm.setSort(fieldName); + vm.setSort(field); assert.deepEqual(vm.currentSort.serialize(), { type: 'asc', - fieldName: fieldName + field: field }, 'Current sort should be ascending and set to field'); - vm.setSort(fieldName); + vm.setSort(field); assert.deepEqual(vm.currentSort.serialize(), { type: 'desc', - fieldName: fieldName + field: field }, 'Current sort should be descending and set to field'); vm.setSort(otherField); assert.deepEqual(vm.currentSort.serialize(), { type: 'asc', - fieldName: otherField + field: otherField }, 'Current sort should be ascending and set to field'); }); diff --git a/test/data/fixtures.js b/test/data/fixtures.js index <HASH>..<HASH> 100644 --- a/test/data/fixtures.js +++ b/test/data/fixtures.js @@ -49,8 +49,8 @@ fixture({ //sort it - if (sortInfo && sortInfo.fieldName) { - const field = sortInfo.fieldName; + if (sortInfo && sortInfo.field) { + const field = sortInfo.field; tempData = tempData.sort((a, b) => { return sortInfo.type === 'asc' ? (a[field] === b[field] ? 0 : a[field] > b[field] ? 1 : -1) : (a[field] === b[field] ? 0 : a[field] > b[field] ? -1 : 1); });
FIX: replacing all instances of sort.fieldName with sort.field
roemhildtg_spectre-canjs
train
f4e95c64b9bbb402e1afc1f85c238f2c8cc51d29
diff --git a/MatisseComponents/Button.php b/MatisseComponents/Button.php index <HASH>..<HASH> 100644 --- a/MatisseComponents/Button.php +++ b/MatisseComponents/Button.php @@ -67,7 +67,7 @@ class Button extends HtmlComponent protected function preRender () { - if (isset($this->props->icon)) + if (exists ($this->props->icon)) $this->addClass ('with-icon'); parent::preRender (); } @@ -107,13 +107,13 @@ class Button extends HtmlComponent $this->beginContent (); - if (isset($prop->icon)) { + if (exists ($prop->icon)) { $this->tag ('i', [ 'class' => $prop->icon, ]); } $txt = trim ($prop->label . $actionData); - echo strlen ($txt) ? $txt : (isset($prop->icon) ? '' : '&nbsp;'); + echo strlen ($txt) ? $txt : (exists ($prop->icon) ? '' : '&nbsp;'); } }
FIX: bug on Button's icon prop.
electro-modules_matisse-components
train
eb9625275bd82bd6038b5b855e369237a9930f69
diff --git a/lib/rack/secure_only/request.rb b/lib/rack/secure_only/request.rb index <HASH>..<HASH> 100644 --- a/lib/rack/secure_only/request.rb +++ b/lib/rack/secure_only/request.rb @@ -3,11 +3,11 @@ require "rack/request" module Rack class Request def http? - true + scheme == 'http' end def https? - false + scheme == 'https' end def use_forwarded_proto=(flag) @@ -21,5 +21,9 @@ module Rack def use_forwarded_proto? true end + + def forwarded_proto + + end end end diff --git a/spec/rack/secure_only/request_spec.rb b/spec/rack/secure_only/request_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rack/secure_only/request_spec.rb +++ b/spec/rack/secure_only/request_spec.rb @@ -28,6 +28,24 @@ describe Rack::Request do it "should respond to use_forwarded_proto" do @req.should respond_to :use_forwarded_proto end + + it "should respond to forwarded_proto" do + @req.should respond_to :forwarded_proto + end + end + + describe "use_forwarded_proto defaults" do + before(:each) do + @req = Rack::Request.new(Rack::MockRequest.env_for("http://example.com/")) + end + + it "should use forwarded_proto header (HTTP_X_FORWARDED_PROTO)" do + @req.should be_use_forwarded_proto + end + + it "should have set use_forwarded_proto to true (HTTP_X_FORWARDED_PROTO)" do + @req.use_forwarded_proto.should == true + end end context "with request http://example.com/" do @@ -42,14 +60,6 @@ describe Rack::Request do it "#https? should return false" do @req.should_not be_https end - - it "should use forwarded_proto header (HTTP_X_FORWARDED_PROTO)" do - @req.should be_use_forwarded_proto - end - - it "should have set use_forwarded_proto to true (HTTP_X_FORWARDED_PROTO)" do - @req.use_forwarded_proto.should == true - end end context "with request https://example.com/" do
Implement http? and https? without forwarded_proto check
spllr_rack-secure_only
train
5e9414f982fbf369ee0daa8b3a98ee789099313e
diff --git a/php/commands/core.php b/php/commands/core.php index <HASH>..<HASH> 100644 --- a/php/commands/core.php +++ b/php/commands/core.php @@ -153,6 +153,9 @@ class Core_Command extends WP_CLI_Command { * * --extra-php * : If set, the command reads additional PHP code from STDIN. + * + * --keys-and-salts + * : Use existing secrets versus generating afresh as the default behavior. * * ## EXAMPLES * @@ -196,9 +199,10 @@ class Core_Command extends WP_CLI_Command { } // TODO: adapt more resilient code from wp-admin/setup-config.php - - $assoc_args['keys-and-salts'] = self::_read( - 'https://api.wordpress.org/secret-key/1.1/salt/' ); + if ( ! isset( $assoc_args['keys-and-salts'] ) ) { + $assoc_args['keys-and-salts'] = self::_read( + 'https://api.wordpress.org/secret-key/1.1/salt/' ); + } $out = Utils\mustache_render( 'wp-config.mustache', $assoc_args ); file_put_contents( ABSPATH . 'wp-config.php', $out );
Allows passing existing keys and salts vs generating afresh In a multi-server environment, if you want a consistent configuration without having to patch the automatically generated wp-config.php, there should be a way to pass the common keys and salts.
wp-cli_extension-command
train
c517df78f9f9edc1bb45af7d58786b4b6dd6ee7f
diff --git a/aeron-client/src/main/java/uk/co/real_logic/aeron/Publication.java b/aeron-client/src/main/java/uk/co/real_logic/aeron/Publication.java index <HASH>..<HASH> 100644 --- a/aeron-client/src/main/java/uk/co/real_logic/aeron/Publication.java +++ b/aeron-client/src/main/java/uk/co/real_logic/aeron/Publication.java @@ -56,7 +56,7 @@ public class Publication implements AutoCloseable private final int sessionId; private final int positionBitsToShift; private final TermAppender[] termAppenders = new TermAppender[PARTITION_COUNT]; - private final ReadablePosition publicationLimit; + private final ReadablePosition positionLimit; private final UnsafeBuffer logMetaDataBuffer; private final ClientConductor clientConductor; private final String channel; @@ -70,7 +70,7 @@ public class Publication implements AutoCloseable final String channel, final int streamId, final int sessionId, - final ReadablePosition publicationLimit, + final ReadablePosition positionLimit, final LogBuffers logBuffers, final long registrationId) { @@ -91,7 +91,7 @@ public class Publication implements AutoCloseable this.logBuffers = logBuffers; this.logMetaDataBuffer = logMetaDataBuffer; this.registrationId = registrationId; - this.publicationLimit = publicationLimit; + this.positionLimit = positionLimit; this.positionBitsToShift = Integer.numberOfTrailingZeros(logBuffers.termLength()); } @@ -152,7 +152,7 @@ public class Publication implements AutoCloseable */ public boolean hasBeenConnected() { - return publicationLimit.getVolatile() > 0; + return positionLimit.getVolatile() > 0; } /** @@ -212,10 +212,22 @@ public class Publication implements AutoCloseable } /** + * Get the position limit beyond which this {@link Publication} will be back pressured. + * + * This should only be used as a guide to determine when back pressure is likely to be applied. + * + * @return the position limit beyond which this {@link Publication} will be back pressured. + */ + public long positionLimit() + { + return positionLimit.getVolatile(); + } + + /** * Non-blocking publish of a buffer containing a message. * * @param buffer containing message. - * @return The new stream position on success, otherwise {@link #BACK_PRESSURED} or {@link #NOT_CONNECTED}. + * @return The new stream position, otherwise {@link #NOT_CONNECTED}, {@link #BACK_PRESSURED} or {@link #ADMIN_ACTION}. */ public long offer(final DirectBuffer buffer) { @@ -235,7 +247,7 @@ public class Publication implements AutoCloseable { ensureOpen(); - final long limit = publicationLimit.getVolatile(); + final long limit = positionLimit.getVolatile(); final int initialTermId = initialTermId(logMetaDataBuffer); final int activeTermId = activeTermId(logMetaDataBuffer); final int activeIndex = indexByTerm(initialTermId, activeTermId); @@ -294,7 +306,7 @@ public class Publication implements AutoCloseable { ensureOpen(); - final long limit = publicationLimit.getVolatile(); + final long limit = positionLimit.getVolatile(); final int initialTermId = initialTermId(logMetaDataBuffer); final int activeTermId = activeTermId(logMetaDataBuffer); final int activeIndex = indexByTerm(initialTermId, activeTermId);
[Java]: Make positionLimit public on the Publication.
real-logic_aeron
train
7e3c06191e15ff144c9962751d82e107f6acfe03
diff --git a/cmd/syncthing/connections.go b/cmd/syncthing/connections.go index <HASH>..<HASH> 100644 --- a/cmd/syncthing/connections.go +++ b/cmd/syncthing/connections.go @@ -394,7 +394,11 @@ func (s *connectionSvc) connect() { func (s *connectionSvc) acceptRelayConns() { for { - s.conns <- s.relaySvc.Accept() + conn := s.relaySvc.Accept() + s.conns <- model.IntermediateConnection{ + Conn: conn, + Type: model.ConnectionTypeRelayAccept, + } } } diff --git a/lib/relay/relay.go b/lib/relay/relay.go index <HASH>..<HASH> 100644 --- a/lib/relay/relay.go +++ b/lib/relay/relay.go @@ -18,15 +18,26 @@ import ( "github.com/syncthing/relaysrv/protocol" "github.com/syncthing/syncthing/lib/config" "github.com/syncthing/syncthing/lib/discover" - "github.com/syncthing/syncthing/lib/model" "github.com/syncthing/syncthing/lib/osutil" "github.com/syncthing/syncthing/lib/sync" "github.com/thejerf/suture" ) +type Svc struct { + *suture.Supervisor + cfg *config.Wrapper + tlsCfg *tls.Config + + tokens map[string]suture.ServiceToken + clients map[string]*client.ProtocolClient + mut sync.RWMutex + invitations chan protocol.SessionInvitation + conns chan *tls.Conn +} + func NewSvc(cfg *config.Wrapper, tlsCfg *tls.Config) *Svc { - conns := make(chan model.IntermediateConnection) + conns := make(chan *tls.Conn) svc := &Svc{ Supervisor: suture.New("Svc", suture.Spec{ @@ -65,18 +76,6 @@ func NewSvc(cfg *config.Wrapper, tlsCfg *tls.Config) *Svc { return svc } -type Svc struct { - *suture.Supervisor - cfg *config.Wrapper - tlsCfg *tls.Config - - tokens map[string]suture.ServiceToken - clients map[string]*client.ProtocolClient - mut sync.RWMutex - invitations chan protocol.SessionInvitation - conns chan model.IntermediateConnection -} - func (s *Svc) VerifyConfiguration(from, to config.Configuration) error { for _, addr := range to.Options.RelayServers { _, err := url.Parse(addr) @@ -210,14 +209,15 @@ func (s *Svc) ClientStatus() map[string]bool { return status } -func (s *Svc) Accept() model.IntermediateConnection { +// Accept returns a new *tls.Conn. The connection is already handshaken. +func (s *Svc) Accept() *tls.Conn { return <-s.conns } type invitationReceiver struct { invitations chan protocol.SessionInvitation tlsCfg *tls.Config - conns chan<- model.IntermediateConnection + conns chan<- *tls.Conn stop chan struct{} } @@ -254,9 +254,7 @@ func (r *invitationReceiver) Serve() { tc.Close() continue } - r.conns <- model.IntermediateConnection{ - tc, model.ConnectionTypeRelayAccept, - } + r.conns <- tc case <-r.stop: return
lib/relay need not depend on lib/model any more
syncthing_syncthing
train
09dfd026ef0b52b307d2d89e930285c90070df41
diff --git a/codecov/__init__.py b/codecov/__init__.py index <HASH>..<HASH> 100644 --- a/codecov/__init__.py +++ b/codecov/__init__.py @@ -253,7 +253,7 @@ def main(*argv): # --- # git # --- - else: + elif '-h' not in argv and '--help' not in argv: # find branch, commit, repo from git command branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True) defaults.update(dict(branch=branch if branch != 'HEAD' else 'master',
wrap branch to allow help fix #<I>
codecov_codecov-python
train
062bded28a61ca1c8b4b9a7902012725c97f7242
diff --git a/file.go b/file.go index <HASH>..<HASH> 100644 --- a/file.go +++ b/file.go @@ -15,7 +15,7 @@ import ( "io/ioutil" "net/http" "os" - "path" + "path/filepath" // "strconv" "strings" "time" @@ -359,7 +359,7 @@ func FileIsDir(dirname string) bool { func FileFind(searchDirs []string, filenames ...string) (filePath string, found bool) { for _, dir := range searchDirs { for _, filename := range filenames { - filePath = path.Join(dir, filename) + filePath = filepath.Join(dir, filename) if FileExists(filePath) { return filePath, true } @@ -371,7 +371,7 @@ func FileFind(searchDirs []string, filenames ...string) (filePath string, found func FileFindModified(searchDirs []string, filenames ...string) (filePath string, found bool, modified time.Time) { for _, dir := range searchDirs { for _, filename := range filenames { - filePath = path.Join(dir, filename) + filePath = filepath.Join(dir, filename) if t := FileTimeModified(filePath); !t.IsZero() { return filePath, true, t } @@ -617,8 +617,8 @@ func FileCopyDir(source string, dest string) (err error) { } entries, err := ioutil.ReadDir(source) for _, entry := range entries { - sourcePath := path.Join(source, entry.Name()) - destinationPath := path.Join(dest, entry.Name()) + sourcePath := filepath.Join(source, entry.Name()) + destinationPath := filepath.Join(dest, entry.Name()) if entry.IsDir() { err = FileCopyDir(sourcePath, destinationPath) } else {
replaced path.Join with filepath.Join in files.go
ungerik_go-dry
train
58e4f99dabceef53c555156802e452980ab217db
diff --git a/lib/reel/request/state_machine.rb b/lib/reel/request/state_machine.rb index <HASH>..<HASH> 100644 --- a/lib/reel/request/state_machine.rb +++ b/lib/reel/request/state_machine.rb @@ -18,9 +18,11 @@ module Reel @hijacked = true end - state :closed do + # FSM fails open for valid transitions + # Set an empty array to disallow transitioning out of closed + state :closed, :to => [] do @socket.close unless @hijacked || @socket.closed? end end end -end \ No newline at end of file +end
Do not allow transitioning out of closed
celluloid_reel
train
1693f57bb03f0d69f8bc117b8fe0a39b43cb7e17
diff --git a/statics/js/components/flow-table.js b/statics/js/components/flow-table.js index <HASH>..<HASH> 100644 --- a/statics/js/components/flow-table.js +++ b/statics/js/components/flow-table.js @@ -536,8 +536,17 @@ Vue.component('flow-table', { case "Last": case "LastUpdateStart": case "LastUpdateLast": - dt = new Date(value); - return dt.toLocaleString(); + case "TCPFlowMetric.ABSynStart": + case "TCPFlowMetric.BASynStart": + case "TCPFlowMetric.ABFinStart": + case "TCPFlowMetric.BAFinStart": + case "TCPFlowMetric.ABRstStart": + case "TCPFlowMetric.BARstStart": + if (value) { + dt = new Date(value); + return dt.toLocaleString(); + } + return value; case "Metric.ABPackets": case "Metric.BAPackets": case "LastUpdateMetric.ABPackets": @@ -547,7 +556,10 @@ Vue.component('flow-table', { case "Metric.BABytes": case "LastUpdateMetric.ABBytes": case "LastUpdateMetric.BABytes": - return prettyBytes(value); + if (value) { + return prettyBytes(value); + } + return value; } return value; }, diff --git a/statics/js/components/object-detail.js b/statics/js/components/object-detail.js index <HASH>..<HASH> 100644 --- a/statics/js/components/object-detail.js +++ b/statics/js/components/object-detail.js @@ -23,23 +23,20 @@ Vue.component('object-detail', { type: String }, - toggleIndex: { - type: Number - } }, template: '\ <div class="object-detail">\ <div class="object-key-value" v-for="(value, key) in object" :class="[typeof(key) == \'string\' ? key.toLowerCase() : key]">\ <div v-if="Array.isArray(value)">\ - <a class="object-key" data-toggle="collapse" :href="\'#\' + getToggleIndex(key)" class="collapse-title">{{key}} :\ + <a class="object-key" data-toggle="collapse" :href="\'#\' + getNewUniqueId()" class="collapse-title">{{key}} :\ <i class="indicator glyphicon glyphicon-chevron-down pull-right"></i>\ </a>\ - <div :class="[collapsedByDefault(key) ? \'collapse\' : \'collapse in\']" :id="getToggleIndex(key)">\ + <div :class="[collapsedByDefault(key) ? \'collapse\' : \'collapse in\']" :id="uniqueId()">\ <div v-for="(v, index) in value">\ <div v-if="typeof v == \'object\'" class="object-sub-detail" style="margin-left: 20px;">\ - <span class="object-key" :class="typeof(value)" style="float:left">- </span>\ - <object-detail :object="v" :path="path ? path+\'.\'+key : key" :transformer="transformer" :toggleIndex="index"></object-detail>\ + <span v-if="Object.keys(v).length > 0" class="object-key" :class="typeof(value)" style="float:left">- </span>\ + <object-detail :object="v" :path="path ? path+\'.\'+key : key" :transformer="transformer"></object-detail>\ </div>\ <div v-else class="object-sub-detail">\ <div class="object-detail" :class="typeof(value)">- {{ transform(path ? path+\'.\'+key : key, v) }}</div>\ @@ -62,16 +59,6 @@ Vue.component('object-detail', { methods: { - getToggleIndex: function(key) { - if (this.toggleIndex && this.path) - return key + this.toggleIndex + this.path; - if (this.path) - return key + this.path - if (this.toggleIndex) - return key + this.toggleIndex - return key; - }, - transform: function(key, value) { if (this.transformer) { return this.transformer(key, value); @@ -80,7 +67,7 @@ Vue.component('object-detail', { }, collapsedByDefault: function(key) { - if (key === "FDB" || key === "Neighbors") return true; + if (key === "FDB" || key === "Neighbors" || key === "RoutingTable") return true; return false; }, } diff --git a/statics/js/utils.js b/statics/js/utils.js index <HASH>..<HASH> 100644 --- a/statics/js/utils.js +++ b/statics/js/utils.js @@ -83,3 +83,13 @@ function prettyBytes(value) { return b.toLocaleString() + " bytes"; } + +_uniqueId = 0; +function uniqueId() { + return "unique_id_" + _uniqueId; +} + +function getNewUniqueId() { + _uniqueId++; + return uniqueId(); +}
ui: fix route prefix indentation, collapse by default
skydive-project_skydive
train
99e10944be2e98ea35e9495195154c3787c6cde9
diff --git a/helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java b/helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java index <HASH>..<HASH> 100644 --- a/helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java +++ b/helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java @@ -18,6 +18,7 @@ package com.spotify.helios.master; import com.google.common.base.Function; +import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; @@ -622,6 +623,43 @@ public class ZooKeeperMasterModel implements MasterModel { } } + private RollingUpdateOp rollingUpdateTimedoutError(final RollingUpdateOpFactory opFactory, + final String host, + final JobId jobId, + final TaskStatus taskStatus) { + final List<TaskStatus.State> previousJobStates = getPreviousJobStates(jobId, host, 10); + final String previousJobStatesString = Joiner.on("->").join(previousJobStates); + + final Map<String, Object> metadata = Maps.newHashMap(); + metadata.put("jobState", taskStatus.getState()); + metadata.put("previousJobStates", previousJobStates); + metadata.put("throttleState", taskStatus.getThrottled()); + + if (taskStatus.getThrottled().equals(ThrottleState.IMAGE_MISSING)) { + return opFactory.error( + "timed out waiting for job to reach RUNNING due to missing Docker image " + + String.format("(previous job states: %s)", previousJobStatesString), + host, + RollingUpdateError.IMAGE_MISSING, + metadata); + } + if (taskStatus.getThrottled().equals(ThrottleState.IMAGE_PULL_FAILED)) { + return opFactory.error( + "timed out waiting for job to reach RUNNING due to failure pulling Docker image " + + String.format("(previous job states: %s)", previousJobStatesString), + host, + RollingUpdateError.IMAGE_PULL_FAILED, + metadata); + } + return opFactory.error( + "timed out waiting for job to reach RUNNING " + + String.format("(previous job states: %s)", previousJobStatesString), + host, + RollingUpdateError.TIMED_OUT_WAITING_FOR_JOB_TO_REACH_RUNNING, + metadata); + + } + private RollingUpdateOp rollingUpdateAwaitRunning(final ZooKeeperClient client, final RollingUpdateOpFactory opFactory, final DeploymentGroup deploymentGroup, @@ -654,25 +692,7 @@ public class ZooKeeperMasterModel implements MasterModel { if (isRolloutTimedOut(client, deploymentGroup)) { // We exceeded the configured deploy timeout, and this job is still not running - final List<TaskStatus.State> previousJobStates = getPreviousJobStates(jobId, host, 10); - final Map<String, Object> metadata = Maps.newHashMap(); - metadata.put("jobState", taskStatus.getState()); - metadata.put("previousJobStates", previousJobStates); - metadata.put("throttleState", taskStatus.getThrottled()); - - if (taskStatus.getThrottled().equals(ThrottleState.IMAGE_MISSING)) { - return opFactory.error("timed out waiting for job to reach RUNNING due to missing Docker image", host, - RollingUpdateError.IMAGE_MISSING, - metadata); - } - if (taskStatus.getThrottled().equals(ThrottleState.IMAGE_PULL_FAILED)) { - return opFactory.error("timed out waiting for job to reach RUNNING due to failure pulling Docker image", host, - RollingUpdateError.IMAGE_PULL_FAILED, - metadata); - } - return opFactory.error("timed out waiting for job to reach RUNNING", host, - RollingUpdateError.TIMED_OUT_WAITING_FOR_JOB_TO_REACH_RUNNING, - metadata); + return rollingUpdateTimedoutError(opFactory, host, jobId, taskStatus); } return opFactory.yield();
Expose a list of previous job states when timing out transitioning to RUNNING Hopefully this will give users some insight into why their jobs are failing to reach RUNNING.
spotify_helios
train
bb4493f9e6fb70dbf6ee6c6d383c8f4fdd3b36cb
diff --git a/great_expectations/profile/basic_dataset_profiler.py b/great_expectations/profile/basic_dataset_profiler.py index <HASH>..<HASH> 100644 --- a/great_expectations/profile/basic_dataset_profiler.py +++ b/great_expectations/profile/basic_dataset_profiler.py @@ -36,10 +36,10 @@ class BasicDatasetProfiler(DatasetProfiler): @classmethod def _get_column_cardinality(cls, df, column): - num_unique = df.expect_column_unique_value_count_to_be_between(column, 0, None)[ + num_unique = df.expect_column_unique_value_count_to_be_between(column, None, None)[ 'result']['observed_value'] pct_unique = df.expect_column_proportion_of_unique_values_to_be_between( - column, 0, None)['result']['observed_value'] + column, None, None)['result']['observed_value'] if pct_unique == 1.0:
Changed args of expect_column_unique_value_count_to_be_between and expect_column_proportion_of_unique_values_to_be_between expectations to None (to mean 'anything')
great-expectations_great_expectations
train
4d05b7210f5dfad41c7bdc2479be734f1cf1ed92
diff --git a/classes/hypeJunction/Interactions/InteractionsService.php b/classes/hypeJunction/Interactions/InteractionsService.php index <HASH>..<HASH> 100644 --- a/classes/hypeJunction/Interactions/InteractionsService.php +++ b/classes/hypeJunction/Interactions/InteractionsService.php @@ -129,33 +129,38 @@ class InteractionsService { $views = self::getActionableViews(); - if (!in_array($river->view, $views)) { - return $object; - } - - // wrapping this in ignore access so that we do not accidentally create duplicate - // river objects - $ia = elgg_set_ignore_access(true); - $objects = elgg_get_entities_from_metadata(array( - 'types' => RiverObject::TYPE, - 'subtypes' => array(RiverObject::SUBTYPE, 'hjstream'), - 'metadata_name_value_pairs' => array( - 'name' => 'river_id', - 'value' => $river->id, - ), - 'limit' => 1, - )); + if (in_array($river->view, $views)) { + + // wrapping this in ignore access so that we do not accidentally create duplicate + // river objects + $ia = elgg_set_ignore_access(true); + $objects = elgg_get_entities_from_metadata([ + 'types' => RiverObject::TYPE, + 'subtypes' => [RiverObject::SUBTYPE, 'hjstream'], + 'metadata_name_value_pairs' => [ + 'name' => 'river_id', + 'value' => $river->id, + ], + 'limit' => 1, + ]); + + $guid = ($objects) ? $objects[0]->guid : false; + + if (!$guid) { + $object = InteractionsService::createActionableRiverObject($river); + $guid = $object->guid; + } - $guid = ($objects) ? $objects[0]->guid : false; + elgg_set_ignore_access($ia); - if (!$guid) { - $object = InteractionsService::createActionableRiverObject($river); - $guid = $object->guid; + $object = get_entity($guid); } - elgg_set_ignore_access($ia); + if ($object instanceof ElggEntity) { + $object->setVolatileData('river_item', $river); + } - return get_entity($guid); + return $object; } /**
fix(comments): make menu aware which river item the object belongs to
hypeJunction_hypeInteractions
train
2a72130e4338d2c0917344c7429a743b4693db5b
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -1135,7 +1135,7 @@ var CodeMirror = (function() { leaveInputAlone = false; prepareInput(); slowPoll(); - }, 50); + }, 100); } // Cursor-blinking
Make context menu work on FF4 on Win7 Apparently, popping up the context menu took more than <I> \(\!\) milliseconds on that platform, and codemirror had already hidden the textarea again by the time the menu arrived.
codemirror_CodeMirror
train
a0e9eb3a647ee860ec641ed279c02d6c0d33c657
diff --git a/crypto/src/main/java/org/springframework/security/crypto/password/NoOpPasswordEncoder.java b/crypto/src/main/java/org/springframework/security/crypto/password/NoOpPasswordEncoder.java index <HASH>..<HASH> 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/password/NoOpPasswordEncoder.java +++ b/crypto/src/main/java/org/springframework/security/crypto/password/NoOpPasswordEncoder.java @@ -16,11 +16,19 @@ package org.springframework.security.crypto.password; /** + * This {@link PasswordEncoder} is provided for legacy and testing purposes only and is + * not considered secure. + * * A password encoder that does nothing. Useful for testing where working with plain text * passwords may be preferred. * * @author Keith Donald + * @deprecated Digest based password encoding is not considered secure. Instead use an + * adaptive one way funciton like BCryptPasswordEncoder, Pbkdf2PasswordEncoder, or + * SCryptPasswordEncoder. Even better use {@link DelegatingPasswordEncoder} which supports + * password upgrades. */ +@Deprecated public final class NoOpPasswordEncoder implements PasswordEncoder { public String encode(CharSequence rawPassword) {
Deprecate NoOpPasswordEncoder Issue: gh-<I>
spring-projects_spring-security
train
421ca33d70e75e5cb4b1bacb726e0a52f0bc47d3
diff --git a/lib/tern.js b/lib/tern.js index <HASH>..<HASH> 100644 --- a/lib/tern.js +++ b/lib/tern.js @@ -115,6 +115,7 @@ for (var i = 0, f; i < this.files.length; ++i) if ((f = this.files[i]).name == name) { clearFile(this, f, null, true); this.files.splice(i--, 1); + delete this.fileMap[name]; return; } },
Delete file object from fileMap in delFile Closes #<I>
ternjs_tern
train
e98ea732ee1d71d7f938be70308fd14e81c165b6
diff --git a/src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java b/src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java +++ b/src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java @@ -47,6 +47,7 @@ import org.dasein.cloud.network.LbListener; import org.dasein.cloud.network.LbProtocol; import org.dasein.cloud.network.LoadBalancer; import org.dasein.cloud.network.LoadBalancerAddressType; +import org.dasein.cloud.network.LoadBalancerServer; import org.dasein.cloud.network.LoadBalancerState; import org.dasein.cloud.network.LoadBalancerSupport; import org.w3c.dom.Document; @@ -290,7 +291,17 @@ public class LoadBalancers implements LoadBalancerSupport { throw e; } } - + + @Override + public Iterable<LoadBalancerServer> getLoadBalancerServerHealth(String loadBalancerId) throws CloudException, InternalException { + return Collections.emptyList(); + } + + @Override + public Iterable<LoadBalancerServer> getLoadBalancerServerHealth(String loadBalancerId, String... serverIdsToCheck) throws CloudException, InternalException { + return Collections.emptyList(); + } + @Override public int getMaxPublicPorts() throws CloudException, InternalException { return 0;
Added in load balancer health skeletons
greese_dasein-cloud-cloudstack
train
6ad44b579ada97ecbef0b66bc7cc2100e3ae9e8c
diff --git a/pkg/datapath/linux/probes/probes.go b/pkg/datapath/linux/probes/probes.go index <HASH>..<HASH> 100644 --- a/pkg/datapath/linux/probes/probes.go +++ b/pkg/datapath/linux/probes/probes.go @@ -119,6 +119,7 @@ type MapTypes struct { type Features struct { SystemConfig `json:"system_config"` MapTypes `json:"map_types"` + Helpers map[string][]string `json:"helpers"` } // ProbeManager is a manager of BPF feature checks. @@ -199,3 +200,19 @@ func (p *ProbeManager) SystemConfigProbes() error { func (p *ProbeManager) GetMapTypes() *MapTypes { return &p.features.MapTypes } + +// GetHelpers returns information about available BPF helpers for the given +// program type. +// If program type is not found, returns nil. +func (p *ProbeManager) GetHelpers(prog string) map[string]struct{} { + for p, helpers := range p.features.Helpers { + if prog+"_available_helpers" == p { + ret := map[string]struct{}{} + for _, h := range helpers { + ret[h] = struct{}{} + } + return ret + } + } + return nil +} diff --git a/pkg/datapath/linux/probes/probes_privileged_test.go b/pkg/datapath/linux/probes/probes_privileged_test.go index <HASH>..<HASH> 100644 --- a/pkg/datapath/linux/probes/probes_privileged_test.go +++ b/pkg/datapath/linux/probes/probes_privileged_test.go @@ -42,3 +42,9 @@ func (s *ProbesPrivTestSuite) TestMapTypes(c *C) { mapTypes := pm.GetMapTypes() c.Assert(mapTypes, NotNil) } + +func (s *ProbesPrivTestSuite) TestHelpers(c *C) { + pm := NewProbeManager() + _, ok := pm.GetHelpers("sched_act")["bpf_map_lookup_elem"] + c.Assert(ok, Equals, true) +}
probes: Probe for BPF helpers This commit adds GetHelpers() method which returns available helper functions for the given program type.
cilium_cilium
train
1c95289e98a6bb7db47c65cc3255de1ee88e3eb1
diff --git a/src/main/java/org/minimalj/frontend/form/element/ListFormElement.java b/src/main/java/org/minimalj/frontend/form/element/ListFormElement.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/minimalj/frontend/form/element/ListFormElement.java +++ b/src/main/java/org/minimalj/frontend/form/element/ListFormElement.java @@ -73,7 +73,7 @@ public abstract class ListFormElement<T> extends AbstractObjectFormElement<List< @Override protected Form<T> createForm() { - return ListFormElement.this.createForm(false); + return ListFormElement.this.createForm(true); } @Override
AddListEntryEditor needs form in edit mode
BrunoEberhard_minimal-j
train
ebdb76b15a256fb4e553ff459e3615ff1d85840a
diff --git a/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKFileBasedSigningUtil.java b/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKFileBasedSigningUtil.java index <HASH>..<HASH> 100644 --- a/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKFileBasedSigningUtil.java +++ b/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKFileBasedSigningUtil.java @@ -187,10 +187,10 @@ public final class PKFileBasedSigningUtil extends PKAbstractSigningUtil { ByteArrayOutputStream byteArrayOutputStreamForZippedPass = new ByteArrayOutputStream(); // closed with the parent ZipOutputStream try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStreamForZippedPass)) { zip(tempPassDir, tempPassDir, zipOutputStream); - return byteArrayOutputStreamForZippedPass.toByteArray(); } catch (IOException e) { throw new PKSigningException("Error while creating a zip package", e); } + return byteArrayOutputStreamForZippedPass.toByteArray(); } private final void zip(final File directory, final File base, final ZipOutputStream zipOutputStream) throws IOException { diff --git a/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKInMemorySigningUtil.java b/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKInMemorySigningUtil.java index <HASH>..<HASH> 100644 --- a/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKInMemorySigningUtil.java +++ b/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKInMemorySigningUtil.java @@ -127,9 +127,9 @@ public final class PKInMemorySigningUtil extends PKAbstractSigningUtil { zipOutputStream.putNextEntry(entry); IOUtils.copy(new ByteArrayInputStream(passResourceFile.getValue().array()), zipOutputStream); } - return byteArrayOutputStreamForZippedPass.toByteArray(); } catch (IOException e) { throw new PKSigningException("Error while creating a zip package", e); } + return byteArrayOutputStreamForZippedPass.toByteArray(); } }
Fix zip file generating: ZipOutputStream should be closed to finish zip creating correctly <URL>
drallgood_jpasskit
train
f3ab81c2bc27fc8bb44e55617da089c532f13e5f
diff --git a/lib/flor/pcore/map.rb b/lib/flor/pcore/map.rb index <HASH>..<HASH> 100644 --- a/lib/flor/pcore/map.rb +++ b/lib/flor/pcore/map.rb @@ -29,6 +29,8 @@ class Flor::Pro::Map < Flor::Procedure def pre_execute + @node['vars'] = {} + #@node['ret'] = Flor.dup(payload['ret']) # now using @node['payload'] @node['col'] = nil @node['idx'] = -1 diff --git a/spec/pcore/map_spec.rb b/spec/pcore/map_spec.rb index <HASH>..<HASH> 100644 --- a/spec/pcore/map_spec.rb +++ b/spec/pcore/map_spec.rb @@ -76,19 +76,23 @@ describe 'Flor procedures' do it 'acts like a lisp let' do flon = %{ - map [ 0, 1, 2 ] - set a 1 - def x - set a - + a 1 - + x a + sequence + map [ 0, 1, 2 ] + set a 1 + def x + set a + + a 1 + + x a } r = @executor.launch(flon) expect(r['point']).to eq('terminated') expect(r['payload']['ret']).to eq([ 2, 4, 6 ]) + expect(r['vars']).to eq({}) end + + it 'shows the index (and more) via vars' end end
let "map" behave like a lisp let
floraison_flor
train
f7d9347287d219acc957487da4ee50472eb9b026
diff --git a/utils/slugify.js b/utils/slugify.js index <HASH>..<HASH> 100644 --- a/utils/slugify.js +++ b/utils/slugify.js @@ -16,18 +16,7 @@ module.exports = function () { */ return function (val) { val = val || ''; - // "replace 1+ non-alphanumerics with - and then trim - from the start and end" return val.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^\-|\-$/g, ''); - /* - return val - .replace(/\//g, '-') - .replace(/[^a-zA-Z0-9\- ]/g, '') - .trim() - .replace(/ /g, '-') - .replace(/--/g, '-'); - */ }; - - // CA: propose changing to: return val.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^\-|\-$/g, ''); };
Removing old slugify code that is not used anymore
gethuman_pancakes-recipe
train
45c2a4b6419957f40d68a432ed18fb9eadad7f11
diff --git a/spec/integration/ssh_spec.rb b/spec/integration/ssh_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/ssh_spec.rb +++ b/spec/integration/ssh_spec.rb @@ -207,7 +207,7 @@ describe Gas::Ssh do # Code to prepare the github environment for testing @sample_rsa = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDn74QR9yHb+hcid8iH3+FTaEwnKtwjttseJDbIA2PaivN2uvESrvHlp8Ss/cRox3fFu34QR5DpdOhlfULjTX7yKVuxhaNrAJaqg8rX8hgr9U1Botnyy1DBueEyyA3o1fxRkmwTf6FNnkt1BxWP635tD0lbmUubwaadXjQqPOf3Uw==" - + Gas.delete(@nickname) Gas::Ssh.stub!(:get_username_and_password_and_authenticate).and_return(@credentials) #Gas::GithubSpeaker.stub!(:get_username_and_password_and_authenticate).and_return({:account_name => @username, :password => @password}) #Gas::Ssh::GithubSpeaker.stub!(:get_username_and_password_and_authenticate).and_return({:account_name => @username, :password => @password})
actually caught a bug in a test where the mysterious account needed to be deleted in a before :all block... also got another test working with vcr tapes
walle_gas
train
ab052961549771ef0bcb4abc14aafb7d5635a3c9
diff --git a/pyxmpp/roster.py b/pyxmpp/roster.py index <HASH>..<HASH> 100644 --- a/pyxmpp/roster.py +++ b/pyxmpp/roster.py @@ -146,10 +146,15 @@ class RosterItem(StanzaPayloadObject): class Roster(StanzaPayloadObject): """Class representing XMPP-IM roster. + Iteration over `Roster` object iterates over roster items. + :Ivariables: - `items_dict`: items indexed by JID. + :Properties: + - `items`: roster items. :Types: - - `items_dict`: `dict` of `JID` -> `RosterItem`""" + - `items_dict`: `dict` of `JID` -> `RosterItem` + - `items`: `list` of `RosterItem`""" xml_element_name = "query" xml_element_namespace = ROSTER_NS @@ -222,11 +227,16 @@ class Roster(StanzaPayloadObject): n.unlinkNode() n.freeNode() return r + + def __iter__(self): + return self.items_dict.itervalues() def get_items(self): """Return a list of items in the roster.""" return self.items_dict.values() + items = property(get_items) + def get_groups(self): """Return a list of groups in the roster.""" r={}
- Roster.items property and an iteration iterface
Jajcus_pyxmpp2
train
658d357c616a96974d3b285c2a45a360bccb3bdd
diff --git a/install/lang/es_utf8/installer.php b/install/lang/es_utf8/installer.php index <HASH>..<HASH> 100644 --- a/install/lang/es_utf8/installer.php +++ b/install/lang/es_utf8/installer.php @@ -193,7 +193,7 @@ $string['mysql'] = 'MySQL (mysql)'; $string['mysql416bypassed'] = 'En cualquier caso, si su sitio únicamente está utilizando idiomas ISO-8859-1 (latin), puede continuar con su versión de MySQL actual (4.1.12 o superior).'; $string['mysql416required'] = 'MySQL 4.1.16 es la versión mínima requerida para trabajar con Moodle 1.6 y garantizar que toda la información podrá ser convertida a UTF-8 en el futuro.'; $string['mysqlextensionisnotpresentinphp'] = 'PHP no ha sido adecuadamente configurado con la extensión MySQL de modo que pueda comunicarse con MySQL. Por favor, compruebe el archivo php.ini o recompile PHP.'; -$string['mysqli'] = 'MySQL Mejorado'; +$string['mysqli'] = 'MySQL Mejorado (mysqli)'; $string['mysqliextensionisnotpresentinphp'] = 'PHP no ha sido configurado adecuadamente con la extensión MySQLi de forma que se pueda comunicar con MySQL. Por favor, compruebe su archivo php.ini o recompile PHP. La extensión MySQLi no está disponible en PHP 4.'; $string['name'] = 'Nombre'; $string['next'] = 'Siguiente';
Automatic installer.php lang files by installer_builder (<I>)
moodle_moodle
train
6f118b65b74581fa868e3d37012f7914f1f10e36
diff --git a/cherrypy/_cpmodpy.py b/cherrypy/_cpmodpy.py index <HASH>..<HASH> 100644 --- a/cherrypy/_cpmodpy.py +++ b/cherrypy/_cpmodpy.py @@ -2,6 +2,7 @@ from mod_python import apache import cherrypy +from cherrypy._cperror import format_exc, bare_error def setup(req): @@ -86,33 +87,31 @@ def handler(req): rfile = _ReadOnlyRequest(req) response = request.run(requestLine, headers, rfile) - sendResponse(req, response) + sendResponse(req, response.status, response.header_list, response.body) request.close() except: - cherrypy.log(traceback=True) + tb = format_exc() + cherrypy.log(tb) + s, h, b = bare_error() + sendResponse(req, s, h, b) return apache.OK -def sendResponse(req, response): +def sendResponse(req, status, headers, body): # Set response status - req.status = int(response.status[:3]) + req.status = int(status[:3]) # Set response headers req.content_type = "text/plain" - for header, value in response.header_list: + for header, value in headers: if header.lower() == 'content-type': req.content_type = value continue req.headers_out.add(header, value) - # Cookie - cook_out = response.simple_cookie.output() - if cook_out: - for line in cook_out.split('\n'): - req.headers_out.add(*tuple(v.strip() for v in line.split(':', 1))) - # Set response body - if isinstance(response.body, basestring): - req.write(response.body) + if isinstance(body, basestring): + req.write(body) else: - for seg in response.body: + for seg in body: req.write(seg) +
Added bare_error trap in _cpmodpy (which fixes some failing tests). Also dropped redundant cookie logic in _cpmodpy.
cherrypy_cheroot
train
f48b316e187a90fbd63b5cb87ee9259ff1c68652
diff --git a/lib/jitsu/package.js b/lib/jitsu/package.js index <HASH>..<HASH> 100644 --- a/lib/jitsu/package.js +++ b/lib/jitsu/package.js @@ -519,7 +519,7 @@ package.properties = function (dir) { help: [ '', 'The ' + 'subdomain '.grey + 'is where your application will reside.', - 'Your application will then become accessible at: http://' + 'yourdomain'.grey + '.nodejitsu.com', + 'Your application will then become accessible at: http://' + 'yourdomain'.grey + '.jit.su', '' ], default: jitsu.config.get('username') + '.' + path.basename(dir)
[ux] Use short domain consistently in `jitsu deploy`. Closes #<I>
nodejitsu_jitsu
train
d44a5fb8896e62c0d12d71d75dd8a918c6ebc194
diff --git a/Exception/InvalidServerResponse.php b/Exception/InvalidServerResponse.php index <HASH>..<HASH> 100644 --- a/Exception/InvalidServerResponse.php +++ b/Exception/InvalidServerResponse.php @@ -17,8 +17,24 @@ namespace Geocoder\Exception; */ class InvalidServerResponse extends \RuntimeException implements Exception { - public static function create($query) + /** + * @param string $query + * @param int $code + * + * @return InvalidServerResponse + */ + public static function create($query, $code = 0) { - return new self(sprintf('The geocoder server returned an invalid response for query "%s". We could not parse it.', $query)); + return new self(sprintf('The geocoder server returned an invalid response (%d) for query "%s". We could not parse it.', $code, $query)); + } + + /** + * @param string $query + * + * @return InvalidServerResponse + */ + public static function emptyResponse($query) + { + return new self(sprintf('The geocoder server returned an empty response for query "%s".', $query)); } } diff --git a/Provider/AbstractHttpProvider.php b/Provider/AbstractHttpProvider.php index <HASH>..<HASH> 100644 --- a/Provider/AbstractHttpProvider.php +++ b/Provider/AbstractHttpProvider.php @@ -10,6 +10,9 @@ namespace Geocoder\Provider; +use Geocoder\Exception\InvalidCredentials; +use Geocoder\Exception\InvalidServerResponse; +use Geocoder\Exception\QuotaExceeded; use Http\Message\MessageFactory; use Http\Discovery\MessageFactoryDiscovery; use Http\Client\HttpClient; @@ -40,6 +43,35 @@ abstract class AbstractHttpProvider extends AbstractProvider } /** + * Get URL and retrun contents. + * + * @param string $url + * + * @return string + */ + protected function getUrlContents($url) + { + $request = $this->getMessageFactory()->createRequest('GET', $url); + $response = $this->getHttpClient()->sendRequest($request); + + $statusCode = $response->getStatusCode(); + if (401 === $statusCode) { + throw new InvalidCredentials(); + } elseif (429 === $statusCode) { + throw new QuotaExceeded(); + } elseif ($statusCode >= 300) { + throw InvalidServerResponse::create($url, $statusCode); + } + + $body = (string) $response->getBody(); + if (empty($body)) { + throw InvalidServerResponse::emptyResponse($url); + } + + return $body; + } + + /** * Returns the HTTP adapter. * * @return HttpClient
Create a common function to fetch data form server (#<I>) * Create a common function to fetch data form server This will be a unified way to throw some exceptions * cs * Removed check * minor fix * Bugfix
geocoder-php_php-common
train
b3ef1162fe034991842a5b3bdeb49b4595f1b45a
diff --git a/src/DiagnosticsProvider.php b/src/DiagnosticsProvider.php index <HASH>..<HASH> 100644 --- a/src/DiagnosticsProvider.php +++ b/src/DiagnosticsProvider.php @@ -65,6 +65,21 @@ class DiagnosticsProvider { } } } + elseif ($node instanceof Node\Statement\NamespaceUseDeclaration) { + if (count($node->useClauses->children) > 1) { + var_dump($node->useClauses); + foreach ($node->useClauses->children as $useClause) { + if($useClause instanceof Node\NamespaceUseClause && !is_null($useClause->openBrace)) { + yield new Diagnostic( + DiagnosticKind::Error, + "Semicolon expected.", + $useClause->getEndPosition(), + 1 + ); + } + } + } + } } foreach ($node->getChildNodesAndTokens() as $child) {
Added a post parse check for invalid brace usage in use declarations
Microsoft_tolerant-php-parser
train
d7b8e50c4fea917996ec8d7a0ee23ba20fec9c35
diff --git a/src/Client/Server/Magento.php b/src/Client/Server/Magento.php index <HASH>..<HASH> 100644 --- a/src/Client/Server/Magento.php +++ b/src/Client/Server/Magento.php @@ -51,7 +51,7 @@ class Magento extends Server public function urlAuthorization() { return $this->isAdmin - ? $this->baseUri . '/admin/oauth_authorize' + ? $this->adminUrl : $this->baseUri . '/oauth/authorize'; } @@ -145,13 +145,17 @@ class Magento extends Server if (isset($url['host'])) { throw new \Exception('Missing Magento Host'); } - $url = parse_url($configuration['host']); $this->baseUri = sprintf('%s://%s', $url['scheme'], $url['host']); if (isset($url['path'])) { $this->baseUri .= '/' . trim($url['path'], '/'); } - $this->isAdmin = !empty($configuration['admin']); + if (!empty($configuration['adminUrl'])) { + $this->adminUrl = $configuration['adminUrl']. '/oauth_authorize'; + } else { + $this->adminUrl = $this->baseUri . '/admin/oauth_authorize'; + } + } }
Added pass in for admin url Added a way to pass in custom admin url
thephpleague_oauth1-client
train
ea2fc22cd54e33efd4c8710edeecc36c09f5e014
diff --git a/redish/types.py b/redish/types.py index <HASH>..<HASH> 100644 --- a/redish/types.py +++ b/redish/types.py @@ -1,5 +1,7 @@ from Queue import Empty, Full +from redis.exceptions import ResponseError + from redish.utils import maybe_list, key @@ -21,23 +23,21 @@ class List(Type): super(List, self).__init__(name, client) self.extend(initial or []) - def extend(self, iterable): - """Append the values in ``iterable`` to this list.""" - for value in iterable: - self.append(value) - - def extendleft(self, iterable): - """Add the values in ``iterable`` to the head of this list.""" - for value in iterable: - self.appendleft(value) - def __getitem__(self, index): """``x.__getitem__(index) <==> x[index]``""" - return self.client.lindex(self.name, index) + item = self.client.lindex(self.name, index) + if item: + return item + raise IndexError("list index out of range") def __setitem__(self, index, value): """``x.__setitem__(index, value) <==> x[index] = value``""" - return self.client.lset(self.name, index, value) + try: + self.client.lset(self.name, index, value) + except ResponseError, exc: + if "index out of range" in exc.args: + raise IndexError("list assignment index out of range") + raise def __len__(self): """``x.__len__() <==> len(x)``""" @@ -53,6 +53,9 @@ class List(Type): def __getslice__(self, i, j): """``x.__getslice__(start, stop) <==> x[start:stop]``""" + # Redis indices are zero-based, while Python indices are 1-based. + if j != -1: + j -= 1 return self.client.lrange(self.name, i, j) def _as_list(self): @@ -68,7 +71,7 @@ class List(Type): def trim(self, start, stop): """Trim the list to the specified range of elements.""" - return self.client.ltrim(self.name, start, stop) + return self.client.ltrim(self.name, start, stop - 1) def pop(self): """Remove and return the last element of the list.""" @@ -90,6 +93,16 @@ class List(Type): raise ValueError("%s not in list" % value) return count + def extend(self, iterable): + """Append the values in ``iterable`` to this list.""" + for value in iterable: + self.append(value) + + def extendleft(self, iterable): + """Add the values in ``iterable`` to the head of this list.""" + for value in iterable: + self.appendleft(value) + class Set(Type): """A set.""" @@ -205,10 +218,9 @@ class SortedSet(Type): for member, score in iterable: self.add(member, score) - - def __getslice__(self, i, j): + def __getslice__(self, start, stop): """``x.__getslice__(start, stop) <==> x[start:stop]``""" - return self.client.zrange(self.name, i, j) + return self.client.zrange(self.name, start, stop) def __len__(self): """``x.__len__() <==> len(x)``""" @@ -232,6 +244,9 @@ class SortedSet(Type): if not self.client.zrem(self.name, member): raise KeyError(member) + def revrange(self, start, stop): + return self.client.zrevrange(self.name, start, stop) + def increment(self, member, amount=1): """Increment the score of ``member`` by ``amount``.""" return self.client.zincrby(self.name, member, amount)
List: __getitem__ + __setitem__ should raise IndexError + Redis indices are 0-based
ask_redish
train
df70cd4664b590c8ceb9442d9037a3b44f40e32a
diff --git a/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/MACCSFingerprinter.java b/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/MACCSFingerprinter.java index <HASH>..<HASH> 100644 --- a/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/MACCSFingerprinter.java +++ b/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/MACCSFingerprinter.java @@ -204,19 +204,6 @@ public class MACCSFingerprinter implements IFingerprinter { } } - // at this point we have skipped the entries whose pattern is "?" - // (bits 1,44,125,166) so let try and do those features by hand - - // bit 125 aromatic ring count > 1 - // bit 101 a ring with more than 8 members - AllRingsFinder ringFinder = new AllRingsFinder(); - IRingSet rings = ringFinder.findAllRings(container); - int ringCount = 0; - for (int i = 0; i < rings.getAtomContainerCount(); i++) { - IAtomContainer ring = rings.getAtomContainer(i); - if (ring.getAtomCount() >= 8) fp.set(100); - } - return new BitSetFingerprint(fp); } diff --git a/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/MACCSFingerprinterTest.java b/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/MACCSFingerprinterTest.java index <HASH>..<HASH> 100644 --- a/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/MACCSFingerprinterTest.java +++ b/descriptor/fingerprint/src/test/java/org/openscience/cdk/fingerprint/MACCSFingerprinterTest.java @@ -141,11 +141,11 @@ public class MACCSFingerprinterTest extends AbstractFixedLengthFingerprinterTest assertThat( superBits.asBitSet(), - is(asBitSet(53, 56, 65, 71, 73, 88, 97, 100, 104, 111, 112, 126, 130, 136, 138, 139, 140, 142, 143, + is(asBitSet(53, 56, 65, 71, 73, 88, 97, 104, 111, 112, 126, 130, 136, 138, 139, 140, 142, 143, 144, 145, 148, 149, 151, 153, 156, 158, 159, 161, 162, 163, 164))); assertThat( subBits.asBitSet(), - is(asBitSet(56, 97, 100, 104, 108, 112, 117, 127, 131, 136, 143, 144, 146, 151, 152, 156, 161, 162, 163, 164))); + is(asBitSet(56, 97, 104, 108, 112, 117, 127, 131, 136, 143, 144, 146, 151, 152, 156, 161, 162, 163, 164))); } }
Remove check for rings >= 8M bit<I>. bit<I> is described as 8M ring but was actually matching >= 8. Removing this and only checking for 8M rings affects a large number of molecules.
cdk_cdk
train
a975ed19505e6988e49cf58d61f708bc1ee48dff
diff --git a/auto_ml/utils.py b/auto_ml/utils.py index <HASH>..<HASH> 100644 --- a/auto_ml/utils.py +++ b/auto_ml/utils.py @@ -1,5 +1,6 @@ from sklearn.base import BaseEstimator, TransformerMixin from sklearn.linear_model import LogisticRegression +from sklearn.ensemble import RandomForestClassifier # originally implemented to be consistent with sklearn's API, but currently used outside of a pipeline @@ -12,7 +13,7 @@ class SplitOutput(BaseEstimator, TransformerMixin): def transform(self, X, y=None): y = [] for row in X: - y.append( + y.append( row.pop(self.output_column_name) ) @@ -24,9 +25,19 @@ class SplitOutput(BaseEstimator, TransformerMixin): return self -def instantiate_model(model_name='LogisticRegression'): - return LogisticRegression() +def instantiate_model(model_name='RandomForestClassifier'): + print(model_name) -# class InstantiateModel(BaseEstimator, TransformerMixin): + model_map = { + 'LogisticRegression': LogisticRegression(), + 'RandomForestClassifier': RandomForestClassifier() + } + + return model_map[model_name] + +class FinalModelATC(BaseEstimator, TransformerMixin): + + def __init__(self, X_train=None, y_train=None): + self.X_train = X_train + self.y_train = y_train -# def __init__
explores creating my own custom wrapper for the final stage of the pipeline
ClimbsRocks_auto_ml
train
c0ec80215e74f0f3b2d2ff02500cd8b134201f94
diff --git a/core/corehttp/webui.go b/core/corehttp/webui.go index <HASH>..<HASH> 100644 --- a/core/corehttp/webui.go +++ b/core/corehttp/webui.go @@ -1,7 +1,7 @@ package corehttp // TODO: move to IPNS -const WebUIPath = "/ipfs/QmRyWyKWmphamkMRnJVjUTzSFSAAZowYP4rnbgnfMXC9Mr" +const WebUIPath = "/ipfs/QmU3o9bvfenhTKhxUakbYrLDnZU7HezAVxPM6Ehjw9Xjqy" // this is a list of all past webUI paths. var WebUIPaths = []string{ @@ -13,6 +13,7 @@ var WebUIPaths = []string{ "/ipfs/QmctngrQAt9fjpQUZr7Bx3BsXUcif52eZGTizWhvcShsjz", "/ipfs/QmS2HL9v5YeKgQkkWMvs1EMnFtUowTEdFfSSeMT4pos1e6", "/ipfs/QmR9MzChjp1MdFWik7NjEjqKQMzVmBkdK3dz14A6B5Cupm", + "/ipfs/QmRyWyKWmphamkMRnJVjUTzSFSAAZowYP4rnbgnfMXC9Mr", } var WebUIOption = RedirectOption("webui", WebUIPath)
feat: Update the webui to work with the latest changes in <I> License: MIT
ipfs_go-ipfs
train
338e93dff430098b2705253c25153fd98170fb7d
diff --git a/worker/uniter/jujuc/server.go b/worker/uniter/jujuc/server.go index <HASH>..<HASH> 100644 --- a/worker/uniter/jujuc/server.go +++ b/worker/uniter/jujuc/server.go @@ -7,6 +7,7 @@ import ( "bytes" "fmt" "launchpad.net/juju-core/cmd" + "launchpad.net/juju-core/log" "net" "net/rpc" "os" @@ -93,6 +94,8 @@ func (j *Jujuc) Main(req Request, resp *Response) error { ctx := &cmd.Context{req.Dir, &stdin, &stdout, &stderr} j.mu.Lock() defer j.mu.Unlock() + log.Printf("worker/uniter/jujuc: running hook %q %q", req.CommandName, req.Args) + log.Printf("worker/uniter/jujuc: hook context id %q; dir %q", req.ContextId, req.Dir) resp.Code = cmd.Main(c, ctx, req.Args) resp.Stdout = stdout.Bytes() resp.Stderr = stderr.Bytes()
worker/uniter/jujuc: log callback
juju_juju
train
afaf1fe8900857a873d950668b7ff2c854ffe7d8
diff --git a/src/OptionParser.php b/src/OptionParser.php index <HASH>..<HASH> 100644 --- a/src/OptionParser.php +++ b/src/OptionParser.php @@ -65,20 +65,12 @@ class OptionParser return 1; } - } else if ($next && !$next->anyOfOptions($this->specs)) { - $spec->setValue($next->arg); - return 1; - } else if ($spec->defaultValue) { - // if (($spec->value || $spec->defaultValue) && $next && !$next->isOption()) { - $spec->setValue($spec->defaultValue); - return 0; - } else if ($next && !$next->isEmpty()) { + } else if ($spec->isOptional() && $next && !$next->isEmpty() && !$next->anyOfOptions($this->specs)) { + $spec->setValue($next->arg); return 1; - } else { - $spec->setValue(true); - return 0; - } + + } return 0; }
should only consume the next tokens when required or optional is defined.
c9s_GetOptionKit
train
026b145be079131e99d88b956b7d463508d35004
diff --git a/lettuce_webdriver/webdriver.py b/lettuce_webdriver/webdriver.py index <HASH>..<HASH> 100644 --- a/lettuce_webdriver/webdriver.py +++ b/lettuce_webdriver/webdriver.py @@ -341,6 +341,18 @@ def dismiss_alert(step): pass +@step('I click on label "([^"]*)"') +def click_on_label(step, label): + """ + Click on a label + """ + + with AssertContextManager(step): + elem = world.browser.find_element_by_xpath( + '//label[normalize-space(text()) = "%s"]' % label) + elem.click() + + @step(r'I should see item with tooltip "([^"]*)"') def see_tooltip(step, tooltip): """
I click on label This is used for clicking on a label and focusing an element. Useful for accessibility testing, and for dealing with radios and checkbuttons.
aloetesting_aloe_webdriver
train
0d1f911d8e4ad1fbdc64185e85dba7a87f1f35a8
diff --git a/src/Arrays.php b/src/Arrays.php index <HASH>..<HASH> 100644 --- a/src/Arrays.php +++ b/src/Arrays.php @@ -6,6 +6,7 @@ namespace TraderInteractive\Util; use InvalidArgumentException; +use UnexpectedValueException; /** * Class of static array utility functions. @@ -301,11 +302,8 @@ final class Arrays self::ensureIsArray($array, '$arrays was not a multi-dimensional array'); $key = self::get($array, $keyIndex); - self::ensureValidKey( - $key, - "Value for \$arrays[{$index}][{$keyIndex}] was not a string or integer", - '\\UnexpectedValueException' - ); + $message = "Value for \$arrays[{$index}][{$keyIndex}] was not a string or integer"; + self::ensureValidKey($key, $message, UnexpectedValueException::class); $value = self::get($array, $valueIndex); if (!array_key_exists($key, $result)) {
Refactor to get code coverage to <I>%
traderinteractive_util-arrays-php
train
65de831cf32d8e4f16c5823b0e2b210077a0a3a7
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/validation/NamesAreUniqueValidator.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/validation/NamesAreUniqueValidator.java index <HASH>..<HASH> 100644 --- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/validation/NamesAreUniqueValidator.java +++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/validation/NamesAreUniqueValidator.java @@ -7,18 +7,14 @@ *******************************************************************************/ package org.eclipse.xtext.validation; -import java.util.Collections; - -import java.util.List; import java.util.Map; -import org.eclipse.xtext.util.CancelIndicator; import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceServiceProvider; +import org.eclipse.xtext.util.CancelIndicator; import com.google.inject.Inject; @@ -44,8 +40,8 @@ public class NamesAreUniqueValidator extends AbstractDeclarativeValidator { private INamesAreUniqueValidationHelper helper; @Override - protected List<EPackage> getEPackages() { - return Collections.emptyList(); + public void register(EValidatorRegistrar registrar) { + // library validator is not registered for a specific language } @Check
[xtext.validation] Don't try to register the NamesAreUniqueValidator for a specific language
eclipse_xtext-core
train
7d2318299e2a4d2e390a709c74a62bade95e8216
diff --git a/src/Controller/MenuItemsController.php b/src/Controller/MenuItemsController.php index <HASH>..<HASH> 100644 --- a/src/Controller/MenuItemsController.php +++ b/src/Controller/MenuItemsController.php @@ -156,6 +156,6 @@ class MenuItemsController extends AppController } else { $this->Flash->error(__('Fail to move {0} {1}.', $node->label, $action)); } - return $this->redirect(['action' => 'index']); + return $this->redirect($this->referer()); } }
Refresh screen on move (task #<I>)
QoboLtd_cakephp-menu
train
c2c539438a5a170a6249dff66ed0ffe1d4c8c873
diff --git a/kundera-core/src/main/java/com/impetus/kundera/db/RelationHolder.java b/kundera-core/src/main/java/com/impetus/kundera/db/RelationHolder.java index <HASH>..<HASH> 100644 --- a/kundera-core/src/main/java/com/impetus/kundera/db/RelationHolder.java +++ b/kundera-core/src/main/java/com/impetus/kundera/db/RelationHolder.java @@ -78,5 +78,6 @@ public class RelationHolder return relations; } return null; - } + } + } diff --git a/kundera-core/src/main/java/com/impetus/kundera/persistence/PersistenceDelegator.java b/kundera-core/src/main/java/com/impetus/kundera/persistence/PersistenceDelegator.java index <HASH>..<HASH> 100644 --- a/kundera-core/src/main/java/com/impetus/kundera/persistence/PersistenceDelegator.java +++ b/kundera-core/src/main/java/com/impetus/kundera/persistence/PersistenceDelegator.java @@ -819,7 +819,8 @@ public class PersistenceDelegator Object parentEntity = objectGraph.getParentEntity(); EntityMetadata metadata = getMetadata(objectGraph.getParentClass()); - List<EntitySaveGraph> relationGraphs = null; + List<EntitySaveGraph> relationGraphs = null; + // If this is a swapped graph and parent has further relations, persist // before the parent @@ -839,20 +840,17 @@ public class PersistenceDelegator } + // Persist parent entity if (parentEntity != null) { - objectGraph.setParentId(getId(parentEntity, metadata)); - - // if (getSession().lookup(parentEntity.getClass(), - // objectGraph.getParentId()) == null) - // { - Client pClient = getClient(metadata); - pClient.persist(objectGraph, metadata); - session.store(objectGraph.getParentId(), objectGraph.getParentEntity()); - - // } + + if(getSession().lookup(objectGraph.getParentClass(), objectGraph.getParentId()) == null) { + Client pClient = getClient(metadata); + pClient.persist(objectGraph, metadata); + session.store(objectGraph.getParentId(), objectGraph.getParentEntity()); + } } // Persist child entity(ies) @@ -860,6 +858,7 @@ public class PersistenceDelegator if (objectGraph.getParentEntity() != null && childEntity != null) { persistChildEntity(objectGraph, childEntity); + } // Persist Join Table diff --git a/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java b/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java index <HASH>..<HASH> 100644 --- a/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java +++ b/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java @@ -110,9 +110,8 @@ public class MongoDBClient implements Client String id = entityGraph.getParentId(); try - { - onPersist(entityMetadata, entity, id, RelationHolder.addRelation(entityGraph, entityGraph.getRevFKeyName(), - entityGraph.getRevFKeyValue())); + { + onPersist(entityMetadata, entity, id, RelationHolder.addRelation(entityGraph, entityGraph.getRevFKeyName(), entityGraph.getRevFKeyValue())); if (entityGraph.getRevParentClass() != null) { diff --git a/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoEntityReader.java b/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoEntityReader.java index <HASH>..<HASH> 100644 --- a/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoEntityReader.java +++ b/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoEntityReader.java @@ -62,7 +62,13 @@ public class MongoEntityReader extends AbstractEntityReader implements EntityRea try { Object o = client.find(m.getEntityClazz(), m, primaryKey, relationNames); - return o instanceof EnhanceEntity ? (EnhanceEntity) o: new EnhanceEntity(o, getId(o, m), null); + if(o == null) { + //No entity found + return null; + } else { + return o instanceof EnhanceEntity ? (EnhanceEntity) o: new EnhanceEntity(o, getId(o, m), null); + } + } catch (Exception e) {
fixed bug with entity finder in mongo
Impetus_Kundera
train
7368a8785624b7d457a6eafedebf9adf3c621b6d
diff --git a/cirq-core/cirq/circuits/circuit_test.py b/cirq-core/cirq/circuits/circuit_test.py index <HASH>..<HASH> 100644 --- a/cirq-core/cirq/circuits/circuit_test.py +++ b/cirq-core/cirq/circuits/circuit_test.py @@ -3345,7 +3345,7 @@ def test_next_moments_operating_on(circuit_cls): circuit = cirq.testing.random_circuit(randint(1, 20), n_moments, random()) circuit_qubits = circuit.all_qubits() n_key_qubits = randint(int(bool(circuit_qubits)), len(circuit_qubits)) - key_qubits = sample(circuit_qubits, n_key_qubits) + key_qubits = sample(sorted(circuit_qubits), n_key_qubits) start = randrange(len(circuit)) next_moments = circuit.next_moments_operating_on(key_qubits, start) for q, m in next_moments.items(): @@ -3396,7 +3396,7 @@ def test_push_frontier_random_circuit(): for _ in range(20): n_moments = randint(1, 10) circuit = cirq.testing.random_circuit(randint(1, 20), n_moments, random()) - qubits = circuit.all_qubits() + qubits = sorted(circuit.all_qubits()) early_frontier = {q: randint(0, n_moments) for q in sample(qubits, randint(0, len(qubits)))} late_frontier = {q: randint(0, n_moments) for q in sample(qubits, randint(0, len(qubits)))} update_qubits = sample(qubits, randint(0, len(qubits)))
Use sorted instead of set for random.sample (#<I>)
quantumlib_Cirq
train
f60168395937bd0be1b7cfdf44de2d1c384d7918
diff --git a/src/Cerbero/Workflow/WorkflowCommand.php b/src/Cerbero/Workflow/WorkflowCommand.php index <HASH>..<HASH> 100644 --- a/src/Cerbero/Workflow/WorkflowCommand.php +++ b/src/Cerbero/Workflow/WorkflowCommand.php @@ -44,6 +44,19 @@ class WorkflowCommand extends Command { } /** + * Retrieve the workflow data. + * + * @author Andrea Marco Sartori + * @return array + */ + protected function getWorkflow() + { + $data = $this->argument() + $this->option(); + + return new WorkflowDataTransfer($data); + } + + /** * Get the console command arguments. * * @return array
Added method to get the workflow DTO
cerbero90_Workflow
train
4ac55a0f5468bdf22d32454e488919c7d5370b45
diff --git a/packages/xod-client-browser/test-func/creatingBlinkPatch.spec.js b/packages/xod-client-browser/test-func/creatingBlinkPatch.spec.js index <HASH>..<HASH> 100644 --- a/packages/xod-client-browser/test-func/creatingBlinkPatch.spec.js +++ b/packages/xod-client-browser/test-func/creatingBlinkPatch.spec.js @@ -17,6 +17,11 @@ import TranspiledCodePopup from './pageObjects/TranspiledCodePopup'; const workspacePath = subPath => path.resolve(__dirname, '../../../workspace/', subPath); +const assertApproximateEqual = (actual, expected, tolerance, message) => + assert.isTrue(Math.abs(actual - expected) <= tolerance, message); + +const NODE_POSITION_TOLERANCE = 2.5; + describe('creating blink patch', () => { let page; let projectBrowser; @@ -91,7 +96,18 @@ describe('creating blink patch', () => { await clockNode.drag(150, 10); const { x, y } = await clockNode.getBoundingClientRect(); - assert.deepEqual({ x, y }, { x: 400.5, y: 142.5 }); + assertApproximateEqual( + x, + 400.5, + NODE_POSITION_TOLERANCE, + `X position of the Node should be 400.5±${NODE_POSITION_TOLERANCE}` + ); + assertApproximateEqual( + y, + 142.5, + NODE_POSITION_TOLERANCE, + `X position of the Node should be 400.5±${NODE_POSITION_TOLERANCE}` + ); }); it('adds rest of the nodes needed for blink patch', async () => {
fix(xod-client-browser): ensure passing "create blinking patch" test on any machine by adding a tolerance to the assertion of the node position
xodio_xod
train
20dbb7318d6a3da8111ce2299e840d7baded8f66
diff --git a/guava/src/com/google/common/util/concurrent/AbstractFuture.java b/guava/src/com/google/common/util/concurrent/AbstractFuture.java index <HASH>..<HASH> 100644 --- a/guava/src/com/google/common/util/concurrent/AbstractFuture.java +++ b/guava/src/com/google/common/util/concurrent/AbstractFuture.java @@ -23,6 +23,7 @@ import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.j2objc.annotations.ReflectionSupport; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -58,6 +59,7 @@ import javax.annotation.Nullable; * @since 1.0 */ @GwtCompatible(emulated = true) +@ReflectionSupport(value = ReflectionSupport.Level.FULL) public abstract class AbstractFuture<V> implements ListenableFuture<V> { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
Add Reflection annotation to j.c.g.common.util.concurrent.AbstractFuture for j2objc compile, in order to strip all other transpiled java reflections. ------------- Created by MOE: <URL>
google_guava
train
501154b79c40027f10e1b52f1dacd890d1ecebd3
diff --git a/src/FakeIdServiceProvider.php b/src/FakeIdServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/FakeIdServiceProvider.php +++ b/src/FakeIdServiceProvider.php @@ -67,7 +67,7 @@ class FakeIdServiceProvider extends ServiceProvider $instance = $this->container->make($class); // Decode FakeId first if applicable. - if (in_array('Propaganistas\LaravelFakeId\FakeIdTrait', class_uses($class))) { + if (in_array('Propaganistas\LaravelFakeId\FakeIdTrait', self::class_uses_deep($class))) { $value = $this->container->make('fakeid')->decode($value); } @@ -87,4 +87,28 @@ class FakeIdServiceProvider extends ServiceProvider }); } + private static function class_uses_deep($class, $autoload = true) + { + $traits = []; + + // Get traits of all parent classes + do { + $traits = array_merge(class_uses($class, $autoload), $traits); + } while ($class = get_parent_class($class)); + + // Get traits of all parent traits + $traitsToSearch = $traits; + while (!empty($traitsToSearch)) { + $newTraits = class_uses(array_pop($traitsToSearch), $autoload); + $traits = array_merge($newTraits, $traits); + $traitsToSearch = array_merge($newTraits, $traitsToSearch); + }; + + foreach ($traits as $trait => $same) { + $traits = array_merge(class_uses($trait, $autoload), $traits); + } + + return array_unique($traits); + } + }
replaces class_uses() trait detection with class_uses_deep() trait detection for parent inherited trait
Propaganistas_Laravel-FakeId
train
b3bca043b2b59fd47a49cb706ae8bd8d06ba76d9
diff --git a/examples/python/data_transmission/client.py b/examples/python/data_transmission/client.py index <HASH>..<HASH> 100644 --- a/examples/python/data_transmission/client.py +++ b/examples/python/data_transmission/client.py @@ -22,6 +22,9 @@ import demo_pb2 SERVER_ADDRESS = "localhost:23333" CLIENT_ID = 1 +# 中文注释和英文翻译 +# Note that this example was contributed by an external user using Chinese comments. +# In all cases, the Chinese comment text is translated to English just below it. # 一元模式(在一次调用中, 客户端只能向服务器传输一次请求数据, 服务器也只能返回一次响应) # unary-unary(In a single call, the client can only send request once, and the server can
Explain that this has Chinese comments with English translation
grpc_grpc
train
d6ca466fd3568d8d35f00cc99b78fbfde9661fdb
diff --git a/routes/web/adminarea.php b/routes/web/adminarea.php index <HASH>..<HASH> 100644 --- a/routes/web/adminarea.php +++ b/routes/web/adminarea.php @@ -6,7 +6,7 @@ Route::domain(domain())->group(function () { Route::name('adminarea.') ->namespace('Cortex\Tenants\Http\Controllers\Adminarea') ->middleware(['web', 'nohttpcache', 'can:access-adminarea']) - ->prefix(config('cortex.foundation.route.locale_prefix') ? '{locale}/'.config('cortex.foundation.route.prefix.adminarea') : config('cortex.foundation.route.prefix.adminarea'))->group(function () { + ->prefix(route_prefix('adminarea'))->group(function () { // Tenants Routes Route::name('cortex.tenants.tenants.')->prefix('tenants')->group(function () { diff --git a/routes/web/managerarea.php b/routes/web/managerarea.php index <HASH>..<HASH> 100755 --- a/routes/web/managerarea.php +++ b/routes/web/managerarea.php @@ -6,7 +6,7 @@ Route::domain('{subdomain}.'.domain())->group(function () { Route::name('managerarea.') ->namespace('Cortex\Tenants\Http\Controllers\Managerarea') ->middleware(['web', 'nohttpcache', 'can:access-managerarea']) - ->prefix(config('cortex.foundation.route.locale_prefix') ? '{locale}/'.config('cortex.foundation.route.prefix.managerarea') : config('cortex.foundation.route.prefix.managerarea'))->group(function () { + ->prefix(route_prefix('managerarea'))->group(function () { // Managerarea Home route Route::name('cortex.tenants.tenants.')->prefix('tenants')->group(function () {
Simplify route prefixes
rinvex_cortex-tenants
train
2e507b68b74271f1aefa70f1687e4a78c8c6f5e0
diff --git a/lib/OpenLayers/Control/Navigation.js b/lib/OpenLayers/Control/Navigation.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Control/Navigation.js +++ b/lib/OpenLayers/Control/Navigation.js @@ -57,6 +57,7 @@ OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, { activate: function() { this.dragPan.activate(); this.wheelHandler.activate(); + this.clickHandler.activate(); this.zoomBox.activate(); return OpenLayers.Control.prototype.activate.apply(this,arguments); }, @@ -67,6 +68,7 @@ OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, { deactivate: function() { this.zoomBox.deactivate(); this.dragPan.deactivate(); + this.clickHandler.deactivate(); this.wheelHandler.deactivate(); return OpenLayers.Control.prototype.deactivate.apply(this,arguments); }, @@ -75,7 +77,12 @@ OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, { * Method: draw */ draw: function() { - this.map.events.register( "dblclick", this, this.defaultDblClick ); + this.clickHandler = new OpenLayers.Handler.Click(this, + { 'dblclick': this.defaultDblClick }, + { + 'double': true, + 'stopDouble': true + }); this.dragPan = new OpenLayers.Control.DragPan({map: this.map}); this.zoomBox = new OpenLayers.Control.ZoomBox( {map: this.map, keyMask: OpenLayers.Handler.MOD_SHIFT}); @@ -96,8 +103,6 @@ OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, { defaultDblClick: function (evt) { var newCenter = this.map.getLonLatFromViewPortPx( evt.xy ); this.map.setCenter(newCenter, this.map.zoom + 1); - OpenLayers.Event.stop(evt); - return false; }, /**
Fix for "When Navigation control is inactive, doubleclick zooms in", using the new click handler that Tim and I created over the weekend. (Hooray for handlers!) r=tschaub (Closes #<I>) git-svn-id: <URL>
openlayers_openlayers
train
971dca494a796eec0504c4c7957cbc145102e3b7
diff --git a/src/main/java/com/github/davidcarboni/restolino/handlers/DefaultNotFoundHandler.java b/src/main/java/com/github/davidcarboni/restolino/handlers/DefaultNotFoundHandler.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/davidcarboni/restolino/handlers/DefaultNotFoundHandler.java +++ b/src/main/java/com/github/davidcarboni/restolino/handlers/DefaultNotFoundHandler.java @@ -12,6 +12,6 @@ import java.io.IOException; public class DefaultNotFoundHandler implements NotFound { @Override public String handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - return "No API endpoint is defined for " + request.getPathInfo(); + return "No API is defined for " + request.getMethod() + " " + request.getPathInfo(); } }
Improved the returned message to include the http method.
davidcarboni_restolino
train
00661eca215df22ea28c2a21103052cec1cfe00a
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ LUYA CHANGELOG **[BC BREAK]** removed $app->storage component and replaced with new storage $app->component see api guide. +- `#582` fixed issue where file downlaod links does not work on multi lingual pages, moved route resolver into urlManager instead of luya urlRule. - `#588` delete the block cache (for the specific block) after updating them via cms admin. - `#487` added URL duplication check (alias) on page move. - `#540` fixed bug where you could create empty tags diff --git a/src/components/UrlRule.php b/src/components/UrlRule.php index <HASH>..<HASH> 100644 --- a/src/components/UrlRule.php +++ b/src/components/UrlRule.php @@ -37,12 +37,18 @@ class UrlRule extends \luya\web\UrlRule return explode('/', rtrim($pathInfo, '/')); } + /** + * @todo verify the $urlParts variable, foreach resolvedValues when $urlParts not empty? + * @param luya\web\UrlManager $manager + * @param luya\web\Request $request + * @return boolean + */ public function parseRequest($manager, $request) { // extra data from request to composition, which changes the pathInfo of the Request-Object. $resolver = Yii::$app->composition->getResolvedPathInfo($request); - $request->setPathInfo($resolver['route']); + //$request->setPathInfo($resolver['route']); // set user env variabls Yii::$app->language = Yii::$app->composition->language; @@ -60,7 +66,6 @@ class UrlRule extends \luya\web\UrlRule if (count($urlParts) > 0 && !array_key_exists($urlParts[0], Yii::$app->modules)) { if (class_exists($this->getDefaultClassName())) { $manager->addRules([['class' => $this->getDefaultClassName()]], false); - return $manager->parseRequest($request); } } diff --git a/src/web/UrlManager.php b/src/web/UrlManager.php index <HASH>..<HASH> 100644 --- a/src/web/UrlManager.php +++ b/src/web/UrlManager.php @@ -29,6 +29,11 @@ class UrlManager extends \yii\web\UrlManager public function parseRequest($request) { + // extra data from request to composition, which changes the pathInfo of the Request-Object. + $resolver = Yii::$app->composition->getResolvedPathInfo($request); + + $request->setPathInfo($resolver['route']); + $route = parent::parseRequest($request); if ($this->composition->hidden) {
fixed issue where file download links does not work on multi lingual pages, moved route resolver into urlManager instead of luya urlRule. closes #<I>
luyadev_luya
train
3dab7a6bcb7029db2f6874297a3b3957fd5a1ada
diff --git a/src/Session/SessionHandler.php b/src/Session/SessionHandler.php index <HASH>..<HASH> 100644 --- a/src/Session/SessionHandler.php +++ b/src/Session/SessionHandler.php @@ -30,7 +30,7 @@ use \PDO; * Session Handler * * Manage http session state across page views. - * @version 1.1.0 + * @version 1.2.0 */ class SessionHandler { @@ -133,6 +133,18 @@ class SessionHandler protected $data = []; /** + * Flash data from the last request. + * @var array + */ + protected $lastFlashData = []; + + /** + * Flash data for the next request. + * @var array + */ + protected $newFlashData = []; + + /** * Current Unix time * @var integer */ @@ -195,7 +207,7 @@ class SessionHandler public function setData($newdata, $value = '') { if (is_string($newdata)) { - $newdata = array($newdata => $value); + $newdata = [$newdata => $value]; } if (!empty($newdata)) { @@ -215,7 +227,7 @@ class SessionHandler public function unsetData($key = null) { if ($key === null) { - $this->data = array(); + $this->data = []; } if ($key !== null and isset($this->data[$key])) { @@ -240,6 +252,42 @@ class SessionHandler } /** + * Set Flash Data + * + * Set flash data that will persist only until next request + * @param mixed $newdata Flash data array or string (key) + * @param string $value Value for single key + */ + public function setFlashData($newdata, $value = '') + { + if (is_string($newdata)) { + $newdata = [$newdata => $value]; + } + + if (!empty($newdata)) { + foreach ($newdata as $key => $val) { + $this->newFlashData[$key] = $val; + } + } + } + + /** + * Get Flash Data + * + * Returns flash data + * @param string $key Flsh data array key + * @return mixed Value or array + */ + public function getFlashData($key = null) + { + if ($key === null) { + return $this->lastFlashData; + } + + return isset($this->lastFlashData[$key]) ? $this->lastFlashData[$key] : null; + } + + /** * Destroy Session * * Destroy the current session. @@ -250,7 +298,7 @@ class SessionHandler // Deletes session from the database if (isset($this->sessionId)) { $stmt = $this->db->prepare("DELETE FROM {$this->tableName} WHERE session_id = ?"); - $stmt->execute(array($this->sessionId)); + $stmt->execute([$this->sessionId]); } // Kill the cookie, every which way @@ -280,7 +328,7 @@ class SessionHandler // Fetch the session from the database $stmt = $this->db->prepare("SELECT data, user_agent, ip_address, time_updated FROM {$this->tableName} WHERE session_id = ?"); - $stmt->execute(array($this->sessionId)); + $stmt->execute([$this->sessionId]); $result = $stmt->fetch(PDO::FETCH_ASSOC); @@ -311,9 +359,11 @@ class SessionHandler } // Make stored user data available - if ($user_data = json_decode($result['data'], true)) { - $this->data = $user_data; - unset($user_data); + if ($sessionData = json_decode($result['data'], true)) { + $this->data = isset($sessionData['data']) ? $sessionData['data'] : []; + $this->lastFlashData = isset($sessionData['flash']) ? $sessionData['flash'] : []; + + unset($sessionData); } // We have a valid session @@ -337,7 +387,7 @@ class SessionHandler // Insert new session into database $stmt = $this->db->prepare("INSERT INTO {$this->tableName} (session_id, user_agent, ip_address, time_updated) VALUES (?, ?, ?, ?)"); - $stmt->execute(array($this->sessionId, $this->userAgent, $this->ipAddress, $this->now)); + $stmt->execute([$this->sessionId, $this->userAgent, $this->ipAddress, $this->now]); } /** @@ -348,16 +398,12 @@ class SessionHandler */ private function write() { - if (empty($this->data)) { - // Custom data does not exist - $custom_data = ''; - } else { - $custom_data = json_encode($this->data); - } + $sessionData['data'] = $this->data; + $sessionData['flash'] = $this->newFlashData; // Write session data to database $stmt = $this->db->prepare("UPDATE {$this->tableName} SET data = ? WHERE session_id = ?"); - $stmt->execute(array($custom_data, $this->sessionId)); + $stmt->execute([json_encode($sessionData), $this->sessionId]); } @@ -391,7 +437,7 @@ class SessionHandler // 5% chance to clean the database of expired sessions if (mt_rand(1, 20) == 1) { $stmt = $this->db->prepare("DELETE FROM {$this->tableName} WHERE (time_updated + {$this->secondsUntilExpiration}) < {$this->now}"); - $stmt->execute(array()); + $stmt->execute(); } } @@ -424,7 +470,7 @@ class SessionHandler // Update session ID in the database $stmt = $this->db->prepare("UPDATE {$this->tableName} SET time_updated = ?, session_id = ? WHERE session_id = ?"); - $stmt->execute(array($this->now, $this->sessionId, $oldSessionId)); + $stmt->execute([$this->now, $this->sessionId, $oldSessionId]); } /**
Added flash data and updated array declarations to PHP <I>+ [] syntax. Added properties to hold last flash data and new, and methods to get and set flash data. Flash data will only persist until the next request, at which time it is cleared from session.
PitonCMS_Session
train
1dc877bfe0e65fc9f1bef52cf95de6d10313ab53
diff --git a/mackup.py b/mackup.py index <HASH>..<HASH> 100755 --- a/mackup.py +++ b/mackup.py @@ -195,6 +195,9 @@ SUPPORTED_APPS = { 'Vimperator': ['.vimperator', '.vimperatorrc'], + 'Viscosity': [APP_SUPPORT + 'Viscosity', + PREFERENCES + 'com.viscosityvpn.Viscosity.plist'], + 'Witch': [PREFERENCES + 'com.manytricks.Witch.plist'], 'X11': ['.Xresources',
Added support for Viscosity VPN
lra_mackup
train
b82e63f12ebdd6342cdb1811be02dc15908bbf4b
diff --git a/cli/api/interfaces.go b/cli/api/interfaces.go index <HASH>..<HASH> 100644 --- a/cli/api/interfaces.go +++ b/cli/api/interfaces.go @@ -38,6 +38,7 @@ type API interface { // Hosts GetHosts() ([]host.Host, error) GetHost(string) (*host.Host, error) + GetHostMap() (map[string]host.Host, error) AddHost(HostConfig) (*host.Host, error) RemoveHost(string) error GetHostMemory(string) (*metrics.MemoryUsageStats, error) diff --git a/cli/api/service.go b/cli/api/service.go index <HASH>..<HASH> 100644 --- a/cli/api/service.go +++ b/cli/api/service.go @@ -30,6 +30,7 @@ import ( "github.com/control-center/serviced/metrics" "github.com/pivotal-golang/bytefmt" + "github.com/control-center/serviced/domain/host" ) const () @@ -106,14 +107,10 @@ func (a *api) GetServiceStatus(serviceID string) (map[string]map[string]interfac } // get hosts - hosts, err := a.GetHosts() + hostmap, err := a.GetHostMap() if err != nil { return nil, err } - hostmap := make(map[string]string) - for _, host := range hosts { - hostmap[host.ID] = host.Name - } // get status rowmap := make(map[string]map[string]interface{}) @@ -167,7 +164,7 @@ func (a *api) GetServiceStatus(serviceID string) (map[string]map[string]interfac row["RAM"] = bytefmt.ByteSize(svc.RAMCommitment.Value) row["Status"] = stat.Status.String() - row["Hostname"] = hostmap[stat.State.HostID] + row["Hostname"] = hostmap[stat.State.HostID].Name row["DockerID"] = fmt.Sprintf("%.12s", stat.State.DockerID) row["Uptime"] = uptime.String() @@ -463,3 +460,15 @@ func (a *api) AssignIP(config IPConfig) error { return nil } + +func (a *api) GetHostMap() (map[string]host.Host, error) { + hosts, err := a.GetHosts() + if err != nil { + return nil, err + } + hostmap := make(map[string]host.Host) + for _, host := range hosts { + hostmap[host.ID] = host + } + return hostmap, nil +} diff --git a/cli/cmd/service.go b/cli/cmd/service.go index <HASH>..<HASH> 100644 --- a/cli/cmd/service.go +++ b/cli/cmd/service.go @@ -30,7 +30,6 @@ import ( "github.com/control-center/serviced/cli/api" dockerclient "github.com/control-center/serviced/commons/docker" "github.com/control-center/serviced/dao" - "github.com/control-center/serviced/domain/host" "github.com/control-center/serviced/domain/service" "github.com/control-center/serviced/node" "github.com/control-center/serviced/utils" @@ -1060,14 +1059,10 @@ func (c *ServicedCli) searchForRunningService(keyword string) (*dao.RunningServi return nil, err } - hosts, err := c.driver.GetHosts() + hostmap, err := c.driver.GetHostMap() if err != nil { return nil, err } - hostmap := make(map[string]host.Host) - for _, host := range hosts { - hostmap[host.ID] = host - } pathmap, err := c.buildRunningServicePaths(rss) if err != nil { @@ -1149,14 +1144,10 @@ func (c *ServicedCli) cmdServiceAttach(ctx *cli.Context) error { } if rs.HostID != myHostID { - hosts, err := c.driver.GetHosts() + hostmap, err := c.driver.GetHostMap() if err != nil { return err } - hostmap := make(map[string]host.Host) - for _, host := range hosts { - hostmap[host.ID] = host - } cmd := []string{"/usr/bin/ssh", "-t", hostmap[rs.HostID].IPAddr, "--", "serviced", "--endpoint", api.GetOptionsRPCEndpoint(), "service", "attach", args[0]} if len(args) > 1 { @@ -1259,14 +1250,10 @@ func (c *ServicedCli) cmdServiceLogs(ctx *cli.Context) error { } if rs.HostID != myHostID { - hosts, err := c.driver.GetHosts() + hostmap, err := c.driver.GetHostMap() if err != nil { return err } - hostmap := make(map[string]host.Host) - for _, host := range hosts { - hostmap[host.ID] = host - } cmd := []string{"/usr/bin/ssh", "-t", hostmap[rs.HostID].IPAddr, "--", "serviced", "--endpoint", api.GetOptionsRPCEndpoint(), "service", "logs", args[0]} if len(args) > 1 {
Refactor: use common GetHostMap() for cli
control-center_serviced
train
1341329d9c3215dee4d3bbb63be42761c813bd95
diff --git a/docs/api/cozy-client.md b/docs/api/cozy-client.md index <HASH>..<HASH> 100644 --- a/docs/api/cozy-client.md +++ b/docs/api/cozy-client.md @@ -473,6 +473,7 @@ Responsible for * [CozyClient](#CozyClient) * [new CozyClient(options)](#new_CozyClient_new) * _instance_ + * [.registerPlugin()](#CozyClient+registerPlugin) * [.login()](#CozyClient+login) ⇒ <code>Promise</code> * [.logout()](#CozyClient+logout) ⇒ <code>Promise</code> * [.collection(doctype)](#CozyClient+collection) ⇒ <code>DocumentCollection</code> @@ -505,6 +506,27 @@ Responsible for | options.schema | <code>Object</code> | Schema description for each doctypes | | options.appMetadata | <code>Object</code> | Metadata about the application that will be used in ensureCozyMetadata Cozy-Client will automatically call `this.login()` if provided with a token and an uri | +<a name="CozyClient+registerPlugin"></a> + +### cozyClient.registerPlugin() +A plugin is a function that receives the client as first argument. +The main mean of interaction with the client should be with events +like "login"/"logout". + +The plugin system is meant to encourage separation of concerns, modularity +and testability : instead of registering events at module level, please +create a plugin that subscribes to events. + +**Kind**: instance method of [<code>CozyClient</code>](#CozyClient) +**Example** +``` +const alertPlugin = client => { + client.on("login", () => { alert("client has logged in !") } + client.on("logout", () => { alert("client has logged out !") } +} + +client.registerPlugin(alertPlugin) +``` <a name="CozyClient+login"></a> ### cozyClient.login() ⇒ <code>Promise</code> diff --git a/packages/cozy-client/src/CozyClient.js b/packages/cozy-client/src/CozyClient.js index <HASH>..<HASH> 100644 --- a/packages/cozy-client/src/CozyClient.js +++ b/packages/cozy-client/src/CozyClient.js @@ -95,6 +95,29 @@ class CozyClient { } /** + * A plugin is a function that receives the client as first argument. + * The main mean of interaction with the client should be with events + * like "login"/"logout". + * + * The plugin system is meant to encourage separation of concerns, modularity + * and testability : instead of registering events at module level, please + * create a plugin that subscribes to events. + * + * @example + * ``` + * const alertPlugin = client => { + * client.on("login", () => { alert("client has logged in !") } + * client.on("logout", () => { alert("client has logged out !") } + * } + * + * client.registerPlugin(alertPlugin) + * ``` + */ + registerPlugin(plugin) { + return plugin(this) + } + + /** * To help with the transition from cozy-client-js to cozy-client, it is possible to instantiate * a client with an instance of cozy-client-js. */ diff --git a/packages/cozy-client/src/CozyClient.spec.js b/packages/cozy-client/src/CozyClient.spec.js index <HASH>..<HASH> 100644 --- a/packages/cozy-client/src/CozyClient.spec.js +++ b/packages/cozy-client/src/CozyClient.spec.js @@ -117,6 +117,15 @@ describe('CozyClient initialization', () => { expect(client.stackClient.token.token).toBe(token) }) + it('can register a plugin', () => { + expect.assertions(1) + const testPlugin = testClient => { + expect(testClient).toBe(client) + } + const client = new CozyClient({}) + client.registerPlugin(testPlugin) + }) + it('should have chained links', async () => { const res = await client.requestQuery({}) expect(res).toBe('foobarbaz')
feat: Add registerPlugin method (#<I>)
cozy_cozy-client
train
9fdf2af0f57ca61a57b938e70ba2470faa063558
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -45,4 +45,9 @@ gulp.task('minify',function(){ }); -gulp.task('default',['minify','bootstrap']); \ No newline at end of file +gulp.task('default',['minify','bootstrap']); + + +gulp.task('watch', function() { + gulp.watch('./src/**/*', ['default']); +});
Added a watch task to gulpfile.js
json-schema-form_angular-schema-form
train
2b7bf06cbbb15fe4747d83ee1038b69d2686b975
diff --git a/Lib/ufo2ft/makeotfParts.py b/Lib/ufo2ft/makeotfParts.py index <HASH>..<HASH> 100644 --- a/Lib/ufo2ft/makeotfParts.py +++ b/Lib/ufo2ft/makeotfParts.py @@ -180,6 +180,6 @@ class FeatureOTFCompiler(object): self.outline[tag] = table elif self.features.strip(): - feapath = os.path.join(self.font.path, "features.fea") + feapath = os.path.join(self.font.path, "features.fea") if self.font.path is not None else None addOpenTypeFeaturesFromString(self.outline, self.features, filename=feapath)
Handle UFOs that have path set to None Fixes <URL>
googlefonts_ufo2ft
train
72ee1816a4446917bad50458dd3b28f7c4e553ae
diff --git a/packages/babel-parser/src/tokenizer/index.js b/packages/babel-parser/src/tokenizer/index.js index <HASH>..<HASH> 100644 --- a/packages/babel-parser/src/tokenizer/index.js +++ b/packages/babel-parser/src/tokenizer/index.js @@ -110,18 +110,6 @@ export class Token { // ## Tokenizer -function codePointToString(code: number): string { - // UTF-16 Decoding - if (code <= 0xffff) { - return String.fromCharCode(code); - } else { - return String.fromCharCode( - ((code - 0x10000) >> 10) + 0xd800, - ((code - 0x10000) & 1023) + 0xdc00, - ); - } -} - export default class Tokenizer extends LocationParser { // Forward-declarations // parser/util.js @@ -226,7 +214,7 @@ export default class Tokenizer extends LocationParser { if (curContext.override) { curContext.override(this); } else { - this.readToken(this.fullCharCodeAtPos()); + this.readToken(this.input.codePointAt(this.state.pos)); } } @@ -240,14 +228,6 @@ export default class Tokenizer extends LocationParser { } } - fullCharCodeAtPos(): number { - const code = this.input.charCodeAt(this.state.pos); - if (code <= 0xd7ff || code >= 0xe000) return code; - - const next = this.input.charCodeAt(this.state.pos + 1); - return (code << 10) + next - 0x35fdc00; - } - pushComment( block: boolean, text: string, @@ -658,7 +638,7 @@ export default class Tokenizer extends LocationParser { } else { this.raise( this.state.pos, - `Unexpected character '${codePointToString(code)}'`, + `Unexpected character '${String.fromCodePoint(code)}'`, ); } @@ -820,7 +800,7 @@ export default class Tokenizer extends LocationParser { this.raise( this.state.pos, - `Unexpected character '${codePointToString(code)}'`, + `Unexpected character '${String.fromCodePoint(code)}'`, ); } @@ -862,7 +842,7 @@ export default class Tokenizer extends LocationParser { while (this.state.pos < this.input.length) { const char = this.input[this.state.pos]; - const charCode = this.fullCharCodeAtPos(); + const charCode = this.input.codePointAt(this.state.pos); if (VALID_REGEX_FLAGS.indexOf(char) > -1) { if (mods.indexOf(char) > -1) { @@ -974,7 +954,7 @@ export default class Tokenizer extends LocationParser { } } - if (isIdentifierStart(this.fullCharCodeAtPos())) { + if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { this.raise(this.state.pos, "Identifier directly after number"); } @@ -1030,7 +1010,7 @@ export default class Tokenizer extends LocationParser { } } - if (isIdentifierStart(this.fullCharCodeAtPos())) { + if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { this.raise(this.state.pos, "Identifier directly after number"); } @@ -1199,7 +1179,7 @@ export default class Tokenizer extends LocationParser { } case charCodes.lowercaseU: { const code = this.readCodePoint(throwOnInvalid); - return code === null ? null : codePointToString(code); + return code === null ? null : String.fromCodePoint(code); } case charCodes.lowercaseT: return "\t"; @@ -1277,7 +1257,7 @@ export default class Tokenizer extends LocationParser { first = true, chunkStart = this.state.pos; while (this.state.pos < this.input.length) { - const ch = this.fullCharCodeAtPos(); + const ch = this.input.codePointAt(this.state.pos); if (isIdentifierChar(ch)) { this.state.pos += ch <= 0xffff ? 1 : 2; } else if (this.state.isIterator && ch === charCodes.atSign) { @@ -1303,7 +1283,7 @@ export default class Tokenizer extends LocationParser { } // $FlowFixMe - word += codePointToString(esc); + word += String.fromCodePoint(esc); chunkStart = this.state.pos; } else { break;
Update to ES6 String methods (#<I>)
babel_babel
train
26c42f1335f80f7b66dfec20af4c42bcbfbb3594
diff --git a/sql.go b/sql.go index <HASH>..<HASH> 100644 --- a/sql.go +++ b/sql.go @@ -61,6 +61,6 @@ func (uuid *UUID) Scan(src interface{}) error { // Value implements sql.Valuer so that UUIDs can be written to databases // transparently. Currently, UUIDs map map to strings. Please consult // database-specific driver documentation for matching types. -func (uuid *UUID) Value() (driver.Value, error) { +func (uuid UUID) Value() (driver.Value, error) { return uuid.String(), nil }
Value() is on UUID, not *UUID.
pborman_uuid
train
d2cd852df4842390b2ea51c429a41aafd1fb981b
diff --git a/core/model/SiteTree.php b/core/model/SiteTree.php index <HASH>..<HASH> 100755 --- a/core/model/SiteTree.php +++ b/core/model/SiteTree.php @@ -1323,7 +1323,7 @@ class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvid } } else if($link == '' || $link[0] == '/') { $this->HasBrokenLink = true; - } else if($candidateFile = DataObject::get_one("File", "\"Filename\" = '" . Convert::raw2sql(urldecode($link)) . "'", false)) { + } else if($candidateFile = File::find(Convert::raw2sql(urldecode($link)))) { $linkedFiles[] = $candidateFile->ID; } } @@ -1333,7 +1333,7 @@ class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvid foreach($images as $image) { $image = Director::makeRelative($image); if(substr($image,0,7) == 'assets/') { - $candidateImage = DataObject::get_one("File", "\"Filename\" = '$image'"); + $candidateImage = File::find($image); if($candidateImage) $linkedFiles[] = $candidateImage->ID; else $this->HasBrokenFile = true; }
BUGFIX: Fix image tracking to take resized images into account (from r<I>) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@<I> <I>b<I>ca-7a2a-<I>-9d3b-<I>d<I>a<I>a9
silverstripe_silverstripe-framework
train
8066498ea7494a0be029e677054ee7de2fdb03a5
diff --git a/lib/helper.js b/lib/helper.js index <HASH>..<HASH> 100644 --- a/lib/helper.js +++ b/lib/helper.js @@ -23,18 +23,18 @@ module.exports.parseOptions = (options) => { var property = module.parent.options.defaults[prop]; // Check for allow-headers option - if(prop == "allow-headers" && property != null){ - property = parseHeader(property, prop); + if(prop == "allow-headers" && options.defaults[prop]){ + property = parseHeader(options.defaults[prop], prop); } // Check for expose-headers option - if(prop == "expose-headers" && property != null){ - property = parseHeader(property, prop); + if(prop == "expose-headers" && options.defaults[prop]){ + property = parseHeader(options.defaults[prop], prop); } // Check for allow-credentials option - if(prop == "allow-credentials" && property != null){ - if(!utils.isBoolean(property)){ + if(prop == "allow-credentials" && options.defaults[prop]){ + if(!utils.isBoolean(options.defaults[prop])){ throw new Error(`Default option for "${prop}" must be boolean`); break; }
* Fixed returned values after parsing *Fixed bug that was causing the values to return always the default instead of parsing the provided values
oscarr-reyes_node-diet-cross-origin
train
02d8fe20aee02788281042733a24b4d11486ab24
diff --git a/common/code_spelling_ignore_words.txt b/common/code_spelling_ignore_words.txt index <HASH>..<HASH> 100644 --- a/common/code_spelling_ignore_words.txt +++ b/common/code_spelling_ignore_words.txt @@ -738,7 +738,6 @@ subprocess subprocesses subquery substring -successfull summarises summarising suppressions diff --git a/master/buildbot/db/builds.py b/master/buildbot/db/builds.py index <HASH>..<HASH> 100644 --- a/master/buildbot/db/builds.py +++ b/master/buildbot/db/builds.py @@ -77,7 +77,7 @@ class BuildsConnectorComponent(base.DBConnectorComponent): ss['branch'], ss['codebase']) for ss in ssBuild]) while rv is None: - # Get some recent successfull builds on the same builder + # Get some recent successful builds on the same builder prevBuilds = yield self._getRecentBuilds(whereclause=((tbl.c.builderid == builderid) & (tbl.c.number < number) & (tbl.c.results == 0)), diff --git a/master/buildbot/db/changes.py b/master/buildbot/db/changes.py index <HASH>..<HASH> 100644 --- a/master/buildbot/db/changes.py +++ b/master/buildbot/db/changes.py @@ -182,7 +182,7 @@ class ChangesConnectorComponent(base.DBConnectorComponent): for ss in ssBuild: fromChanges[ss['codebase']] = yield self.getChangeFromSSid(ss['ssid']) - # Get the last successfull build on the same builder + # Get the last successful build on the same builder previousBuild = yield self.master.db.builds.getPrevSuccessfulBuild(currentBuild['builderid'], currentBuild[ 'number'], @@ -191,7 +191,7 @@ class ChangesConnectorComponent(base.DBConnectorComponent): for ss in (yield gssfb(previousBuild['id'])): toChanges[ss['codebase']] = yield self.getChangeFromSSid(ss['ssid']) else: - # If no successfull previous build, then we need to catch all + # If no successful previous build, then we need to catch all # changes for cb in fromChanges: toChanges[cb] = {'changeid': None}
fix typo: "successfull" -> "successful"
buildbot_buildbot
train
57d4b8e36359a7dfe331765d677b29edbc56ffa5
diff --git a/helios-tools/src/main/java/com/spotify/helios/cli/CliParser.java b/helios-tools/src/main/java/com/spotify/helios/cli/CliParser.java index <HASH>..<HASH> 100644 --- a/helios-tools/src/main/java/com/spotify/helios/cli/CliParser.java +++ b/helios-tools/src/main/java/com/spotify/helios/cli/CliParser.java @@ -78,6 +78,7 @@ import static net.sourceforge.argparse4j.impl.Arguments.storeTrue; public class CliParser { private static final String NAME_AND_VERSION = "Spotify Helios CLI " + Version.POM_VERSION; + private static final String TESTED_DOCKER_VERSION = "1.6.2"; private static final String HELP_ISSUES = "Report improvements/bugs at https://github.com/spotify/helios/issues"; private static final String HELP_WIKI = @@ -97,7 +98,7 @@ public class CliParser { final ArgumentParser parser = ArgumentParsers.newArgumentParser("helios") .defaultHelp(true) - .version(NAME_AND_VERSION) + .version(format("%s%nTested on Docker %s", NAME_AND_VERSION, TESTED_DOCKER_VERSION)) .description(format("%s%n%n%s%n%s", NAME_AND_VERSION, HELP_ISSUES, HELP_WIKI)); cliConfig = CliConfig.fromUserConfig();
Say what Docker version Helios has been tested on Include this in CLI's `helios --version`. Fixes #<I>
spotify_helios
train
978c59015795c74e79e2691e04b5c70fca414054
diff --git a/src/main/java/com/github/noraui/application/steps/Step.java b/src/main/java/com/github/noraui/application/steps/Step.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/noraui/application/steps/Step.java +++ b/src/main/java/com/github/noraui/application/steps/Step.java @@ -55,11 +55,12 @@ import com.github.noraui.exception.Result; import com.github.noraui.exception.TechnicalException; import com.github.noraui.gherkin.GherkinConditionedLoopedStep; import com.github.noraui.gherkin.GherkinStepCondition; +import com.github.noraui.service.UserNameService; import com.github.noraui.utils.Constants; import com.github.noraui.utils.Context; import com.github.noraui.utils.Messages; -import com.github.noraui.utils.NameUtilities; import com.github.noraui.utils.Utilities; +import com.google.inject.Inject; import cucumber.api.CucumberOptions; import cucumber.runtime.java.StepDefAnnotation; @@ -71,6 +72,9 @@ public class Step implements IStep { */ protected static final Logger logger = LoggerFactory.getLogger(Step.class); + @Inject + private UserNameService userNameService; + protected Step() { } @@ -870,7 +874,7 @@ public class Step implements IStep { private void setDropDownValue(PageElement element, String text) throws TechnicalException, FailureException { final WebElement select = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(element))); final Select dropDown = new Select(select); - final int index = NameUtilities.findOptionByIgnoreCaseText(text, dropDown); + final int index = userNameService.findOptionByIgnoreCaseText(text, dropDown); if (index != -1) { dropDown.selectByIndex(index); } else {
use UserNameService instead of deprecated method (NameUtilities)
NoraUi_NoraUi
train
e0f341d72632ceb4a700a744028f6d9f9126b623
diff --git a/lib/metro/scene.rb b/lib/metro/scene.rb index <HASH>..<HASH> 100644 --- a/lib/metro/scene.rb +++ b/lib/metro/scene.rb @@ -356,6 +356,7 @@ module Metro def base_update updaters.each { |updater| updater.update } update + updaters.reject! { |updater| updater.completed? } end #
Updaters are removed after they are considered complete
burtlo_metro
train
d80fe54a9a93cad4234aecfc7e1c549d3eaddcfb
diff --git a/test/db/mysql/table_name_test.rb b/test/db/mysql/table_name_test.rb index <HASH>..<HASH> 100644 --- a/test/db/mysql/table_name_test.rb +++ b/test/db/mysql/table_name_test.rb @@ -28,7 +28,9 @@ class MySQLTableNameTest < Test::Unit::TestCase end end - class SerialNumber < ActiveRecord::Base; end + class SerialNumber < ActiveRecord::Base + #self.primary_key = 'serial' unless MySQLTableNameTest.ar_version('3.0') + end test 'serial number' do sn = SerialNumber.new; sn.serial = 1234567890; sn.serial_patch = 11 @@ -36,7 +38,7 @@ class MySQLTableNameTest < Test::Unit::TestCase assert sn.reload SerialNumber.columns - end + end if ar_version('3.2') class SerialMigration < ActiveRecord::Migration def self.up diff --git a/test/db/oracle/table_name_test.rb b/test/db/oracle/table_name_test.rb index <HASH>..<HASH> 100644 --- a/test/db/oracle/table_name_test.rb +++ b/test/db/oracle/table_name_test.rb @@ -36,7 +36,7 @@ class OracleTableNameTest < Test::Unit::TestCase assert sn.reload SerialNumber.columns - end + end if ar_version('3.1') class SerialMigration < ActiveRecord::Migration diff --git a/test/db/postgresql/table_name_test.rb b/test/db/postgresql/table_name_test.rb index <HASH>..<HASH> 100644 --- a/test/db/postgresql/table_name_test.rb +++ b/test/db/postgresql/table_name_test.rb @@ -42,12 +42,13 @@ class PostgreSQLTableNameTest < Test::Unit::TestCase class SerialNumber < ActiveRecord::Base; end test 'serial number' do + skip('fails with prepared statements') if ar_version('3.1') && prepared_statements? sn = SerialNumber.new; sn.serial = 1234567890; sn.serial_patch = 11 sn.save! assert sn.reload SerialNumber.columns - end + end if ar_version('3.2') class SerialMigration < ActiveRecord::Migration def self.up
these new tests fail (but it's not our fault) on AR < <I>
jruby_activerecord-jdbc-adapter
train
daa245de300a01394bac7b5f439ebd4b79c00c29
diff --git a/core/Archive.php b/core/Archive.php index <HASH>..<HASH> 100644 --- a/core/Archive.php +++ b/core/Archive.php @@ -168,6 +168,14 @@ class Archive implements ArchiveQuery private static $cache; /** + * If true, this Archive instance will not launch the archiving process, even if the current request + * is authorized to. + * + * @var bool + */ + private $forceFetchingWithoutLaunchingArchiving; + + /** * @param Parameters $params * @param bool $forceIndexedBySite Whether to force index the result of a query by site ID. * @param bool $forceIndexedByDate Whether to force index the result of a query by period. @@ -557,7 +565,9 @@ class Archive implements ArchiveQuery // cache id archives for plugins we haven't processed yet if (!empty($archiveGroups)) { - if (!Rules::isArchivingDisabledFor($this->params->getIdSites(), $this->params->getSegment(), $this->getPeriodLabel())) { + if (!Rules::isArchivingDisabledFor($this->params->getIdSites(), $this->params->getSegment(), $this->getPeriodLabel()) + && !$this->forceFetchingWithoutLaunchingArchiving + ) { $this->cacheArchiveIdsAfterLaunching($archiveGroups, $plugins); } else { $this->cacheArchiveIdsWithoutLaunching($plugins); @@ -852,4 +862,9 @@ class Archive implements ArchiveQuery { self::$cache = null; } + + public function forceFetchingWithoutLaunchingArchiving() + { + $this->forceFetchingWithoutLaunchingArchiving = true; + } } diff --git a/core/ArchiveProcessor.php b/core/ArchiveProcessor.php index <HASH>..<HASH> 100644 --- a/core/ArchiveProcessor.php +++ b/core/ArchiveProcessor.php @@ -116,6 +116,11 @@ class ArchiveProcessor $subPeriods = $this->params->getSubPeriods(); $idSites = $this->params->getIdSites(); $this->archive = Archive::factory($this->params->getSegment(), $subPeriods, $idSites); + + /** + * @internal + */ + Piwik::postEvent('ArchiveProcessor.getArchive', [$this->archive]); } return $this->archive;
allow forcing Archive to not initiate archiving for child archives (#<I>)
matomo-org_matomo
train
c8c32c74593563c77a64953e87ae4e73e096f7f7
diff --git a/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java b/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java index <HASH>..<HASH> 100644 --- a/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java +++ b/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java @@ -250,6 +250,8 @@ public abstract class BaseWrapperManagedConnectionFactory /** Connection listener plugin */ private ConnectionListener connectionListenerPlugin; + private ClassLoader originalTCCL; + /** * Constructor */ @@ -920,7 +922,8 @@ public abstract class BaseWrapperManagedConnectionFactory { try { - clz = Class.forName(connectionListenerClassName, true, + + clz = Class.forName(connectionListenerClassName, true, SecurityActions.getClassLoader(BaseWrapperManagedConnectionFactory.class)); usedCl = SecurityActions.getClassLoader(BaseWrapperManagedConnectionFactory.class); } @@ -975,7 +978,16 @@ public abstract class BaseWrapperManagedConnectionFactory try { if (connectionListenerClassName != null && connectionListenerPlugin == null) - loadConnectionListenerPlugin(); + { + ClassLoader tccl = SecurityActions.getThreadContextClassLoader(); + try { + SecurityActions.setThreadContextClassLoader(originalTCCL); + loadConnectionListenerPlugin(); + } finally { + SecurityActions.setThreadContextClassLoader(tccl); + } + + } return connectionListenerPlugin; } @@ -1682,4 +1694,14 @@ public abstract class BaseWrapperManagedConnectionFactory { this.classLoaderPlugin = clPlugin; } + + /** + * Set the originalTCCL. + * + * @param clPlugin The clPlugin to set. + */ + public final void setOriginalTCCLn(ClassLoader cl) + { + this.originalTCCL = cl; + } } diff --git a/adapters/src/main/java/org/jboss/jca/adapters/jdbc/WrapperDataSource.java b/adapters/src/main/java/org/jboss/jca/adapters/jdbc/WrapperDataSource.java index <HASH>..<HASH> 100644 --- a/adapters/src/main/java/org/jboss/jca/adapters/jdbc/WrapperDataSource.java +++ b/adapters/src/main/java/org/jboss/jca/adapters/jdbc/WrapperDataSource.java @@ -134,6 +134,7 @@ public class WrapperDataSource extends JBossWrapper implements Referenceable, Da public Connection getConnection() throws SQLException { ClassLoader tccl = SecurityActions.getThreadContextClassLoader(); + mcf.setOriginalTCCLn(tccl); try { SecurityActions.setThreadContextClassLoader(classLoaderPlugin.getClassLoader());
[JBJCA-<I>] adding TCCL in Wrapper* Fixing a bug on reading custom ConnectionListener class
ironjacamar_ironjacamar
train
3cdf7d32fc51c10f8a9d0f63ed78b59209f4f46d
diff --git a/src/Helpers/User.php b/src/Helpers/User.php index <HASH>..<HASH> 100644 --- a/src/Helpers/User.php +++ b/src/Helpers/User.php @@ -1,6 +1,7 @@ <?php namespace Taskforcedev\LaravelSupport\Helpers; -use \Auth; +use Auth; +use Config; use Illuminate\Console\AppNamespaceDetectorTrait; class User @@ -13,7 +14,12 @@ class User */ public function getUserModel() { - /* Get the namespace */ + /* Check the app's auth config, first */ + $model = Config::get('auth.model'); + if (class_exists($model)) { + return $model; + } + /* That didn't work, so let's try our fallback. First get the namespace */ $ns = $this->getAppNamespace(); if ($ns) { /* Try laravel default convention (models in the app folder). */ @@ -36,7 +42,7 @@ class User */ public function getUser() { - return (Auth::check() ? \Auth::user() : $this->createGuest()); + return (Auth::check() ? Auth::user() : $this->createGuest()); } /**
Consult App's Auth Config For User Model Laravel includes a configuration option in `app/config/auth.php` to specify which model to use to represent users. It should be consulted first, before falling back on convention to determine the model name. (Also removed extraneous namespace characters.)
taskforcedev_laravel-support
train