hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
afce911835863ee44d33e3d4d2f8b351f9ee3145
diff --git a/javascript/atoms/frame.js b/javascript/atoms/frame.js index <HASH>..<HASH> 100644 --- a/javascript/atoms/frame.js +++ b/javascript/atoms/frame.js @@ -51,7 +51,7 @@ bot.frame.activeElement = function() { * @return {Window} The window reference for the given iframe or frame element. */ bot.frame.getFrameWindow = function(element) { - if (/^i?frame$/i.test(element.tagName)) { + if (bot.frame.isFrame_(element)) { var frame = /** @type {HTMLFrameElement|HTMLIFrameElement} */ element; return goog.dom.getFrameContentWindow(frame); } @@ -61,6 +61,18 @@ bot.frame.getFrameWindow = function(element) { /** + * Returns whether an element is a frame (or iframe). + * + * @param {!Element} element The element to check. + * @return {boolean} Whether the element is a frame (or iframe). + */ +bot.frame.isFrame_ = function(element) { + return bot.dom.isElement(element, goog.dom.TagName.FRAME) || + bot.dom.isElement(element, goog.dom.TagName.IFRAME); +}; + + +/** * Looks for a frame by its name or id (preferring name over id) * under the given root. If no frame was found, we look for an * iframe by name or id. @@ -86,14 +98,14 @@ bot.frame.findFrameByNameOrId = function(nameOrId, opt_root) { } // Lookup frame by id - var isFrame = function(element) { - return bot.dom.isElement(element, goog.dom.TagName.FRAME) || - bot.dom.isElement(element, goog.dom.TagName.IFRAME); - } + + + + var elements = bot.locators.findElements({id: nameOrId}, domWindow.document); for (var i = 0; i < elements.length; i++) { - if (isFrame(elements[i])) { + if (bot.frame.isFrame_(elements[i])) { return goog.dom.getFrameContentWindow(elements[i]); } }
DanielWagnerHall: Oops, helps if you save the whole file before committing the change. Fixing frame index lookup in IE7/8 r<I>
SeleniumHQ_selenium
train
6e3039f2e1d73ae4a71ffd274b5ebae0230900c9
diff --git a/docs/testdox.txt b/docs/testdox.txt index <HASH>..<HASH> 100644 --- a/docs/testdox.txt +++ b/docs/testdox.txt @@ -2789,6 +2789,7 @@ s9e\TextFormatter\Tests\Renderers\PHP [x] The last output of the renderer is omitted for serialization [x] Internal objects and resources are unset after rendering [x] The abstract renderer has a default implementation for renderQuickTemplate() + [x] render() throws an exception on invalid XML with a "r" root tag that could be rendered by the Quick renderer [x] Renders plain text [x] Renders multi-line text [x] Renders rich text diff --git a/src/Renderers/PHP.php b/src/Renderers/PHP.php index <HASH>..<HASH> 100644 --- a/src/Renderers/PHP.php +++ b/src/Renderers/PHP.php @@ -102,7 +102,7 @@ abstract class PHP extends Renderer */ protected function canQuickRender($xml) { - return ($this->enableQuickRenderer && !preg_match($this->quickRenderingTest, $xml)); + return ($this->enableQuickRenderer && !preg_match($this->quickRenderingTest, $xml) && substr($xml, -4) === '</r>'); } /** diff --git a/tests/Renderers/PHPTest.php b/tests/Renderers/PHPTest.php index <HASH>..<HASH> 100644 --- a/tests/Renderers/PHPTest.php +++ b/tests/Renderers/PHPTest.php @@ -98,6 +98,16 @@ class PHPTest extends Test $renderer = new DummyRenderer; $renderer->callRenderQuickTemplate(); } + + /** + * @testdox render() throws an exception on invalid XML with a "r" root tag that could be rendered by the Quick renderer + * @expectedException InvalidArgumentException + * @expectedExceptionMessage Cannot load XML: Premature end of data in tag r + */ + public function testInvalidXMLQuick() + { + $this->configurator->rendering->getRenderer()->render('<r>'); + } } class DummyRenderer extends PHP
PHP Quick renderer: detect truncated XML with a "r" root tag
s9e_TextFormatter
train
ae4ffe754f82688d1b93f17db4b82fd00a320709
diff --git a/cmd/k8sagent/unit/manifolds_test.go b/cmd/k8sagent/unit/manifolds_test.go index <HASH>..<HASH> 100644 --- a/cmd/k8sagent/unit/manifolds_test.go +++ b/cmd/k8sagent/unit/manifolds_test.go @@ -54,6 +54,8 @@ func (s *ManifoldsSuite) TestManifoldNames(c *gc.C) { "proxy-config-updater", "logging-config-updater", "api-address-updater", + "caas-prober", + "probe-http-server", } keys := make([]string, 0, len(manifolds)) for k := range manifolds { @@ -182,4 +184,8 @@ var expectedUnitManifoldsWithDependencies = map[string][]string{ "migration-fortress", "migration-inactive-flag", }, + "probe-http-server": {}, + "caas-prober": { + "probe-http-server", + }, } diff --git a/worker/caasprober/manifold.go b/worker/caasprober/manifold.go index <HASH>..<HASH> 100644 --- a/worker/caasprober/manifold.go +++ b/worker/caasprober/manifold.go @@ -9,12 +9,10 @@ import ( "github.com/juju/worker/v2/dependency" "github.com/juju/juju/apiserver/apiserverhttp" - "github.com/juju/juju/worker/uniter" ) type ManifoldConfig struct { - MuxName string - UniterName string + MuxName string } func Manifold(config ManifoldConfig) dependency.Manifold { @@ -37,17 +35,10 @@ func (c ManifoldConfig) Start(context dependency.Context) (worker.Worker, error) return nil, errors.Trace(err) } - var uniterProbe *uniter.Probe - if err := context.Get(c.UniterName, &uniterProbe); err != nil { - return nil, errors.Trace(err) - } - return NewController(&caasProbes{ Liveness: &ProbeSuccess{}, Readiness: &ProbeSuccess{}, - Startup: ProberFunc(func() (bool, error) { - return uniterProbe.HasStarted(), nil - }), + Startup: &ProbeSuccess{}, }, mux) } @@ -55,8 +46,5 @@ func (c ManifoldConfig) Validate() error { if c.MuxName == "" { return errors.NotValidf("empty mux name") } - if c.UniterName == "" { - return errors.NotValidf("empty uniter name") - } return nil }
Adds missing uniter name to probe worker k8sagent manifold was missing the uniter name to the caas prober
juju_juju
train
22500ddd8b18042f41f19cab7e8d28a1e9706d10
diff --git a/lib/rails-footnotes.rb b/lib/rails-footnotes.rb index <HASH>..<HASH> 100644 --- a/lib/rails-footnotes.rb +++ b/lib/rails-footnotes.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/attribute_accessors' + module Footnotes mattr_accessor :before_hooks @@before_hooks = []
Fix: undefined method mattr_accessor, we know have to require it explicitely
josevalim_rails-footnotes
train
577ade2c86f8a3c5c4c8fce6ae092de6de18f565
diff --git a/src/Runtime/Utilities/Requests.php b/src/Runtime/Utilities/Requests.php index <HASH>..<HASH> 100644 --- a/src/Runtime/Utilities/Requests.php +++ b/src/Runtime/Utilities/Requests.php @@ -105,6 +105,8 @@ class Requests curl_setopt($ch, CURLOPT_POST, 1); } else if($options->Method == HttpMethod::Patch) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $options->Method); + } else if($options->Method == HttpMethod::Put) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $options->Method); } else if($options->Method == HttpMethod::Delete) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $options->Method); }
Accepting PUT option when executing curl request In Runtime/Utilities/Requests::init() I added a handler method for PUT request types since at the moment only POST, PATCH, and DELETE are accounted for. This helped resolve some method not allowed errors I was getting when running requests on the graph API.
vgrem_phpSPO
train
df82f4224c98e6826e8645166499ed01d68d120b
diff --git a/ecs/zones.go b/ecs/zones.go index <HASH>..<HASH> 100644 --- a/ecs/zones.go +++ b/ecs/zones.go @@ -27,11 +27,16 @@ type AvailableDiskCategoriesType struct { DiskCategories []DiskCategory //enum for cloud, ephemeral, ephemeral_ssd } +type AvailableInstanceTypesType struct { + InstanceTypes []string +} + // // You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&zonetype type ZoneType struct { ZoneId string LocalName string + AvailableInstanceTypes AvailableInstanceTypesType AvailableResourceCreation AvailableResourceCreationType AvailableDiskCategories AvailableDiskCategoriesType }
add AvailableInstanceTypes to ZoneType struct
denverdino_aliyungo
train
03981b535bda5c314e4cf008948f46fcbfbd0abf
diff --git a/src/Generators/Webserver/Database/DatabaseGenerator.php b/src/Generators/Webserver/Database/DatabaseGenerator.php index <HASH>..<HASH> 100644 --- a/src/Generators/Webserver/Database/DatabaseGenerator.php +++ b/src/Generators/Webserver/Database/DatabaseGenerator.php @@ -189,7 +189,6 @@ class DatabaseGenerator public function updated(Events\Websites\Updated $event) { - if (!config('tenancy.db.auto-rename-tenant-database', false)) { return; }
Apply fixes from StyleCI (#<I>)
tenancy_multi-tenant
train
4b0948df96d05bd8a4b9e889130c55833996b141
diff --git a/test/core.js b/test/core.js index <HASH>..<HASH> 100644 --- a/test/core.js +++ b/test/core.js @@ -159,6 +159,8 @@ exports["Strip"] = { // tests if setting strip off results in black pixel colour test.expect(1); + this.strip.color("#FF0000"); + var colourcheck = { r: 0, g: 0, b: 0, hexcode: "#000000",
initialise strip pixels with a colour in Strip.off test
ajfisher_node-pixel
train
77dabcb6002b84dd22b39f7a37eb2ae2807d6424
diff --git a/mbed/mbed.py b/mbed/mbed.py index <HASH>..<HASH> 100644 --- a/mbed/mbed.py +++ b/mbed/mbed.py @@ -1221,9 +1221,9 @@ class Program(object): try: with open(os.path.join(req_path, req_file), 'r') as f: import pip - installed_packages = [package.project_name.lower() for package in pip.get_installed_distributions(local_only=True)] + installed_packages = [re.sub(r'-', '_', package.project_name.lower()) for package in pip.get_installed_distributions(local_only=True)] for line in f.read().splitlines(): - pkg = re.sub(r'^([\w-]+).*$', r'\1', line).lower() + pkg = re.sub(r'-', '_', re.sub(r'^([\w-]+).*$', r'\1', line).lower()) if not pkg in installed_packages: missing.append(pkg)
Convert '-' to '_' when matching pip installed packages and requirements.txt
ARMmbed_mbed-cli
train
20b6d5025e8454adcab027e6ae2f3a4f3269b92d
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,11 @@ Batch processing of several input files is possible, including video files. ## Usage ffmpeg-normalize [-h] [-o OUTPUT [OUTPUT ...]] [-of OUTPUT_FOLDER] [-f] - [-d] [-v] [-n] [-nt {ebu,rms,peak}] [-t TARGET_LEVEL] - [-lrt LOUDNESS_RANGE_TARGET] [-tp TRUE_PEAK] - [--offset OFFSET] [--dual-mono] [-c:a AUDIO_CODEC] - [-b:a AUDIO_BITRATE] [-ar SAMPLE_RATE] [-vn] - [-c:v VIDEO_CODEC] [-sn] [-mn] + [-d] [-v] [-n] [--version] [-nt {ebu,rms,peak}] + [-t TARGET_LEVEL] [-lrt LOUDNESS_RANGE_TARGET] + [-tp TRUE_PEAK] [--offset OFFSET] [--dual-mono] + [-c:a AUDIO_CODEC] [-b:a AUDIO_BITRATE] + [-ar SAMPLE_RATE] [-vn] [-c:v VIDEO_CODEC] [-sn] [-mn] [-e EXTRA_OUTPUT_OPTIONS] [-ofmt OUTPUT_FORMAT] [-ext EXTENSION] input [input ...] @@ -89,6 +89,8 @@ File Input/Output: - `-n, --dry-run`: Do not run normalization, only print what would be done +- `--version`: Print version and exit + Normalization: - `-nt {ebu,rms,peak}, --normalization-type {ebu,rms,peak}`: Normalization type (default: `ebu`). diff --git a/ffmpeg_normalize/__main__.py b/ffmpeg_normalize/__main__.py index <HASH>..<HASH> 100644 --- a/ffmpeg_normalize/__main__.py +++ b/ffmpeg_normalize/__main__.py @@ -10,9 +10,9 @@ logger = setup_custom_logger('ffmpeg_normalize') def create_parser(): parser = argparse.ArgumentParser( - prog="ffmpeg_normalize", + prog="ffmpeg-normalize", description=textwrap.dedent("""\ - ffmpeg_normalize v{} -- command line tool for normalizing audio files + ffmpeg-normalize v{} -- command line tool for normalizing audio files """.format(__version__)), formatter_class=argparse.RawTextHelpFormatter, epilog=textwrap.dedent("""\ @@ -71,6 +71,12 @@ def create_parser(): action='store_true', help="Do not run normalization, only print what would be done" ) + group_general.add_argument( + '--version', + action='version', + version='%(prog)s v{}'.format(__version__), + help="Print version and exit" + ) group_normalization = parser.add_argument_group("Normalization") group_normalization.add_argument( @@ -290,7 +296,7 @@ def main(): os.path.splitext(os.path.basename(input_file))[0] + '.' + cli_args.extension, ) - if not os.path.isdir(cli_args.output_folder): + if not os.path.isdir(cli_args.output_folder) and not cli_args.dry_run: logger.warning( "Output directory '{}' does not exist, will create" .format(cli_args.output_folder) diff --git a/test/test.py b/test/test.py index <HASH>..<HASH> 100755 --- a/test/test.py +++ b/test/test.py @@ -45,6 +45,10 @@ class TestFFmpegNormalize(unittest.TestCase): output, _ = sys_call(['test/test.mp4', '-v']) self.assertTrue("exists" in output) + def test_dry(self): + sys_call(['test/test.mp4', '-n']) + self.assertFalse(os.path.isfile('normalized/test.mkv')) + def test_output(self): Path('normalized').mkdir(exist_ok=True) output, _ = sys_call(['test/test.mp4', '-o', 'normalized/test.wav', '-v']) @@ -100,6 +104,10 @@ class TestFFmpegNormalize(unittest.TestCase): sys_call(['test/test.mp4', '-ext', 'mp3']) self.assertTrue(os.path.isfile('normalized/test.mp3')) + def test_version(self): + output, _ = sys_call(['--version']) + self.assertTrue("ffmpeg-normalize v" in output) + def tearDown(self): for file in ['test.mkv', 'test.wav', 'test.mp3', 'test.aac']: if os.path.isfile('normalized/' + file):
add version info and test case for dry run
slhck_ffmpeg-normalize
train
c2555c41bb641549d8e5fd03c0f8a22a1df5f3e3
diff --git a/src/queue.js b/src/queue.js index <HASH>..<HASH> 100644 --- a/src/queue.js +++ b/src/queue.js @@ -68,6 +68,11 @@ Queue.prototype.process = function(opts, cb) { Queue.prototype.numJobs = function(states, cb) { var self = this; + if (typeof states === 'function' && !cb) { + cb = states; + states = ['inactive', 'active', 'completed', 'failed', 'queued']; + } + if (!Array.isArray(states)) states = [states]; var data = {}; @@ -78,10 +83,17 @@ Queue.prototype.numJobs = function(states, cb) { states.forEach(function(state) { batch.push(function(done) { - self.redis.zcard('qp:' + self.name + '.' + state, function(e, r) { - data[state] = r; - done(); - }); + if (state === 'queued') { + self.redis.llen('qp:' + self.name + ':jobs', function(e, r) { + data[state] = r; + done(); + }); + } else { + self.redis.zcard('qp:' + self.name + '.' + state, function(e, r) { + data[state] = r; + done(); + }); + } }); });
add ability to get the llen of queued jobs
simontabor_qp
train
ee2a4bdf524f793908aae973ba6fbafc92879544
diff --git a/wikitextparser/wikitextparser_test.py b/wikitextparser/wikitextparser_test.py index <HASH>..<HASH> 100644 --- a/wikitextparser/wikitextparser_test.py +++ b/wikitextparser/wikitextparser_test.py @@ -317,11 +317,17 @@ class Sections(unittest.TestCase): wt = wtp.WikiText('== s ==\nc\n') self.assertEqual('== s ==\nc\n', wt.sections[1].string) - def test_only_lead_section(self): + def test_blank_lead(self): s = 'text1 HTTP://mediawiki.org text2' wt = wtp.WikiText('== s ==\nc\n') self.assertEqual('== s ==\nc\n', wt.sections[1].string) + @unittest.expectedFailure + def test_multiline_with_carriage_return(self): + s = 'text\r\n= s =\r\n{|\r\n| a \r\n|}\r\ntext' + p = wtp.parse(s) + self.assertEqual('text\r\n', p.sections[0].string) + class Template(unittest.TestCase):
Add multiline_with_carriage_return as an expectedFailure
5j9_wikitextparser
train
c97b3da0e08204a75d733bfb4de6365b9d3fb25d
diff --git a/src/python/test/test_dxclient.py b/src/python/test/test_dxclient.py index <HASH>..<HASH> 100644 --- a/src/python/test/test_dxclient.py +++ b/src/python/test/test_dxclient.py @@ -3335,7 +3335,7 @@ class TestDXClientWorkflow(DXTestCaseBuildWorkflows): self.assertIn('foo', analysis_desc) analysis_desc = json.loads(run("dx describe --json " + analysis_id )) self.assertTrue(analysis_desc["runInput"], {"foo": 747}) - time.sleep(2) # May need to wait for job to be created in the system + time.sleep(20) # May need to wait for job to be created in the system job_desc = run("dx describe " + analysis_desc["stages"][0]["execution"]["id"]) self.assertIn(' number = 474', job_desc)
Extend sleep in test_dx_run_workflow (#<I>)
dnanexus_dx-toolkit
train
34d5ed2b889cb8b6daa50975cd96b7ecf877722c
diff --git a/extensions/dom_tester.php b/extensions/dom_tester.php index <HASH>..<HASH> 100644 --- a/extensions/dom_tester.php +++ b/extensions/dom_tester.php @@ -16,9 +16,9 @@ require_once dirname(__FILE__) . '/dom_tester/css_selector.php'; */ class CssSelectorExpectation extends SimpleExpectation { - protected $dom; - protected $selector; - protected $value; + public $dom; + public $selector; + public $value; /** * Sets the dom tree and the css selector to compare against @@ -97,7 +97,7 @@ class DomTestCase extends WebTestCase public function getElementsBySelector($selector) { $this->loadDom(); - + $css_selector = new CssSelectorExpectation($this->dom, $selector); return $css_selector->value; diff --git a/extensions/dom_tester/test/dom_tester_doc_test.php b/extensions/dom_tester/test/dom_tester_doc_test.php index <HASH>..<HASH> 100644 --- a/extensions/dom_tester/test/dom_tester_doc_test.php +++ b/extensions/dom_tester/test/dom_tester_doc_test.php @@ -3,7 +3,7 @@ require_once dirname(__FILE__) . '/../../../autorun.php'; require_once dirname(__FILE__) . '/../../dom_tester.php'; -SimpleTest :: prefer(new TextReporter()); +SimpleTest::prefer(new TextReporter()); class TestOfLiveCssSelectors extends DomTestCase { diff --git a/extensions/dom_tester/test/dom_tester_test.php b/extensions/dom_tester/test/dom_tester_test.php index <HASH>..<HASH> 100644 --- a/extensions/dom_tester/test/dom_tester_test.php +++ b/extensions/dom_tester/test/dom_tester_test.php @@ -12,7 +12,7 @@ class TestOfLiveCssSelectors extends DomTestCase public function testGet() { - $url = 'file://' . dirname(__FILE__) . '/support/dom_tester.html'; + $url = 'file://' . __DIR__ . '/support/dom_tester.html'; $this->assertTrue($this->get($url)); $this->assertElementsBySelector('h1', array('Test page')); $this->assertElementsBySelector('ul#list li a[href]', array('link')); @@ -23,9 +23,11 @@ class TestOfLiveCssSelectors extends DomTestCase class TestOfCssSelectors extends UnitTestCase { - public function __construct() + public $dom; + + public function setup() { - $html = file_get_contents(dirname(__FILE__) . '/support/dom_tester.html'); + $html = file_get_contents(__DIR__ . '/support/dom_tester.html'); $this->dom = new DomDocument('1.0', 'utf-8'); $this->dom->validateOnParse = true; $this->dom->loadHTML($html); @@ -136,7 +138,8 @@ class TestOfCssSelectors extends UnitTestCase $this->assertTrue($expectation->test(array('works great', 'test 2', 'test 4'))); } - public function testChildSelectors() + /* TODO - disabled, because tests fail (fix implementation or fix tests) -- jakoch + /*public function testChildSelectors() { $expectation = new CssSelectorExpectation($this->dom, '.myfoo:contains("bis")'); $this->assertTrue($expectation->test(array('myfoo bis'))); @@ -185,7 +188,7 @@ class TestOfCssSelectors extends UnitTestCase $expectation = new CssSelectorExpectation($this->dom, '#simplelist li:last-child'); $this->assertTrue($expectation->test(array('Second with a link', 'Third with another link'))); - } + }*/ } class TestsOfChildAndAdjacentSelectors extends DomTestCase diff --git a/web_tester.php b/web_tester.php index <HASH>..<HASH> 100644 --- a/web_tester.php +++ b/web_tester.php @@ -448,7 +448,7 @@ class NoTextExpectation extends TextExpectation */ class WebTestCase extends SimpleTestCase { - private $browser; + public $browser; private $ignore_errors = false; /**
change visibility of browser property, else it's not available in extension DomTester disable failing tests in dom_tester (child selectors)
simpletest_simpletest
train
2c0fb442e446abbbd784ebc6613361e520345ad5
diff --git a/bigtable-grpc-interface/src/main/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScanner.java b/bigtable-grpc-interface/src/main/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScanner.java index <HASH>..<HASH> 100644 --- a/bigtable-grpc-interface/src/main/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScanner.java +++ b/bigtable-grpc-interface/src/main/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScanner.java @@ -69,7 +69,8 @@ public class ResumingStreamingResultScanner extends AbstractBigtableResultScanne return result; } catch (IOExceptionWithStatus ioe) { Status status = ioe.getStatus(); - if (status.getCode() == Status.INTERNAL.getCode()) { + if (status.getCode() == Status.INTERNAL.getCode() + || status.getCode() == Status.UNAVAILABLE.getCode()) { long nextBackOff = currentBackoff.nextBackOffMillis(); if (nextBackOff == BackOff.STOP) { throw new BigtableRetriesExhaustedException( diff --git a/bigtable-grpc-interface/src/test/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScannerTest.java b/bigtable-grpc-interface/src/test/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScannerTest.java index <HASH>..<HASH> 100644 --- a/bigtable-grpc-interface/src/test/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScannerTest.java +++ b/bigtable-grpc-interface/src/test/java/com/google/cloud/hadoop/hbase/ResumingStreamingResultScannerTest.java @@ -14,8 +14,6 @@ import com.google.bigtable.v1.ReadRowsRequest; import com.google.bigtable.v1.Row; import com.google.protobuf.ByteString; -import io.grpc.Status; -import io.grpc.Status.OperationRuntimeException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,6 +21,9 @@ import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import io.grpc.Status; +import io.grpc.Status.OperationRuntimeException; + import java.io.IOException; @@ -71,6 +72,15 @@ public class ResumingStreamingResultScannerTest { @Test public void testInternalErrorsResume() throws IOException { + doErrorsResume(Status.INTERNAL); + } + + @Test + public void testUnavailableErrorsResume() throws IOException { + doErrorsResume(Status.UNAVAILABLE); + } + + private void doErrorsResume(Status status) throws IOException { Row row1 = buildRow("row1"); Row row2 = buildRow("row2"); Row row3 = buildRow("row3"); @@ -92,7 +102,7 @@ public class ResumingStreamingResultScannerTest { .thenReturn(row1) .thenReturn(row2) .thenThrow( - new IOExceptionWithStatus("Test", new OperationRuntimeException(Status.INTERNAL))) + new IOExceptionWithStatus("Test", new OperationRuntimeException(status))) .thenThrow( new IOException( "Next invoked on scanner post-exception. This is most "
Allow resume in scan read when the status is Unavailable.
googleapis_cloud-bigtable-client
train
459626fe12cfd715afa457440e86c321353d097c
diff --git a/safe/definitions.py b/safe/definitions.py index <HASH>..<HASH> 100644 --- a/safe/definitions.py +++ b/safe/definitions.py @@ -37,32 +37,45 @@ do_not_use_attribute = { 'name': tr('Don\'t use') } +# Concepts (used in various places, defined once to +# keep things DRY +concept_hazard = tr( + 'A <b>hazard</b> represents a natural process or phenomenon ' + 'that may cause loss of life, injury or other health impacts, ' + 'property damage, loss of livelihoods and services, social and ' + 'economic disruption, or environmental damage. For example; flood, ' + 'earthquake, tsunami and volcano are all examples of hazards.') + +concept_exposure = tr( + '<b>Exposure</b> represents people, property, systems, or ' + 'other elements present in hazard zones that are subject to ' + 'potential losses in the event of a flood, earthquake, volcano etc.') + +concept_generic_hazard = tr( + 'This is a ternary description for an area used with generic impact ' + 'functions. The area may have either <b>low</b>, <b>medium</b>, or ' + '<b>high</b> classification for the hazard.') + # Layer Purpose layer_purpose_hazard = { 'key': 'hazard', 'name': tr('Hazard'), - 'description': tr( - 'A <b>hazard</b> layer represents ' - 'something that will impact on the people, infrastructure or ' - 'land cover in an area. For example; flood, earthquake, tsunami and ' - 'volcano are all examples of hazards.') + 'description': concept_hazard } + layer_purpose_exposure = { 'key': 'exposure', 'name': tr('Exposure'), - 'description': tr( - 'An <b>exposure</b> layer represents ' - 'people, property, infrastructure or land cover that may be affected ' - 'in the event of a flood, earthquake, volcano etc.') + 'description': concept_exposure } layer_purpose_aggregation = { 'key': 'aggregation', 'name': tr('Aggregation'), 'description': tr( - 'An <b>aggregation</b> layer represents ' - 'regions that can be used to summarise impact analysis results. ' - 'For example, we might summarise the affected people after ' - 'a flood according to administration boundaries.') + 'An <b>aggregation</b> layer represents regions that can be used to ' + 'summarise impact analysis results. For example, we might summarise ' + 'the affected people after a flood according to administration ' + 'boundaries.') } layer_purpose = { @@ -330,12 +343,7 @@ hazard_all = [ hazards = { 'key': 'hazards', 'name': tr('Hazards'), - 'description': tr( - '<b>Hazards</b> (also called disasters) are what we call the data ' - 'layers that describe the extent and magnitude of natural events ' - '(such as earthquakes, tsunamis and volcanic eruptions) that could ' - 'potentially cause an event or series of events that threaten and ' - 'disrupt the lives and livelihoods of people.'), + 'description': concept_hazard , 'types': hazard_all } @@ -490,9 +498,7 @@ exposure_all = [ exposures = { 'key': 'exposures', 'name': tr('Exposure'), - 'description': tr( - '<b>Exposure</b> data represents things that are at risk when faced ' - 'with a potential hazard. '), + 'description': concept_exposure, 'types': exposure_all } @@ -624,10 +630,7 @@ continuous_hazard_unit_all = continuous_hazard_unit['types'] generic_vector_hazard_classes = { 'key': 'generic_vector_hazard_classes', 'name': tr('Generic classes'), - 'description': tr( - 'This is a ternary description for an area. The area may have either ' - '<b>low</b>, <b>medium</b>, or <b>high</b> classification for the ' - 'hazard.'), + 'description': concept_generic_hazard, 'default_attribute': 'affected', 'classes': [ { @@ -664,9 +667,8 @@ volcano_vector_hazard_classes = { 'key': 'volcano_vector_hazard_classes', 'name': tr('Volcano classes'), 'description': tr( - 'This is a ternary description for an area. The area has either a ' - '<b>low</b>, <b>medium</b>, or <b>high</b> classification for ' - 'volcano hazard.'), + 'Three classes are supported for volcano vector hazard data: ' + '<b>low</b>, <b>medium</b>, or <b>high</b>.'), 'default_attribute': 'affected', 'classes': [ { @@ -777,9 +779,7 @@ flood_raster_hazard_classes = { generic_raster_hazard_classes = { 'key': 'generic_raster_hazard_classes', 'name': tr('Generic classes'), - 'description': tr( - 'This is a ternary description for an area. The area is classified as ' - 'either a <b>low</b>, <b>medium</b>, or <b>high</b> hazard class.'), + 'description': concept_generic_hazard, 'classes': [ { 'key': 'high',
fix #<I> - remove duplication of hazard and exposure concepts in def… (#<I>) * fix #<I> - remove duplication of hazard and exposure concepts in definitions.py. Also did some other refactoring and cleaups in definitions.py. See also #<I> * Update hazard and exposure terms to use Libby's terms from #<I>
inasafe_inasafe
train
1831e82a3ab16f68df07ee4d27c02374238c1873
diff --git a/provider/nomock/provider.go b/provider/nomock/provider.go index <HASH>..<HASH> 100644 --- a/provider/nomock/provider.go +++ b/provider/nomock/provider.go @@ -8,14 +8,12 @@ import ( "syscall" "github.com/essentier/gopencils" - "github.com/essentier/nomockutil" "github.com/essentier/spickspan/config" "github.com/essentier/spickspan/model" ) const ( - noReleaseServiceID string = "noReleaseServiceID" - containerImagePrefix string = "gcr.io/divine-actor-126805/" // IP:5000/nomock/ + noReleaseServiceID string = "noReleaseServiceID" ) func CreateProvider(config config.Model) model.Provider { @@ -85,19 +83,16 @@ func (p *TestingProvider) GetService(serviceName string) (model.Service, error) func (p *TestingProvider) createService(serviceConfig config.Service) (model.Service, error) { newService := model.Service{} - userId, err := nomockutil.GetSubjectInToken(p.token) - if err != nil { - return newService, err - } + //userId, err := nomockutil.GetSubjectInToken(p.token) + // if err != nil { + // return newService, err + // } servicesResource := p.nomockApi.NewChildResource("nomockserver/services", &newService) - if serviceConfig.IsSourceProject() { - serviceConfig.ContainerImage = containerImagePrefix + userId + "_" + serviceConfig.ServiceName + ":latest" - } log.Printf("service config %v", serviceConfig) servicesResource.SetHeader("Authorization", "Bearer "+p.token) - _, err = servicesResource.Post(serviceConfig) + _, err := servicesResource.Post(serviceConfig) if err != nil { log.Printf("Failed to call the service rest api. Error is: %v. Error string is %v", err, err.Error()) }
move container image logic to nomock server
essentier_spickspan
train
713ecaae2af5f3f2c2e71eba53d6ce6995af641c
diff --git a/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/LDAPAuthenticationProvider.java b/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/LDAPAuthenticationProvider.java index <HASH>..<HASH> 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/LDAPAuthenticationProvider.java +++ b/extensions/guacamole-auth-ldap/src/main/java/net/sourceforge/guacamole/net/auth/ldap/LDAPAuthenticationProvider.java @@ -35,6 +35,7 @@ import java.util.TreeMap; import org.glyptodon.guacamole.GuacamoleException; import org.glyptodon.guacamole.net.auth.Credentials; import net.sourceforge.guacamole.net.auth.ldap.properties.LDAPGuacamoleProperties; +import org.glyptodon.guacamole.GuacamoleServerException; import org.glyptodon.guacamole.net.auth.simple.SimpleAuthenticationProvider; import org.glyptodon.guacamole.properties.GuacamoleProperties; import org.glyptodon.guacamole.protocol.GuacamoleConfiguration; @@ -126,42 +127,50 @@ public class LDAPAuthenticationProvider extends SimpleAuthenticationProvider { @Override public Map<String, GuacamoleConfiguration> getAuthorizedConfigurations(Credentials credentials) throws GuacamoleException { - try { + // Require username + if (credentials.getUsername() == null) { + logger.debug("Anonymous bind is not currently allowed by the LDAP authentication provider."); + return null; + } - // Require username - if (credentials.getUsername() == null) { - logger.info("Anonymous bind is not currently allowed by the LDAP authentication provider."); - return null; - } + // Require password, and do not allow anonymous binding + if (credentials.getPassword() == null + || credentials.getPassword().length() == 0) { + logger.debug("Anonymous bind is not currently allowed by the LDAP authentication provider."); + return null; + } - // Require password, and do not allow anonymous binding - if (credentials.getPassword() == null - || credentials.getPassword().length() == 0) { - logger.info("Anonymous bind is not currently allowed by the LDAP authentication provider."); - return null; - } + // Connect to LDAP server + LDAPConnection ldapConnection; + try { - // Connect to LDAP server - LDAPConnection ldapConnection = new LDAPConnection(); + ldapConnection = new LDAPConnection(); ldapConnection.connect( GuacamoleProperties.getRequiredProperty(LDAPGuacamoleProperties.LDAP_HOSTNAME), GuacamoleProperties.getRequiredProperty(LDAPGuacamoleProperties.LDAP_PORT) ); - // Get username attribute - String username_attribute = GuacamoleProperties.getRequiredProperty( - LDAPGuacamoleProperties.LDAP_USERNAME_ATTRIBUTE - ); + } + catch (LDAPException e) { + throw new GuacamoleServerException("Unable to connect to LDAP server.", e); + } - // Get user base DN - String user_base_dn = GuacamoleProperties.getRequiredProperty( - LDAPGuacamoleProperties.LDAP_USER_BASE_DN - ); + // Get username attribute + String username_attribute = GuacamoleProperties.getRequiredProperty( + LDAPGuacamoleProperties.LDAP_USERNAME_ATTRIBUTE + ); - // Construct user DN - String user_dn = - escapeDN(username_attribute) + "=" + escapeDN(credentials.getUsername()) - + "," + user_base_dn; + // Get user base DN + String user_base_dn = GuacamoleProperties.getRequiredProperty( + LDAPGuacamoleProperties.LDAP_USER_BASE_DN + ); + + // Construct user DN + String user_dn = + escapeDN(username_attribute) + "=" + escapeDN(credentials.getUsername()) + + "," + user_base_dn; + + try { // Bind as user try { @@ -175,10 +184,19 @@ public class LDAPAuthenticationProvider extends SimpleAuthenticationProvider { throw new GuacamoleException(e); } - // Get config base DN - String config_base_dn = GuacamoleProperties.getRequiredProperty( - LDAPGuacamoleProperties.LDAP_CONFIG_BASE_DN - ); + } + catch (LDAPException e) { + logger.debug("LDAP bind failed.", e); + return null; + } + + // Get config base DN + String config_base_dn = GuacamoleProperties.getRequiredProperty( + LDAPGuacamoleProperties.LDAP_CONFIG_BASE_DN + ); + + // Pull all connections + try { // Find all guac configs for this user LDAPSearchResults results = ldapConnection.search( @@ -248,7 +266,7 @@ public class LDAPAuthenticationProvider extends SimpleAuthenticationProvider { } catch (LDAPException e) { - throw new GuacamoleException(e); + throw new GuacamoleServerException("Error while querying for connections.", e); } }
GUAC-<I>: Handle errors during connect/bind/query distinctly. Only rethrow server error if connection or query fails - failure to bind is just an invalid login.
glyptodon_guacamole-client
train
44d2ad68c32caf6b7e82092d7e25e7eeb61b73eb
diff --git a/firebase.ios.js b/firebase.ios.js index <HASH>..<HASH> 100755 --- a/firebase.ios.js +++ b/firebase.ios.js @@ -257,13 +257,14 @@ firebase._registerForRemoteNotifications = function () { curNotCenter.delegate = firebase._userNotificationCenterDelegate; firebase._firebaseRemoteMessageDelegate = FIRMessagingDelegateImpl.new().initWithCallback(function (appDataDictionary) { - var asJs = firebase.toJsObject(appDataDictionary.objectForKey("notification")); - var userInfoJSON = firebase.toJsObject(appDataDictionary); firebase._pendingNotifications.push(userInfoJSON); - userInfoJSON.title = asJs.title; - userInfoJSON.body = asJs.body; + var asJs = firebase.toJsObject(appDataDictionary.objectForKey("notification")); + if(asJs) { + userInfoJSON.title = asJs.title; + userInfoJSON.body = asJs.body; + } var app = utils.ios.getter(UIApplication, UIApplication.sharedApplication); if (app.applicationState === UIApplicationState.UIApplicationStateActive) {
Fix app crash when notification structure is missing
EddyVerbruggen_nativescript-plugin-firebase
train
f8759cd87503bc7d50c441a85415b4d6283b04d2
diff --git a/core/lib/rom/auto_curry.rb b/core/lib/rom/auto_curry.rb index <HASH>..<HASH> 100644 --- a/core/lib/rom/auto_curry.rb +++ b/core/lib/rom/auto_curry.rb @@ -20,7 +20,7 @@ module ROM end def auto_curried_methods - @__auto_curried_methods__ ||= [] + @__auto_curried_methods__ ||= Set.new end def auto_curry(name, &block) diff --git a/core/lib/rom/relation/class_interface.rb b/core/lib/rom/relation/class_interface.rb index <HASH>..<HASH> 100644 --- a/core/lib/rom/relation/class_interface.rb +++ b/core/lib/rom/relation/class_interface.rb @@ -252,7 +252,7 @@ module ROM ancestor_methods = ancestors.reject { |klass| klass == self } .map(&:instance_methods).flatten(1) - instance_methods - ancestor_methods + auto_curried_methods + instance_methods - ancestor_methods + auto_curried_methods.to_a end # @api private diff --git a/core/spec/unit/rom/auto_curry_spec.rb b/core/spec/unit/rom/auto_curry_spec.rb index <HASH>..<HASH> 100644 --- a/core/spec/unit/rom/auto_curry_spec.rb +++ b/core/spec/unit/rom/auto_curry_spec.rb @@ -23,7 +23,7 @@ RSpec.describe ROM::AutoCurry do end def arity_2(x, y) - [x,y] + [x, y] end def arity_many(*args) @@ -34,6 +34,14 @@ RSpec.describe ROM::AutoCurry do yield(arg) end + def repeated(x) + end + + undef repeated + + def repeated(x) + end + protected def leave_me_alone(foo) @@ -43,7 +51,8 @@ RSpec.describe ROM::AutoCurry do end it 'registers auto-curried methods' do - expect(object.class.auto_curried_methods).to eql(%i[arity_1 arity_2 arity_many yielding_block]) + expect(object.class.auto_curried_methods). + to eql(%i[arity_1 arity_2 arity_many yielding_block repeated].to_set) end it 'auto-curries method with arity == 0' do
Filter out duplications in list of curried methods
rom-rb_rom
train
dd345a0f74d949d7686269a85dce12e635c48df9
diff --git a/src/Statistics/Descriptive.php b/src/Statistics/Descriptive.php index <HASH>..<HASH> 100644 --- a/src/Statistics/Descriptive.php +++ b/src/Statistics/Descriptive.php @@ -385,24 +385,28 @@ class Descriptive * * IQR = Q₃ - Q₁ * - * @param array $numbers + * @param array $numbers + * @param string $method What quartile method to use (optional - default: exclusive) + * * @return number */ - public static function interquartileRange(array $numbers) + public static function interquartileRange(array $numbers, string $method = 'exclusive') { - return self::quartiles($numbers)['IQR']; + return self::quartiles($numbers, $method)['IQR']; } /** * IQR - Interquartile range (midspread, middle fifty) * Convenience wrapper function for interquartileRange. * - * @param array $numbers + * @param array $numbers + * @param string $method What quartile method to use (optional - default: exclusive) + * * @return number */ - public static function IQR(array $numbers) + public static function IQR(array $numbers, string $method = 'exclusive') { - return self::quartiles($numbers)['IQR']; + return self::quartiles($numbers, $method)['IQR']; } /**
Add option to select quartile method when computing IQR.
markrogoyski_math-php
train
c0506f9f8dc35a83aee3b0b35cbf901f2eff912d
diff --git a/lib/pronto/flay.rb b/lib/pronto/flay.rb index <HASH>..<HASH> 100644 --- a/lib/pronto/flay.rb +++ b/lib/pronto/flay.rb @@ -10,14 +10,10 @@ module Pronto def run(patches) return [] unless patches - ruby_patches = patches.select do |patch| - path = patch.delta.new_file_full_path - patch.additions > 0 && ruby_file?(path) - end + ruby_patches = patches.select { |patch| patch.additions > 0 } + .select { |patch| ruby_file?(patch.new_file_full_path) } - files = ruby_patches.map do |patch| - File.new(patch.delta.new_file_full_path) - end + files = ruby_patches.map { |patch| File.new(patch.new_file_full_path) } if files.any? @flay.process(*files) @@ -49,12 +45,8 @@ module Pronto end def patch_for_node(ruby_patches, node) - repo = ruby_patches.first.delta.repo - repo_path = Pathname.new(repo.path).parent - path = Pathname.new(node.file.path).relative_path_from(repo_path) - ruby_patches.select do |patch| - patch.delta.new_file[:path] == path.to_s + patch.new_file_full_path.to_s == node.file.path end.first end end
Slightly refactor runner
prontolabs_pronto-flay
train
5d46ff41d85a825d508d8c9ec32b90a27de18350
diff --git a/staging/src/k8s.io/apiserver/pkg/audit/policy/reader.go b/staging/src/k8s.io/apiserver/pkg/audit/policy/reader.go index <HASH>..<HASH> 100644 --- a/staging/src/k8s.io/apiserver/pkg/audit/policy/reader.go +++ b/staging/src/k8s.io/apiserver/pkg/audit/policy/reader.go @@ -55,17 +55,26 @@ func LoadPolicyFromFile(filePath string) (*auditinternal.Policy, error) { return nil, fmt.Errorf("failed to read file path %q: %+v", filePath, err) } + ret, err := LoadPolicyFromBytes(policyDef) + if err != nil { + return nil, fmt.Errorf("%v: from file %v", err.Error(), filePath) + } + + return ret, nil +} + +func LoadPolicyFromBytes(policyDef []byte) (*auditinternal.Policy, error) { policy := &auditinternal.Policy{} decoder := audit.Codecs.UniversalDecoder(apiGroupVersions...) _, gvk, err := decoder.Decode(policyDef, nil, policy) if err != nil { - return nil, fmt.Errorf("failed decoding file %q: %v", filePath, err) + return nil, fmt.Errorf("failed decoding: %v", err) } // Ensure the policy file contained an apiVersion and kind. if !apiGroupVersionSet[schema.GroupVersion{Group: gvk.Group, Version: gvk.Version}] { - return nil, fmt.Errorf("unknown group version field %v in policy file %s", gvk, filePath) + return nil, fmt.Errorf("unknown group version field %v in policy", gvk) } if err := validation.ValidatePolicy(policy); err != nil { @@ -74,8 +83,8 @@ func LoadPolicyFromFile(filePath string) (*auditinternal.Policy, error) { policyCnt := len(policy.Rules) if policyCnt == 0 { - return nil, fmt.Errorf("loaded illegal policy with 0 rules from file %s", filePath) + return nil, fmt.Errorf("loaded illegal policy with 0 rules") } - glog.V(4).Infof("Loaded %d audit policy rules from file %s", policyCnt, filePath) + glog.V(4).Infof("Loaded %d audit policy rules", policyCnt) return policy, nil }
allow audit policy to be loaded from any byte source
kubernetes_kubernetes
train
0a4b3ffdddb8b1a232488b8cea1de38a4ff8b90b
diff --git a/example/world.js b/example/world.js index <HASH>..<HASH> 100644 --- a/example/world.js +++ b/example/world.js @@ -62,8 +62,8 @@ game.on('tick', sky); // create a share thing var share = require('../')({ game: game, - // api key from imgur.com - key: '1e6b6f6b09df169bcdcbd86a52e869c5' + // api v3 key from imgur.com + key: '' }); // if ctrl is pressed diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -2,12 +2,13 @@ function Share(opts) { if (!(this instanceof Share)) return new Share(opts || {}); if (opts.THREE) opts = {game:opts}; if (!opts.key) throw new Error('Get a key: http://api.imgur.com/'); - this.key = opts.key; - this.game = opts.game; - this.message = opts.message || 'Greetings from voxel.js! @voxeljs'; - this.type = opts.type || 'image/png'; - this.quality = opts.quality || 0.75; - this.opened = false; + this.key = opts.key; + this.game = opts.game; + this.hashtags = opts.hashtags || ''; + this.message = opts.message || 'Greetings from voxel.js! @voxeljs'; + this.type = opts.type || 'image/png'; + this.quality = opts.quality || 0.75; + this.opened = false; } module.exports = Share; @@ -31,20 +32,21 @@ Share.prototype.submit = function() { var self = this; var fd = new FormData(); fd.append('image', String(this.image.src).split(',')[1]); - fd.append('key', this.key); - if (this.message) fd.append('caption', this.message); + if (this.message) fd.append('description', this.message); var xhr = new XMLHttpRequest(); - xhr.open('POST', 'http://api.imgur.com/2/upload.json'); + xhr.open('POST', 'https://api.imgur.com/3/upload'); + var auth = 'Client-ID ' + this.key + xhr.setRequestHeader('Authorization', auth); xhr.onload = function() { // todo: error check - self.tweet(JSON.parse(xhr.responseText).upload.links.imgur_page); + self.tweet(JSON.parse(xhr.responseText).data.link); self.close(); }; xhr.send(fd); }; Share.prototype.tweet = function(imgUrl) { - var url = 'http://twitter.com/home?status=' + this.message + ' ' + imgUrl; + var url = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(this.message) + ' ' + imgUrl + '&hashtags=' + this.hashtags window.open(url, 'twitter', 'width=550,height=450'); };
imgur v3 compat and twitter hashtag support
shama_voxel-share
train
2a88f90c719bdb79f0c6f8c2f30c52ae7dde9dec
diff --git a/salt/fileclient.py b/salt/fileclient.py index <HASH>..<HASH> 100644 --- a/salt/fileclient.py +++ b/salt/fileclient.py @@ -593,35 +593,38 @@ class Client(object): get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url + + destfp = None try: + if no_cache: + result = [] + + def on_chunk(chunk): + result.append(chunk) + else: + dest_tmp = "{0}.part".format(dest) + destfp = salt.utils.fopen(dest_tmp, 'wb') + + def on_chunk(chunk): + destfp.write(chunk) + query = salt.utils.http.query( fixed_url, stream=True, + streaming_callback=on_chunk, username=url_data.username, password=url_data.password, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0}'.format(query['error'])) - response = query['handle'] - chunk_size = 32 * 1024 - if not no_cache: - with salt.utils.fopen(dest, 'wb') as destfp: - if hasattr(response, 'iter_content'): - for chunk in response.iter_content(chunk_size=chunk_size): - destfp.write(chunk) - else: - while True: - chunk = response.buffer.read(chunk_size) - destfp.write(chunk) - if len(chunk) < chunk_size: - break - return dest + if no_cache: + return ''.join(result) else: - if hasattr(response, 'text'): - return response.text - else: - return response['text'] + destfp.close() + destfp = None + os.rename(dest_tmp, dest) + return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, @@ -629,6 +632,9 @@ class Client(object): *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) + finally: + if destfp is not None: + destfp.close() def get_template( self, diff --git a/salt/utils/http.py b/salt/utils/http.py index <HASH>..<HASH> 100644 --- a/salt/utils/http.py +++ b/salt/utils/http.py @@ -118,6 +118,7 @@ def query(url, headers_out=None, decode_out=None, stream=False, + streaming_callback=None, handle=False, agent=USERAGENT, hide_fields=None, @@ -403,7 +404,7 @@ def query(url, data = urllib.urlencode(data) try: - result = HTTPClient().fetch( + result = HTTPClient(max_body_size=100*1024*1024*1024).fetch( url_full, method=method, headers=header_dict, @@ -412,6 +413,8 @@ def query(url, body=data, validate_cert=verify_ssl, allow_nonstandard_methods=True, + streaming_callback=streaming_callback, + request_timeout=3600.0, **req_kwargs ) except tornado.httpclient.HTTPError as exc:
Fix for Tornado HTTPClient file size and timeout limits issues.
saltstack_salt
train
74e3d56ba22db2790e98afb3c5de41b585fe5f7c
diff --git a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java index <HASH>..<HASH> 100644 --- a/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java +++ b/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java @@ -324,21 +324,19 @@ public class EnhancedDebugger extends SmackDebugger { menu.add(menuItem1); // Add listener to the text area so the popup menu can come up. messageTextArea.addMouseListener(new PopupListener(menu)); - // CHECKSTYLE:OFF - JPanel sublayout = new JPanel(new BorderLayout()); + JPanel sublayout = new JPanel(new BorderLayout()); sublayout.add(new JScrollPane(messageTextArea), BorderLayout.CENTER); JButton clearb = new JButton("Clear All Packets"); - clearb.addActionListener(new AbstractAction() { - private static final long serialVersionUID = -8576045822764763613L; + clearb.addActionListener(new AbstractAction() { + private static final long serialVersionUID = -8576045822764763613L; - @Override - public void actionPerformed(ActionEvent e) { - messagesTable.setRowCount(0); - } - }); - // CHECKSTYLE:ON + @Override + public void actionPerformed(ActionEvent e) { + messagesTable.setRowCount(0); + } + }); sublayout.add(clearb, BorderLayout.NORTH); allPane.setBottomComponent(sublayout);
Fix style issues in EnhancedDebugger
igniterealtime_Smack
train
5f17b05d77b0532fdba3208cadac5928235039c8
diff --git a/alot/command.py b/alot/command.py index <HASH>..<HASH> 100644 --- a/alot/command.py +++ b/alot/command.py @@ -702,7 +702,9 @@ class EnvelopeSendCommand(Command): sname, saddr = email.Utils.parseaddr(frm) account = ui.accountman.get_account_by_address(saddr) if account: + clearme = ui.notify('sending..', timeout=-1, block=False) success, reason = account.sender.send_mail(mail) + ui.clear_notify([clearme]) if success: cmd = BufferCloseCommand(buffer=envelope) ui.apply_command(cmd) diff --git a/alot/ui.py b/alot/ui.py index <HASH>..<HASH> 100644 --- a/alot/ui.py +++ b/alot/ui.py @@ -163,13 +163,23 @@ class UI: def get_buffers_of_type(self, t): return filter(lambda x: isinstance(x, t), self.buffers) - def notify(self, message, priority='normal', timeout=0): + def clear_notify(self, messages): + footer = self.mainframe.get_footer() + newpile = self.notificationbar.widget_list + for l in messages: + newpile.remove(l) + if newpile: + self.notificationbar = urwid.Pile(newpile) + else: + self.notificationbar = None + self.update() + def notify(self, message, priority='normal', timeout=0, block=True): def build_line(msg, prio): cols =urwid.Columns([urwid.Text(msg)]) return urwid.AttrMap(cols, 'notify_' + prio) msgs = [build_line(message, priority)] - if timeout == -1: + if timeout == -1 and block: msgs.append(build_line('(hit any key to proceed)', 'normal')) footer = self.mainframe.get_footer() @@ -180,25 +190,19 @@ class UI: self.notificationbar = urwid.Pile(newpile) self.update() - def clear_notify(*args): - footer = self.mainframe.get_footer() - newpile = self.notificationbar.widget_list - for l in msgs : - newpile.remove(l) - if newpile: - self.notificationbar = urwid.Pile(newpile) - else: - self.notificationbar = None - self.update() + def clear(*args): + self.clear_notify(msgs) if timeout == -1: self.mainloop.draw_screen() - keys = self.mainloop.screen.get_input() - clear_notify() + if block: + keys = self.mainloop.screen.get_input() + clear() else: if timeout == 0: timeout = config.getint('general', 'notify_timeout') - self.mainloop.set_alarm_in(timeout, clear_notify) + self.mainloop.set_alarm_in(timeout, clear) + return msgs[0] def update(self): """
"sending.." notification that gets cleared issue #<I>
pazz_alot
train
0e97d97d50708ff9c8cfac9d7e33534eb37a8f08
diff --git a/python-package/xgboost/core.py b/python-package/xgboost/core.py index <HASH>..<HASH> 100644 --- a/python-package/xgboost/core.py +++ b/python-package/xgboost/core.py @@ -5,9 +5,8 @@ import collections # pylint: disable=no-name-in-module,import-error from collections.abc import Mapping -from typing import List, Optional, Any, Union +from typing import List, Optional, Any, Union, Dict # pylint: enable=no-name-in-module,import-error -from typing import Dict, Union, List import ctypes import os import re
Fix merge conflict. (#<I>)
dmlc_xgboost
train
8216fbacb70152c75104a78f33405eb1ca4da929
diff --git a/dev/com.ibm.ws.jaxrs.2.0.client/src/com/ibm/ws/jaxrs20/client/JAXRSClientImpl.java b/dev/com.ibm.ws.jaxrs.2.0.client/src/com/ibm/ws/jaxrs20/client/JAXRSClientImpl.java index <HASH>..<HASH> 100644 --- a/dev/com.ibm.ws.jaxrs.2.0.client/src/com/ibm/ws/jaxrs20/client/JAXRSClientImpl.java +++ b/dev/com.ibm.ws.jaxrs.2.0.client/src/com/ibm/ws/jaxrs20/client/JAXRSClientImpl.java @@ -93,7 +93,7 @@ public class JAXRSClientImpl extends ClientImpl { } try { - BundleContext bc = AccessController.doPrivileged(new PrivilegedExceptionAction<BundleContext>() { + final BundleContext bc = AccessController.doPrivileged(new PrivilegedExceptionAction<BundleContext>() { @Override public BundleContext run() throws Exception { @@ -107,21 +107,29 @@ public class JAXRSClientImpl extends ClientImpl { // we don't send feature list for client APIs final Set<String> features = Collections.emptySet(); - Collection<ServiceReference<JaxRsProviderRegister>> refs = bc.getServiceReferences(JaxRsProviderRegister.class, null); - - for (ServiceReference<JaxRsProviderRegister> ref : refs) { - JaxRsProviderRegister providerRegister = bc.getService(ref); - try { - providerRegister.installProvider(true, providers, features); - } catch (Throwable t) { - if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { - String providerRegisterBundleLoc = ref.getBundle() == null ? "unknown" : ref.getBundle().getSymbolicName() + " " + ref.getBundle().getVersion(); - Tr.debug(tc, "<init> failed to install providers from " + providerRegister.getClass().getName() + - " loaded from " + providerRegisterBundleLoc, - t); + AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() { + + @Override + public Void run() throws Exception { + Collection<ServiceReference<JaxRsProviderRegister>> refs = bc.getServiceReferences(JaxRsProviderRegister.class, null); + + for (ServiceReference<JaxRsProviderRegister> ref : refs) { + JaxRsProviderRegister providerRegister = bc.getService(ref); + try { + providerRegister.installProvider(true, providers, features); + } catch (Throwable t) { + if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { + String providerRegisterBundleLoc = ref.getBundle() == null ? "unknown" : ref.getBundle().getSymbolicName() + " " + ref.getBundle().getVersion(); + Tr.debug(tc, "<init> failed to install providers from " + providerRegister.getClass().getName() + + " loaded from " + providerRegisterBundleLoc, + t); + } + } } + return null; } - } + }); + // now that we have a list of providers, register them for (Object provider : providers) { if (provider != null) {
Surround calls to getServiceReferences() and getService() in doPriv
OpenLiberty_open-liberty
train
05fcd8c77fca3ec08705ec141a6d823d7f905e05
diff --git a/lib/Doctrine/DBAL/Connection.php b/lib/Doctrine/DBAL/Connection.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/DBAL/Connection.php +++ b/lib/Doctrine/DBAL/Connection.php @@ -1034,9 +1034,9 @@ class Connection implements DriverConnection * * This method supports PDO binding types as well as DBAL mapping types. * - * @param string $query The SQL query. - * @param mixed[] $params The query parameters. - * @param int[]|string[] $types The parameter types. + * @param string $query The SQL query. + * @param array<mixed> $params The query parameters. + * @param array<int|string|null> $types The parameter types. * * @return int The number of affected rows. * diff --git a/lib/Doctrine/DBAL/Logging/SQLLogger.php b/lib/Doctrine/DBAL/Logging/SQLLogger.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/DBAL/Logging/SQLLogger.php +++ b/lib/Doctrine/DBAL/Logging/SQLLogger.php @@ -10,9 +10,9 @@ interface SQLLogger /** * Logs a SQL statement somewhere. * - * @param string $sql The SQL to be executed. - * @param mixed[]|null $params The SQL parameters. - * @param int[]|string[]|null $types The SQL parameter types. + * @param string $sql The SQL to be executed. + * @param mixed[]|null $params The SQL parameters. + * @param array<int|string|null> $types The SQL parameter types. * * @return void */ diff --git a/lib/Doctrine/DBAL/SQLParserUtils.php b/lib/Doctrine/DBAL/SQLParserUtils.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/DBAL/SQLParserUtils.php +++ b/lib/Doctrine/DBAL/SQLParserUtils.php @@ -118,9 +118,9 @@ class SQLParserUtils /** * For a positional query this method can rewrite the sql statement with regard to array parameters. * - * @param string $query The SQL query to execute. - * @param mixed[] $params The parameters to bind to the query. - * @param int[]|string[] $types The types the previous parameters are in. + * @param string $query The SQL query to execute. + * @param mixed[] $params The parameters to bind to the query. + * @param array<string|int|null> $types The types the previous parameters are in. * * @return mixed[] *
Document null as a possible type
doctrine_dbal
train
290d0e874a0adf8e4ab37a0a28da207895c47ce2
diff --git a/src/middlewares/parsing/blob.js b/src/middlewares/parsing/blob.js index <HASH>..<HASH> 100644 --- a/src/middlewares/parsing/blob.js +++ b/src/middlewares/parsing/blob.js @@ -34,6 +34,9 @@ module.exports = function () { next(); }; + + // next will be called on load + return; } } // if content type says this is an image, then we should transform the blob into an Image object @@ -53,10 +56,12 @@ module.exports = function () { next(); }; + + // next will be called on load. + return; } } - else { - next(); - } + + next(); }; };
fix #<I>; always call next()
englercj_resource-loader
train
a8189cd6207632252c8f0e8a15c6c0a4f0586267
diff --git a/lib/cli.js b/lib/cli.js index <HASH>..<HASH> 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -33,6 +33,9 @@ var fs = require('fs-extra'), if (!fs.existsSync(file)) { return 'Could not find the file:' + file; } + }, + transform: function(file) { + return fileHelper.getFileAsArray(file); } }, sites: { @@ -42,6 +45,9 @@ var fs = require('fs-extra'), if (!fs.existsSync(file)) { return 'Couldn\'t find the file:' + file; } + }, + transform: function(file) { + return fileHelper.getFileAsArray(file); } }, version: { @@ -178,6 +184,9 @@ var fs = require('fs-extra'), if (!fs.existsSync(file)) { return 'Couldn\'t find the BrowserTime JSON file:' + fs.realpathSync(file); } + }, + transform: function(file) { + return fileHelper.getFileAsJSON(file); } }, profile: { @@ -227,6 +236,9 @@ var fs = require('fs-extra'), if (!fs.existsSync(file)) { return 'Couldn\'t find the budget JSON file:' + fs.realpathSync(file); } + }, + transform: function(file) { + return fileHelper.getFileAsJSON(file); } }, maxPagesToTest: { @@ -314,6 +326,9 @@ var fs = require('fs-extra'), if (!fs.existsSync(file)) { return 'Couldn\'t find the WPT JSON configuration file:' + fs.realpathSync(file); } + }, + transform: function(file) { + return fileHelper.getFileAsJSON(file); } }, wptUrl: { @@ -331,6 +346,9 @@ var fs = require('fs-extra'), if (!fs.existsSync(file)) { return 'Couldn\'t find the request headers JSON file:' + fs.realpathSync(file); } + }, + transform: function(file) { + return fileHelper.getFileAsJSON(file); } } }).parse(); @@ -341,29 +359,4 @@ if ((!cli.url) && (!cli.file) && (!cli.sites)) { process.exit(1); } -// read configuration files -if (cli.requestHeaders) { - cli.requestHeaders = fileHelper.getFileAsJSON(cli.requestHeaders); -} - -if (cli.wptConfig) { - cli.wptConfig = fileHelper.getFileAsJSON(cli.wptConfig); -} - -if (cli.budget) { - cli.budget = fileHelper.getFileAsJSON(cli.budget); -} - -if (cli.btConfig) { - cli.btConfig = fileHelper.getFileAsJSON(cli.btConfig); -} - -if (cli.file) { - cli.urls = fileHelper.getFileAsArray(cli.file); -} - -if (cli.sites) { - cli.sites = fileHelper.getFileAsArray(cli.sites); -} - module.exports = cli;
Simplify parsing of cli file parameters.
sitespeedio_sitespeed.io
train
6a7c56c96fda45494fed324d0f4de2c985c1b1c4
diff --git a/spf/parser_test.go b/spf/parser_test.go index <HASH>..<HASH> 100644 --- a/spf/parser_test.go +++ b/spf/parser_test.go @@ -593,6 +593,9 @@ func TestHandleRedirect(t *testing.T) { ParseTestCase{"v=spf1 -ip4:127.0.0.1 redirect=nospf.matching.net", net.IP{127, 0, 0, 1}, Fail}, ParseTestCase{"v=spf1 +include:_spf.matching.net redirect=_spf.matching.net", net.IP{127, 0, 0, 1}, Fail}, ParseTestCase{"v=spf1 ~include:_spf.matching.net redirect=_spf.matching.net", net.IP{172, 100, 100, 1}, Softfail}, + // Ensure recursive redirects work + ParseTestCase{"v=spf1 redirect=redirect.matching.com", net.IP{172, 18, 0, 2}, Pass}, + ParseTestCase{"v=spf1 redirect=redirect.matching.com", net.IP{127, 0, 0, 1}, Fail}, } for _, testcase := range ParseTestCases {
Add redirect tests. Ensure that recursive call with SPF term set to 'redirect' works as expected - calls another recursive query. There are two tests matching (positive) and not matching (negative).
zaccone_spf
train
7ba54a06874a307b1e706f3389ae00c8c7dd7c60
diff --git a/commands/helpers.rb b/commands/helpers.rb index <HASH>..<HASH> 100644 --- a/commands/helpers.rb +++ b/commands/helpers.rb @@ -94,6 +94,7 @@ end helper :print_commits do |cherries, commits, options| ignores = ignore_sha_array our_commits = cherries.map { |item| c = commits.assoc(item[1]); [item, c] if c } + our_commits.delete_if { |item| item == nil } case options[:sort] when 'branch'
Remove nil objects before we try to sort.
defunkt_github-gem
train
95042bdae67c0395844b918ec5a6a5f89ffd4a65
diff --git a/syntax/parser.go b/syntax/parser.go index <HASH>..<HASH> 100644 --- a/syntax/parser.go +++ b/syntax/parser.go @@ -1646,19 +1646,18 @@ func (p *Parser) caseClause() *CaseClause { cc := &CaseClause{Case: p.pos} p.next() cc.Word = p.followWord("case", cc.Case) + end := "esac" if p.gotRsrv("{") { if p.lang != LangMirBSDKorn { p.posErr(cc.Pos(), `"case i {" is a mksh feature`) } - cc.Items = p.caseItems("}") - cc.Last, p.accComs = p.accComs, nil - cc.Esac = p.stmtEnd(cc, "case", "}") + end = "}" } else { p.followRsrv(cc.Case, "case x", "in") - cc.Items = p.caseItems("esac") - cc.Last, p.accComs = p.accComs, nil - cc.Esac = p.stmtEnd(cc, "case", "esac") } + cc.Items = p.caseItems(end) + cc.Last, p.accComs = p.accComs, nil + cc.Esac = p.stmtEnd(cc, "case", end) return cc }
syntax: dedup posix and mksh case clause code
mvdan_sh
train
739b2b01c22c7291c7419cbcde5993b3fc13b389
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -43,10 +43,10 @@ setup( 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', ], packages = [ 'pex',
Update supported python classifiers.
pantsbuild_pex
train
508a19f1471cf4d826c6ea6a286d42ed4b86d559
diff --git a/src/atoms/Icon/constants.js b/src/atoms/Icon/constants.js index <HASH>..<HASH> 100644 --- a/src/atoms/Icon/constants.js +++ b/src/atoms/Icon/constants.js @@ -37,6 +37,7 @@ module.exports = { 'chevronLeft', 'chevronRight', 'chevronUp', + 'circlePlus', 'clock', 'close', 'closeAccent',
Add circlePlus icon to icon constants
policygenius_athenaeum
train
1efe220e3d065068d9bb83decffdcce1916001d2
diff --git a/moneywagon/core.py b/moneywagon/core.py index <HASH>..<HASH> 100644 --- a/moneywagon/core.py +++ b/moneywagon/core.py @@ -175,13 +175,16 @@ class Service(object): time - datetime, when this transaction was confirmed. block_hash - string, the id of the block this tx is confirmed in. - block_number - integer, which block numbe this tx is confirmed in. + block_number - integer, which block number this tx is confirmed in. hex - the entire tx encoded in hex format - inputs - list of {address:, amount:}, amount is in satoshi - outputs - list of {address:, amount:, scriptPubKey:}, amount is in satoshi, scriptPubKey is hex + size - size of TX in bytes. + inputs - list of {address:, amount:}, amount is in satoshis + outputs - list of {address:, amount:, scriptPubKey:}, amount is in satoshis, scriptPubKey is hex txid - total_out - confirmations + total_out - (in satoshis) + total_ins - (in satoshis) + confirmations - number of confirmations this TX curently has + fee - total amount of fees this TX leaves for miners (in satoshis) """ raise NotImplementedError( diff --git a/moneywagon/crypto_data.py b/moneywagon/crypto_data.py index <HASH>..<HASH> 100644 --- a/moneywagon/crypto_data.py +++ b/moneywagon/crypto_data.py @@ -29,7 +29,7 @@ crypto_data = { BitpayInsight, Blockonomics, NeoCrypto ], 'single_transaction': [ - BitpayInsight, Blockr, BlockChainInfo, Blockonomics, NeoCrypto + BitpayInsight, Blockr, BitGo, BlockChainInfo, Blockonomics, NeoCrypto ], 'push_tx': [ BlockChainInfo, BlockExplorerCom, Blockr, ChainSo, CoinPrism, diff --git a/moneywagon/services.py b/moneywagon/services.py index <HASH>..<HASH> 100644 --- a/moneywagon/services.py +++ b/moneywagon/services.py @@ -745,7 +745,13 @@ class BlockChainInfo(Service): self.domain, txid ) tx = self.get_url(url).json() - outs = [{'address': x['addr'], 'amount': x['value']} for x in tx['out']] + outs = [ + { + 'address': x['addr'], + 'amount': x['value'], + 'scriptPubKey': x['script'] + } for x in tx['out'] + ] ins = [] for in_ in tx['inputs']: @@ -1294,7 +1300,9 @@ class BitGo(Service): total_in=sum(x['amount'] for x in ins), total_out=sum(x['amount'] for x in outs), txid=txid, - hex=r['hex'] + hex=r['hex'], + block_number=r['height'], + block_hash=r['blockhash'] ) def get_block(self, crypto, block_number='', block_hash='', latest=False):
added scriptPubKey to blockchain.info single tx
priestc_moneywagon
train
1d0ba7ef6461ccdd25af74bfed61d3ceb5bc926d
diff --git a/github/Requester.py b/github/Requester.py index <HASH>..<HASH> 100644 --- a/github/Requester.py +++ b/github/Requester.py @@ -177,13 +177,13 @@ class Requester: return responseHeaders, output def __createException(self, status, output): - if status == 401 and output["message"] == "Bad credentials": + if status == 401 and output.get("message") == "Bad credentials": cls = GithubException.BadCredentialsException - elif status == 403 and output["message"].startswith("Missing or invalid User Agent string"): + elif status == 403 and output.get("message").startswith("Missing or invalid User Agent string"): cls = GithubException.BadUserAgentException - elif status == 403 and output["message"].startswith("API Rate Limit Exceeded"): + elif status == 403 and output.get("message").startswith("API Rate Limit Exceeded"): cls = GithubException.RateLimitExceededException - elif status == 404 and output["message"] == "Not Found": + elif status == 404 and output.get("message") == "Not Found": cls = GithubException.UnknownObjectException else: cls = GithubException.GithubException
Don't assume there is a 'message' field in case of error
PyGithub_PyGithub
train
19caad2301e5cccb53627b1ba550c1530dd085b1
diff --git a/core/commands/urlstore.go b/core/commands/urlstore.go index <HASH>..<HASH> 100644 --- a/core/commands/urlstore.go +++ b/core/commands/urlstore.go @@ -8,6 +8,7 @@ import ( filestore "github.com/ipfs/go-ipfs/filestore" balanced "github.com/ipfs/go-ipfs/importer/balanced" ihelper "github.com/ipfs/go-ipfs/importer/helpers" + trickle "github.com/ipfs/go-ipfs/importer/trickle" cmds "gx/ipfs/QmNueRyPRQiV7PUEpnP4GgGLuK1rKQLaRW7sfPvUetYig1/go-ipfs-cmds" mh "gx/ipfs/QmPnFwZ2JXKnXgMw8CdBPxn7FWh6LLdjUjxV1fKHuJnkr8/go-multihash" @@ -42,6 +43,9 @@ found. It may disappear or the semantics can change at any time. `, }, + Options: []cmdkit.Option{ + cmdkit.BoolOption(trickleOptionName, "t", "Use trickle-dag format for dag generation."), + }, Arguments: []cmdkit.Argument{ cmdkit.StringArg("url", true, false, "URL to add to IPFS"), }, @@ -71,6 +75,8 @@ time. return } + useTrickledag, _ := req.Options[trickleOptionName].(bool) + hreq, err := http.NewRequest("GET", url, nil) if err != nil { res.SetError(err, cmdkit.ErrNormal) @@ -98,14 +104,18 @@ time. URL: url, } - blc, err := balanced.Layout(dbp.New(chk)) + layout := balanced.Layout + if useTrickledag { + layout = trickle.Layout + } + root, err := layout(dbp.New(chk)) if err != nil { res.SetError(err, cmdkit.ErrNormal) return } cmds.EmitOnce(res, BlockStat{ - Key: blc.Cid().String(), + Key: root.Cid().String(), Size: int(hres.ContentLength), }) },
add trickle-dag support to the urlstore fixes #<I> License: MIT
ipfs_go-ipfs
train
899385a72f5cadda8853afb56934bdfa5087139e
diff --git a/lib/rbvmomi/vim/Folder.rb b/lib/rbvmomi/vim/Folder.rb index <HASH>..<HASH> 100644 --- a/lib/rbvmomi/vim/Folder.rb +++ b/lib/rbvmomi/vim/Folder.rb @@ -41,19 +41,23 @@ class RbVmomi::VIM::Folder x if x.is_a? type end - # Retrieve a virtual machine or host by BIOS UUID. - # @param uuid [String] The UUID to find. - # @param type [Class] Return nil unless the found entity <tt>is_a? type</tt>. - # @param dc [RbVmomi::VIM::Datacenter] Restricts the query to entities in the given Datacenter. + # Finds a virtual machine or host by BIOS or instance UUID + # + # @param uuid [String] UUID to find + # @param type [Class] return nil unless found entity <tt>is_a?(type)</tt> + # @param dc [RbVmomi::VIM::Datacenter] restricts query to specified datacenter + # # @return [VIM::ManagedEntity] - def findByUuid uuid, type=RbVmomi::VIM::VirtualMachine, dc=nil - propSpecs = { - :entity => self, :uuid => uuid, :instanceUuid => false, - :vmSearch => type == RbVmomi::VIM::VirtualMachine + def findByUuid(uuid, type = RbVmomi::VIM::VirtualMachine, dc = nil, instance_uuid = false) + prop_specs = { + entity: self, + instanceUuid: instance_uuid, + uuid: uuid, + vmSearch: type == RbVmomi::VIM::VirtualMachine } - propSpecs[:datacenter] = dc if dc - x = _connection.searchIndex.FindByUuid(propSpecs) - x if x.is_a? type + prop_specs[:datacenter] = dc if dc + x = _connection.searchIndex.FindByUuid(prop_specs) + x if x.is_a?(type) end # Retrieve a managed entity by inventory path.
Add search for VM or host by instance UUID Update `findByUuid` to accept an optional parameter to search for instance UUID. It was added as an optional parameter to maintain backward compatability. Closes #<I>
vmware_rbvmomi
train
5262db00a868f3c76ad49bf3e76ee03756829f8c
diff --git a/packages/vx-geo/src/projections/Projection.js b/packages/vx-geo/src/projections/Projection.js index <HASH>..<HASH> 100644 --- a/packages/vx-geo/src/projections/Projection.js +++ b/packages/vx-geo/src/projections/Projection.js @@ -79,7 +79,7 @@ export default function Projection({ <path className={cx(`vx-geo-${projection}`, className)} d={path(feature)} - ref={ref => innerRef && innerRef(ref, feature, i)} + ref={innerRef && innerRef(feature, i)} {...additionalProps(restProps, { ...feature, index: i,
Make innerRef same as other props
hshoff_vx
train
7a19d96a756f99894ca580d905b195798352e489
diff --git a/pqhelper/base.py b/pqhelper/base.py index <HASH>..<HASH> 100644 --- a/pqhelper/base.py +++ b/pqhelper/base.py @@ -58,8 +58,8 @@ class StateInvestigator(object): _game_finders = {'capture': v.TemplateFinder(_data.capture_template, sizes=_GAME_SIZES, scale_for_speed=0.5, - immediate_threshold=0.05, - acceptable_threshold=0.1), + immediate_threshold=0.1, + acceptable_threshold=0.3), 'versus': v.TemplateFinder(_data.versus_template, sizes=_GAME_SIZES, scale_for_speed=0.5,
Again adjusted discovery thresholds. Better to have false positives than totally miss a game that is actually there.
kobejohn_PQHelper
train
986522eaeb73cd1ae75ce9fb61d083561aba56be
diff --git a/src/emir/recipes/engineering/detectorgain.py b/src/emir/recipes/engineering/detectorgain.py index <HASH>..<HASH> 100644 --- a/src/emir/recipes/engineering/detectorgain.py +++ b/src/emir/recipes/engineering/detectorgain.py @@ -26,7 +26,8 @@ import scipy.stats import pyfits import numina.qa -from numina.recipes import RecipeBase, provides, Parameter +from numina.recipes import RecipeBase, provides, Parameter, DataFrame +from numina.exceptions import RecipeError #from emir.dataproducts import create_result from emir.instrument.detector import CHANNELS, QUADRANTS @@ -75,8 +76,10 @@ class GainRecipe1(RecipeBase): for frame in obresult.frames: if frame.itype == 'RESET': resets.append(frame.label) + _logger.debug('%s is RESET', frame.label) elif frame.itype == 'RAMP': ramps.append(frame.label) + _logger.debug('%s is RAMP', frame.label) else: raise RecipeError('frame is neither a RAMP nor a RESET') @@ -87,11 +90,17 @@ class GainRecipe1(RecipeBase): counts = numpy.zeros((len(ramps), len(channels))) variance = numpy.zeros_like(counts) + ir = 0 + for i, di in enumerate(ramps): with pyfits.open(di, mode='readonly') as fd: for j, channel in enumerate(channels): - counts[i][j] = fd[0].data[channel].mean() - variance[i][j] = fd[0].data[channel].var(ddof=1) + c = fd[0].data[channel].mean() + _logger.debug('%f counts in channel', c) + counts[i][j] = c + v = fd[0].data[channel].var(ddof=1) + _logger.debug('%f variance in channel', v) + variance[i][j] = v for j, _ in enumerate(channels): ig, ron,_,_,_ = scipy.stats.linregress(counts[:,j], variance[:,j]) @@ -110,22 +119,21 @@ class GainRecipe1(RecipeBase): cube[0][channel] = gain cube[1][channel] = var - #result = create_result(cube[0], variance=cube[1]) - - val= {'qa': numina.qa.UNKNOWN, 'gain': {'mean': list(gch_mean.flat), - 'var': list(gch_var.flat), - 'image': result - }, - 'ron': {'mean': list(rch_mean.flat), - 'var': list(rch_var.flat)}, - } - prods= {'qa': numina.qa.UNKNOWN, 'gain': {'mean': list(gch_mean.flat), - 'var': list(gch_var.flat), - 'image': result + hdu = pyfits.PrimaryHDU(cube[0]) + hduvar = pyfits.ImageHDU(cube[1]) + hdulist = pyfits.HDUList([hdu, hduvar]) + gmean = map(float, gch_mean.flat) + gvar = map(float, gch_var.flat) + rmean = map(float, rch_mean.flat) + rvar = map(float, rch_var.flat) + + prods= {'qa': numina.qa.UNKNOWN, 'gain': {'mean': gmean, + 'var': gvar, + 'image': DataFrame(hdulist) }, - 'ron': {'mean': list(rch_mean.flat), - 'var': list(rch_var.flat)}, + 'ron': {'mean': rmean, + 'var': rvar } - print val + } #return {'products': [MasterGainMap(), MasterRONMap()]} return {'products': [prods]}
GainRecipe1 reads its inputs and writes outputs
guaix-ucm_pyemir
train
94ac3f782027c4b707470b1aa0f5f66c6702ad9f
diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -254,28 +254,28 @@ module ActiveSupport #:nodoc: UNSAFE_STRING_METHODS_WITH_BACKREF.each do |unsafe_method| if unsafe_method.respond_to?(unsafe_method) class_eval <<-EOT, __FILE__, __LINE__ + 1 - def #{unsafe_method}(*args, &block) - if block - to_str.#{unsafe_method}(*args) { |*params| - set_block_back_references(block, $~) - block.call(*params) - } - else - to_str.#{unsafe_method}(*args) - end - end - - def #{unsafe_method}!(*args, &block) - @html_safe = false - if block - super(*args) { |*params| - set_block_back_references(block, $~) - block.call(*params) - } - else - super - end - end + def #{unsafe_method}(*args, &block) # def gsub(*args, &block) + if block # if block + to_str.#{unsafe_method}(*args) { |*params| # to_str.gsub(*args) { |*params| + set_block_back_references(block, $~) # set_block_back_references(block, $~) + block.call(*params) # block.call(*params) + } # } + else # else + to_str.#{unsafe_method}(*args) # to_str.gsub(*args) + end # end + end # end + + def #{unsafe_method}!(*args, &block) # def gsub!(*args, &block) + @html_safe = false # @html_safe = false + if block # if block + super(*args) { |*params| # super(*args) { |*params| + set_block_back_references(block, $~) # set_block_back_references(block, $~) + block.call(*params) # block.call(*params) + } # } + else # else + super # super + end # end + end # end EOT end end
Add a commented code example of what will be produced
rails_rails
train
3952bc099b0a64c89fd44206c42ad61ea322df19
diff --git a/History.md b/History.md index <HASH>..<HASH> 100644 --- a/History.md +++ b/History.md @@ -49,6 +49,12 @@ Fixes ----- - Performance tweaks regarding temp_objects model accessors and job objects +0.8.4 (2010-04-27) +================== +Fixes +----- +- Security fix for file data store + 0.8.2 (2010-01-11) ================== Fixes diff --git a/lib/dragonfly/data_storage/file_data_store.rb b/lib/dragonfly/data_storage/file_data_store.rb index <HASH>..<HASH> 100644 --- a/lib/dragonfly/data_storage/file_data_store.rb +++ b/lib/dragonfly/data_storage/file_data_store.rb @@ -6,6 +6,7 @@ module Dragonfly class FileDataStore # Exceptions + class BadUID < RuntimeError; end class UnableToFormUrl < RuntimeError; end include Configurable @@ -39,6 +40,7 @@ module Dragonfly end def retrieve(relative_path) + validate_uid!(relative_path) path = absolute(relative_path) pathname = Pathname.new(path) raise DataNotFound, "couldn't find file #{path}" unless pathname.exist? @@ -49,6 +51,7 @@ module Dragonfly end def destroy(relative_path) + validate_uid!(relative_path) path = absolute(relative_path) FileUtils.rm path FileUtils.rm_f meta_data_path(path) @@ -135,6 +138,10 @@ module Dragonfly end end + def validate_uid!(uid) + raise BadUID, "tried to fetch uid #{uid.inspect} - perhaps due to a malicious user" if uid['..'] + end + end end diff --git a/spec/dragonfly/data_storage/file_data_store_spec.rb b/spec/dragonfly/data_storage/file_data_store_spec.rb index <HASH>..<HASH> 100644 --- a/spec/dragonfly/data_storage/file_data_store_spec.rb +++ b/spec/dragonfly/data_storage/file_data_store_spec.rb @@ -152,6 +152,7 @@ describe Dragonfly::DataStorage::FileDataStore do pathname, meta = @data_store.retrieve(uid) pathname.should be_a(Pathname) end + it "should be able to retrieve any file, stored or not (and without meta data)" do FileUtils.mkdir_p("#{@data_store.root_path}/jelly_beans/are") File.open("#{@data_store.root_path}/jelly_beans/are/good", 'w'){|f| f.write('hey dog') } @@ -159,16 +160,22 @@ describe Dragonfly::DataStorage::FileDataStore do pathname.read.should == 'hey dog' meta.should == {} end + it "should work even if meta is stored in old .extra file" do uid = @data_store.store(@temp_object, :meta => {:dog => 'food'}) FileUtils.mv("#{@data_store.root_path}/#{uid}.meta", "#{@data_store.root_path}/#{uid}.extra") pathname, meta = @data_store.retrieve(uid) meta.should == {:dog => 'food'} end + + it "should raise an error if the file path has .. in it" do + expect{ + @data_store.retrieve('jelly_beans/../are/good') + }.to raise_error(Dragonfly::DataStorage::FileDataStore::BadUID) + end end describe "destroying" do - it "should prune empty directories when destroying" do uid = @data_store.store(@temp_object) @data_store.destroy(uid) @@ -192,6 +199,11 @@ describe Dragonfly::DataStorage::FileDataStore do File.exist?("#{@data_store.root_path}/#{uid}.extra").should be_false end + it "should raise an error if the file path has .. in it" do + expect{ + @data_store.destroy('jelly_beans/../are/good') + }.to raise_error(Dragonfly::DataStorage::FileDataStore::BadUID) + end end describe "relative paths" do
Security fix for file data store (cherry-picked from <I>)
markevans_dragonfly
train
220a077ed364d548e9caa71d69a19adf26cc2c63
diff --git a/test/smartcoin/charge_spec.rb b/test/smartcoin/charge_spec.rb index <HASH>..<HASH> 100644 --- a/test/smartcoin/charge_spec.rb +++ b/test/smartcoin/charge_spec.rb @@ -34,6 +34,17 @@ describe SmartCoin::Charge do expect(charge.installments.first.class).to eq(SmartCoin::Installment) end + it 'should create a bank_slip charge types' do + charge_params = {amount: 1000, currency: 'brl', type: 'bank_slip'} + charge = SmartCoin::Charge.create(charge_params) + expect(charge.id).to match(/ch_(.*)/) + expect(charge.amount).to eq(charge_params[:amount]) + expect(charge.paid).to be_false + expect(charge.card).to be_nil + expect(charge.bank_slip).to_not be_nil + expect(charge.bank_slip.link).to match(/https:\/\/api\.smartcoin\.com\.br\/v1\/charges\/ch_(.*)\/bank_slip\/test/) + end + it 'should retrieve a charge that has already created' do token_params = {number: 4242424242424242, exp_month: 11,
New Test for bank_slip charge types
smartcoinpayments_smartcoin-ruby
train
1a54f7d0202dba2499cdce30d731cfc65a1720c9
diff --git a/HARK/ConsumptionSaving/ConsIndShockModel.py b/HARK/ConsumptionSaving/ConsIndShockModel.py index <HASH>..<HASH> 100644 --- a/HARK/ConsumptionSaving/ConsIndShockModel.py +++ b/HARK/ConsumptionSaving/ConsIndShockModel.py @@ -184,74 +184,6 @@ class ConsumerSolution(HARKobject): self.vPPfunc.append(new_solution.vPPfunc) self.mNrmMin.append(new_solution.mNrmMin) -class MargValueFunc(HARKobject): - """ - A class for representing a marginal value function in models where the - standard envelope condition of v'(m) = u'(c(m)) holds (with CRRA utility). - """ - - distance_criteria = ["cFunc", "CRRA"] - - def __init__(self, cFunc, CRRA): - """ - Constructor for a new marginal value function object. - - Parameters - ---------- - cFunc : function - A real function representing the marginal value function composed - with the inverse marginal utility function, defined on market - resources: uP_inv(vPfunc(m)). Called cFunc because when standard - envelope condition applies, uP_inv(vPfunc(m)) = cFunc(m). - CRRA : float - Coefficient of relative risk aversion. - - Returns - ------- - None - """ - self.cFunc = deepcopy(cFunc) - self.CRRA = CRRA - - def __call__(self, *cFuncArgs): - """ - Evaluate the marginal value function at given levels of market resources m. - - Parameters - ---------- - m : float or np.array - Market resources (normalized by permanent income) whose marginal - value is to be found. - - Returns - ------- - vP : float or np.array - Marginal lifetime value of beginning this period with market - resources m; has same size as input m. - """ - return utilityP(self.cFunc(*cFuncArgs), gam=self.CRRA) - - def derivative(self, *cFuncArgs): - """ - Evaluate the derivative of the marginal value function at given levels - of market resources m; this is the marginal marginal value function. - - Parameters - ---------- - m : float or np.array - Market resources (normalized by permanent income) whose marginal - marginal value is to be found. - - Returns - ------- - vPP : float or np.array - Marginal marginal lifetime value of beginning this period with market - resources m; has same size as input m. - """ - c, MPC = self.cFunc.eval_with_derivative(*cFuncArgs) - return MPC * utilityPP(c, gam=self.CRRA) - - class MargMargValueFunc(HARKobject): """ A class for representing a marginal marginal value function in models where
Delete original MargValueFunc from ConsIndShock
econ-ark_HARK
train
89578fab0947c5a58e8838125b6b84945d349a1d
diff --git a/grimoire_elk/elk/bugzilla.py b/grimoire_elk/elk/bugzilla.py index <HASH>..<HASH> 100644 --- a/grimoire_elk/elk/bugzilla.py +++ b/grimoire_elk/elk/bugzilla.py @@ -182,7 +182,7 @@ class BugzillaEnrich(Enrich): eitem["status"] = issue['bug_status'][0]['__text__'] if "short_desc" in issue: if "__text__" in issue["short_desc"][0]: - eitem["main_description"] = issue['short_desc'][0]['__text__'] + eitem["main_description"] = issue['short_desc'][0]['__text__'][:self.KEYWORD_MAX_SIZE] if "summary" in issue: if "__text__" in issue["summary"][0]: eitem["summary"] = issue['summary'][0]['__text__']
[elk] Limit text size of short description attribute for Bugzilla data This patch limits the text size of the short description attribute to <I>, thus avoiding max_bytes_length_exceeded_exception.
chaoss_grimoirelab-elk
train
921922d39d1128fe721261547358fe9f7af6bcf6
diff --git a/src/python/pants/backend/experimental/python/lockfile.py b/src/python/pants/backend/experimental/python/lockfile.py index <HASH>..<HASH> 100644 --- a/src/python/pants/backend/experimental/python/lockfile.py +++ b/src/python/pants/backend/experimental/python/lockfile.py @@ -13,7 +13,11 @@ from pants.backend.experimental.python.lockfile_metadata import ( LockfileMetadata, calculate_invalidation_digest, ) -from pants.backend.python.subsystems.python_tool_base import PythonToolRequirementsBase +from pants.backend.python.subsystems.python_tool_base import ( + DEFAULT_TOOL_LOCKFILE, + NO_TOOL_LOCKFILE, + PythonToolRequirementsBase, +) from pants.backend.python.target_types import EntryPoint, PythonRequirementsField from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints from pants.backend.python.util_rules.pex import PexRequest, PexRequirements, VenvPex, VenvPexProcess @@ -289,7 +293,7 @@ async def generate_all_tool_lockfiles( results = await MultiGet( Get(PythonLockfile, PythonLockfileRequest, req) for req in requests - if req.dest not in {"<none>", "<default>"} + if req.dest not in {NO_TOOL_LOCKFILE, DEFAULT_TOOL_LOCKFILE} ) merged_digest = await Get(Digest, MergeDigests(res.digest for res in results)) workspace.write_digest(merged_digest) diff --git a/src/python/pants/backend/python/subsystems/python_tool_base.py b/src/python/pants/backend/python/subsystems/python_tool_base.py index <HASH>..<HASH> 100644 --- a/src/python/pants/backend/python/subsystems/python_tool_base.py +++ b/src/python/pants/backend/python/subsystems/python_tool_base.py @@ -14,6 +14,9 @@ from pants.engine.fs import FileContent from pants.option.errors import OptionsError from pants.option.subsystem import Subsystem +DEFAULT_TOOL_LOCKFILE = "<default>" +NO_TOOL_LOCKFILE = "<none>" + class PythonToolRequirementsBase(Subsystem): """Base class for subsystems that configure a set of requirements for a python tool.""" @@ -84,15 +87,15 @@ class PythonToolRequirementsBase(Subsystem): register( "--experimental-lockfile", type=str, - default="<none>", + default=NO_TOOL_LOCKFILE, advanced=True, help=( "Path to a lockfile used for installing the tool.\n\n" - "Set to the string `<default>` to use a lockfile provided by " + f"Set to the string `{DEFAULT_TOOL_LOCKFILE}` to use a lockfile provided by " "Pants, so long as you have not changed the `--version`, " "`--extra-requirements`, and `--interpreter-constraints` options. See " f"{cls.default_lockfile_url} for the default lockfile contents.\n\n" - "Set to the string `<none>` to opt out of using a lockfile. We do not " + f"Set to the string `{NO_TOOL_LOCKFILE}` to opt out of using a lockfile. We do not " "recommend this, as lockfiles are essential for reproducible builds.\n\n" "To use a custom lockfile, set this option to a file path relative to the " "build root, then activate the backend_package " @@ -136,7 +139,7 @@ class PythonToolRequirementsBase(Subsystem): hex_digest = calculate_invalidation_digest(requirements) - if self.lockfile == "<default>": + if self.lockfile == DEFAULT_TOOL_LOCKFILE: assert self.default_lockfile_resource is not None return PexRequirements( file_content=FileContent( @@ -155,7 +158,7 @@ class PythonToolRequirementsBase(Subsystem): @property def lockfile(self) -> str: - """The path to a lockfile or special strings '<none>' and '<default>'. + f"""The path to a lockfile or special strings '{NO_TOOL_LOCKFILE}' and '{DEFAULT_TOOL_LOCKFILE}'. This assumes you have set the class property `register_lockfile = True`. """ @@ -163,7 +166,7 @@ class PythonToolRequirementsBase(Subsystem): @property def uses_lockfile(self) -> bool: - return self.register_lockfile and self.lockfile != "<none>" + return self.register_lockfile and self.lockfile != NO_TOOL_LOCKFILE @property def interpreter_constraints(self) -> InterpreterConstraints:
[internal] Use constants for magic strings `<none>` and `<default>` for tool lockfiles (#<I>) [ci skip-rust]
pantsbuild_pants
train
10f7d6143039f85c7d59b6069f496986dc543a6a
diff --git a/lib/memfs/file.rb b/lib/memfs/file.rb index <HASH>..<HASH> 100644 --- a/lib/memfs/file.rb +++ b/lib/memfs/file.rb @@ -19,9 +19,10 @@ module MemFs SUCCESS = 0 - def_delegator :original_file_class, :path - def_delegator :original_file_class, :basename - def_delegator :original_file_class, :dirname + def_delegators :original_file_class, + :basename, + :dirname, + :path def self.chmod(mode_int, *paths) paths.each do |path|
Using def_delegators to group def_delegator
simonc_memfs
train
c7aedf2bd424279e4984a13895472f187263a286
diff --git a/web/server.js b/web/server.js index <HASH>..<HASH> 100644 --- a/web/server.js +++ b/web/server.js @@ -27,7 +27,7 @@ const broadcast = data => { wss.clients, client => { try { - client.send(JSON.stringify(data); + client.send(JSON.stringify(data)); } catch(e) { log.warn('unable to send data to client'); }
make sure to properly enclose broadcast catch wrap
askmike_gekko
train
69e706c721cd34de248f678b7f8fa744d2a4a960
diff --git a/src/Basset/Collection.php b/src/Basset/Collection.php index <HASH>..<HASH> 100644 --- a/src/Basset/Collection.php +++ b/src/Basset/Collection.php @@ -1,9 +1,6 @@ <?php namespace Basset; -use Basset\Filter\Filterable; -use Basset\Factory\FilterFactory; - -class Collection extends Filterable { +class Collection { /** * The collection identifier. @@ -26,12 +23,10 @@ class Collection extends Filterable { * @param \Basset\Directory $directory * @return void */ - public function __construct($identifier, Directory $directory, FilterFactory $filterFactory) + public function __construct($identifier, Directory $directory) { $this->identifier = $identifier; $this->directory = $directory; - $this->filterFactory = $filterFactory; - $this->filters = new \Illuminate\Support\Collection; } /** @@ -105,14 +100,7 @@ class Collection extends Filterable { $this->orderAsset($asset, $ordered); } - $ordered = new \Illuminate\Support\Collection($ordered); - - $this->filters->each(function($filter) use (&$ordered) - { - $ordered->each(function($asset) use ($filter) { $asset->apply($filter); }); - }); - - return $ordered; + return new \Illuminate\Support\Collection($ordered); } /** diff --git a/src/Basset/Environment.php b/src/Basset/Environment.php index <HASH>..<HASH> 100644 --- a/src/Basset/Environment.php +++ b/src/Basset/Environment.php @@ -86,7 +86,7 @@ class Environment implements ArrayAccess { { $directory = $this->prepareDefaultDirectory(); - $this->collections[$name] = new Collection($name, $directory, $this->filterFactory); + $this->collections[$name] = new Collection($name, $directory); } // If the collection has been given a callable closure then we'll execute the closure with diff --git a/tests/Basset/CollectionTest.php b/tests/Basset/CollectionTest.php index <HASH>..<HASH> 100644 --- a/tests/Basset/CollectionTest.php +++ b/tests/Basset/CollectionTest.php @@ -16,7 +16,7 @@ class CollectionTest extends PHPUnit_Framework_TestCase { public function setUp() { - $this->collection = new Collection('foo', $this->directory = m::mock('Basset\Directory'), m::mock('Basset\Factory\FilterFactory')); + $this->collection = new Collection('foo', $this->directory = m::mock('Basset\Directory')); }
Filter apply falls through to the default directory.
Marwelln_basset
train
49acbd22f76b42157f7fa1ee91824793d806bf23
diff --git a/src/org/zaproxy/zap/extension/api/OptionsParamApi.java b/src/org/zaproxy/zap/extension/api/OptionsParamApi.java index <HASH>..<HASH> 100644 --- a/src/org/zaproxy/zap/extension/api/OptionsParamApi.java +++ b/src/org/zaproxy/zap/extension/api/OptionsParamApi.java @@ -34,7 +34,7 @@ public class OptionsParamApi extends AbstractParam { @Override protected void parse() { - enabled = getConfig().getBoolean(ENABLED, false); + enabled = getConfig().getBoolean(ENABLED, true); //postActions = getConfig().getBoolean(POST_ACTIONS, false); }
Issue <I>: API enabled by default
zaproxy_zaproxy
train
ae7bc782b786d8421c9536b624888f7d9419af54
diff --git a/guava/src/com/google/common/base/Joiner.java b/guava/src/com/google/common/base/Joiner.java index <HASH>..<HASH> 100644 --- a/guava/src/com/google/common/base/Joiner.java +++ b/guava/src/com/google/common/base/Joiner.java @@ -95,7 +95,8 @@ public class Joiner { */ @Beta @Deprecated - public final <A extends Appendable, I extends Object & Iterable<?> & Iterator<?>> A + public + final <A extends Appendable, I extends Object & Iterable<?> & Iterator<?>> A appendTo(A appendable, I parts) throws IOException { return appendTo(appendable, (Iterator<?>) parts); } @@ -154,7 +155,8 @@ public class Joiner { */ @Beta @Deprecated - public final <I extends Object & Iterable<?> & Iterator<?>> StringBuilder + public + final <I extends Object & Iterable<?> & Iterator<?>> StringBuilder appendTo(StringBuilder builder, I parts) { return appendTo(builder, (Iterator<?>) parts); } @@ -214,7 +216,8 @@ public class Joiner { */ @Beta @Deprecated - public final <I extends Object & Iterable<?> & Iterator<?>> String join(I parts) { + public + final <I extends Object & Iterable<?> & Iterator<?>> String join(I parts) { return join((Iterator<?>) parts); } @@ -388,7 +391,8 @@ public class Joiner { */ @Beta @Deprecated - public <A extends Appendable, + public + <A extends Appendable, I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> A appendTo(A appendable, I entries) throws IOException { Iterator<? extends Entry<?, ?>> iterator = entries; @@ -444,7 +448,8 @@ public class Joiner { */ @Beta @Deprecated - public <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> + public + <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> StringBuilder appendTo(StringBuilder builder, I entries) throws IOException { Iterator<? extends Entry<?, ?>> iterator = entries; return appendTo(builder, iterator); @@ -490,7 +495,8 @@ public class Joiner { */ @Beta @Deprecated - public <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> + public + <I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>> String join(I entries) throws IOException { Iterator<? extends Entry<?, ?>> iterator = entries; return join(iterator);
Make the Joiner Iterator/Iterable accepting overloads package-private (MOE public). ------------- Created by MOE: <URL>
google_guava
train
37e6b535844056652ef7a1e0de981db138bdefc8
diff --git a/build_tools/aws-sdk-code-generator/lib/aws-sdk-code-generator/code_builder.rb b/build_tools/aws-sdk-code-generator/lib/aws-sdk-code-generator/code_builder.rb index <HASH>..<HASH> 100644 --- a/build_tools/aws-sdk-code-generator/lib/aws-sdk-code-generator/code_builder.rb +++ b/build_tools/aws-sdk-code-generator/lib/aws-sdk-code-generator/code_builder.rb @@ -44,8 +44,8 @@ module AwsSdkCodeGenerator end # @return [Enumerable<String<path>, String<code>>] - def source_files - prefix = @service.gem_name + def source_files(options = {}) + prefix = options.fetch(:prefix, @service.gem_name) Enumerator.new do |y| y.yield("#{prefix}.rb", service_module) y.yield("#{prefix}/customizations.rb", '')
Generator fix for sts.
aws_aws-sdk-ruby
train
cf772300f933db3aafca72ec0f6aa5b16d80014e
diff --git a/Serializer/JSONFlattenedSerializer.php b/Serializer/JSONFlattenedSerializer.php index <HASH>..<HASH> 100644 --- a/Serializer/JSONFlattenedSerializer.php +++ b/Serializer/JSONFlattenedSerializer.php @@ -103,9 +103,7 @@ final class JSONFlattenedSerializer implements JWESerializer $iv = Base64Url::decode($data['iv']); $tag = Base64Url::decode($data['tag']); $aad = array_key_exists('aad', $data) ? Base64Url::decode($data['aad']) : null; - $encodedSharedProtectedHeader = array_key_exists('protected', $data) ? $data['protected'] : null; - $sharedProtectedHeader = $encodedSharedProtectedHeader ? $this->jsonConverter->decode(Base64Url::decode($encodedSharedProtectedHeader)) : []; - $sharedHeader = array_key_exists('unprotected', $data) ? $data['unprotected'] : []; + list($encodedSharedProtectedHeader, $sharedProtectedHeader, $sharedHeader) = $this->processHeaders($data); $encryptedKey = array_key_exists('encrypted_key', $data) ? Base64Url::decode($data['encrypted_key']) : null; $header = array_key_exists('header', $data) ? $data['header'] : []; @@ -119,4 +117,18 @@ final class JSONFlattenedSerializer implements JWESerializer $encodedSharedProtectedHeader, [Recipient::create($header, $encryptedKey)]); } + + /** + * @param array $data + * + * @return array + */ + private function processHeaders(array $data): array + { + $encodedSharedProtectedHeader = array_key_exists('protected', $data) ? $data['protected'] : null; + $sharedProtectedHeader = $encodedSharedProtectedHeader ? $this->jsonConverter->decode(Base64Url::decode($encodedSharedProtectedHeader)) : []; + $sharedHeader = array_key_exists('unprotected', $data) ? $data['unprotected'] : []; + + return [$encodedSharedProtectedHeader, $sharedProtectedHeader, $sharedHeader]; + } }
JWE Flattened Serializer refactored
web-token_jwt-encryption
train
4b97b4bc1817b5ad7ee113381321c94ff9a15799
diff --git a/chirptext/__version__.py b/chirptext/__version__.py index <HASH>..<HASH> 100644 --- a/chirptext/__version__.py +++ b/chirptext/__version__.py @@ -14,6 +14,6 @@ __description__ = "A minimalist collection of text processing tools for Python 3 __url__ = "https://github.com/letuananh/chirptext/" __maintainer__ = "Le Tuan Anh" __version_major__ = "0.2" -__version__ = "{}a3.post3".format(__version_major__) -__version_long__ = "{} - alpha 3.post3".format(__version_major__) +__version__ = "{}a4".format(__version_major__) +__version_long__ = "{} - alpha 4".format(__version_major__) __status__ = "3 - Alpha"
pump version to <I>a4
letuananh_chirptext
train
a200dbae8bf03c6883ac737a40a4d64f43f19aab
diff --git a/datalist-polyfill.js b/datalist-polyfill.js index <HASH>..<HASH> 100644 --- a/datalist-polyfill.js +++ b/datalist-polyfill.js @@ -13,7 +13,7 @@ 'use strict'; // feature detection - var nativedatalist = !!( 'list' in document.createElement('input') ) && + var nativedatalist = ( 'list' in document.createElement('input') ) && !!( document.createElement('datalist') && window.HTMLDataListElement ); // in case of that the feature doesn't exist, emulate it's functionality @@ -273,16 +273,16 @@ dataListSelect.style.minWidth = rects[0].width + 'px'; if (touched) { - var message = document.createElement('option'); + var messageElement = document.createElement('option'); // ... and it's first entry should contain the localized message to select an entry - message.innerText = message; + messageElement.innerText = message; // ... and disable this option, as it shouldn't get selected by the user - message.disabled = true; + messageElement.disabled = true; // ... and assign a dividable class to it - message.setAttribute('class', 'message'); + messageElement.setAttribute('class', 'message'); // ... and finally insert it into the select - dataListSelect.appendChild(message); + dataListSelect.appendChild(messageElement); } // add select to datalist element ...
fix after renaming all dollar-signed vars
mfranzke_datalist-polyfill
train
d75e2f82049d528bb40a5cfa6b94abd1981076bd
diff --git a/core/CliMulti/Process.php b/core/CliMulti/Process.php index <HASH>..<HASH> 100644 --- a/core/CliMulti/Process.php +++ b/core/CliMulti/Process.php @@ -142,6 +142,7 @@ class Process public static function isSupported() { + return false; if (SettingsServer::isWindows()) { return false; } diff --git a/plugins/MultiSites/angularjs/dashboard/dashboard.html b/plugins/MultiSites/angularjs/dashboard/dashboard.html index <HASH>..<HASH> 100644 --- a/plugins/MultiSites/angularjs/dashboard/dashboard.html +++ b/plugins/MultiSites/angularjs/dashboard/dashboard.html @@ -66,6 +66,7 @@ piwik-multisites-site date-sparkline="dateSparkline" show-sparklines="showSparklines" + metric="predicate" display-revenue-column="displayRevenueColumn" ng-repeat="website in model.sites | orderBy:predicate:reverse | multiSitesGroupFilter:model.getCurrentPagingOffsetStart():model.pageSize"> </tr> diff --git a/plugins/MultiSites/angularjs/site/site-directive.js b/plugins/MultiSites/angularjs/site/site-directive.js index <HASH>..<HASH> 100644 --- a/plugins/MultiSites/angularjs/site/site-directive.js +++ b/plugins/MultiSites/angularjs/site/site-directive.js @@ -27,7 +27,8 @@ angular.module('piwikApp').directive('piwikMultisitesSite', function($document, evolutionMetric: '=', showSparklines: '=', dateSparkline: '=', - displayRevenueColumn: '=' + displayRevenueColumn: '=', + metric: '=' }, templateUrl: 'plugins/MultiSites/angularjs/site/site.html?cb=' + piwik.cacheBuster, controller: function ($scope) { @@ -47,7 +48,7 @@ angular.module('piwikApp').directive('piwikMultisitesSite', function($document, append = '&token_auth=' + token_auth; } - return piwik.piwik_url + '?module=MultiSites&action=getEvolutionGraph&period=' + $scope.period + '&date=' + $scope.dateSparkline + '&evolutionBy=' +$scope.evolutionMetric + '&columns=' + $scope.evolutionMetric + '&idSite=' + website.idsite + '&idsite=' + website.idsite + '&viewDataTable=sparkline' + append + '&colors=' + encodeURIComponent(JSON.stringify(piwik.getSparklineColors())); + return piwik.piwik_url + '?module=MultiSites&action=getEvolutionGraph&period=' + $scope.period + '&date=' + $scope.dateSparkline + '&evolutionBy=' +$scope.metric + '&columns=' + $scope.metric + '&idSite=' + website.idsite + '&idsite=' + website.idsite + '&viewDataTable=sparkline' + append + '&colors=' + encodeURIComponent(JSON.stringify(piwik.getSparklineColors())); } } }
fixes #<I> sparklines in all websites dashboard were not working
matomo-org_matomo
train
f27e73fcb88a1d0c55cc5da572a2be425df73aac
diff --git a/chainntnfs/txnotifier.go b/chainntnfs/txnotifier.go index <HASH>..<HASH> 100644 --- a/chainntnfs/txnotifier.go +++ b/chainntnfs/txnotifier.go @@ -1118,9 +1118,11 @@ out: } // DisconnectTip handles the tip of the current chain being disconnected during -// a chain reorganization. If any watched transactions were included in this -// block, internal structures are updated to ensure a confirmation notification -// is not sent unless the transaction is included in the new chain. +// a chain reorganization. If any watched transactions or spending transactions +// for registered outpoints were included in this block, internal structures are +// updated to ensure confirmation/spend notifications are consumed (if not +// already), and reorg notifications are dispatched instead. Confirmation/spend +// notifications will be dispatched again upon block inclusion. func (n *TxNotifier) DisconnectTip(blockHeight uint32) error { select { case <-n.quit: @@ -1193,9 +1195,34 @@ func (n *TxNotifier) DisconnectTip(blockHeight uint32) error { } } - // Finally, we can remove the transactions we're currently watching that - // were included in this block height. + // We'll also go through our watched outpoints and attempt to drain + // their dispatched notifications to ensure dispatching notifications to + // clients later on is always non-blocking. We're only interested in + // outpoints whose spending transaction was included at the height being + // disconnected. + for op := range n.opsBySpendHeight[blockHeight] { + // Since the spending transaction is being reorged out of the + // chain, we'll need to clear out the spending details of the + // outpoint. + spendSet := n.spendNotifications[op] + spendSet.details = nil + + // For all requests which have had a spend notification + // dispatched, we'll attempt to drain it and send a reorg + // notification instead. + for _, ntfn := range spendSet.ntfns { + if err := n.dispatchSpendReorg(ntfn); err != nil { + return err + } + } + } + + // Finally, we can remove the transactions that were confirmed and the + // outpoints that were spent at the height being disconnected. We'll + // still continue to track them until they have been confirmed/spent and + // are no longer under the risk of being reorged out of the chain again. delete(n.txsByInitialHeight, blockHeight) + delete(n.opsBySpendHeight, blockHeight) return nil } @@ -1243,6 +1270,35 @@ func (n *TxNotifier) dispatchConfReorg(ntfn *ConfNtfn, return nil } +// dispatchSpendReorg dispatches a reorg notification to the client if a spend +// notiification was already delivered. +// +// NOTE: This must be called with the TxNotifier's lock held. +func (n *TxNotifier) dispatchSpendReorg(ntfn *SpendNtfn) error { + if !ntfn.dispatched { + return nil + } + + // Attempt to drain the spend notification to ensure sends to the Spend + // channel are always non-blocking. + select { + case <-ntfn.Event.Spend: + default: + } + + // Send a reorg notification to the client in order for them to + // correctly handle reorgs. + select { + case ntfn.Event.Reorg <- struct{}{}: + case <-n.quit: + return ErrTxNotifierExiting + } + + ntfn.dispatched = false + + return nil +} + // TearDown is to be called when the owner of the TxNotifier is exiting. This // closes the event channels of all registered notifications that have not been // dispatched yet.
chainntnfs/txnotifier: detect reorgs for spending transactions of registered outpoints In this commit, we introduce support to the TxNotifier to detect spending transactions of registered outpoints being reorged out of the chain. In the event that a reorg does occur, we'll consume the Spend notification if it hasn't been consumed yet, and dispatch a Reorg notification instead.
lightningnetwork_lnd
train
08df01ae7abb461d707fb857fca7db2046c18bd9
diff --git a/src/program/wrap.js b/src/program/wrap.js index <HASH>..<HASH> 100644 --- a/src/program/wrap.js +++ b/src/program/wrap.js @@ -4,7 +4,6 @@ import Node from './Node.js'; import keys from './keys.js'; const statementsWithBlocks = { - IfStatement: 'consequent', ForStatement: 'body', ForInStatement: 'body', ForOfStatement: 'body', @@ -13,6 +12,16 @@ const statementsWithBlocks = { ArrowFunctionExpression: 'body' }; +function synthetic ( expression ) { + return { + start: expression.start, + end: expression.end, + type: 'BlockStatement', + body: [ expression ], + synthetic: true + }; +} + export default function wrap ( raw, parent ) { if ( !raw ) return; @@ -31,20 +40,13 @@ export default function wrap ( raw, parent ) { keys[ raw.type ] = Object.keys( raw ).filter( key => typeof raw[ key ] === 'object' ); } - // special case – body-less if/for/while statements. TODO others? - const bodyType = statementsWithBlocks[ raw.type ]; - if ( bodyType && raw[ bodyType ].type !== 'BlockStatement' ) { - const expression = raw[ bodyType ]; - - // create a synthetic block statement, otherwise all hell - // breaks loose when it comes to block scoping - raw[ bodyType ] = { - start: expression.start, - end: expression.end, - type: 'BlockStatement', - body: [ expression ], - synthetic: true - }; + // create synthetic block statements, otherwise all hell + // breaks loose when it comes to block scoping + if ( raw.type === 'IfStatement' ) { + if ( raw.consequent.type !== 'BlockStatement' ) raw.consequent = synthetic( raw.consequent ); + if ( raw.alternate && raw.alternate.type !== 'BlockStatement' ) raw.alternate = synthetic( raw.alternate ); + } else if ( statementsWithBlocks[ raw.type ] && raw.body.type !== 'BlockStatement' ) { + raw.body = synthetic( raw.body ); } Node( raw, parent ); diff --git a/test/samples/if.js b/test/samples/if.js index <HASH>..<HASH> 100644 --- a/test/samples/if.js +++ b/test/samples/if.js @@ -505,5 +505,20 @@ module.exports = [ };`, // TODO `function foo(){a?a():b||d();e?f():g()}` output: `function foo(){if(a)a();else if(b);else d();e?f():g()}` + }, + + { + description: 'adds semi after break statement', + input: ` + function foo () { + x: { + if ( a ) { + a(); + } else break x; + + b(); + } + }`, + output: `function foo(){x: {if(a)a();else break x;b()}}` } ];
create synthetic block statements for if statement alternates
Rich-Harris_butternut
train
37f65c64c4608b5a7d55227e4f53a10ff65ec496
diff --git a/telapi/inboundxml/__init__.py b/telapi/inboundxml/__init__.py index <HASH>..<HASH> 100644 --- a/telapi/inboundxml/__init__.py +++ b/telapi/inboundxml/__init__.py @@ -32,7 +32,7 @@ class Element(object): def __unicode__(self): attribute_string = '' - body_string = ''.join([unicode(child) for child in self._children]) or self._body + body_string = ''.join([unicode(child) for child in self._children]) or escape(unicode(self._body)) if not self._allow_blank and not body_string.strip(): raise ValueError('The "%s" element cannot be blank!' % @@ -42,7 +42,7 @@ class Element(object): attribute_string = ' ' + ' '.join(['%s="%s"' % (escape(unicode(k)), escape(unicode(v))) for k, v in self._attributes.items()]) - return u"<%s%s>%s</%s>" % (self._element_name, attribute_string, escape(body_string), self._element_name) + return u"<%s%s>%s</%s>" % (self._element_name, attribute_string, body_string, self._element_name) def _ensure_attribute(self, name): if name not in self._allowed_attributes:
Fixed escaping body of inboundxml Elements.
TelAPI_telapi-python
train
29b4615848591eaf4c982a0be722879671ad026f
diff --git a/pyrogram/methods/invite_links/create_chat_invite_link.py b/pyrogram/methods/invite_links/create_chat_invite_link.py index <HASH>..<HASH> 100644 --- a/pyrogram/methods/invite_links/create_chat_invite_link.py +++ b/pyrogram/methods/invite_links/create_chat_invite_link.py @@ -27,8 +27,10 @@ class CreateChatInviteLink(Scaffold): async def create_chat_invite_link( self, chat_id: Union[int, str], + name: str = None, expire_date: int = None, member_limit: int = None, + creates_join_request: bool = None ) -> "types.ChatInviteLink": """Create an additional invite link for a chat. @@ -41,6 +43,9 @@ class CreateChatInviteLink(Scaffold): Unique identifier for the target chat or username of the target channel/supergroup (in the format @username). + name (``str``, *optional*): + Invite link name. + expire_date (``int``, *optional*): Point in time (Unix timestamp) when the link will expire. Defaults to None (no expiration date). @@ -50,6 +55,10 @@ class CreateChatInviteLink(Scaffold): this invite link; 1-99999. Defaults to None (no member limit). + creates_join_request (``bool``, *optional*): + True, if users joining the chat via the link need to be approved by chat administrators. + If True, member_limit can't be specified. + Returns: :obj:`~pyrogram.types.ChatInviteLink`: On success, the new invite link is returned. @@ -67,6 +76,8 @@ class CreateChatInviteLink(Scaffold): peer=await self.resolve_peer(chat_id), expire_date=expire_date, usage_limit=member_limit, + title=name, + request_needed=creates_join_request ) ) diff --git a/pyrogram/methods/invite_links/edit_chat_invite_link.py b/pyrogram/methods/invite_links/edit_chat_invite_link.py index <HASH>..<HASH> 100644 --- a/pyrogram/methods/invite_links/edit_chat_invite_link.py +++ b/pyrogram/methods/invite_links/edit_chat_invite_link.py @@ -28,8 +28,10 @@ class EditChatInviteLink(Scaffold): self, chat_id: Union[int, str], invite_link: str, + name: str = None, expire_date: int = None, member_limit: int = None, + creates_join_request: bool = None ) -> "types.ChatInviteLink": """Edit a non-primary invite link. @@ -43,6 +45,9 @@ class EditChatInviteLink(Scaffold): invite_link (``str``): The invite link to edit + name (``str``, *optional*): + Invite link name. + expire_date (``int``, *optional*): Point in time (Unix timestamp) when the link will expire. Defaults to None (no change), pass 0 to set no expiration date. @@ -52,6 +57,10 @@ class EditChatInviteLink(Scaffold): invite link; 1-99999. Defaults to None (no change), pass 0 to set no member limit. + creates_join_request (``bool``, *optional*): + True, if users joining the chat via the link need to be approved by chat administrators. + If True, member_limit can't be specified. + Returns: :obj:`~pyrogram.types.ChatInviteLink`: On success, the new invite link is returned @@ -70,6 +79,8 @@ class EditChatInviteLink(Scaffold): link=invite_link, expire_date=expire_date, usage_limit=member_limit, + title=name, + request_needed=creates_join_request ) )
Update create/edit_chat_invite_link
pyrogram_pyrogram
train
b77d81f8d931cf1b29225384500049d5f9599efa
diff --git a/xbee/frame.py b/xbee/frame.py index <HASH>..<HASH> 100644 --- a/xbee/frame.py +++ b/xbee/frame.py @@ -49,7 +49,11 @@ class APIFrame: total = total & 0xFF # Subtract from 0xFF - return bytes(chr(0xFF - total)) + if hasattr(bytes(), 'encode'): + # Python 2.X + return chr(0xFF - total) + else: + return bytes([0xFF - total]) def verify(self, chksum): """
Branched on returning proper bytes type
niolabs_python-xbee
train
34853103d315775e8796945c12440f6218eb4d66
diff --git a/ImageUploaderBehavior.php b/ImageUploaderBehavior.php index <HASH>..<HASH> 100644 --- a/ImageUploaderBehavior.php +++ b/ImageUploaderBehavior.php @@ -191,10 +191,20 @@ class ImageUploaderBehavior extends Behavior $rnddir = static::getRandomDir($imageFolder); $fullImagePath = $imageFolder . $DS . $rnddir . $DS . $name; // Полный путь к изображению if ($image->saveAs($fullImagePath)) { + // Reduce image if image is very large + $imageComponent = static::getImageComponent(); + $imageInfo = getimagesize($fullImagePath); + $img_width = $imageInfo[0]; + if ($img_width > 1024) { + /* @var $image_o Image_GD|Image_Imagick */ + $image_o = $imageComponent->load($fullImagePath); + $image_o->resize(1024, static::getMaxHeight(1024)); + $image_o->save($fullImagePath); + } + // Save original file $originalImage = $imageFolder . $DS . $rnddir . $DS . $namePart . '_original.' . $image->extension; @copy($fullImagePath, $originalImage); - // Если изображение успешно сохранено - делаем ресайзные копии $sizes = $this->_imageSizes; $imageInfo = getimagesize($fullImagePath); @@ -212,9 +222,8 @@ class ImageUploaderBehavior extends Behavior $height = $img_width / $this->_aspectRatio; $width = $height * $this->_aspectRatio; } - $imageComponent = static::getImageComponent(); - $image_c = $imageComponent->load($fullImagePath); /* @var $image_c Image_GD|Image_Imagick */ + $image_c = $imageComponent->load($fullImagePath); $image_c->crop($width, $height); $img_width = $width; $image_c->save($fullImagePath);
Reduce original image size for very large images
demisang_yii2-image-uploader
train
11529b570d8fcc3cff6d60710f69f5a88bd98f58
diff --git a/internal/cmd/logger.go b/internal/cmd/logger.go index <HASH>..<HASH> 100644 --- a/internal/cmd/logger.go +++ b/internal/cmd/logger.go @@ -6,6 +6,7 @@ import ( "io" stdlog "log" "os" + "runtime" "time" "github.com/hairyhenderson/gomplate/v3/env" @@ -50,7 +51,7 @@ func createLogger(format string, out io.Writer) zerolog.Logger { switch format { case "console": useColour := false - if f, ok := out.(*os.File); ok && term.IsTerminal(int(f.Fd())) { + if f, ok := out.(*os.File); ok && term.IsTerminal(int(f.Fd())) && runtime.GOOS != "windows" { useColour = true } l = l.Output(zerolog.ConsoleWriter{
Stop emitting ANSI colour codes on Windows in unsupported terminals
hairyhenderson_gomplate
train
a58cf68957545a723774bfdc0b8f8730c9cceda9
diff --git a/src/Kunstmaan/MediaBundle/Entity/Media.php b/src/Kunstmaan/MediaBundle/Entity/Media.php index <HASH>..<HASH> 100644 --- a/src/Kunstmaan/MediaBundle/Entity/Media.php +++ b/src/Kunstmaan/MediaBundle/Entity/Media.php @@ -3,6 +3,7 @@ namespace Kunstmaan\MediaBundle\Entity; use Doctrine\ORM\Mapping as ORM; +use Gedmo\Mapping\Annotation as Gedmo; use Kunstmaan\AdminBundle\Entity\AbstractEntity; /** @@ -14,6 +15,14 @@ use Kunstmaan\AdminBundle\Entity\AbstractEntity; */ class Media extends AbstractEntity { + /** + * @var string + * + * @Gedmo\Locale + * Used locale to override Translation listener`s locale + * this is not a mapped field of entity metadata, just a simple property + */ + protected $locale; /** * @var string @@ -33,6 +42,22 @@ class Media extends AbstractEntity /** * @var string * + * @ORM\Column(name="description", type="text", nullable=true) + * @Gedmo\Translatable + */ + protected $description; + + /** + * @var string + * + * @ORM\Column(name="copyright", type="string", nullable=true) + * @Gedmo\Translatable + */ + protected $copyright; + + /** + * @var string + * * @ORM\Column(type="string", name="location", nullable=true) */ protected $location; @@ -111,6 +136,18 @@ class Media extends AbstractEntity } /** + * @param string $locale + * + * @return Media + */ + public function setTranslatableLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + /** * @return string */ public function getFileSize() @@ -439,6 +476,46 @@ class Media extends AbstractEntity } /** + * @param string $copyright + * + * @return Media + */ + public function setCopyright($copyright) + { + $this->copyright = $copyright; + + return $this; + } + + /** + * @return string + */ + public function getCopyright() + { + return $this->copyright; + } + + /** + * @param string $description + * + * @return Media + */ + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + /** + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** * @return string */ public function getClassType() diff --git a/src/Kunstmaan/MediaBundle/Form/File/FileType.php b/src/Kunstmaan/MediaBundle/Form/File/FileType.php index <HASH>..<HASH> 100644 --- a/src/Kunstmaan/MediaBundle/Form/File/FileType.php +++ b/src/Kunstmaan/MediaBundle/Form/File/FileType.php @@ -25,8 +25,28 @@ class FileType extends AbstractType */ public function buildForm(FormBuilderInterface $builder, array $options) { - $builder->add('name', 'text', array('required' => false)); + $builder->add( + 'name', + 'text', + array( + 'required' => false + ) + ); $builder->add('file', 'file'); + $builder->add( + 'copyright', + 'text', + array( + 'required' => false + ) + ); + $builder->add( + 'description', + 'textarea', + array( + 'required' => false + ) + ); } /** @@ -47,9 +67,9 @@ class FileType extends AbstractType public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( - array( - 'data_class' => 'Kunstmaan\MediaBundle\Helper\File\FileHelper', - ) + array( + 'data_class' => 'Kunstmaan\MediaBundle\Helper\File\FileHelper', + ) ); } } \ No newline at end of file
extra fields for media (description & copyright)
Kunstmaan_KunstmaanBundlesCMS
train
9c971a96431067aa2d9e9f657ca85c2e8a3909b8
diff --git a/test/client/docs_test.rb b/test/client/docs_test.rb index <HASH>..<HASH> 100644 --- a/test/client/docs_test.rb +++ b/test/client/docs_test.rb @@ -36,13 +36,16 @@ describe Elastomer::Client::Docs do end after do - @docs.delete_by_query :q => '*:*' - @index.flush - @index.refresh - # @index.close; sleep 0.020; @index.open + # @docs.delete_by_query :q => '*:*' + # @index.flush + # @index.refresh + @index.delete if @index.exists? end it 'gets documents from the search index' do + h = @docs.get :id => '1', :type => 'doc1' + assert_equal false, h['exists'] + populate! h = @docs.get :id => '1', :type => 'doc1'
seems the only way to do this is to delete the index each time
github_elastomer-client
train
1ab9311dfe0026fceb204fd83a9629255648e739
diff --git a/compliance_checker/cf/cf.py b/compliance_checker/cf/cf.py index <HASH>..<HASH> 100644 --- a/compliance_checker/cf/cf.py +++ b/compliance_checker/cf/cf.py @@ -117,6 +117,7 @@ class CFBaseCheck(BaseCheck): self._coord_vars = defaultdict(list) self._ancillary_vars = defaultdict(list) self._clim_vars = defaultdict(list) + self._metadata_vars = defaultdict(list) self._boundary_vars = defaultdict(dict) self._std_names = StandardNameTable(u'cf-standard-name-table.xml') @@ -132,6 +133,7 @@ class CFBaseCheck(BaseCheck): self._find_ancillary_vars(ds) self._find_clim_vars(ds) self._find_boundary_vars(ds) + self._find_metadata_vars(ds) def _find_coord_vars(self, ds, refresh=False): """ @@ -181,6 +183,32 @@ class CFBaseCheck(BaseCheck): return self._ancillary_vars + def _find_metadata_vars(self, ds, refresh=False): + ''' + Finds all variables that could be considered purely metadata + + Returns a list of netCDF variable instances for those that are likely metadata variables + ''' + if ds in self._metadata_vars and not refresh: + return self._metadata_vars[ds] + + for name, var in ds.dataset.variables.iteritems(): + + if name in self._find_ancillary_vars(ds) or name in self._find_coord_vars(ds): + continue + + if name in (u'platform_name', u'station_name', u'instrument_name', u'station_id', u'platform_id', u'surface_altitude'): + self._metadata_vars[ds].append(var) + + elif getattr(var, 'cf_role', None) == 'timeseries_id': + self._metadata_vars[ds].append(var) + + elif len(var.dimensions) == 0: + self._metadata_vars[ds].append(var) + + return self._metadata_vars[ds] + + def _find_data_vars(self, ds): """ Finds all variables that could be considered Data variables. @@ -190,13 +218,25 @@ class CFBaseCheck(BaseCheck): Excludes variables that are: - coordinate variables - ancillary variables - - no dimensions + - dimensionless + - metadata variables Results are NOT CACHED. """ - return {k:v for k, v in ds.dataset.variables.iteritems() if v not in self._find_coord_vars(ds) \ - and v not in self._find_ancillary_vars(ds) \ - and v.dimensions} + candidates = {} + for var_name, variable in ds.dataset.variables.iteritems(): + + if variable in self._find_coord_vars(ds): + continue + if variable in self._find_ancillary_vars(ds): + continue + if variable in self._find_metadata_vars(ds): + continue + if not variable.dimensions: + continue + candidates[var_name] = variable + + return candidates def _find_clim_vars(self, ds, refresh=False): """ @@ -2510,17 +2550,28 @@ class CFBaseCheck(BaseCheck): feature_tuple_list.append(feature_tuple) - data_vars = [each for name,each in ds.dataset.variables.iteritems() if hasattr(each,u'coordinates')] - - for each in data_vars: - this_feature_tuple = tuple([ds.dataset.variables[every].ndim for every in each.dimensions]) - feature_tuple_list.append(this_feature_tuple) - + data_vars = self._find_data_vars(ds) + + feature_map = {} + for var_name, variable in data_vars.iteritems(): + feature = variable.dimensions + feature_map[var_name] = feature + + + features = feature_map.values() + valid = all((features[0] == feature for feature in features)) + reasoning = [] + if not valid: + reasoning.append("At least one of the variables has a different feature type than the rest of the variables.") + feature_mess = [] + for var_name, feature in feature_map.iteritems(): + feature_mess.append("%s(%s)" % (var_name, ', '.join(feature) )) + reasoning.append(' '.join(feature_mess)) + - valid = all(x == feature_tuple_list[0] for x in feature_tuple_list) - return Result(BaseCheck.HIGH, valid, name=u'§9.1 Feature Types') + return Result(BaseCheck.HIGH, valid, u'§9.1 Feature Types are all the same', reasoning)
Adds better description for the <I> checking
ioos_compliance-checker
train
c68b3266651cc15475963ae11fc41f6b9bf94b3c
diff --git a/src/Symfony/Bundle/TwigBundle/TwigEngine.php b/src/Symfony/Bundle/TwigBundle/TwigEngine.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Bundle/TwigBundle/TwigEngine.php +++ b/src/Symfony/Bundle/TwigBundle/TwigEngine.php @@ -89,7 +89,7 @@ class TwigEngine implements EngineInterface */ public function load($name) { - return $this->environment->loadTemplate($this->parser->parse($name)); + return $this->environment->loadTemplate($this->parser->parse($name), is_array($name) ? json_encode($name) : $name); } /**
[TwigBundle] fixed error messages when an error occurs during template compilation
symfony_symfony
train
af93f161a95f55c009cbd1265ff31f021aa0b866
diff --git a/raven/utils/stacks.py b/raven/utils/stacks.py index <HASH>..<HASH> 100644 --- a/raven/utils/stacks.py +++ b/raven/utils/stacks.py @@ -55,6 +55,9 @@ def get_lines_from_file(filename, lineno, context_lines, loader=None, module_nam except (OSError, IOError): pass + if source is None: + return None, None, None + encoding = 'ascii' for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 @@ -65,9 +68,6 @@ def get_lines_from_file(filename, lineno, context_lines, loader=None, module_nam break source = [six.text_type(sline, encoding, 'replace') for sline in source] - if source is None: - return None, None, None - lower_bound = max(0, lineno - context_lines) upper_bound = min(lineno + 1 + context_lines, len(source))
Fixed a stack issue when there's no source file found.
getsentry_raven-python
train
e05f208781811ab496a43ed76a02e0b972c4436a
diff --git a/lib/dm-core/property.rb b/lib/dm-core/property.rb index <HASH>..<HASH> 100644 --- a/lib/dm-core/property.rb +++ b/lib/dm-core/property.rb @@ -765,7 +765,9 @@ module DataMapper # if the type can be found within DataMapper::Types then # use that class rather than the primitive - type = DataMapper::Types.find_const(type.name) + unless type.name.blank? + type = DataMapper::Types.find_const(type.name) + end unless TYPES.include?(type) || (DataMapper::Type > type && TYPES.include?(type.primitive)) raise ArgumentError, "+type+ was #{type.inspect}, which is not a supported type", caller
Only lookup the type if it the class has a name * Anonymous classes may not have a name, so do not look them up
datamapper_dm-core
train
33f2ea6aa487f43e486acd3e632b6acd73b739f6
diff --git a/tests/unit/test_unpack.py b/tests/unit/test_unpack.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_unpack.py +++ b/tests/unit/test_unpack.py @@ -155,12 +155,28 @@ def test_invite(): def test_channel_message_commands(): """ channel and message commands """ - cmds = ["RPL_TOPIC", "RPL_NOTOPIC", "RPL_ENDOFNAMES"] + cmds = ["RPL_TOPIC", "RPL_NOTOPIC", "RPL_ENDOFNAMES" ] expected_kwargs = {"channel": "#ch", "message": "m"} for command in cmds: message = command + " nick #ch :m" validate(command, message, expected_kwargs) +def test_who_reply(): + """ WHO response """ + command = 'WHOREPLY' + expected_kwargs = { "target": "#t", "channel": "#ch", "server": "srv", + "real_name": "rn", "host": "hst", + "nick": "nck", "hg_code":"H", + "hopcount": 27, "user": "usr" } + message = command + " #t #ch usr hst srv nck H :27 rn" + validate(command, message, expected_kwargs) + +def test_end_of_who_reply(): + command = "RPL_ENDOFWHO" + expected_kwargs = {"name": "#nm", "message": "m"} + message = command + " #nm :m" + validate(command, message, expected_kwargs) + def test_message_commands(): """ message-only commands """
Add unit tests for WHOREPLY and RPL_ENDOFWHO
numberoverzero_bottom
train
2925a9704a1ec81129fe2607c341191ad713bb06
diff --git a/ouimeaux/cli.py b/ouimeaux/cli.py index <HASH>..<HASH> 100644 --- a/ouimeaux/cli.py +++ b/ouimeaux/cli.py @@ -192,6 +192,9 @@ Usage: wemo maker NAME (on|off|toggle|sensor|switch)""" def on_motion(maker): return + + def on_bridge(maker): + return def on_maker(maker): if matches(maker.name): @@ -219,7 +222,7 @@ Usage: wemo maker NAME (on|off|toggle|sensor|switch)""" getattr(maker, state)() sys.exit(0) - scan(args, on_switch, on_motion, on_maker) + scan(args, on_switch, on_motion, on_bridge, on_maker) # If we got here, we didn't find anything print "No device found with that name." sys.exit(1)
Fix maker handling in CLI Maker handler was being passed to scan as bridge handler. Added no-op bridge handler similar to existing switch and motion handlers.
iancmcc_ouimeaux
train
43ebdc43cb7ad442a9f1d77561431940a2165055
diff --git a/example/index.js b/example/index.js index <HASH>..<HASH> 100644 --- a/example/index.js +++ b/example/index.js @@ -1,5 +1,5 @@ var tabs = TABS = require('../') -var autonode = require('autonode').inject(tabs) +var Autonode = require('autonode').inject(tabs) var Repred = require('repred') var h = require('h') @@ -24,20 +24,34 @@ var repred = Repred(function (value) { console.log(tabs) -autonode(function (stream) { - console.log('autonode - connect') - stream.pipe(repred.createStream()).pipe(stream) -}).listen('hi') +var autonode = + Autonode(function (stream) { + console.log('autonode - connect') + stream.pipe(repred.createStream()).pipe(stream) + }).listen('hi') -var input = h('input', {input: function () { - repred.update(input.value) - } -}) +var input, label + +document.body.appendChild( + h('div', + input = h('input', {input: function () { + repred.update(input.value) + } + }), + label = h('label', '(unconnected)') + ) +) repred.on('update', function (up) { -// if(input.value != up.val) + if(input.value != up.val) input.value = up.val }) -document.body.appendChild(input) +autonode + .on('listening', function () { + label.innerText = '(server)' + }) + .on('connecting', function () { + label.innerText = '(client)' + })
only update input if the value has changed (keeps cursor from jumping)
dominictarr_tab-stream
train
772ab8039beb10b5c2a8743015e2b7a37be8990b
diff --git a/views/js/qtiCreator/editor/blockAdder/blockAdder.js b/views/js/qtiCreator/editor/blockAdder/blockAdder.js index <HASH>..<HASH> 100644 --- a/views/js/qtiCreator/editor/blockAdder/blockAdder.js +++ b/views/js/qtiCreator/editor/blockAdder/blockAdder.js @@ -82,11 +82,13 @@ define([ }); //when clicking outside of the selector popup, consider it done - $itemEditorPanel.on(`click${_ns} mousedown${_ns}`, function(e){ - const popup = selector.getPopup()[0]; - if(popup !== e.target && !$.contains(popup, e.target)){ - _done($wrap); - } + $editorPanel.on('ready.qti-widget', function(e){ + $itemEditorPanel.off(`click${_ns} mousedown${_ns}`).on(`click${_ns} mousedown${_ns}`, function() { + const popup = selector.getPopup()[0]; + if(widget && widget.element && popup !== e.target && !$.contains(popup, e.target)){ + _done($wrap); + } + }); }); //select a default element type @@ -137,12 +139,14 @@ define([ //activate the new widget: _.defer(function(){ - if(widget.element.is('interaction')){ - widget.changeState('question'); - }else{ - widget.changeState('active'); + if(widget) { + if(widget.elemen && widget.element.is('interaction')){ + widget.changeState('question'); + }else{ + widget.changeState('active'); + } + _endInsertion(); } - _endInsertion(); }); }
fix: listen click outside after widget is ready
oat-sa_extension-tao-itemqti
train
ed0f44b89666dcb5b889cf7309c1470d8958bf0a
diff --git a/castWebApi.js b/castWebApi.js index <HASH>..<HASH> 100644 --- a/castWebApi.js +++ b/castWebApi.js @@ -76,11 +76,11 @@ prog console.log(value); }) .catch(error => { - if (error.stdout.includes("sudo env")) { + if (error.stdout && error.stdout.includes("sudo env")) { spinner.fail("Permissions required. To do this, just copy/paste and run this command:"); } else { spinner.fail(error.error.message); - console.error(error); + //console.error(error); } console.log(error.stdout); }); @@ -99,7 +99,7 @@ prog spinner.fail("Permissions required. To do this, just copy/paste and run this command:"); } else { spinner.fail(error.error.message); - console.error(error); + // console.error(error); } console.log(error.stdout); }); diff --git a/manager.js b/manager.js index <HASH>..<HASH> 100644 --- a/manager.js +++ b/manager.js @@ -1,3 +1,4 @@ +const fs = require('fs') const pm2 = require('pm2'); const { exec } = require('child_process'); @@ -60,9 +61,17 @@ class Manager { } static startup() { - let windows = process.platform === "win32"; - if (windows) return Manager.startupWin(); - else return Manager.startupPm2(); + return new Promise((resolve, reject) => { + let windows = process.platform === "win32"; + Manager.save(windows) + .then(() => { + if (windows) resolve(Manager.startupWin()); + else resolve(Manager.startupPm2()); + }) + .catch(error => { + reject({error: {message: "Couldn't save pm2 processes"}, stdout: "", stderr: error}); + }) + }) } static startupPm2() { @@ -81,13 +90,12 @@ class Manager { static startupWin() { return new Promise((resolve, reject) => { - let cmd = require.resolve('pm2-windows-service').replace('src/index.js', 'bin/pm2-service-install'); - exec(`${cmd}`, (error, stdout, stderr) => { - if (error || stderr) { - reject({error: error, stdout: stdout, stderr: stderr}); - } - resolve(stdout); - }); + let pm2WindowsStartupPath = require.resolve('pm2-windows-startup'); + Manager.fixWinResurrectBat(pm2WindowsStartupPath.replace('index.js', 'pm2_resurrect.cmd')) + .then(()=>{ + reject({error: {message: "Windows, to auto start, just copy/paste and run the command below: \n"}, stdout: `node ${pm2WindowsStartupPath} install`, stderr: ""}); + }) + .catch(error => {reject(error)}); }); } @@ -111,8 +119,16 @@ class Manager { static unstartupWin() { return new Promise((resolve, reject) => { - let cmd = require.resolve('pm2-windows-service').replace('src/index.js', 'bin/pm2-service-uninstall'); - exec(`${cmd}`, (error, stdout, stderr) => { + let cmd = `${require.resolve('pm2-windows-startup')} uninstall`; + reject({error: {message: "Windows, to stop auto start, just copy/paste and run the command below: \n"}, stdout: `node ${cmd}`, stderr: ""}); + }); + } + + static save(windows) { + return new Promise((resolve, reject) => { + let cmd = `${require.resolve('pm2').replace('index.js', 'bin/pm2')} save`; + if (windows) cmd = `node ${require.resolve('pm2').replace('index.js', 'bin\\pm2')} save`; + exec(cmd, (error, stdout, stderr) => { if (error || stderr) { reject({error: error, stdout: stdout, stderr: stderr}); } @@ -121,6 +137,26 @@ class Manager { }); } + static fixWinResurrectBat(resurrectBatPath) { + return new Promise((resolve, reject) => { + fs.readFile(resurrectBatPath, 'utf8', (err, data) => { + if (err) reject(err); //TODO: adapt to custom object format + + if (!data.includes('\\pm2')) { + let newPM2Path = `node ${require.resolve('pm2').replace('index.js', 'bin\\pm2')}`; + let newResurrectBat = data.replace('pm2', newPM2Path); + + fs.writeFile(resurrectBatPath, newResurrectBat, 'utf8', err => { + if (err) reject(err); //TODO: adapt to custom object format + else resolve(true); + }); + } else { + resolve(true); + } + }); + }); + } + static getProcessDescriptionList() { return new Promise((resolve, reject) => { Manager.isReady().then(ready => { diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ }, "optionalDependencies": { "google-assistant": "^0.5.2", - "pm2-windows-service": "0.2.1" + "pm2-windows-startup": "1.0.3" }, "repository": { "type": "git",
Updated: pm2 upstart - replaced service with pm2-windows-startup
vervallsweg_cast-web-api
train
0d95e4141ace7cc63f10c8428a76c47b98355b2f
diff --git a/src/com/backendless/FootprintsManager.java b/src/com/backendless/FootprintsManager.java index <HASH>..<HASH> 100644 --- a/src/com/backendless/FootprintsManager.java +++ b/src/com/backendless/FootprintsManager.java @@ -1,6 +1,7 @@ package com.backendless; import com.backendless.exceptions.BackendlessException; +import com.backendless.geo.GeoPoint; import weborb.reader.AnonymousObject; import weborb.reader.ArrayType; import weborb.reader.NamedObject; @@ -37,7 +38,9 @@ public class FootprintsManager public String getObjectId( Object entity ) { if( persistenceCache.containsKey( entity ) ) + { return getEntityFootprint( entity ).getObjectId(); + } return null; } @@ -45,7 +48,9 @@ public class FootprintsManager public String getMeta( Object entity ) { if( persistenceCache.containsKey( entity ) ) + { return getEntityFootprint( entity ).get__meta(); + } return null; } @@ -53,7 +58,9 @@ public class FootprintsManager public Date getCreated( Object entity ) { if( persistenceCache.containsKey( entity ) ) + { return getEntityFootprint( entity ).getCreated(); + } return null; } @@ -61,7 +68,9 @@ public class FootprintsManager public Date getUpdated( Object entity ) { if( persistenceCache.containsKey( entity ) ) + { return getEntityFootprint( entity ).getUpdated(); + } return null; } @@ -82,7 +91,9 @@ public class FootprintsManager String objectId = getObjectId( entity ); if( objectId != null ) + { entityMap.put( Footprint.OBJECT_ID_FIELD_NAME, objectId ); + } } //put __meta if exists in cache @@ -91,7 +102,9 @@ public class FootprintsManager String meta = getMeta( entity ); if( meta != null ) + { entityMap.put( Footprint.META_FIELD_NAME, meta ); + } } } @@ -99,15 +112,17 @@ public class FootprintsManager * When the object is created on server, client gets new instance of it. In order to remember the system fields * (objectId, __meta etc.) it is required to duplicate the old instance in cache. * - * @param serialized entity's map used to iterate through fields and duplicate footprints recursively - * @param persistedEntity entity from server - * @param initialEntity entity on which a method was called (.save(), .create() etc.) + * @param serialized entity's map used to iterate through fields and duplicate footprints recursively + * @param persistedEntity entity from server + * @param initialEntity entity on which a method was called (.save(), .create() etc.) */ void duplicateFootprintForObject( Map serialized, Object persistedEntity, Object initialEntity ) { //to avoid endless recursion if( marked.contains( persistedEntity ) ) + { return; + } else { marked.add( persistedEntity ); @@ -136,6 +151,12 @@ public class FootprintsManager } else if( entry.getValue() instanceof Collection ) { + // TODO: discuss and decide what to do with GeoPoints here + if( ((Collection) entry.getValue()).iterator().next() instanceof GeoPoint ) + { + continue; + } + // retrieve persisted entity's field value (which is collection) Field persistedEntityField = persistedEntity.getClass().getDeclaredField( (String) entry.getKey() ); persistedEntityField.setAccessible( true ); // in case the field is private @@ -191,9 +212,13 @@ public class FootprintsManager { //to avoid endless recursion if( marked.contains( newEntity ) ) + { return; + } else + { marked.add( newEntity ); + } try { @@ -312,9 +337,13 @@ public class FootprintsManager { //to avoid endless recursion if( marked.contains( entity ) ) + { return; + } else + { marked.add( entity ); + } try { @@ -380,9 +409,13 @@ public class FootprintsManager { //to avoid endless recursion if( marked.contains( entity ) ) + { return; + } else + { marked.add( entity ); + } try { @@ -407,7 +440,9 @@ public class FootprintsManager Object[] arrayInstance = instance instanceof List ? ((List) instance).toArray() : (Object[]) instance; for( int i = 0; i < arrayInstance.length; i++ ) + { putEntityFootprintToCache( arrayInstance[ i ], entities[ i ] ); + } } else {
Added temporary fix to handle GeoPoints in FootprintsManager.
Backendless_Android-SDK
train
57a7305843701d46e4fab000582cfbcac694d5bb
diff --git a/api/tests/test_build.py b/api/tests/test_build.py index <HASH>..<HASH> 100644 --- a/api/tests/test_build.py +++ b/api/tests/test_build.py @@ -62,6 +62,7 @@ class BuildTest(TestCase): body = {'image': 'autotest/example'} response = self.client.post(url, json.dumps(body), content_type='application/json') self.assertEqual(response.status_code, 201) + self.assertIn('x-deis-release', response._headers) build3 = response.data self.assertEqual(response.data['image'], body['image']) self.assertNotEqual(build2['uuid'], build3['uuid']) diff --git a/api/tests/test_config.py b/api/tests/test_config.py index <HASH>..<HASH> 100644 --- a/api/tests/test_config.py +++ b/api/tests/test_config.py @@ -51,6 +51,7 @@ class ConfigTest(TestCase): body = {'values': json.dumps({'NEW_URL1': 'http://localhost:8080/'})} response = self.client.post(url, json.dumps(body), content_type='application/json') self.assertEqual(response.status_code, 201) + self.assertIn('x-deis-release', response._headers) config2 = response.data self.assertNotEqual(config1['uuid'], config2['uuid']) self.assertIn('NEW_URL1', json.loads(response.data['values'])) diff --git a/api/views.py b/api/views.py index <HASH>..<HASH> 100644 --- a/api/views.py +++ b/api/views.py @@ -345,11 +345,16 @@ class AppBuildViewSet(BaseAppViewSet): model = models.Build serializer_class = serializers.BuildSerializer - def post_save(self, obj, created=False): + def post_save(self, build, created=False): if created: - release = obj.app.release_set.latest() - new_release = release.new(self.request.user, build=obj) - obj.app.deploy(new_release) + release = build.app.release_set.latest() + self.release = release.new(self.request.user, build=build) + build.app.deploy(self.release) + + def get_success_headers(self, data): + headers = super(AppBuildViewSet, self).get_success_headers(data) + headers.update({'X-Deis-Release': self.release.version}) + return headers def create(self, request, *args, **kwargs): app = get_object_or_404(models.App, id=self.kwargs['id']) @@ -372,11 +377,16 @@ class AppConfigViewSet(BaseAppViewSet): return app.release_set.latest().config raise PermissionDenied() - def post_save(self, obj, created=False): + def post_save(self, config, created=False): if created: - release = obj.app.release_set.latest() - new_release = release.new(self.request.user, config=obj) - obj.app.deploy(new_release) + release = config.app.release_set.latest() + self.release = release.new(self.request.user, config=config) + config.app.deploy(self.release) + + def get_success_headers(self, data): + headers = super(AppConfigViewSet, self).get_success_headers(data) + headers.update({'X-Deis-Release': self.release.version}) + return headers def create(self, request, *args, **kwargs): request._data = request.DATA.copy()
refactor(builder): improve build + config = release - add release version as header on build and config creation - provide dynamic output on build/config CLI, including resulting release - add `deis push` CLI shortcut for builds:create
deis_controller-sdk-go
train
d466fed18d23195f59f412efad9c9d71cedb1595
diff --git a/vcs/utils/diffs.py b/vcs/utils/diffs.py index <HASH>..<HASH> 100644 --- a/vcs/utils/diffs.py +++ b/vcs/utils/diffs.py @@ -62,8 +62,10 @@ def get_gitdiff(filenode_old, filenode_new): old_raw_id = getattr(filenode_old.changeset, 'raw_id', '0' * 40) new_raw_id = getattr(filenode_new.changeset, 'raw_id', '0' * 40) - file_filter = match(filenode_old.changeset.repository.path, '', - [filenode_new.path]) + + root = filenode_new.changeset.repository.path + + file_filter = match(root, '', [filenode_new.path]) vcs_gitdiff = patch.diff(repo._repo, old_raw_id,
typo: changed to filenode_new in git diff
codeinn_vcs
train
bc92e190e040be69a2b77d03c426175d3139edac
diff --git a/src/Pingpong/Admin/Uploader/ImageUploader.php b/src/Pingpong/Admin/Uploader/ImageUploader.php index <HASH>..<HASH> 100644 --- a/src/Pingpong/Admin/Uploader/ImageUploader.php +++ b/src/Pingpong/Admin/Uploader/ImageUploader.php @@ -1,5 +1,6 @@ <?php namespace Pingpong\Admin\Uploader; +use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Input; use Intervention\Image\Facades\Image; @@ -68,6 +69,11 @@ class ImageUploader { return $this; } + public function getDestinationDirectory() + { + return dirname($this->getDestinationFile()); + } + /** * @param null $path * @return mixed @@ -76,6 +82,11 @@ class ImageUploader { { if ( ! is_null($path)) $this->path = $path; + if( ! is_dir($path = $this->getDestinationDirectory())) + { + File::makeDirectory($path, 0777, true); + } + $this->image->save($this->getDestinationFile()); return $this->filename;
Auto create destination directory when upload photo if does not exist
pingpong-labs_admin
train
4502fa3cfcd6025ba434f8626102e56d09d95b7e
diff --git a/staging/src/k8s.io/client-go/tools/record/event.go b/staging/src/k8s.io/client-go/tools/record/event.go index <HASH>..<HASH> 100644 --- a/staging/src/k8s.io/client-go/tools/record/event.go +++ b/staging/src/k8s.io/client-go/tools/record/event.go @@ -270,7 +270,7 @@ func recordEvent(sink EventSink, event *v1.Event, patch []byte, updateExistingEv default: // This case includes actual http transport errors. Go ahead and retry. } - klog.Errorf("Unable to write event: '%v' (may retry after sleeping)", err) + klog.Errorf("Unable to write event: '%#v': '%v'(may retry after sleeping)", event, err) return false }
Improve ability to debug Events e2e failure
kubernetes_kubernetes
train
b980d6f53eb327f8e277efa071b3165230520388
diff --git a/cov_core.py b/cov_core.py index <HASH>..<HASH> 100644 --- a/cov_core.py +++ b/cov_core.py @@ -8,23 +8,8 @@ import sys import os -def multiprocessing_hook(): - try: - import multiprocessing.util - multiprocessing.util.register_after_fork(multiprocessing_start, - multiprocessing_start) - except ImportError: - pass - - def multiprocessing_start(obj): - cov = cov_core_init.init() - if cov: - import multiprocessing.util - multiprocessing.util.Finalize(None, - multiprocessing_finish, - args=(cov,), - exitpriority=1000) + cov_core_init.init() def multiprocessing_finish(cov): @@ -32,12 +17,19 @@ def multiprocessing_finish(cov): cov.save() +try: + import multiprocessing.util + multiprocessing.util.register_after_fork(multiprocessing_start, + multiprocessing_start) +except ImportError: + pass + + class CovController(object): """Base class for different plugin implementations.""" def __init__(self, cov_source, cov_report, cov_config, config=None, nodeid=None): """Get some common config used by multiple derived classes.""" - self.cov_source = cov_source self.cov_report = cov_report self.cov_config = cov_config @@ -56,7 +48,6 @@ class CovController(object): os.environ['COV_CORE_SOURCE'] = UNIQUE_SEP.join(self.cov_source) os.environ['COV_CORE_DATA_FILE'] = self.cov_data_file os.environ['COV_CORE_CONFIG'] = self.cov_config - multiprocessing_hook() @staticmethod def unset_env(): diff --git a/cov_core_init.py b/cov_core_init.py index <HASH>..<HASH> 100644 --- a/cov_core_init.py +++ b/cov_core_init.py @@ -14,8 +14,11 @@ that code coverage is being collected we activate coverage based on info passed via env vars. """ + UNIQUE_SEP = '084031f3d2994d40a88c8b699b69e148' +import cov_core + def init(): @@ -55,7 +58,14 @@ def init(): cov.erase() cov.start() - return cov + try: + import multiprocessing.util + multiprocessing.util.Finalize(None, + cov_core.multiprocessing_finish, + args=(cov,), + exitpriority=1000) + except ImportError: + pass except Exception: pass
Fixed multiprocessing_hook on Windows.
pytest-dev_pytest-cov
train
04765bb11cbadf22ed01ea12cb6f2834e9ee1ec5
diff --git a/plumbing/transport/common.go b/plumbing/transport/common.go index <HASH>..<HASH> 100644 --- a/plumbing/transport/common.go +++ b/plumbing/transport/common.go @@ -187,6 +187,7 @@ func (e urlEndpoint) Path() string { type scpEndpoint struct { user string host string + port string path string } @@ -194,8 +195,14 @@ func (e *scpEndpoint) Protocol() string { return "ssh" } func (e *scpEndpoint) User() string { return e.user } func (e *scpEndpoint) Password() string { return "" } func (e *scpEndpoint) Host() string { return e.host } -func (e *scpEndpoint) Port() int { return 22 } func (e *scpEndpoint) Path() string { return e.path } +func (e *scpEndpoint) Port() int { + i, err := strconv.Atoi(e.port) + if err != nil { + return 22 + } + return i +} func (e *scpEndpoint) String() string { var user string @@ -220,7 +227,7 @@ func (e *fileEndpoint) String() string { return e.path } var ( isSchemeRegExp = regexp.MustCompile(`^[^:]+://`) - scpLikeUrlRegExp = regexp.MustCompile(`^(?:(?P<user>[^@]+)@)?(?P<host>[^:\s]+):(?P<path>[^\\].*)$`) + scpLikeUrlRegExp = regexp.MustCompile(`^(?:(?P<user>[^@]+)@)?(?P<host>[^:\s]+):(?:(?P<port>[0-9]+):)?(?P<path>[^\\].*)$`) ) func parseSCPLike(endpoint string) (Endpoint, bool) { @@ -232,7 +239,8 @@ func parseSCPLike(endpoint string) (Endpoint, bool) { return &scpEndpoint{ user: m[1], host: m[2], - path: m[3], + port: m[3], + path: m[4], }, true } diff --git a/plumbing/transport/common_test.go b/plumbing/transport/common_test.go index <HASH>..<HASH> 100644 --- a/plumbing/transport/common_test.go +++ b/plumbing/transport/common_test.go @@ -74,6 +74,18 @@ func (s *SuiteCommon) TestNewEndpointSCPLike(c *C) { c.Assert(e.String(), Equals, "git@github.com:user/repository.git") } +func (s *SuiteCommon) TestNewEndpointSCPLikeWithPort(c *C) { + e, err := NewEndpoint("git@github.com:9999:user/repository.git") + c.Assert(err, IsNil) + c.Assert(e.Protocol(), Equals, "ssh") + c.Assert(e.User(), Equals, "git") + c.Assert(e.Password(), Equals, "") + c.Assert(e.Host(), Equals, "github.com") + c.Assert(e.Port(), Equals, 9999) + c.Assert(e.Path(), Equals, "user/repository.git") + c.Assert(e.String(), Equals, "git@github.com:user/repository.git") +} + func (s *SuiteCommon) TestNewEndpointFileAbs(c *C) { e, err := NewEndpoint("/foo.git") c.Assert(err, IsNil)
Adds port to SCP Endpoints The port for SCP-like URLs was hardcoded to <I>. This commit modifies the regex to find a port (optional), and adds a new test case that covers this scenario.
src-d_go-git
train
11f4d70cf534ab71f99b44ed7c290b4edee9a0d9
diff --git a/src/Container.php b/src/Container.php index <HASH>..<HASH> 100644 --- a/src/Container.php +++ b/src/Container.php @@ -31,6 +31,33 @@ class Container implements ContainerInterface { } /** + * Deep clone rules. + */ + public function __clone() { + $this->rules = $this->arrayClone($this->rules); + $this->rule($this->currentRuleName); + } + + /** + * Deep clone an array. + * + * @param array $array The array to clone. + * @return array Returns the cloned array. + * @see http://stackoverflow.com/a/17729234 + */ + private function arrayClone(array $array) { + return array_map(function ($element) { + return ((is_array($element)) + ? $this->arrayClone($element) + : ((is_object($element)) + ? clone $element + : $element + ) + ); + }, $array); + } + + /** * Normalize a container entry ID. * * @param string $id The ID to normalize. diff --git a/tests/ContainerTest.php b/tests/ContainerTest.php index <HASH>..<HASH> 100644 --- a/tests/ContainerTest.php +++ b/tests/ContainerTest.php @@ -356,4 +356,23 @@ class ContainerTest extends TestBase { $this->assertFalse($dic->has(self::DB_INTERFACE)); } + + /** + * Test cloning with rules. + */ + public function testCloning() { + $dic = $dic = new Container(); + $dic->rule(self::DB) + ->setShared(true); + + $dic2 = clone $dic; + $dic2->rule(self::DB) + ->setConstructorArgs(['foo']); + + $db1 = $dic->get(self::DB); + $db2 = $dic2->get(self::DB); + + $this->assertNotSame($db1, $db2); + $this->assertNotSame('foo', $db1->name); + } }
Deep copy rules when cloning (#<I>)
vanilla_garden-container
train
da56abd1530ce85640479a6b6cf292009891a0f5
diff --git a/status.go b/status.go index <HASH>..<HASH> 100644 --- a/status.go +++ b/status.go @@ -26,7 +26,7 @@ func (s Status) IsUntracked(path string) bool { return ok && stat.Worktree == Untracked } -// IsClean returns true if all the files aren't in Unmodified status. +// IsClean returns true if all the files are in Unmodified status. func (s Status) IsClean() bool { for _, status := range s { if status.Worktree != Unmodified || status.Staging != Unmodified {
git: Fix Status.IsClean() documentation The documentation of the IsClean Method contained a negation, so it was describing the opposite of its actual behavior. Fixes #<I>
src-d_go-git
train
f614a8230c84a505597de0bd6380e5e2fea117ea
diff --git a/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java b/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java index <HASH>..<HASH> 100644 --- a/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java +++ b/web/src/main/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapper.java @@ -107,8 +107,8 @@ public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequest if (auth.getPrincipal() instanceof UserDetails) { return ((UserDetails) auth.getPrincipal()).getUsername(); } - if (auth.getPrincipal() instanceof AbstractAuthenticationToken) { - return ((AbstractAuthenticationToken) auth.getPrincipal()).getName(); + if (auth instanceof AbstractAuthenticationToken) { + return auth.getName(); } return auth.getPrincipal().toString(); }
Polish getRemoteUser - Corrected instanceof check Issue gh-<I>
spring-projects_spring-security
train
24946fef189eb6f21792cb3dcf93ae236f7611f4
diff --git a/salt/renderers/gpg.py b/salt/renderers/gpg.py index <HASH>..<HASH> 100644 --- a/salt/renderers/gpg.py +++ b/salt/renderers/gpg.py @@ -247,12 +247,18 @@ def _get_key_dir(): gpg_keydir = None if 'config.get' in __salt__: gpg_keydir = __salt__['config.get']('gpg_keydir') + if not gpg_keydir: - gpg_keydir = __opts__.get('gpg_keydir') - if not gpg_keydir and 'config_dir' in __opts__: - gpg_keydir = os.path.join(__opts__['config_dir'], 'gpgkeys') - else: - gpg_keydir = os.path.join(os.path.split(__opts__['conf_file'])[0], 'gpgkeys') + gpg_keydir = __opts__.get( + 'gpg_keydir', + os.path.join( + __opts__.get( + 'config_dir', + os.path.dirname(__opts__['conf_file']), + ), + 'gpgkeys' + )) + return gpg_keydir
gpg renderer: fix gpg_keydir always reverting to default
saltstack_salt
train
764c1bfe8193d6e023b356cd542b42f3b0896816
diff --git a/packages/babili/src/index.js b/packages/babili/src/index.js index <HASH>..<HASH> 100644 --- a/packages/babili/src/index.js +++ b/packages/babili/src/index.js @@ -2,8 +2,24 @@ import { transformFromAst } from "babel-core"; import * as t from "babel-types"; -const babiliPreset = require.resolve("babel-preset-babili"); - +const plugins = [ + "babel-plugin-minify-constant-folding", + // This plugin does not yet work correctly with classes and ES6 exports. + // "babel-plugin-minify-dead-code-elimination", + "babel-plugin-minify-flip-comparisons", + "babel-plugin-minify-guarded-expressions", + "babel-plugin-minify-infinity", + "babel-plugin-minify-mangle-names", + "babel-plugin-minify-replace", + "babel-plugin-minify-simplify", + "babel-plugin-minify-type-constructors", + "babel-plugin-transform-member-expression-literals", + "babel-plugin-transform-merge-sibling-variables", + "babel-plugin-transform-minify-booleans", + "babel-plugin-transform-property-literals", + "babel-plugin-transform-simplify-comparison-operators", + "babel-plugin-transform-undefined-to-void" +].map(require.resolve.bind(require)); export default function () { return (override, transform) => { @@ -11,7 +27,7 @@ export default function () { const config = { code: false, ast: true, - presets: [ babiliPreset ] + plugins }; const programWrapper = t.program([ bundleAst ]);
Disable `babel-plugin-minify-dead-code-elimination` until it stabilizes.
interlockjs_plugins
train
9b0277738fd235c35a550fc47cf39f675756762a
diff --git a/lib/pkgr/addon.rb b/lib/pkgr/addon.rb index <HASH>..<HASH> 100644 --- a/lib/pkgr/addon.rb +++ b/lib/pkgr/addon.rb @@ -45,13 +45,13 @@ module Pkgr end end - def install!(package_name) + def install!(package_name, src_dir) install_addon = Mixlib::ShellOut.new %{curl -L --max-redirs 3 --retry 5 -s '#{tarball_url}' | tar xzf - --strip-components=1 -C '#{dir}'} install_addon.logger = Pkgr.logger install_addon.run_command install_addon.error! - compile_addon = Mixlib::ShellOut.new %{#{dir}/bin/compile '#{package_name}'} + compile_addon = Mixlib::ShellOut.new %{#{dir}/bin/compile '#{package_name}' '#{src_dir}'} compile_addon.logger = Pkgr.logger compile_addon.run_command compile_addon.error! diff --git a/lib/pkgr/builder.rb b/lib/pkgr/builder.rb index <HASH>..<HASH> 100644 --- a/lib/pkgr/builder.rb +++ b/lib/pkgr/builder.rb @@ -140,7 +140,7 @@ module Pkgr def resolve_addon!(addon_name) addon = Addon.new(addon_name, addons_dir) - addon.install!(config.name) + addon.install!(config.name, source_dir) addon end
Pass app source dir to addon compile script.
crohr_pkgr
train
2c261b578ade199ab8795478bb970d9a70c90a15
diff --git a/src/Phimple/Container.php b/src/Phimple/Container.php index <HASH>..<HASH> 100644 --- a/src/Phimple/Container.php +++ b/src/Phimple/Container.php @@ -208,26 +208,31 @@ class Container implements \ArrayAccess, ContainerInterface /** * Extends a service definition. * - * @param string $name - * @param callable $callable + * @param string $name + * @param callable $callable + * @param boolean $strict * * @return callable * * @throws \InvalidArgumentException */ - public function extend($name, $callable) + public function extend($name, $callable, $strict = true) { if ( ! $this->services->has($name)) { - throw new \InvalidArgumentException(sprintf('Service "%s" is not defined.', $name)); + if ($strict) { + throw new \InvalidArgumentException(sprintf('Service "%s" is not defined.', $name)); + } else { + return false; + } } $factory = $this->services->get($name); - if (!is_object($factory) || !method_exists($factory, '__invoke')) { + if ( ! is_object($factory) || ! method_exists($factory, '__invoke')) { throw new \InvalidArgumentException(sprintf('Service "%s" does not contain an object definition.', $name)); } - if (!is_object($callable) || !method_exists($callable, '__invoke')) { + if ( ! is_object($callable) || ! method_exists($callable, '__invoke')) { throw new \InvalidArgumentException('Extension service definition is not a Closure or invokable object.'); }
Service extention is more flexible now.
strident_Phimple
train
70833d3a3ce693603f1734bfa5ef5d2ee77e284c
diff --git a/pkg/cmd/pulumi/about.go b/pkg/cmd/pulumi/about.go index <HASH>..<HASH> 100644 --- a/pkg/cmd/pulumi/about.go +++ b/pkg/cmd/pulumi/about.go @@ -604,7 +604,7 @@ func getNodeProgramDependencies(rootDir string, transitive bool) ([]programDepen if _, err = os.Stat(yarnFile); err == nil { ex, err = executable.FindExecutable("yarn") if err != nil { - return nil, errors.Wrapf(err, "Found %s but not yarn", yarnFile) + return nil, errors.Wrapf(err, "Found %s but not %s", yarnFile, ex) } cmdArgs := []string{"list", "--json"} cmd := exec.Command(ex, cmdArgs...) diff --git a/sdk/go/common/util/executable/executable.go b/sdk/go/common/util/executable/executable.go index <HASH>..<HASH> 100644 --- a/sdk/go/common/util/executable/executable.go +++ b/sdk/go/common/util/executable/executable.go @@ -17,9 +17,20 @@ const unableToFindProgramTemplate = "unable to find program: %s" // FindExecutable attempts to find the needed executable in various locations on the // filesystem, eventually resorting to searching in $PATH. func FindExecutable(program string) (string, error) { + var err error + var ex string if runtime.GOOS == "windows" && !strings.HasSuffix(program, ".exe") { - program = fmt.Sprintf("%s.exe", program) + exe := fmt.Sprintf("%s.exe", program) + ex, err = findExecutableNoExe(exe) + if err != nil { + return ex, nil + } } + return findExecutableNoExe(program) +} + +func findExecutableNoExe(program string) (string, error) { + // look in the same directory cwd, err := os.Getwd() if err != nil { diff --git a/tests/integration/integration_nodejs_test.go b/tests/integration/integration_nodejs_test.go index <HASH>..<HASH> 100644 --- a/tests/integration/integration_nodejs_test.go +++ b/tests/integration/integration_nodejs_test.go @@ -1147,13 +1147,6 @@ func TestAboutNodeJS(t *testing.T) { } }() e.ImportDirectory(dir) - if runtime.GOOS == WindowsOS { - // Because there is a package-lock.json file, and we delete the yarn - // file, pulumi will use the package-lock file for the about. - assert.NoError(t, os.Remove(filepath.Join(e.RootPath, "yarn.lock")), - "removing yarn.lock") - } - e.RunCommand("yarn", "link", "@pulumi/pulumi") e.RunCommand("yarn", "install") e.RunCommand("pulumi", "login", "--cloud-url", e.LocalURL())
Allow windows to find commands without .exe
pulumi_pulumi
train
42feb8dff63cecd7bac4278e8a271369d573de8a
diff --git a/lib/Cake/Test/Case/View/Helper/FormHelperTest.php b/lib/Cake/Test/Case/View/Helper/FormHelperTest.php index <HASH>..<HASH> 100644 --- a/lib/Cake/Test/Case/View/Helper/FormHelperTest.php +++ b/lib/Cake/Test/Case/View/Helper/FormHelperTest.php @@ -7092,7 +7092,7 @@ class FormHelperTest extends CakeTestCase { ), 'input' => array('type' => 'hidden', 'name' => '_method', 'value' => 'POST'), '/form', - 'a' => array('class' => 'btn btn-danger', 'href' => '#', 'onclick' => 'preg:/if \(confirm\(\'Confirm thing\'\)\) \{ document\.post_\w+\.submit\(\); \} event\.returnValue = false; return false;/'), + 'a' => array('class' => 'btn btn-danger', 'href' => '#', 'onclick' => 'preg:/if \(confirm\(\&quot\;Confirm thing\&quot\;\)\) \{ document\.post_\w+\.submit\(\); \} event\.returnValue = false; return false;/'), '/a' )); }
Fix failing test. Quote encoding in confirm handlers has changed in <I>. Update the relevant test.
cakephp_cakephp
train
79b828ea9df02dd848323870277789715650faf9
diff --git a/src/Operation/Update.php b/src/Operation/Update.php index <HASH>..<HASH> 100644 --- a/src/Operation/Update.php +++ b/src/Operation/Update.php @@ -54,7 +54,7 @@ class Update implements Executable, Explainable private static $wireVersionForDocumentLevelValidation = 4; /** @var integer */ - private static $wireVersionForHint = 8; + private static $wireVersionForHintServerSideError = 5; /** @var string */ private $databaseName; @@ -202,7 +202,10 @@ class Update implements Executable, Explainable throw UnsupportedException::collationNotSupported(); } - if (isset($this->options['hint']) && ! server_supports_feature($server, self::$wireVersionForHint)) { + /* Server versions >= 3.4.0 raise errors for unknown update + * options. For previous versions, the CRUD spec requires a client-side + * error. */ + if (isset($this->options['hint']) && ! server_supports_feature($server, self::$wireVersionForHintServerSideError)) { throw UnsupportedException::hintNotSupported(); }
Rework client-side error logic for hints in updates
mongodb_mongo-php-library
train
6fd704fbfaa3509bbdc10465fca273ace8f4f025
diff --git a/telemetry/telemetry/android_browser_finder.py b/telemetry/telemetry/android_browser_finder.py index <HASH>..<HASH> 100644 --- a/telemetry/telemetry/android_browser_finder.py +++ b/telemetry/telemetry/android_browser_finder.py @@ -81,11 +81,13 @@ def FindAllAvailableBrowsers(options, logging=real_logging): logging.warn(' adb kill-server') logging.warn(' sudo `which adb` devices\n\n') except OSError: - if sys.platform.startswith('linux'): - os.environ['PATH'] = os.pathsep.join([ - os.path.join(os.path.dirname(__file__), - '../../../third_party/android_tools/sdk/platform-tools'), - os.environ['PATH']]) + platform_tools_path = os.path.join( + os.path.dirname(__file__), '..', '..', '..', + 'third_party', 'android_tools', 'sdk', 'platform-tools') + if (sys.platform.startswith('linux') and + os.path.exists(os.path.join(platform_tools_path, 'adb'))): + os.environ['PATH'] = os.pathsep.join([platform_tools_path, + os.environ['PATH']]) else: logging.info('No adb command found. ' + 'Will not try searching for Android browsers.')
[Telemetry] Only add android_tools' adb to the path if it exists. This directory is only checked out when target_os=['android']. So we can't assume that adb will always be in the chrome checkout. TBR=<EMAIL> BUG=None TEST=./tools/perf/run_multipage_benchmarks --browser=list Review URL: <URL>
catapult-project_catapult
train
3813211c19505bb0a0f3f59989ebf6f6a991e016
diff --git a/src/renderer.js b/src/renderer.js index <HASH>..<HASH> 100644 --- a/src/renderer.js +++ b/src/renderer.js @@ -8,8 +8,11 @@ class Renderer { } async createPage(url, options = {}) { - const { timeout, waitUntil, credentials } = options + const { timeout, waitUntil, credentials, emulateMedia } = options const page = await this.browser.newPage() + if (emulateMedia) { + await page.emulateMedia(emulateMedia); + } if (credentials) { await page.authenticate(credentials) @@ -40,7 +43,7 @@ class Renderer { let page = null try { const { timeout, waitUntil, credentials, ...extraOptions } = options - page = await this.createPage(url, { timeout, waitUntil, credentials }) + page = await this.createPage(url, { timeout, waitUntil, credentials, emulateMedia: 'print' }) const { scale = 1.0, displayHeaderFooter, printBackground, landscape } = extraOptions const buffer = await page.pdf({
media=print for pdf creation (#<I>) page.emulateMedia('print') for PDF creation to make sure all assets that are only visible in print-css are loaded
zenato_puppeteer-renderer
train
7e4d154b430f0a3cb845d15b1499b63afb0d1de6
diff --git a/src/MultiSelect/MultiSelect.js b/src/MultiSelect/MultiSelect.js index <HASH>..<HASH> 100644 --- a/src/MultiSelect/MultiSelect.js +++ b/src/MultiSelect/MultiSelect.js @@ -26,12 +26,15 @@ export const PROPERTY_TYPES = { showSearch: PropTypes.bool, showClear: PropTypes.bool, - popupHeader: PropTypes.bool + popupHeader: PropTypes.bool, + + selectedOnTop: PropTypes.bool }; const DEFAULT_PROPS = { placeholder: 'Select...', searchPlaceholder: 'Search ...', getText: selectedOptions => `${selectedOptions.length} item(s) selected`, + selectedOnTop: true, disabled: false }; @@ -156,6 +159,7 @@ class MultiSelect extends React.Component { </Popup> <MultiSelectPopup + selectedOnTop={this.props.selectedOnTop} showSearch={this.props.showSearch} showClear={this.props.showClear} popupHeader={this.props.popupHeader} diff --git a/src/MultiSelect/MultiSelectPopup.js b/src/MultiSelect/MultiSelectPopup.js index <HASH>..<HASH> 100644 --- a/src/MultiSelect/MultiSelectPopup.js +++ b/src/MultiSelect/MultiSelectPopup.js @@ -23,6 +23,7 @@ const PROPERTY_TYPES = { compare: PropTypes.func, showSearch: PropTypes.bool, showClear: PropTypes.bool, + selectedOnTop: PropTypes.bool, popupHeader: PropTypes.element }; const DEFAULT_PROPS = { @@ -30,7 +31,8 @@ const DEFAULT_PROPS = { compare: compare, showSearch: true, showClear: true, - popupHeader: null + popupHeader: null, + selectedOnTop: true }; class MultiSelectPopup extends React.Component { @@ -55,7 +57,9 @@ class MultiSelectPopup extends React.Component { getAllSorted() { let result = this.props.options.slice(0); - result.sort(this._sortSelectedOnTop); + if(this.props.selectedOnTop){ + result.sort(this._sortSelectedOnTop); + } return result; } @@ -149,7 +153,9 @@ class MultiSelectPopup extends React.Component { this.resetNav(); let filtered = trim(value).length === 0 ? this.props.options : this.fuse.search(value); - filtered.sort(this._sortSelectedOnTop); + if(this.props.selectedOnTop) { + filtered.sort(this._sortSelectedOnTop); + } this.setState({ filtered: filtered, @@ -160,7 +166,7 @@ class MultiSelectPopup extends React.Component { resetSearch = (options = this.props.options) => { this.resetNav(); this.setState({ - filtered: options.sort(this._sortSelectedOnTop), + filtered: this.props.selectedOnTop ? options.sort(this._sortSelectedOnTop) : options, query: '' }); }; diff --git a/src/TreeSelect/TreeSelect.js b/src/TreeSelect/TreeSelect.js index <HASH>..<HASH> 100644 --- a/src/TreeSelect/TreeSelect.js +++ b/src/TreeSelect/TreeSelect.js @@ -87,6 +87,7 @@ export class TreeSelectRaw extends React.Component { return ( <MultiSelect {...this.props} + selectedOnTop={false} value={this.state.selected} options={this.options} renderOptions={this.renderOptions} diff --git a/src/index.d.ts b/src/index.d.ts index <HASH>..<HASH> 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -120,23 +120,26 @@ declare namespace __RosemaryUI { class MonthPickerPopup extends React.Component<any> {} type MultiSelectProps = { + disabled?: boolean; + placeholder?: string; + searchPlaceholder?: string; + options: { id: number; displayString: string; }[]; + + className?: string; onChange: (value: number) => any; value: number[]; - - getText?: (...any) => React.ReactNode; handleTooltipStateChange?: (...any) => any; - className?: string; - disabled?: boolean; - placeholder?: string; - searchPlaceholder?: string; - compare?: (a: any, b: any) => any; + getText?: (...any) => React.ReactNode; + showSearch?: boolean; showClear?: boolean; popupHeader?: React.ReactNode; + + selectedOnTop?: boolean; }; class MultiSelect extends React.Component<MultiSelectProps> {}
Multiselect move sorting to props as optional - fixes when sorting breaks tree list
ctco_rosemary-ui
train
c3fb469119f4b2fbd465809f05ab589b8fcc35f0
diff --git a/src/main/java/com/github/bedrin/jdbc/sniffer/Sniffer.java b/src/main/java/com/github/bedrin/jdbc/sniffer/Sniffer.java index <HASH>..<HASH> 100755 --- a/src/main/java/com/github/bedrin/jdbc/sniffer/Sniffer.java +++ b/src/main/java/com/github/bedrin/jdbc/sniffer/Sniffer.java @@ -128,7 +128,27 @@ public class Sniffer { reset(); } - public static RecordedQueries recordQueries(Runnable runnable) { + public static interface Executable { + void execute() throws Exception; + } + + public static RecordedQueries execute(Executable executable) { + int queries = executedStatements(); + int tlQueries = ThreadLocalSniffer.executedStatements(); + int otQueries = OtherThreadsSniffer.executedStatements(); + try { + executable.execute(); + } catch (Exception e) { + throw new RuntimeException(e); + } + return new RecordedQueries( + executedStatements() - queries, + ThreadLocalSniffer.executedStatements() - tlQueries, + OtherThreadsSniffer.executedStatements() - otQueries + ); + } + + public static RecordedQueries run(Runnable runnable) { int queries = executedStatements(); int tlQueries = ThreadLocalSniffer.executedStatements(); int otQueries = OtherThreadsSniffer.executedStatements(); @@ -140,12 +160,12 @@ public class Sniffer { ); } - public static <T> RecordedQueriesWithValue<T> recordQueries(Callable<T> callable) throws Exception { + public static <T> RecordedQueriesWithValue<T> call(Callable<T> callable) throws Exception { int queries = executedStatements(); int tlQueries = ThreadLocalSniffer.executedStatements(); int otQueries = OtherThreadsSniffer.executedStatements(); T value = callable.call(); - return new RecordedQueriesWithValue<T>( + return new RecordedQueriesWithValue<>( value, executedStatements() - queries, ThreadLocalSniffer.executedStatements() - tlQueries, diff --git a/src/test/java/com/github/bedrin/jdbc/sniffer/SnifferTest.java b/src/test/java/com/github/bedrin/jdbc/sniffer/SnifferTest.java index <HASH>..<HASH> 100755 --- a/src/test/java/com/github/bedrin/jdbc/sniffer/SnifferTest.java +++ b/src/test/java/com/github/bedrin/jdbc/sniffer/SnifferTest.java @@ -25,13 +25,13 @@ public class SnifferTest { @Test public void testRecordQueriesPositive() throws Exception { - Sniffer.recordQueries(Sniffer::executeStatement).verifyNotMoreThanOne(); + Sniffer.run(Sniffer::executeStatement).verifyNotMoreThanOne(); } @Test public void testRecordQueriesNegative() throws Exception { try { - Sniffer.recordQueries(Sniffer::executeStatement).verifyNotMore(); + Sniffer.run(Sniffer::executeStatement).verifyNotMore(); fail(); } catch (IllegalStateException e) { assertNotNull(e); @@ -40,22 +40,18 @@ public class SnifferTest { @Test public void testRecordQueriesThreadLocalPositive() throws Exception { - Sniffer.recordQueries(() -> { + Sniffer.execute(() -> { Sniffer.executeStatement(); Thread thread = new Thread(Sniffer::executeStatement); thread.start(); - try { - thread.join(); - } catch (InterruptedException e) { - fail(e.getMessage()); - } + thread.join(); }).verifyNotMoreThanOneThreadLocal(); } @Test public void testRecordQueriesThreadLocalNegative() throws Exception { try { - Sniffer.recordQueries(Sniffer::executeStatement).verifyNotMoreThreadLocal(); + Sniffer.run(Sniffer::executeStatement).verifyNotMoreThreadLocal(); fail(); } catch (IllegalStateException e) { assertNotNull(e); @@ -64,24 +60,22 @@ public class SnifferTest { @Test public void testRecordQueriesOtherThreadsPositive() throws Exception { - Sniffer.recordQueries(() -> { + Sniffer.execute(() -> { Sniffer.executeStatement(); Thread thread = new Thread(Sniffer::executeStatement); thread.start(); thread.join(); - return null; }).verifyNotMoreThanOneOtherThreads(); } @Test public void testRecordQueriesOtherThreadsNegative() throws Exception { try { - Sniffer.recordQueries(() -> { + Sniffer.execute(() -> { Sniffer.executeStatement(); Thread thread = new Thread(Sniffer::executeStatement); thread.start(); thread.join(); - return null; }).verifyNotMoreOtherThreads(); fail(); } catch (IllegalStateException e) {
Added new method which allows throwing exceptions inside callback API
sniffy_sniffy
train
86543118f9646728447d3fdfc44b58a3ce951ed7
diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/BuildCommandExecutor.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/BuildCommandExecutor.java index <HASH>..<HASH> 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/BuildCommandExecutor.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/BuildCommandExecutor.java @@ -204,7 +204,7 @@ public class BuildCommandExecutor extends CommandExecutor { Path repeatsFilesDir = input.resolve(EtlCommons.REPEATS_FOLDER); copyVersionFiles(Arrays.asList(repeatsFilesDir.resolve(EtlCommons.TRF_VERSION_FILE))); // TODO: chunk size is not really used in ConvervedRegionParser, remove? - CellBaseFileSerializer serializer = new CellBaseJsonFileSerializer(output); + CellBaseFileSerializer serializer = new CellBaseJsonFileSerializer(output, EtlCommons.REPEATS_JSON); return new RepeatsParser(repeatsFilesDir, serializer); } diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/EtlCommons.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/EtlCommons.java index <HASH>..<HASH> 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/EtlCommons.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/EtlCommons.java @@ -48,6 +48,7 @@ public class EtlCommons { public static final String TRF_FILE = "simpleRepeat.txt.gz"; public static final String TRF_VERSION_FILE = "clinvarVersion.json"; public static final String REPEATS_FOLDER = "repeats"; + public static final String REPEATS_JSON = "repeats"; public static boolean runCommandLineProcess(File workingDirectory, String binPath, List<String> args, String logFilePath) diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/transform/RepeatsParser.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/transform/RepeatsParser.java index <HASH>..<HASH> 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/transform/RepeatsParser.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/transform/RepeatsParser.java @@ -10,7 +10,6 @@ import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.concurrent.Callable; /** * Created by fjlopez on 05/05/17. @@ -41,8 +40,9 @@ public class RepeatsParser extends CellBaseParser { try (BufferedReader bufferedReader = FileUtils.newBufferedReader(filePath)) { String line = bufferedReader.readLine(); - Callable<Long> callable = () -> 200L; - ProgressLogger progressLogger = new ProgressLogger("Parsed TRF lines:", callable, 300); + // ProgressLogger progressLogger = new ProgressLogger("Parsed TRF lines:"); + ProgressLogger progressLogger = new ProgressLogger("Parsed TRF lines:", () -> countFileLines(filePath), 200) + .setBatchSize(10000); while (line != null) { serializer.serialize(parseTrfLine(line)); line = bufferedReader.readLine(); @@ -51,6 +51,19 @@ public class RepeatsParser extends CellBaseParser { } } + private Long countFileLines(Path filePath) throws IOException { + try (BufferedReader bufferedReader1 = FileUtils.newBufferedReader(filePath)) { + long nLines = 0; + String line1 = bufferedReader1.readLine(); + while (line1 != null) { + nLines++; + line1 = bufferedReader1.readLine(); + } + return nLines; + } + + } + private Repeat parseTrfLine(String line) { String[] parts = line.split("\t");
feature-str: TRF parser ready
opencb_cellbase
train