hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
6a762b958a03404411135945836ec7569d896e2e
diff --git a/server/src/main/java/io/atomix/copycat/server/state/ServerSessionContext.java b/server/src/main/java/io/atomix/copycat/server/state/ServerSessionContext.java index <HASH>..<HASH> 100644 --- a/server/src/main/java/io/atomix/copycat/server/state/ServerSessionContext.java +++ b/server/src/main/java/io/atomix/copycat/server/state/ServerSessionContext.java @@ -233,7 +233,12 @@ class ServerSessionContext implements ServerSession { * @return The server session context. */ ServerSessionContext resetRequestSequence(long requestSequence) { - this.requestSequence = requestSequence; + // If the request sequence number is less than the applied sequence number, update the request + // sequence number. This is necessary to ensure that if the local server is a follower that is + // later elected leader, its sequences are consistent for commands. + if (requestSequence > this.requestSequence) { + this.requestSequence = requestSequence; + } return this; } @@ -272,14 +277,6 @@ class ServerSessionContext implements ServerSession { } } } - - // If the request sequence number is less than the applied sequence number, update the request - // sequence number. This is necessary to ensure that if the local server is a follower that is - // later elected leader, its sequences are consistent for commands. - if (sequence > requestSequence) { - this.requestSequence = sequence; - } - return this; }
Never allow the request sequence number to decrease.
atomix_copycat
train
0ede01fe69518e2948f6500ac9d830a6890457fd
diff --git a/test/slop_test.rb b/test/slop_test.rb index <HASH>..<HASH> 100644 --- a/test/slop_test.rb +++ b/test/slop_test.rb @@ -314,7 +314,7 @@ class SlopTest < TestCase end test "separators" do - opts = Slop.new(banner: false) do + opts = Slop.new(:banner => false) do on :foo separator "hello" separator "world"
avoid <I> specific syntax for tests
leejarvis_slop
train
9e13889cbc3f80bac2711cd5052c9dc0b8753788
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,8 +1,11 @@ -from distutils.core import setup +try: + from setuptools import setup +except ImportError: + from distutils.core import setup setup( name='sciunit', - version='0.1.3.4', + version='0.1.4', author='Rick Gerkin', author_email='rgerkin@asu.edu', packages=['sciunit', 'sciunit.tests'],
Updated version and switched to setuptools
scidash_sciunit
train
6c5b4f015814a6c4f6b33230dfd1a860aedc0aaf
diff --git a/lib/util/resolveCommand.js b/lib/util/resolveCommand.js index <HASH>..<HASH> 100644 --- a/lib/util/resolveCommand.js +++ b/lib/util/resolveCommand.js @@ -8,7 +8,7 @@ function resolveCommandAttempt(parsed, withoutPathExt) { const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined; + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd
fix: fix worker threads in Node >=<I> (#<I>)
moxystudio_node-cross-spawn
train
467a1c8845afea80b1307ae2ad9d7bcd3f18ed64
diff --git a/liquibase-core/src/main/java/liquibase/integration/commandline/CommandLineUtils.java b/liquibase-core/src/main/java/liquibase/integration/commandline/CommandLineUtils.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/integration/commandline/CommandLineUtils.java +++ b/liquibase-core/src/main/java/liquibase/integration/commandline/CommandLineUtils.java @@ -17,6 +17,8 @@ import liquibase.exception.DatabaseException; import liquibase.exception.LiquibaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.ExecutorService; +import liquibase.license.LicenseService; +import liquibase.license.LicenseServiceFactory; import liquibase.resource.ClassLoaderResourceAccessor; import liquibase.resource.ResourceAccessor; import liquibase.statement.core.RawSqlStatement; @@ -308,10 +310,24 @@ public class CommandLineUtils { banner.append(String.format( coreBundle.getString("starting.liquibase.at.timestamp"), dateFormat.format(calendar.getTime()) )); + if (StringUtils.isNotEmpty(myVersion) && StringUtils.isNotEmpty(buildTimeString)) { banner.append(String.format(coreBundle.getString("liquibase.version.builddate"), myVersion, buildTimeString)); } + + LicenseService licenseService = LicenseServiceFactory.getInstance().getLicenseService("PRO"); + if (licenseService != null) { + if (licenseService.licenseIsValid("PRO")) { + banner.append("Found valid LiquibasePro license"); + } + else { + banner.append("No valid LiquibasePro license"); + } + } else { + banner.append("No license service found"); + } + return banner.toString(); } diff --git a/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java b/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java +++ b/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java @@ -1096,15 +1096,6 @@ public class Main { } Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database); - LicenseService licenseService = LicenseServiceFactory.getInstance().getLicenseService("PRO"); - if (licenseService != null) { - if (licenseService.licenseIsValid("PRO")) { - LOG.info("Found valid LiquibasePro license"); - } - else { - LOG.info("No valid LiquibasePro license"); - } - } ChangeExecListener listener = ChangeExecListenerUtils.getChangeExecListener( liquibase.getDatabase(), liquibase.getResourceAccessor(), changeExecListenerClass, changeExecListenerPropertiesFile);
Move initial license check from Main.doMigration into CommandLineUtils.getBanner
liquibase_liquibase
train
45632876ca533b20ff57070768c0ed0a50c12b9b
diff --git a/src/renderers/canvas.js b/src/renderers/canvas.js index <HASH>..<HASH> 100644 --- a/src/renderers/canvas.js +++ b/src/renderers/canvas.js @@ -273,6 +273,8 @@ Physics.renderer('canvas', function( proto ){ hiddenCtx.restore(); view.src = hiddenCanvas.toDataURL("image/png"); + view.width = hiddenCanvas.width; + view.height = hiddenCanvas.height; return view; }, @@ -332,4 +334,4 @@ Physics.renderer('canvas', function( proto ){ } } }; -}); \ No newline at end of file +});
fix the problem that sometimes the body been rendered in the wrong position in ie<I> I don't know whether to add two temporary variables to store the values of "2 * hw + 2 + (2 * styles.lineWidth|0)" and "2 * hh + 2 + (2 * styles.lineWidth|0)",then assign them to hiddenCanvas.width,hiddenCanvas.height,view.width and view.height for improving a little performance.
wellcaffeinated_PhysicsJS
train
93322307e684ea4d43fd7fbd38dcf9419a09b0fa
diff --git a/lib/rubycritic/report_generators/turbulence.rb b/lib/rubycritic/report_generators/turbulence.rb index <HASH>..<HASH> 100644 --- a/lib/rubycritic/report_generators/turbulence.rb +++ b/lib/rubycritic/report_generators/turbulence.rb @@ -6,7 +6,7 @@ module Rubycritic def self.data(analysed_modules) analysed_modules.map do |analysed_module| { - :name => analysed_module.pathname, + :name => analysed_module.name, :x => analysed_module.churn, :y => analysed_module.complexity } diff --git a/test/lib/rubycritic/report_generators/turbulence_test.rb b/test/lib/rubycritic/report_generators/turbulence_test.rb index <HASH>..<HASH> 100644 --- a/test/lib/rubycritic/report_generators/turbulence_test.rb +++ b/test/lib/rubycritic/report_generators/turbulence_test.rb @@ -4,10 +4,10 @@ require "rubycritic/report_generators/turbulence" describe Rubycritic::Turbulence do describe "::data" do it "returns json data that maps pathname, churn and complexity to name, x and y" do - files = [AnalysedModuleDouble.new(:pathname => "./foo.rb", :churn => 1, :complexity => 2)] + files = [AnalysedModuleDouble.new(:name => "Foo", :churn => 1, :complexity => 2)] turbulence_data = Rubycritic::Turbulence.data(files) instance_parsed_json = JSON.parse(turbulence_data).first - instance_parsed_json["name"].must_equal "./foo.rb" + instance_parsed_json["name"].must_equal "Foo" instance_parsed_json["x"].must_equal 1 instance_parsed_json["y"].must_equal 2 end
Use a module's name instead of its pathname in the Turbulence graph
whitesmith_rubycritic
train
fc3a7b7a97a17f15a7862568d13defdde75df67d
diff --git a/collector/ntp.go b/collector/ntp.go index <HASH>..<HASH> 100644 --- a/collector/ntp.go +++ b/collector/ntp.go @@ -30,7 +30,8 @@ var ( ) type ntpCollector struct { - drift prometheus.Gauge + drift prometheus.Gauge + stratum prometheus.Gauge } func init() { @@ -53,6 +54,11 @@ func NewNtpCollector() (Collector, error) { Name: "ntp_drift_seconds", Help: "Time between system time and ntp time.", }), + stratum: prometheus.NewGauge(prometheus.GaugeOpts{ + Namespace: Namespace, + Name: "ntp_stratum", + Help: "NTP server stratum.", + }), }, nil } @@ -65,5 +71,10 @@ func (c *ntpCollector) Update(ch chan<- prometheus.Metric) (err error) { log.Debugf("Set ntp_drift_seconds: %f", driftSeconds) c.drift.Set(driftSeconds) c.drift.Collect(ch) - return err + + stratum := float64(resp.Stratum) + log.Debugf("Set ntp_stratum: %f", stratum) + c.stratum.Set(stratum) + c.stratum.Collect(ch) + return nil }
Add NTP stratum to NTP collector
prometheus_node_exporter
train
7b90ebbb64a523776e448eb91aa13dda190746da
diff --git a/api.php b/api.php index <HASH>..<HASH> 100644 --- a/api.php +++ b/api.php @@ -8302,6 +8302,34 @@ namespace Tqdev\PhpCrudApi\Middleware { } } +// file: src/Tqdev/PhpCrudApi/Middleware/SslRedirectMiddleware.php +namespace Tqdev\PhpCrudApi\Middleware { + + use Psr\Http\Message\ResponseInterface; + use Psr\Http\Message\ServerRequestInterface; + use Psr\Http\Server\RequestHandlerInterface; + use Tqdev\PhpCrudApi\Middleware\Base\Middleware; + use Tqdev\PhpCrudApi\ResponseFactory; + + class SslRedirectMiddleware extends Middleware + { + public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface + { + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + if ($scheme == 'http') { + $uri = $request->getUri(); + $uri = $uri->withScheme('https'); + $response = ResponseFactory::fromStatus(301); + $response = $response->withHeader('Location', $uri->__toString()); + } else { + $response = $next->handle($request); + } + return $response; + } + } +} + // file: src/Tqdev/PhpCrudApi/Middleware/ValidationMiddleware.php namespace Tqdev\PhpCrudApi\Middleware { @@ -10545,13 +10573,14 @@ namespace Tqdev\PhpCrudApi { use Tqdev\PhpCrudApi\Middleware\IpAddressMiddleware; use Tqdev\PhpCrudApi\Middleware\JoinLimitsMiddleware; use Tqdev\PhpCrudApi\Middleware\JwtAuthMiddleware; - use Tqdev\PhpCrudApi\Middleware\XmlMiddleware; use Tqdev\PhpCrudApi\Middleware\MultiTenancyMiddleware; use Tqdev\PhpCrudApi\Middleware\PageLimitsMiddleware; use Tqdev\PhpCrudApi\Middleware\ReconnectMiddleware; use Tqdev\PhpCrudApi\Middleware\Router\SimpleRouter; use Tqdev\PhpCrudApi\Middleware\SanitationMiddleware; + use Tqdev\PhpCrudApi\Middleware\SslRedirectMiddleware; use Tqdev\PhpCrudApi\Middleware\ValidationMiddleware; + use Tqdev\PhpCrudApi\Middleware\XmlMiddleware; use Tqdev\PhpCrudApi\Middleware\XsrfMiddleware; use Tqdev\PhpCrudApi\OpenApi\OpenApiService; use Tqdev\PhpCrudApi\Record\ErrorCode; @@ -10582,6 +10611,9 @@ namespace Tqdev\PhpCrudApi { $router = new SimpleRouter($config->getBasePath(), $responder, $cache, $config->getCacheTime(), $config->getDebug()); foreach ($config->getMiddlewares() as $middleware => $properties) { switch ($middleware) { + case 'sslRedirect': + new SslRedirectMiddleware($router, $responder, $properties); + break; case 'cors': new CorsMiddleware($router, $responder, $properties); break;
Add SslRedirectMiddleware to api.php for #<I>
mevdschee_php-crud-api
train
98b25a4f51c69c90713ab175a5f3be2526e16429
diff --git a/src/adapters/mocha-blanket.js b/src/adapters/mocha-blanket.js index <HASH>..<HASH> 100644 --- a/src/adapters/mocha-blanket.js +++ b/src/adapters/mocha-blanket.js @@ -47,9 +47,11 @@ //I dont know why these became global leaks runner.globals(['stats', 'failures', 'runner']); - originalReporter(runner); + originalReporter.call(this, runner); }; + blanketReporter.prototype = mocha._reporter.prototype; + mocha.reporter(blanketReporter); var oldRun = mocha.run, oldCallback = null;
New version of mocha requires suiteURL function that provides HTML runner - blanketRunner has to inherit from it
alex-seville_blanket
train
c0a9562c5a55d79b90546c455ee535dc2dbdc761
diff --git a/devassistant/assistants/yaml/sample_assistant.yaml.noload b/devassistant/assistants/yaml/sample_assistant.yaml.noload index <HASH>..<HASH> 100644 --- a/devassistant/assistants/yaml/sample_assistant.yaml.noload +++ b/devassistant/assistants/yaml/sample_assistant.yaml.noload @@ -53,6 +53,7 @@ c: # name of the assistant as will be used on commandline; should be the same as - else: - log_i: 'blahblah already exists' - log_i: 'Finished' + - run: run_misc # runs "run_misc" section here run_mock: # if mock parameter is specified, use this instead of "run" - cl_f: mock blah blah # "cl_f" runs the command in foreground, displaying its output interactively diff --git a/devassistant/assistants/yaml_assistant.py b/devassistant/assistants/yaml_assistant.py index <HASH>..<HASH> 100644 --- a/devassistant/assistants/yaml_assistant.py +++ b/devassistant/assistants/yaml_assistant.py @@ -80,17 +80,9 @@ class YamlAssistant(assistant_base.AssistantBase): logger.warning('Unknown dependency type {0}, skipping.'.format(dep_type)) def run(self, **kwargs): - # determine which run* section to invoke - to_run = self._run - for method in dir(self): - if method.startswith('_run_'): - parameter = method.split('_', 2)[-1] - if kwargs.get(parameter, False): - to_run = getattr(self, method) - + to_run = self._get_section_to_run(section='run', kwargs_override=True, **kwargs) self._run_one_section(to_run, **kwargs) - def _run_one_section(self, section, **kwargs): execute_else = False @@ -104,6 +96,9 @@ class YamlAssistant(assistant_base.AssistantBase): self._dot_devassistant_comm(comm_type, comm, **kwargs) elif comm_type == 'github': self._github_comm(comm_type, comm, **kwargs) + elif comm_type.startswith('run'): + s = self._get_section_to_run(section=comm, kwargs_override=False, **kwargs) + self._run_one_section(s, **kwargs) elif comm_type.startswith('if'): if self._evaluate_condition(comm_type[2:].strip(), **kwargs): self._run_one_section(comm) @@ -122,6 +117,25 @@ class YamlAssistant(assistant_base.AssistantBase): else: logger.warning('Unknown action type {0}, skipping.'.format(comm_type)) + def _get_section_to_run(self, section, kwargs_override=False, **kwargs): + to_run = None + + if section: + underscored = '_' + section + if underscored in dir(self): + to_run = getattr(self, underscored) + + if kwargs_override: + for method in dir(self): + if method.startswith('_run_'): + if kwargs.get(method[len('_run_'):], False): + to_run = getattr(self, method) + + if not to_run: + logger.warning('Couldn\'t find section {0} or any other appropriate.'.format(section)) + return to_run + + def _dot_devassistant_comm(self, comm_type, comm, **kwargs): if comm_type == 'dda_c': self._dot_devassistant_create(self._format(comm, **kwargs), **kwargs) diff --git a/test/assistants/test_yaml_assistant.py b/test/assistants/test_yaml_assistant.py index <HASH>..<HASH> 100644 --- a/test/assistants/test_yaml_assistant.py +++ b/test/assistants/test_yaml_assistant.py @@ -87,11 +87,17 @@ class TestYamlAssistant(object): self.ya.run() assert self.tlh.msgs == [('WARNING', 'Unknown action type foo, skipping.')] - def test_run_chooses_proper_method(self): + def test_get_section_to_run_chooses_selected(self): self.ya._run = [{'cl': 'ls'}] self.ya._run_foo = [{'cl': 'pwd'}] - flexmock(ClHelper).should_receive('run_command').with_args('pwd', False, False) - self.ya.run(foo='bar') + section = self.ya._get_section_to_run(section='run', kwargs_override=False, foo=True) + assert section is self.ya._run + + def test_get_section_to_run_overrides_if_allowed(self): + self.ya._run = [{'cl': 'ls'}] + self.ya._run_foo = [{'cl': 'pwd'}] + section = self.ya._get_section_to_run(section='run', kwargs_override=True, foo=True) + assert section is self.ya._run_foo def test_run_runs_in_foreground_if_asked(self): self.ya._run = [{'cl_f': 'ls'}]
Allow running run* section from another run* section. Fixes #<I>
devassistant_devassistant
train
cd440047eb4049aa35c614a3c9adebb72d777ad5
diff --git a/src/main/java/com/hubspot/jackson/datatype/protobuf/builtin/serializers/MessageSerializer.java b/src/main/java/com/hubspot/jackson/datatype/protobuf/builtin/serializers/MessageSerializer.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/hubspot/jackson/datatype/protobuf/builtin/serializers/MessageSerializer.java +++ b/src/main/java/com/hubspot/jackson/datatype/protobuf/builtin/serializers/MessageSerializer.java @@ -44,11 +44,7 @@ public class MessageSerializer extends ProtobufSerializer<MessageOrBuilder> { this(config, false); } - public MessageSerializer(ProtobufJacksonConfig config, boolean unwrappingSerializer) { - this(config, null, unwrappingSerializer); - } - - public MessageSerializer(ProtobufJacksonConfig config, NameTransformer nameTransformer, boolean unwrappingSerializer) { + private MessageSerializer(ProtobufJacksonConfig config, boolean unwrappingSerializer) { super(MessageOrBuilder.class); this.config = config; this.unwrappingSerializer = unwrappingSerializer; @@ -123,7 +119,7 @@ public class MessageSerializer extends ProtobufSerializer<MessageOrBuilder> { @Override public MessageSerializer unwrappingSerializer(NameTransformer nameTransformer) { - return new MessageSerializer(config, nameTransformer, true); + return new MessageSerializer(config, true); } private Function<FieldDescriptor, String> getPropertyNaming(Descriptor descriptor, SerializerProvider serializerProvider) {
Implemented review comments from jaher
HubSpot_jackson-datatype-protobuf
train
e46d506154e994565585729c82e7991cb284a438
diff --git a/grpc/src/test/java/com/linecorp/armeria/client/grpc/GrpcClientTest.java b/grpc/src/test/java/com/linecorp/armeria/client/grpc/GrpcClientTest.java index <HASH>..<HASH> 100644 --- a/grpc/src/test/java/com/linecorp/armeria/client/grpc/GrpcClientTest.java +++ b/grpc/src/test/java/com/linecorp/armeria/client/grpc/GrpcClientTest.java @@ -445,7 +445,20 @@ public class GrpcClientTest { } requestStream.onCompleted(); recorder.awaitCompletion(); - assertSuccess(recorder); + + try { + assertSuccess(recorder); + } catch (AssertionError e) { + if (System.getenv("CI") != null) { + // On CI, it seems relatively common for the socket to get killed during this test. Just log + // the error instead of failing it. + logger.warn("Ignoring test failure.", e); + return; + } + + throw e; + } + assertThat(recorder.getValues()).hasSize(responseSizes.size() * numRequests); for (int ix = 0; ix < recorder.getValues().size(); ++ix) { StreamingOutputCallResponse response = recorder.getValues().get(ix);
Ignore flaky test (GrpcClientTest.halfDuplexCallShouldSucceed) in CI (#<I>) Motivation: On CI, it seems relatively common for the socket to get killed during some of the test cases in GrpcClientTest. Modifications: - Just log the error instead of failing it. Result: - Build stability
line_armeria
train
dc9d9da8d27b314897ac8842f63b9b3b6031e307
diff --git a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/protocol/ProtocolRESTService.java b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/protocol/ProtocolRESTService.java index <HASH>..<HASH> 100644 --- a/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/protocol/ProtocolRESTService.java +++ b/guacamole/src/main/java/org/glyptodon/guacamole/net/basic/rest/protocol/ProtocolRESTService.java @@ -24,14 +24,15 @@ package org.glyptodon.guacamole.net.basic.rest.protocol; import com.google.inject.Inject; import java.util.Map; -import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.glyptodon.guacamole.GuacamoleException; import org.glyptodon.guacamole.net.basic.ProtocolInfo; import org.glyptodon.guacamole.net.basic.rest.AuthProviderRESTExposure; +import org.glyptodon.guacamole.net.basic.rest.auth.AuthenticationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,9 +41,8 @@ import org.slf4j.LoggerFactory; * * @author James Muehlner */ -@Path("/protocol") +@Path("/protocols") @Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public class ProtocolRESTService { /** @@ -51,6 +51,12 @@ public class ProtocolRESTService { private static final Logger logger = LoggerFactory.getLogger(ProtocolRESTService.class); /** + * A service for authenticating users from auth tokens. + */ + @Inject + private AuthenticationService authenticationService; + + /** * Service for retrieving protocol definitions. */ @Inject @@ -59,15 +65,27 @@ public class ProtocolRESTService { /** * Gets a map of protocols defined in the system - protocol name to protocol. * - * @return The protocol map. - * @throws GuacamoleException If a problem is encountered while listing protocols. + * @param authToken + * The authentication token that is used to authenticate the user + * performing the operation. + * + * @return + * A map of protocol information, where each key is the unique name + * associated with that protocol. + * + * @throws GuacamoleException + * If an error occurs while retrieving the available protocols. */ @GET @AuthProviderRESTExposure - public Map<String, ProtocolInfo> getProtocols() throws GuacamoleException { + public Map<String, ProtocolInfo> getProtocols(@QueryParam("token") String authToken) throws GuacamoleException { + // Verify the given auth token is valid + authenticationService.getUserContext(authToken); + // Get and return a map of all protocols. return protocolRetrievalservice.getProtocolMap(); + } } diff --git a/guacamole/src/main/webapp/app/rest/services/protocolService.js b/guacamole/src/main/webapp/app/rest/services/protocolService.js index <HASH>..<HASH> 100644 --- a/guacamole/src/main/webapp/app/rest/services/protocolService.js +++ b/guacamole/src/main/webapp/app/rest/services/protocolService.js @@ -23,7 +23,8 @@ /** * Service for operating on protocol metadata via the REST API. */ -angular.module('rest').factory('protocolService', ['$http', function protocolService($http) { +angular.module('rest').factory('protocolService', ['$http', 'authenticationService', + function protocolService($http, authenticationService) { var service = {}; @@ -37,7 +38,19 @@ angular.module('rest').factory('protocolService', ['$http', function protocolSer * objects upon success. */ service.getProtocols = function getProtocols() { - return $http.get("api/protocol"); + + // Build HTTP parameters set + var httpParameters = { + token : authenticationService.getCurrentToken() + }; + + // Retrieve available protocols + return $http({ + method : 'GET', + url : 'api/protocols', + params : httpParameters + }); + }; return service;
GUAC-<I>: Require auth token for listing protocols. Clean style of JS and Java.
glyptodon_guacamole-client
train
594a45f92d1c764ab9c4cc70a777d3e932647b74
diff --git a/lib/cli/file-pipeline/stdout.js b/lib/cli/file-pipeline/stdout.js index <HASH>..<HASH> 100644 --- a/lib/cli/file-pipeline/stdout.js +++ b/lib/cli/file-pipeline/stdout.js @@ -45,6 +45,7 @@ function stdout(context) { var file = context.file; if ( + !fileSet.cli.watch && fileSet.cli.out && fileSet.length === 1 && (!context.output || !file.filePath())
Remove output to stdout(4) when watching This update disables output written to stdout(4) when watching. This started to occur a lot since e<I>d2 (“Add processing of just the changed watched file to mdast(1)”) and was neither useful nor pretty.
remarkjs_remark
train
6852dc43a0454123f09ab90923bffed66b5a5aa9
diff --git a/classylss/cosmology.py b/classylss/cosmology.py index <HASH>..<HASH> 100644 --- a/classylss/cosmology.py +++ b/classylss/cosmology.py @@ -396,7 +396,17 @@ def verify_parameters(args, extra): def set_sigma8(cosmo, sigma8, inplace=False): """ Return a clone of the input Cosmology object, with the ``sigma8`` value - set to the specified value + set to the specified value. + + Parameters + ---------- + cosmo : Cosmology + the input cosmology object + sigma8 : float + the desired sigma8 value + inplace : bool, optional + if ``True``, update sigma8 of the input ``cosmo`` object, else return + a new Cosmology object """ # the new scalar amplitude A_s A_s = cosmo.A_s * (sigma8/cosmo.sigma8)**2 @@ -429,25 +439,28 @@ def sanitize_class_params(cosmo, pars): ``kwargs`` holds all of the extra keywords. """ args = {} + kwargs = pars.copy() + # loop over all parameters - for name in list(pars.keys()): - val = pars.pop(name) + for name in list(kwargs.keys()): # parameter is a main parameter if name in CONFLICTS: + kwargs.pop(name) alias = ALIASES.get(name, name) # check for attribute alias args[name] = getattr(cosmo, alias) else: # check if parameter conflicts with main parameter for c in CONFLICTS: if name in CONFLICTS[c]: + kwargs.pop(name) alias = ALIASES.get(c, c) args[c] = getattr(cosmo, alias) # set all named keywords that do not have parameter conflicts args['gauge'] = cosmo.gauge - return args + return args, kwargs # dict mapping input CLASS params to the Cosmology attribute name ALIASES = {'Omega_b': 'Omega0_b', 'Omega_cdm':'Omega0_cdm', 'T_cmb':'T0_cmb'}
fix sanitize_params
nickhand_classylss
train
f20ff7c513e5852b59726ccc5f2b767383e6230a
diff --git a/lib/Core/Site/QueryType/Location/Children.php b/lib/Core/Site/QueryType/Location/Children.php index <HASH>..<HASH> 100644 --- a/lib/Core/Site/QueryType/Location/Children.php +++ b/lib/Core/Site/QueryType/Location/Children.php @@ -41,7 +41,7 @@ final class Children extends Location $location = $options['location']; try { - return $location->parent->innerLocation->getSortClauses(); + return $location->innerLocation->getSortClauses(); } catch (NotImplementedException $e) { return []; }
NGSTACK-<I> Fix wrong location usage
netgen_ezplatform-site-api
train
5c820a894115d8a553a4313e8b4caaaad2d7f750
diff --git a/lib/test.js b/lib/test.js index <HASH>..<HASH> 100644 --- a/lib/test.js +++ b/lib/test.js @@ -663,6 +663,9 @@ Test.prototype.current = function () { // as an arg, to run a reporter on a previous run. // We DO however need to parse it to set the exit failure. Test.prototype.stdin = function (name, extra, deferred) { + // This has to be here for node 0.10's wonky streams + process.stdin.pause() + if (typeof name === 'object') { extra = name name = null diff --git a/test/runner-timeout.js b/test/runner-timeout.js index <HASH>..<HASH> 100644 --- a/test/runner-timeout.js +++ b/test/runner-timeout.js @@ -35,7 +35,10 @@ t.test('-t or --timeout to set timeout', function (t) { out += c }) child.on('close', function (code, signal) { - var skip = process.platform === 'win32' && 'SIGTERM on windows is weird' + var skip = + process.platform === 'win32' ? 'SIGTERM on windows is weird' + : process.version.match(/^v0\.10\./) ? 'v0.10 reports signals wrong' + : false t.equal(code, 1) t.equal(signal, null) t.match(
Make tests pass on <I>
tapjs_node-tap
train
fdea9dd47ea3310c9c26f17cdc801427815602c6
diff --git a/sphinx_click/ext.py b/sphinx_click/ext.py index <HASH>..<HASH> 100644 --- a/sphinx_click/ext.py +++ b/sphinx_click/ext.py @@ -150,9 +150,16 @@ def _format_option(opt: click.Option) -> ty.Generator[str, None, None]: yield '.. option:: {}'.format(opt_help[0]) if opt_help[1]: yield '' + bar_enabled = False for line in statemachine.string2lines( ANSI_ESC_SEQ_RE.sub('', opt_help[1]), tab_width=4, convert_whitespace=True ): + if line == '\b': + bar_enabled = True + continue + if line == '': + bar_enabled = False + line = '| ' + line if bar_enabled else line yield _indent(line) diff --git a/tests/test_formatter.py b/tests/test_formatter.py index <HASH>..<HASH> 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -424,6 +424,19 @@ And this is a paragraph that will be rewrapped again. """ ) + @click.option( + '--param', + help="""An option containing pre-wrapped text. + + \b + This is + a paragraph + without rewrapping. + + And this is a paragraph + that will be rewrapped again. + """, + ) def cli(): """A command containing pre-wrapped text. @@ -457,6 +470,19 @@ that will be rewrapped again. cli [OPTIONS] + .. rubric:: Options + + .. option:: --param <param> + + An option containing pre-wrapped text. + + | This is + | a paragraph + | without rewrapping. + + And this is a paragraph + that will be rewrapped again. + An epilog containing pre-wrapped text. | This is
Extend pre-wrapped text support to options Seems click will let you use the '\b' character in help text for options also.
click-contrib_sphinx-click
train
fcb686ac5fd2d29c6204c7bf825d11db1ac6d7ef
diff --git a/rb/gen_user_guide.rb b/rb/gen_user_guide.rb index <HASH>..<HASH> 100644 --- a/rb/gen_user_guide.rb +++ b/rb/gen_user_guide.rb @@ -19,15 +19,15 @@ class Generator class Section attr_reader :number attr_reader :title - attr_reader :new_page + attr_reader :page attr_reader :contents attr_reader :anchor - def initialize(number, title, new_page) + def initialize(number, title, page, anchor) @number = number @title = title.gsub(/[`]/, "") - @new_page = new_page + @page = page + @anchor = anchor @contents = "" - @anchor = "s" + ("#{number} #{title}").gsub(/[^a-zA-Z0-9]/, "_") end def append(contents) @contents += contents @@ -35,6 +35,12 @@ class Generator end def initialize(input, output_file, multi_file) + current_page = + if multi_file + "index.html" + else + File.basename(output_file) + end @sections = [] @current_section_number = [0] @lines = input.lines @@ -47,7 +53,11 @@ class Generator level = $1.size new_page = !new_page_text.nil? section_number = get_next_section_number(level) - @sections << Section.new(section_number, title_text, new_page) + anchor = make_anchor(section_number, title_text) + if new_page + current_page = anchor + end + @sections << Section.new(section_number, title_text, current_page, anchor) @sections.last.append("#{level_text} #{section_number} #{title_text}") elsif @sections.size > 0 @sections.last.append(line) @@ -78,6 +88,10 @@ class Generator end end + def make_anchor(section_number, section_title) + "s" + ("#{section_number} #{section_title}").gsub(/[^a-zA-Z0-9]/, "_") + end + def gather_code_section(syntax) code = "" loop do
user guide: keep track of page for sections
holtrop_rscons
train
77f58c994f5e2876eb07009542b6d150d55f42fe
diff --git a/src/View/Helper/UrlHelper.php b/src/View/Helper/UrlHelper.php index <HASH>..<HASH> 100644 --- a/src/View/Helper/UrlHelper.php +++ b/src/View/Helper/UrlHelper.php @@ -29,15 +29,35 @@ class UrlHelper extends Helper /** * Returns a URL based on provided parameters. * + * ### Options: + * + * - `escape`: If false, the URL will be returned unescaped, do only use if it is manually + * escaped afterwards before being displayed. + * - `full`: If true, the full base URL will be prepended to the result + * * @param string|array|null $url Either a relative string url like `/products/view/23` or * an array of URL parameters. Using an array for URLs will allow you to leverage * the reverse routing features of CakePHP. - * @param bool $full If true, the full base URL will be prepended to the result + * @param bool $options Array options; bool $full for BC reasons. * @return string Full translated URL with base path. */ - public function build($url = null, $full = false) + public function build($url = null, $options = false) { - return h(Router::url($url, $full)); + $defaults = [ + 'full' => false, + 'escape' => true, + ]; + if (!is_array($options)) { + $options = ['full' => $options]; + } + $options += $defaults; + + $url = Router::url($url, $options['full']); + if ($options['escape']) { + $url = h($url); + } + + return $url; } /** diff --git a/tests/TestCase/View/Helper/UrlHelperTest.php b/tests/TestCase/View/Helper/UrlHelperTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/View/Helper/UrlHelperTest.php +++ b/tests/TestCase/View/Helper/UrlHelperTest.php @@ -100,6 +100,26 @@ class UrlHelperTest extends TestCase } /** + * @return void + */ + public function testUrlConversionUnescaped() + { + $result = $this->Helper->build('/controller/action/1?one=1&two=2', ['escape' => false]); + $this->assertEquals('/controller/action/1?one=1&two=2', $result); + + $result = $this->Helper->build([ + 'controller' => 'posts', + 'action' => 'view', + 'param' => '%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24', + '?' => [ + 'k' => 'v', + '1' => '2' + ] + ], ['escape' => false]); + $this->assertEquals("/posts/view?k=v&1=2&param=%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524", $result); + } + + /** * test assetTimestamp application * * @return void
Allow unescaped URLs to be built. Other helpers need this internally.
cakephp_cakephp
train
2c267985bf47ac378df35ac034dca98392b31092
diff --git a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/CaseRule.java b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/CaseRule.java index <HASH>..<HASH> 100644 --- a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/CaseRule.java +++ b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/CaseRule.java @@ -32,6 +32,8 @@ import org.languagetool.tagging.de.GermanToken.POSType; import org.languagetool.tools.StringTools; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; import java.util.*; import java.util.regex.Pattern; @@ -543,6 +545,15 @@ public class CaseRule extends GermanRule { } @Override + public URL getUrl() { + try { + return new URL("http://www.canoo.net/services/GermanSpelling/Regeln/Gross-klein/index.html"); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + @Override public String getDescription() { return "Großschreibung von Nomen und substantivierten Verben"; }
[de] provide URL for case rule
languagetool-org_languagetool
train
07522a784f1c7972d7d194c73b8c67ab0e3f5aa6
diff --git a/src/widget.resource.js b/src/widget.resource.js index <HASH>..<HASH> 100644 --- a/src/widget.resource.js +++ b/src/widget.resource.js @@ -121,6 +121,12 @@ RDFauthor.registerWidget({ <div class="rdfauthor-container resource-value">\ <input type="text" id="resource-input-' + this.ID + '" class="text resource-edit-input is-processing" \ value="' + value + '" title="' + value + '"/>\ + <div class="rdfauthor-container util" style="padding:0px;">\ + <label><span style="padding-right: 5px;">Filter by</span>\ + <input class="checkbox checkbox-range" type="checkbox" name="range"\ + '+ (this._options.filterRange ? 'checked="checked"' : '') + '">\ + <label>Range</label></label>\ + </div>\ </div>'; return markup; @@ -509,6 +515,11 @@ RDFauthor.registerWidget({ _initAutocomplete: function () { var self = this; if (this._pluginLoaded && this._domReady && !this._initialized) { + // set range option + self.element().parent().find('input[name=range]').click(function() { + self._options.filterRange = $(this).is(':checked'); + }); + self.element().data('objects',[]); self.element().parent().parent().parent().parent().parent().parent().find('input').each(function() { self.element().data('objects').push($(this).attr('title'));
extend resource widget to disable range restriction #<I>
AKSW_RDFauthor
train
bd3bf5c82cc4600aa01c63dd07ad46839ef34b07
diff --git a/lib/cql.rb b/lib/cql.rb index <HASH>..<HASH> 100644 --- a/lib/cql.rb +++ b/lib/cql.rb @@ -91,14 +91,6 @@ module CQL value end - def rotate_array(array) - return if array.empty? - - first = array.shift - - array << first - end - def space_data space_renamings space_transforms
Dead code removal. Getting rid of an unused method.
enkessler_cql
train
cad1636ae2a2c8471c659a317e2d4bd7dbd077ba
diff --git a/lib/puppet/reports/store.rb b/lib/puppet/reports/store.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/reports/store.rb +++ b/lib/puppet/reports/store.rb @@ -1,6 +1,6 @@ require 'puppet' require 'fileutils' -require 'tempfile' +require 'puppet/util' SEPARATOR = [Regexp.escape(File::SEPARATOR.to_s), Regexp.escape(File::ALT_SEPARATOR.to_s)].join @@ -31,17 +31,12 @@ Puppet::Reports.register_report(:store) do file = File.join(dir, name) - f = Tempfile.new(name, dir) begin - begin - f.chmod(0640) - f.print to_yaml - ensure - f.close + Puppet::Util.replace_file(file, 0640) do |fh| + fh.print to_yaml end - FileUtils.mv(f.path, file) rescue => detail - Puppet.log_exception(detail, "Could not write report for #{host} at #{file}: #{detail}") + Puppet.log_exception(detail, "Could not write report for #{host} at #{file}: #{detail}") end # Only testing cares about the return value diff --git a/spec/unit/reports/store_spec.rb b/spec/unit/reports/store_spec.rb index <HASH>..<HASH> 100755 --- a/spec/unit/reports/store_spec.rb +++ b/spec/unit/reports/store_spec.rb @@ -30,25 +30,9 @@ describe processor do File.read(File.join(Puppet[:reportdir], @report.host, "201101061200.yaml")).should == @report.to_yaml end - it "should write to the report directory in the correct sequence" do - # By doing things in this sequence we should protect against race - # conditions - Time.stubs(:now).returns(Time.parse("2011-01-06 12:00:00 UTC")) - writeseq = sequence("write") - file = mock "file" - Tempfile.expects(:new).in_sequence(writeseq).returns(file) - file.expects(:chmod).in_sequence(writeseq).with(0640) - file.expects(:print).with(@report.to_yaml).in_sequence(writeseq) - file.expects(:close).in_sequence(writeseq) - file.stubs(:path).returns(File.join(Dir.tmpdir, "foo123")) - FileUtils.expects(:mv).in_sequence(writeseq).with(File.join(Dir.tmpdir, "foo123"), File.join(Puppet[:reportdir], @report.host, "201101061200.yaml")) - @report.process - end - it "rejects invalid hostnames" do @report.host = ".." Puppet::FileSystem.expects(:exist?).never - Tempfile.expects(:new).never expect { @report.process }.to raise_error(ArgumentError, /Invalid node/) end end
(PUP-<I>) Refactor 'store' report to use replace_file There was some logic in the 'store' report processor that was almost identical to the logic in 'puppet/util.rb''s 'replace_file' method. This commit refactors 'store' to re-use the existing logic.
puppetlabs_puppet
train
b090e9c2d0f708580106ae17f39302d3a4bebde7
diff --git a/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/AuthorAdminListController.php b/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/AuthorAdminListController.php index <HASH>..<HASH> 100755 --- a/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/AuthorAdminListController.php +++ b/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/AuthorAdminListController.php @@ -31,7 +31,7 @@ class {{ entity_class }}AuthorAdminListController extends AbstractArticleAuthorA */ public function indexAction(Request $request) { - return parent::doIndexAction($this->getAdminListConfigurator(), $request); + return parent::doIndexAction($this->getAdminListConfigurator($request), $request); } /** @@ -43,7 +43,7 @@ class {{ entity_class }}AuthorAdminListController extends AbstractArticleAuthorA */ public function addAction(Request $request) { - return parent::doAddAction($this->getAdminListConfigurator(), null, $request); + return parent::doAddAction($this->getAdminListConfigurator($request), null, $request); } /** @@ -58,7 +58,7 @@ class {{ entity_class }}AuthorAdminListController extends AbstractArticleAuthorA */ public function editAction(Request $request, $id) { - return parent::doEditAction($this->getAdminListConfigurator(), $id, $request); + return parent::doEditAction($this->getAdminListConfigurator($request), $id, $request); } /** @@ -73,7 +73,7 @@ class {{ entity_class }}AuthorAdminListController extends AbstractArticleAuthorA */ public function deleteAction(Request $request, $id) { - return parent::doDeleteAction($this->getAdminListConfigurator(), $id, $request); + return parent::doDeleteAction($this->getAdminListConfigurator($request), $id, $request); } /** @@ -88,6 +88,6 @@ class {{ entity_class }}AuthorAdminListController extends AbstractArticleAuthorA */ public function exportAction(Request $request, $_format) { - return parent::doExportAction($this->getAdminListConfigurator(), $_format, $request); + return parent::doExportAction($this->getAdminListConfigurator($request), $_format, $request); } } diff --git a/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/PageAdminListController.php b/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/PageAdminListController.php index <HASH>..<HASH> 100755 --- a/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/PageAdminListController.php +++ b/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/article/Controller/PageAdminListController.php @@ -31,7 +31,7 @@ class {{ entity_class }}PageAdminListController extends AbstractArticlePageAdmin */ public function indexAction(Request $request) { - return parent::doIndexAction($this->getAdminListConfigurator(), $request); + return parent::doIndexAction($this->getAdminListConfigurator($request), $request); } /** @@ -43,7 +43,7 @@ class {{ entity_class }}PageAdminListController extends AbstractArticlePageAdmin */ public function addAction(Request $request) { - return parent::doAddAction($this->getAdminListConfigurator(), $request); + return parent::doAddAction($this->getAdminListConfigurator($request), $request); } /** @@ -58,7 +58,7 @@ class {{ entity_class }}PageAdminListController extends AbstractArticlePageAdmin */ public function editAction(Request $request, $id) { - return parent::doEditAction($this->getAdminListConfigurator(), $id, $request); + return parent::doEditAction($this->getAdminListConfigurator($request), $id, $request); } /** @@ -73,7 +73,7 @@ class {{ entity_class }}PageAdminListController extends AbstractArticlePageAdmin */ public function deleteAction(Request $request, $id) { - return parent::doDeleteAction($this->getAdminListConfigurator(), $id, $request); + return parent::doDeleteAction($this->getAdminListConfigurator($request), $id, $request); } /** @@ -88,6 +88,6 @@ class {{ entity_class }}PageAdminListController extends AbstractArticlePageAdmin */ public function exportAction(Request $request, $_format) { - return parent::doExportAction($this->getAdminListConfigurator(), $_format, $request); + return parent::doExportAction($this->getAdminListConfigurator($request), $_format, $request); } }
[GeneratorBundle]: request needs to be passed
Kunstmaan_KunstmaanBundlesCMS
train
031dc6796b771a2d42649a5e759a1763b76d131c
diff --git a/tornado/testing.py b/tornado/testing.py index <HASH>..<HASH> 100644 --- a/tornado/testing.py +++ b/tornado/testing.py @@ -179,7 +179,12 @@ class AsyncTestCase(unittest.TestCase): assert self.__stopped self.__stopped = False if self.__failure is not None: - raise self.__failure[0], self.__failure[1], self.__failure[2] + # 2to3 isn't smart enough to convert three-argument raise + # statements correctly in some cases. + if isinstance(self.__failure[1], self.__failure[0]): + raise self.__failure[1], None, self.__failure[2] + else: + raise self.__failure[0], self.__failure[1], self.__failure[2] result = self.__stop_args self.__stop_args = None return result
Help 2to3 with a tricky three-argument raise statement
tornadoweb_tornado
train
8b3107ba6a51d834f27dcbb2f39202c8d8302fca
diff --git a/src/Error/JsonApiExceptionRenderer.php b/src/Error/JsonApiExceptionRenderer.php index <HASH>..<HASH> 100644 --- a/src/Error/JsonApiExceptionRenderer.php +++ b/src/Error/JsonApiExceptionRenderer.php @@ -175,7 +175,16 @@ class JsonApiExceptionRenderer extends ExceptionRenderer $result = json_decode($json, true); $result['debug'] = $debug; - return json_encode($result, JSON_PRETTY_PRINT); + try { + return json_encode($result, JSON_PRETTY_PRINT); + } catch (\Exception $e) { + $result['debug']['message'] = $e->getMessage(); + $result['debug']['trace'] = [ + 'error' => 'Unable to encode stack trace', + ]; + + return json_encode($result, JSON_PRETTY_PRINT); + } } /**
Do not break requests adding the debug node Requests which result in an sql error do not return json; instead they can collapse trying to generate the stack trace and then only output "An Internal Server Error Occurred" If this happens, just don't add the stack trace to the response.
FriendsOfCake_crud-json-api
train
8f54f6a8d52985c53d34e0c0b47391455891230c
diff --git a/docs.js b/docs.js index <HASH>..<HASH> 100644 --- a/docs.js +++ b/docs.js @@ -225,6 +225,7 @@ function copyDocs(srcDir, destDir) { if (err) { reject(err); } else { + console.log('Copied docs to ' + destDir); resolve(); } }); @@ -262,7 +263,7 @@ function removeDir(dir) { if (err) { reject(err); } else { - console.log('Finished writing documentation files.'); + console.log('Removed directory ' + dir); resolve(); } }); @@ -304,6 +305,9 @@ function removeDir(dir) { // Delete the temporary directory return removeDir(tmpDir); }) + .then(function() { + console.log('Finished writing documentation files.'); + }) .catch(function(reason) { console.log(reason.stack); });
Updated log messages in docs.js
san650_ember-cli-page-object
train
ff9b21e498a5aac10807dff89a114c9d46b901f9
diff --git a/desktop/ui/src/main/java/org/datacleaner/windows/DataCloudLogInWindow.java b/desktop/ui/src/main/java/org/datacleaner/windows/DataCloudLogInWindow.java index <HASH>..<HASH> 100644 --- a/desktop/ui/src/main/java/org/datacleaner/windows/DataCloudLogInWindow.java +++ b/desktop/ui/src/main/java/org/datacleaner/windows/DataCloudLogInWindow.java @@ -174,10 +174,10 @@ public class DataCloudLogInWindow extends AbstractDialog { .addGroup(layout.createSequentialGroup() .addGap(PADDING, PADDING, Integer.MAX_VALUE) .addComponent(usernameLabel, textFieldHeight, textFieldHeight, textFieldHeight) - .addComponent(usernameTextField, GroupLayout.DEFAULT_SIZE, 140, 140) + .addComponent(usernameTextField, GroupLayout.DEFAULT_SIZE, 150, 150) .addGap(PADDING) .addComponent(passwordLabel, textFieldHeight, textFieldHeight, textFieldHeight) - .addComponent(passwordTextField, GroupLayout.DEFAULT_SIZE, 100,100) + .addComponent(passwordTextField, GroupLayout.DEFAULT_SIZE, 150, 150) .addGap(PADDING) .addComponent(signInButton) .addGap(PADDING, PADDING, Integer.MAX_VALUE)
I changed size of textFields
datacleaner_DataCleaner
train
261f6965c0e48fa19505bdc8e3d4f3781fc2fd49
diff --git a/HISTORY.rst b/HISTORY.rst index <HASH>..<HASH> 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -7,7 +7,7 @@ History * Added type hinting to call signatures of many functions for more explicit type-checking * Now supporting explicit builds for Windows OS via Travis CI * Fix failing test with Python 3.7 - +* Fixed bug in subset.subset_bbox that could add unwanted coordinates/dims to some variables when applied to an entire dataset 0.10.x-beta (2019-06-18) ------------------------ diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ requirements = [ "scipy>=1.2", "numpy>=1.15", "pandas>=0.23", - "cftime==1.0.3", + "cftime~=1.0.3.4", "netCDF4>=1.4", "dask[complete]", "bottleneck>=1.2.1", diff --git a/tests/test_subset.py b/tests/test_subset.py index <HASH>..<HASH> 100644 --- a/tests/test_subset.py +++ b/tests/test_subset.py @@ -343,6 +343,20 @@ class TestSubsetBbox: assert np.all(out.lat.values[mask1.values] >= np.min(self.lat)) assert np.all(out.lat.values[mask1.values] <= np.max(self.lat)) + def test_irregular_datset(self): + da = xr.open_dataset(self.nc_2dlonlat) + out = subset.subset_bbox(da, lon_bnds=self.lon, lat_bnds=self.lat) + variables = list(da.data_vars) + variables.pop(variables.index("tasmax")) + # only tasmax should be subsetted/masked others should remain untouched + for v in variables: + assert out[v].dims == da[v].dims + np.testing.assert_array_equal(out[v], da[v]) + + # ensure results are equal to previous test on DataArray only + out1 = subset.subset_bbox(da.tasmax, lon_bnds=self.lon, lat_bnds=self.lat) + np.testing.assert_array_equal(out1, out.tasmax) + # test datasets with descending coords def test_inverted_coords(self): lon = np.linspace(-90, -60, 200) diff --git a/xclim/subset.py b/xclim/subset.py index <HASH>..<HASH> 100644 --- a/xclim/subset.py +++ b/xclim/subset.py @@ -243,7 +243,15 @@ def subset_bbox( lon_cond = in_bounds(lon_b, da.lon) # Mask coordinates outside the bounding box - da = da.where(lon_cond & lat_cond, drop=True) + if isinstance(da, xarray.Dataset): + # If da is a xr.DataSet Mask only variables that have the + # same 2d coordinates as da.lat (or da.lon) + for var in da.data_vars: + if set(da.lat.dims).issubset(da[var].dims): + da[var] = da[var].where(lon_cond & lat_cond, drop=True) + else: + + da = da.where(lon_cond & lat_cond, drop=True) else: raise (
fix-<I> (#<I>) *fix bug that adds unwanted dims to variables using curvlinear subset_bbox when applied to a xr.DataSet * update history * Update setup.py
Ouranosinc_xclim
train
bbc371097cefade37eebd09053e9a17a7ee264ca
diff --git a/core/src/main/java/lucee/runtime/tag/Schedule.java b/core/src/main/java/lucee/runtime/tag/Schedule.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/lucee/runtime/tag/Schedule.java +++ b/core/src/main/java/lucee/runtime/tag/Schedule.java @@ -499,7 +499,7 @@ public final class Schedule extends TagImpl { */ private void doDelete() throws PageException { try { - scheduler.removeScheduleTask(task, false); + scheduler.removeScheduleTask(task, true); } catch (Exception e) { throw Caster.toPageException(e);
Added a fix for delete non-existing schedule task in LDEV-<I> (#<I>)
lucee_Lucee
train
53a156d252941c35d719af034df4ed9a1cf92baf
diff --git a/src/grid.js b/src/grid.js index <HASH>..<HASH> 100644 --- a/src/grid.js +++ b/src/grid.js @@ -80,7 +80,8 @@ export function createGrid() { .from(unpackNestedRows, 'showRowWhenCollapsed') , grid = compose( - call(() => coreEvents.call('draw')) + call(d => window.timeGrid && console.timeEnd('grid')) + , call(() => coreEvents.call('draw')) , call(s => s.on('settings-changed', () => coreEvents.call('settings-changed'))) , call(runExternalComponents) , call(createScrollers()) @@ -107,6 +108,7 @@ export function createGrid() { , each(shareDispatcher.dispatcher(redispatcher)) , each(ensureData) , each(ensureId) + , call(d => window.timeGrid && console.time('grid')) ) return api(autodirty(redraw(throttle(throttleToAnimationFrame(skipWhenHidden(grid)), 10))))
Add some debug times for grid test.
zambezi_grid
train
b88799cca293ded3b6a830b8d58085d445fa19a2
diff --git a/javascript/node/selenium-webdriver/chrome.js b/javascript/node/selenium-webdriver/chrome.js index <HASH>..<HASH> 100644 --- a/javascript/node/selenium-webdriver/chrome.js +++ b/javascript/node/selenium-webdriver/chrome.js @@ -152,12 +152,13 @@ const Command = { GET_NETWORK_CONDITIONS: 'getNetworkConditions', SET_NETWORK_CONDITIONS: 'setNetworkConditions', SEND_DEVTOOLS_COMMAND: 'sendDevToolsCommand', + SEND_AND_GET_DEVTOOLS_COMMAND: 'sendAndGetDevToolsCommand', + GET_CAST_SINKS: 'getCastSinks', SET_CAST_SINK_TO_USE: 'setCastSinkToUse', START_CAST_TAB_MIRRORING: 'setCastTabMirroring', GET_CAST_ISSUE_MESSAGE: 'getCastIssueMessage', STOP_CASTING: 'stopCasting', - SEND_DEVTOOLS_COMMAND_AND_GET_RETURN: 'sendDevToolsCommandAndGetReturn', }; @@ -197,6 +198,10 @@ function configureExecutor(executor) { 'POST', '/session/:sessionId/chromium/send_command'); executor.defineCommand( + Command.SEND_AND_GET_DEVTOOLS_COMMAND, + 'POST', + '/session/:sessionId/chromium/send_command_and_get_result'); + executor.defineCommand( Command.GET_CAST_SINKS, 'GET', '/session/:sessionId/goog/cast/get_sinks'); @@ -216,10 +221,6 @@ function configureExecutor(executor) { Command.STOP_CASTING, 'POST', '/session/:sessionId/goog/cast/stop_casting'); - executor.defineCommand( - Command.SEND_DEVTOOLS_COMMAND_AND_GET_RETURN, - 'POST', - '/session/:sessionId/goog/cdp/execute'); } @@ -438,20 +439,20 @@ class Driver extends chromium.Driver { } /** - * Sends an arbitrary devtools command to the browser and returns its result. + * Sends an arbitrary devtools command to the browser and get the result. * * @param {string} cmd The name of the command to send. * @param {Object=} params The command parameters. - * @return {!Promise<(T|null)>} A promise that will be resolved with the command - * result. + * @return {!Promise<Object>} A promise that will be resolved when the command + * has finished. * @see <https://chromedevtools.github.io/devtools-protocol/> - * @see #sendDevToolsCommand */ - sendDevToolsCommandAndGetReturn(cmd, params = {}) { - return this.execute( - new command.Command(Command.SEND_DEVTOOLS_COMMAND_AND_GET_RETURN) - .setParameter('cmd', cmd) - .setParameter('params', params)); + sendAndGetDevToolsCommand(cmd, params = {}) { + return this.schedule( + new command.Command(Command.SEND_AND_GET_DEVTOOLS_COMMAND) + .setParameter('cmd', cmd) + .setParameter('params', params) + ); } /** diff --git a/javascript/node/selenium-webdriver/test/chrome/devtools_test.js b/javascript/node/selenium-webdriver/test/chrome/devtools_test.js index <HASH>..<HASH> 100644 --- a/javascript/node/selenium-webdriver/test/chrome/devtools_test.js +++ b/javascript/node/selenium-webdriver/test/chrome/devtools_test.js @@ -47,6 +47,7 @@ test.suite(function(env) { assert.equal(await driver.getCurrentUrl(), test.Pages.echoPage); }); + it('can send commands to devtools and get return', async function() { await driver.get(test.Pages.ajaxyPage); assert.equal(await driver.getCurrentUrl(), test.Pages.ajaxyPage);
Get and send devtools commands from NodeJS for Chrome. (#<I>)
SeleniumHQ_selenium
train
b974e90c00d0de5e1f5801203f7700ed8405dc19
diff --git a/src/main/java/io/vlingo/actors/Environment.java b/src/main/java/io/vlingo/actors/Environment.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/vlingo/actors/Environment.java +++ b/src/main/java/io/vlingo/actors/Environment.java @@ -9,7 +9,6 @@ package io.vlingo.actors; import java.util.ArrayList; import java.util.List; -import java.util.ListIterator; public class Environment { private static final byte FLAG_RESET = 0x00;
Deleted ListIterator since no longer used.
vlingo_vlingo-actors
train
425d6327087d024c068d9044cce0baca33e8c884
diff --git a/src/rez/resolver.py b/src/rez/resolver.py index <HASH>..<HASH> 100644 --- a/src/rez/resolver.py +++ b/src/rez/resolver.py @@ -223,8 +223,17 @@ class Resolver(object): new_state = variant_states.get(variant) if new_state is None: - repo = variant.resource._repository - new_state = repo.get_variant_state_handle(variant.resource) + try: + repo = variant.resource._repository + new_state = repo.get_variant_state_handle(variant.resource) + except (IOError, OSError) as e: + # if, ie a package file was deleted on disk, then + # an IOError or OSError will be raised when we try to + # read from it - assume that the packages have changed! + self._print("Error loading %r (assuming cached state " + "changed): %s", variant.qualified_name, + e) + return True variant_states[variant] = new_state if old_state != new_state:
invalidate memcache if a package file has been deleted / moved / etc
nerdvegas_rez
train
d6ad79487281a1e149a0c5872fc614da1ee72f44
diff --git a/org.jenetics/src/main/java/org/jenetics/SinglePointCrossover.java b/org.jenetics/src/main/java/org/jenetics/SinglePointCrossover.java index <HASH>..<HASH> 100644 --- a/org.jenetics/src/main/java/org/jenetics/SinglePointCrossover.java +++ b/org.jenetics/src/main/java/org/jenetics/SinglePointCrossover.java @@ -19,6 +19,7 @@ */ package org.jenetics; +import static java.lang.Math.min; import static java.lang.String.format; import java.util.Random; @@ -51,7 +52,7 @@ import org.jenetics.util.RandomRegistry; * * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a> * @since 1.0 - * @version 3.0 + * @version !__version__! */ public class SinglePointCrossover< G extends Gene<?, G>, @@ -81,10 +82,10 @@ public class SinglePointCrossover< @Override protected int crossover(final MSeq<G> that, final MSeq<G> other) { - assert that.length() == other.length(); - final Random random = RandomRegistry.getRandom(); - crossover(that, other, random.nextInt(that.length())); + + final int index = random.nextInt(min(that.length(), other.length())); + crossover(that, other, index); return 2; } @@ -100,7 +101,7 @@ public class SinglePointCrossover< that.length(), index ); - that.swap(index, that.length(), other, index); + that.swap(index, min(that.length(), other.length()), other, index); } @Override
#<I>: Make 'SinglePointCrossover' class ready for chromosomes with different length.
jenetics_jenetics
train
952acaad564b0200d18351f73406e2ba315a97d7
diff --git a/test/sync_test.rb b/test/sync_test.rb index <HASH>..<HASH> 100644 --- a/test/sync_test.rb +++ b/test/sync_test.rb @@ -67,14 +67,12 @@ class SyncTest < Minitest::Test end def test_data_rules - conn1 = PG::Connection.open(dbname: "pgsync_test1") 2.times do - conn1.exec("INSERT INTO \"Users\" (email, phone, token, attempts, created_on, updated_at, ip, name, nonsense, untouchable) + $conn1.exec("INSERT INTO \"Users\" (email, phone, token, attempts, created_on, updated_at, ip, name, nonsense, untouchable) VALUES ('hi@example.org', '555-555-5555', 'token123', 1, NOW(), NOW(), '127.0.0.1', 'Hi', 'Text', 'rock');") end assert_works "Users --from pgsync_test1 --to pgsync_test2 --config test/support/config.yml" - conn2 = PG::Connection.open(dbname: "pgsync_test2") - result = conn2.exec("SELECT * FROM \"Users\"").to_a + result = $conn2.exec("SELECT * FROM \"Users\"").to_a row = result.first assert_equal "email#{row["Id"]}@example.org", row["email"] assert_equal "secret#{row["Id"]}", row["token"]
Use existing connections [skip ci]
ankane_pgsync
train
0d1b9279596f5c46f18111c23760b512c3a900f6
diff --git a/core-bundle/src/EventListener/DataContainer/ContentCompositionListener.php b/core-bundle/src/EventListener/DataContainer/ContentCompositionListener.php index <HASH>..<HASH> 100644 --- a/core-bundle/src/EventListener/DataContainer/ContentCompositionListener.php +++ b/core-bundle/src/EventListener/DataContainer/ContentCompositionListener.php @@ -18,6 +18,7 @@ use Contao\CoreBundle\Framework\ContaoFramework; use Contao\CoreBundle\Routing\Page\PageRegistry; use Contao\CoreBundle\Security\ContaoCorePermissions; use Contao\CoreBundle\ServiceAnnotation\Callback; +use Contao\Database\Result; use Contao\DataContainer; use Contao\Image; use Contao\LayoutModel; @@ -131,7 +132,7 @@ class ContentCompositionListener $pageModel = $this->framework->createInstance(PageModel::class); $pageModel->preventSaving(false); - $pageModel->setRow((array) $dc->activeRecord); + $pageModel->setRow($dc->activeRecord instanceof Result ? $dc->activeRecord->row() : (array) $dc->activeRecord); if ( empty($pageModel->title)
Correctly set the active record in the ContentCompositionListener (see #<I>) Description ----------- | Q | A | -----------------| --- | Fixed issues | Fixes #<I> | Docs PR or issue | - Commits ------- a<I>e Correctly set the active record in the ContentCompositionListener
contao_contao
train
f3bd1e2444b8da23e3757d2616f8ca637751ec0a
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +<h2>v1.0.0-alpha36</h2> + +<h3>Framework</h3> +* Fixed `Make*` commands to use latest directory structure in skeleton project + <h2>v1.0.0-alpha35</h2> <h3>General</h3> diff --git a/src/Opulence/Applications/Application.php b/src/Opulence/Applications/Application.php index <HASH>..<HASH> 100644 --- a/src/Opulence/Applications/Application.php +++ b/src/Opulence/Applications/Application.php @@ -18,7 +18,7 @@ use Opulence\Applications\Tasks\TaskTypes; class Application { /** @var string The current Opulence version */ - private static $version = "1.0.0-alpha35"; + private static $version = "1.0.0-alpha36"; /** @var IDispatcher The task dispatcher */ private $taskDispatcher = null; /** @var bool Whether or not the application is currently running */ diff --git a/src/Opulence/Framework/Console/Commands/MakeCommandCommand.php b/src/Opulence/Framework/Console/Commands/MakeCommandCommand.php index <HASH>..<HASH> 100644 --- a/src/Opulence/Framework/Console/Commands/MakeCommandCommand.php +++ b/src/Opulence/Framework/Console/Commands/MakeCommandCommand.php @@ -29,7 +29,7 @@ class MakeCommandCommand extends MakeCommand */ protected function getDefaultNamespace(string $rootNamespace) : string { - return $rootNamespace . "\\Console\\Commands"; + return $rootNamespace . "\\Application\\Console\\Commands"; } /** diff --git a/src/Opulence/Framework/Console/Commands/MakeControllerCommand.php b/src/Opulence/Framework/Console/Commands/MakeControllerCommand.php index <HASH>..<HASH> 100644 --- a/src/Opulence/Framework/Console/Commands/MakeControllerCommand.php +++ b/src/Opulence/Framework/Console/Commands/MakeControllerCommand.php @@ -29,7 +29,7 @@ class MakeControllerCommand extends MakeCommand */ protected function getDefaultNamespace(string $rootNamespace) : string { - return $rootNamespace . "\\Http\\Controllers"; + return $rootNamespace . "\\Application\\Http\\Controllers"; } /** diff --git a/src/Opulence/Framework/Console/Commands/MakeDataMapperCommand.php b/src/Opulence/Framework/Console/Commands/MakeDataMapperCommand.php index <HASH>..<HASH> 100644 --- a/src/Opulence/Framework/Console/Commands/MakeDataMapperCommand.php +++ b/src/Opulence/Framework/Console/Commands/MakeDataMapperCommand.php @@ -56,7 +56,7 @@ class MakeDataMapperCommand extends MakeCommand */ protected function getDefaultNamespace(string $rootNamespace) : string { - return $rootNamespace . "\\Orm"; + return $rootNamespace . "\\Infrastructure\\Orm"; } /** diff --git a/src/Opulence/Framework/Console/Commands/MakeHttpMiddlewareCommand.php b/src/Opulence/Framework/Console/Commands/MakeHttpMiddlewareCommand.php index <HASH>..<HASH> 100644 --- a/src/Opulence/Framework/Console/Commands/MakeHttpMiddlewareCommand.php +++ b/src/Opulence/Framework/Console/Commands/MakeHttpMiddlewareCommand.php @@ -29,7 +29,7 @@ class MakeHttpMiddlewareCommand extends MakeCommand */ protected function getDefaultNamespace(string $rootNamespace) : string { - return $rootNamespace . "\\Http\\Middleware"; + return $rootNamespace . "\\Application\\Http\\Middleware"; } /**
Fixed Make* commands to use latest DDD directory structure in skeleton project
opulencephp_Opulence
train
9f2c48ac6335f63fc450732d8b4fe69b94597745
diff --git a/src/model/Api/JsonValidationTrait.php b/src/model/Api/JsonValidationTrait.php index <HASH>..<HASH> 100644 --- a/src/model/Api/JsonValidationTrait.php +++ b/src/model/Api/JsonValidationTrait.php @@ -10,10 +10,11 @@ use Tracy\Debugger; trait JsonValidationTrait { - public function validateInput($jsonSchemaPath): JsonValidationResult + public function validateInput(string $jsonSchemaPath, ?string $request = null): JsonValidationResult { - $request = file_get_contents('php://input'); - + if (empty($request)) { + $request = file_get_contents('php://input'); + } if (empty($request)) { $response = new JsonResponse(['status' => 'error', 'message' => 'Empty request']); $response->setHttpCode(Response::S400_BAD_REQUEST);
Api validateInput accepts request source from caller Updated `JsonValidationTrait`, method `validateInput()` now accepts `$request` from caller. If no `$request` is provided, `php://input` _(application/json)_ is used. This can be used in case we need to decode `application/json` first and than validate it. Eg. Google pub/sub sends DeveloperNotification base<I> encoded as one of the elements.
remp2020_crm-api-module
train
fdd1331db6fa29462da698bc774040e63cc8ba22
diff --git a/nomad/config.go b/nomad/config.go index <HASH>..<HASH> 100644 --- a/nomad/config.go +++ b/nomad/config.go @@ -39,7 +39,7 @@ func init() { } var ( - DefaultRPCAddr = &net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 4647} + DefaultRPCAddr = &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 4647} ) // Config is used to parameterize the server diff --git a/nomad/worker.go b/nomad/worker.go index <HASH>..<HASH> 100644 --- a/nomad/worker.go +++ b/nomad/worker.go @@ -13,11 +13,19 @@ import ( ) const ( - // backoffBaseline is the baseline time for exponential backoff - backoffBaseline = 20 * time.Millisecond + // backoffBaselineFast is the baseline time for exponential backoff + backoffBaselineFast = 20 * time.Millisecond - // backoffLimit is the limit of the exponential backoff - backoffLimit = 5 * time.Second + // backoffBaselineSlow is the baseline time for exponential backoff + // but that is much slower than backoffBaselineFast + backoffBaselineSlow = 500 * time.Millisecond + + // backoffLimitFast is the limit of the exponential backoff + backoffLimitFast = time.Second + + // backoffLimitSlow is the limit of the exponential backoff for + // the slower backoff + backoffLimitSlow = 10 * time.Second // dequeueTimeout is used to timeout an evaluation dequeue so that // we can check if there is a shutdown event @@ -132,7 +140,7 @@ REQ: metrics.MeasureSince([]string{"nomad", "worker", "dequeue_eval"}, start) if err != nil { w.logger.Printf("[ERR] worker: failed to dequeue evaluation: %v", err) - if w.backoffErr() { + if w.backoffErr(backoffBaselineSlow, backoffLimitSlow) { return nil, "", true } goto REQ @@ -206,7 +214,7 @@ CHECK: } // Exponential back off if we haven't yet reached it - if w.backoffErr() { + if w.backoffErr(backoffBaselineFast, backoffLimitFast) { return fmt.Errorf("shutdown while waiting for state sync") } goto CHECK @@ -269,7 +277,7 @@ SUBMIT: if err := w.srv.RPC("Plan.Submit", &req, &resp); err != nil { w.logger.Printf("[ERR] worker: failed to submit plan for evaluation %s: %v", plan.EvalID, err) - if w.shouldResubmit(err) && !w.backoffErr() { + if w.shouldResubmit(err) && !w.backoffErr(backoffBaselineSlow, backoffLimitSlow) { goto SUBMIT } return nil, nil, err @@ -332,7 +340,7 @@ SUBMIT: if err := w.srv.RPC("Eval.Update", &req, &resp); err != nil { w.logger.Printf("[ERR] worker: failed to update evaluation %#v: %v", eval, err) - if w.shouldResubmit(err) && !w.backoffErr() { + if w.shouldResubmit(err) && !w.backoffErr(backoffBaselineSlow, backoffLimitSlow) { goto SUBMIT } return err @@ -362,10 +370,10 @@ func (w *Worker) shouldResubmit(err error) bool { // maintained statefully for the worker. Returns if attempts should be // abandoneded due to shutdown. // be made or abandoned. -func (w *Worker) backoffErr() bool { - backoff := (1 << (2 * w.failures)) * backoffBaseline - if backoff > backoffLimit { - backoff = backoffLimit +func (w *Worker) backoffErr(base, limit time.Duration) bool { + backoff := (1 << (2 * w.failures)) * base + if backoff > limit { + backoff = limit } else { w.failures++ }
nomad: use fast and slow exponential backoff in worker
hashicorp_nomad
train
286cdca371af1238ab855bf898e79240ece6a62a
diff --git a/concrete/controllers/single_page/dashboard/system/seo/codes.php b/concrete/controllers/single_page/dashboard/system/seo/codes.php index <HASH>..<HASH> 100644 --- a/concrete/controllers/single_page/dashboard/system/seo/codes.php +++ b/concrete/controllers/single_page/dashboard/system/seo/codes.php @@ -24,8 +24,8 @@ class Codes extends DashboardSitePageController return $this->view(); } $config = $this->getSite()->getConfigRepository(); - $config->save('seo.tracking.code.header', (string) $post->get('tracking_code_header')); - $config->save('seo.tracking.code.footer', (string) $post->get('tracking_code_footer')); + $config->save('seo.tracking.code.header', (string) base64_decode($post->get('tracking_code_header'))); + $config->save('seo.tracking.code.footer', (string) base64_decode($post->get('tracking_code_footer'))); PageCache::getLibrary()->flush(); $this->flash('success', t('Tracking code settings updated successfully.') . "\n" . t('Cached files removed.')); diff --git a/concrete/single_pages/dashboard/system/seo/codes.php b/concrete/single_pages/dashboard/system/seo/codes.php index <HASH>..<HASH> 100644 --- a/concrete/single_pages/dashboard/system/seo/codes.php +++ b/concrete/single_pages/dashboard/system/seo/codes.php @@ -19,17 +19,42 @@ defined('C5_EXECUTE') or die('Access Denied.'); <div class="form-group"> <?= $form->label('tracking_code_header', t('Header Tracking Codes')) ?> - <?= $form->textarea('tracking_code_header', $tracking_code_header, ['style' => 'height: 250px;', 'class' => 'form-control font-monospace', 'spellcheck' => 'false']) ?> + <?= $form->textarea('tracking_code_header_input', $tracking_code_header, ['style' => 'height: 250px;', 'class' => 'form-control font-monospace', 'spellcheck' => 'false']) ?> + <?= $form->hidden('tracking_code_header', '') ?> </div> <div class="form-group"> <?= $form->label('tracking_code_footer', t('Footer Tracking Codes')) ?> - <?= $form->textarea('tracking_code_footer', $tracking_code_footer, ['style' => 'height: 250px;', 'class' => 'form-control font-monospace', 'spellcheck' => 'false']) ?> + <?= $form->textarea('tracking_code_footer_input', $tracking_code_footer, ['style' => 'height: 250px;', 'class' => 'form-control font-monospace', 'spellcheck' => 'false']) ?> + <?= $form->hidden('tracking_code_footer', '') ?> </div> <div class="ccm-dashboard-form-actions-wrapper"> <div class="ccm-dashboard-form-actions"> - <button type="submit" class="btn btn-primary float-end"><?= t('Save') ?></button> + <button type="submit" id="tracking-code-form-button" class="btn btn-primary float-end"><?= t('Save') ?></button> </div> </div> </form> + +<script> + document.addEventListener('DOMContentLoaded', function(event) { + var trackingCodeForm = document.getElementById("tracking-code-form-button"); + var trackingCodeHeaderInput = document.getElementById("tracking_code_header_input"); + var trackingCodeFooterInput = document.getElementById("tracking_code_footer_input"); + var trackingCodeHeader = document.getElementById("tracking_code_header"); + var trackingCodeFooter = document.getElementById("tracking_code_footer"); + + trackingCodeForm.addEventListener("click", function(e) { + trackingCodeHeader.value = b64EncodeUnicode(trackingCodeHeaderInput.value); + trackingCodeHeaderInput.setAttribute("disabled", "disabled"); + trackingCodeFooter.value = b64EncodeUnicode(trackingCodeFooterInput.value); + trackingCodeFooterInput.setAttribute("disabled", "disabled"); + }); + }); + + function b64EncodeUnicode(str) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { + return String.fromCharCode('0x' + p1); + })); + } +</script>
Use base<I> encoding and decoding on submitted tracking codes, to avoid Mod Security related blocks
concrete5_concrete5
train
41e3625339413b3ba7bae8fa5ac990a16108da8f
diff --git a/lib/wp2txt.rb b/lib/wp2txt.rb index <HASH>..<HASH> 100755 --- a/lib/wp2txt.rb +++ b/lib/wp2txt.rb @@ -6,6 +6,7 @@ $: << File.join(File.dirname(__FILE__)) require "nokogiri" require "parallel" +require 'etc' require 'pp' require "wp2txt/article" require "wp2txt/utils"
fix: cannot initialize Etc variables
yohasebe_wp2txt
train
77aa4b94877e411953437abb07eff633ce5254fb
diff --git a/lib/bibformat_regression_tests.py b/lib/bibformat_regression_tests.py index <HASH>..<HASH> 100644 --- a/lib/bibformat_regression_tests.py +++ b/lib/bibformat_regression_tests.py @@ -231,7 +231,12 @@ class BibFormatNLMTest(unittest.TestCase): pageurl = CFG_SITE_URL + '/record/70?of=xn' result = test_web_page_content(pageurl, expected_text=self.record_70_xn) - self.assertEqual([], result) + try: + self.assertEqual([], result) + except AssertionError: + result = test_web_page_content(pageurl, + expected_text=self.record_70_xn.replace('<fpage/>', '<fpage></fpage>').replace('<lpage/>', '<lpage></lpage>')) + self.assertEqual([], result) class BibFormatBriefHTMLTest(unittest.TestCase): """Check output produced by BibFormat for brief HTML ouput for
Fixed NLM output test for XSL processors that don't group empty elements.
inveniosoftware_invenio-formatter
train
4f814323219baf1be6509be6b4bd7a721a652bea
diff --git a/tests/unit/transport/test_zeromq.py b/tests/unit/transport/test_zeromq.py index <HASH>..<HASH> 100644 --- a/tests/unit/transport/test_zeromq.py +++ b/tests/unit/transport/test_zeromq.py @@ -383,7 +383,7 @@ class PubServerChannel(TestCase, AdaptedConfigurationTestCaseMixin): ctx = zmq.Context() sock = ctx.socket(zmq.SUB) sock.setsockopt(zmq.LINGER, -1) - sock.subscribe(b'') + sock.setsockopt(zmq.SUBSCRIBE, b'') sock.connect(pub_uri) last_msg = time.time() serial = salt.payload.Serial(opts)
Set subscribe via sockopt for better compatibility
saltstack_salt
train
0e2c7fb7e617f264dfb7a96df202bb643f26a2d5
diff --git a/plexapi/base.py b/plexapi/base.py index <HASH>..<HASH> 100644 --- a/plexapi/base.py +++ b/plexapi/base.py @@ -251,14 +251,6 @@ class PlexObject(object): def _loadData(self, data): raise NotImplementedError('Abstract method not implemented.') - def delete(self): - try: - return self._server.query(self.key, method=self._server._session.delete) - except BadRequest: - log.error("Failed to delete %s. This could be because you havn't allowed " - "items to be deleted" % self.key) - raise - class PlexPartialObject(PlexObject): """ Not all objects in the Plex listings return the complete list of elements @@ -267,6 +259,14 @@ class PlexPartialObject(PlexObject): automatically and update itself. """ + def delete(self): + try: + return self._server.query(self.key, method=self._server._session.delete) + except BadRequest: + log.error("Failed to delete %s. This could be because you havn't allowed " + "items to be deleted" % self.key) + raise + def __eq__(self, other): return other is not None and self.key == other.key diff --git a/tests/conftest.py b/tests/conftest.py index <HASH>..<HASH> 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -163,6 +163,7 @@ def monkeydownload(request, monkeypatch): def callable_http_patch(): + """This intented to stop some http requests inside some tests.""" return patch('plexapi.server.requests.sessions.Session.send', return_value=MagicMock(status_code=200, text='<xml><child></child></xml>')) @@ -176,6 +177,7 @@ def empty_response(mocker): @pytest.fixture() def patched_http_call(mocker): + """This will stop any http calls inside any test.""" return mocker.patch('plexapi.server.requests.sessions.Session.send', return_value=MagicMock(status_code=200, text='<xml><child></child></xml>') diff --git a/tests/test_library.py b/tests/test_library.py index <HASH>..<HASH> 100644 --- a/tests/test_library.py +++ b/tests/test_library.py @@ -128,8 +128,7 @@ def test_library_MovieSection_refresh(movies, patched_http_call): def test_library_MovieSection_search_genre(movie, movies): - # assert len(movie.genres[0].items()) # TODO - assert len(movies.search(genre=movie.genres[0])) > 1 + assert len(movies.search(genre=animation[0])) > 1 def test_library_MovieSection_cancelUpdate(movies): diff --git a/tests/test_video.py b/tests/test_video.py index <HASH>..<HASH> 100644 --- a/tests/test_video.py +++ b/tests/test_video.py @@ -64,9 +64,9 @@ def test_video_Movie_delete_part(movie, mocker): # we need to reload this as there is a bug in part.delete # See https://github.com/pkkid/python-plexapi/issues/201 m = movie.reload() - for part in m.iterParts(): + for media in m.media: with utils.callable_http_patch(): - part.delete() + media.delete() def test_video_Movie_iterParts(movie):
fixup move delete to partial as not everything is deletable fix library genre test fix delete media.
pkkid_python-plexapi
train
ab7fd2d087ced69b48ef830ed7218b97b663b000
diff --git a/fireplace/cards/classic/hunter.py b/fireplace/cards/classic/hunter.py index <HASH>..<HASH> 100644 --- a/fireplace/cards/classic/hunter.py +++ b/fireplace/cards/classic/hunter.py @@ -123,6 +123,22 @@ class EX1_544: self.controller.draw() +# Freezing Trap +class EX1_611: + def ATTACK(self, source, target): + if source.controller is self.controller.opponent and source.type == CardType.MINION: + source.bounce() + self.buff(source, "EX1_611e") + self.reveal() + +class EX1_611e: + Cost = 2 + + # Remove the buff when the card is played + def AFTER_SELF_CARD_PLAYED(self): + self.destroy() + + # Deadly Shot class EX1_617: def action(self): diff --git a/tests/test_main.py b/tests/test_main.py index <HASH>..<HASH> 100755 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -2535,6 +2535,37 @@ def test_flare(): assert not worgen.stealthed +def test_freezing_trap(): + game = prepare_game() + wisp = game.player1.give(WISP) + wisp.play() + game.endTurn(); game.endTurn() + game.endTurn() + + trap = game.player2.give("EX1_611") + trap.play() + assert game.player2.secrets + game.endTurn() + + assert wisp.cost == 0 + assert not wisp.buffs + assert wisp.zone == Zone.PLAY + assert game.player2.hero.health == 30 + wisp.attack(target=game.player2.hero) + assert not game.player2.secrets + assert trap.zone == Zone.GRAVEYARD + assert game.player2.hero.health == 30 + assert wisp.zone == Zone.HAND + assert wisp in game.player1.hand + assert wisp.buffs + assert wisp.cost == 2 + assert wisp.zone == Zone.HAND + wisp.play() + assert game.player1.usedMana == 2 + assert not wisp.buffs + assert wisp.cost == 0 + + def test_warlock(): game = prepare_game(WARLOCK, WARLOCK) sacpact = game.currentPlayer.give("NEW1_003")
Implement Freezing Trap, with tests
jleclanche_fireplace
train
945096828fa5a3b89ee23fad363a178a1a2e2f92
diff --git a/tests/test-sessions.php b/tests/test-sessions.php index <HASH>..<HASH> 100644 --- a/tests/test-sessions.php +++ b/tests/test-sessions.php @@ -82,4 +82,36 @@ class User_Switching_Test_Sessions extends User_Switching_Test { $this->assertSame( $admin_token, $parts['token'] ); } + public function testPreviousSessionForUserIsReusedWhenSwitchingBack() { + if ( is_multisite() ) { + $admin = self::$testers['super']; + } else { + $admin = self::$testers['admin']; + } + + // Set up the admin session manager with a session + $admin_manager = WP_Session_Tokens::get_instance( $admin->ID ); + $admin_token = $admin_manager->create( time() + DAY_IN_SECONDS ); + $admin_before = $admin_manager->get_all(); + + // Set up the admin user state + wp_set_current_user( $admin->ID ); + wp_set_auth_cookie( $admin->ID, false, '', $admin_token ); + + // Verify the initial state + $this->assertCount( 1, $admin_before ); + + // Switch user + $user = $this->switch_to_user( self::$users['author']->ID ); + + // Verify no new sessions were created for the old user + $this->assertCount( 1, $admin_manager->get_all() ); + + // Switch back + $user = $this->switch_to_user( $admin->ID, false, false ); + + // Verify no new sessions were created for the original user + $this->assertCount( 1, $admin_manager->get_all() ); + } + } diff --git a/user-switching.php b/user-switching.php index <HASH>..<HASH> 100644 --- a/user-switching.php +++ b/user-switching.php @@ -1029,17 +1029,23 @@ if ( ! function_exists( 'switch_to_user' ) ) { return false; } - $old_user_id = ( is_user_logged_in() ) ? get_current_user_id() : false; - $old_token = function_exists( 'wp_get_session_token' ) ? wp_get_session_token() : ''; + $old_user_id = ( is_user_logged_in() ) ? get_current_user_id() : false; + $old_token = function_exists( 'wp_get_session_token' ) ? wp_get_session_token() : ''; + $auth_cookie = user_switching_get_auth_cookie(); + $cookie_parts = wp_parse_auth_cookie( end( $auth_cookie ) ); if ( $set_old_user && $old_user_id ) { + // switching to another user + $new_token = ''; user_switching_set_olduser_cookie( $old_user_id, false, $old_token ); } else { + // switching back, either after being switched off or after being switched to another user + $new_token = isset( $cookie_parts['token'] ) ? $cookie_parts['token'] : ''; user_switching_clear_olduser_cookie( false ); } wp_clear_auth_cookie(); - wp_set_auth_cookie( $user_id, $remember ); + wp_set_auth_cookie( $user_id, $remember, '', $new_token ); wp_set_current_user( $user_id ); if ( $set_old_user ) {
First pass at reusing existing session when switching back to the original user.
johnbillion_user-switching
train
9e4a44b302d3a3e49aa014062b42de84480a8d4f
diff --git a/git/test/test_submodule.py b/git/test/test_submodule.py index <HASH>..<HASH> 100644 --- a/git/test/test_submodule.py +++ b/git/test/test_submodule.py @@ -344,8 +344,9 @@ class TestSubmodule(TestBase): abspmp = nsm.abspath assert nsm.move(nmp) is nsm nmp = nmp[:-1] # cut last / - assert nsm.path == nmp - assert rwrepo.submodules[0].path == nmp + nmpl = to_native_path_linux(nmp) + assert nsm.path == nmpl + assert rwrepo.submodules[0].path == nmpl mpath = 'newsubmodule' absmpath = join_path_native(rwrepo.working_tree_dir, mpath)
fixed submodule test to work on windows
gitpython-developers_GitPython
train
308c233ddb6b3294080c8f3c44950debf4a88d6b
diff --git a/datapoint/Manager.py b/datapoint/Manager.py index <HASH>..<HASH> 100644 --- a/datapoint/Manager.py +++ b/datapoint/Manager.py @@ -287,18 +287,11 @@ class Manager(object): return self.get_nearest_forecast_site(latitude, longitude) - def get_nearest_forecast_site(self, latitude=None, longitude=None): + def get_nearest_forecast_site(self, latitude, longitude): """ This function returns the nearest Site object to the specified coordinates. """ - if longitude is None: - print('ERROR: No latitude given.') - return False - - if latitude is None: - print('ERROR: No latitude given.') - return False nearest = False distance = None
Require arguments to get_nearest_forecast_site. Remove logic which checked if arguments were given
jacobtomlinson_datapoint-python
train
2c9e480037e3efaa7a90c45715cb1b371b3e9a18
diff --git a/tests/Export/PgsqlTestCase.php b/tests/Export/PgsqlTestCase.php index <HASH>..<HASH> 100644 --- a/tests/Export/PgsqlTestCase.php +++ b/tests/Export/PgsqlTestCase.php @@ -79,7 +79,7 @@ class Doctrine_Export_Pgsql_TestCase extends Doctrine_UnitTestCase } public function testExportSql() { - $sql = $this->export->exportClassesSql(array("FooRecord", "FooReferenceRecord", "FooLocallyOwned", "FooForeignlyOwned", "FooBarRecord", "BarRecord")); + $sql = $this->export->exportClassesSql(array("FooRecord", "FooReferenceRecord", "FooLocallyOwned", "FooForeignlyOwned", "FooForeignlyOwnedWithPK", "FooBarRecord", "BarRecord")); //dirname(__FILE__) . DIRECTORY_SEPARATOR . '_files'); $this->assertEqual($sql, array ( 0 => 'CREATE TABLE foo_reference (foo1 BIGINT, foo2 BIGINT, PRIMARY KEY(foo1, foo2))',
fixed propper input to test so that it runs successfully
doctrine_orm
train
0e37beb93c0e9b6a13777c482a675727b552b415
diff --git a/tests/semantic_tree_test.js b/tests/semantic_tree_test.js index <HASH>..<HASH> 100644 --- a/tests/semantic_tree_test.js +++ b/tests/semantic_tree_test.js @@ -9942,5 +9942,5 @@ sre.SemanticTreeTest.prototype.testStreeActions = function() { '<number>2</number>'); this.executeTreeTest( '<maction><mtext>something</mtext><mi>a</mi></maction>', - '<identifier>2</identifier>'); + '<identifier>a</identifier>'); };
Fixes second maction test.
zorkow_speech-rule-engine
train
fe76a7c9217ec3dc8e30a0a963e8f94e51319798
diff --git a/upload/admin/controller/extension/openbay.php b/upload/admin/controller/extension/openbay.php index <HASH>..<HASH> 100644 --- a/upload/admin/controller/extension/openbay.php +++ b/upload/admin/controller/extension/openbay.php @@ -126,7 +126,7 @@ class ControllerExtensionOpenbay extends Controller { $data['extensions'][] = array( 'name' => $this->language->get('heading_title'), 'edit' => $this->url->link('openbay/' . $extension . '', 'token=' . $this->session->data['token'], 'SSL'), - 'status' => $this->config->get($extension . '_status') ? $this->language->get('text_enabled') : $this->language->get('text_disabled'), + 'status' => ($this->config->get('openbay_' . $extension . '_status') || $this->config->get($extension . '_status')) ? $this->language->get('text_enabled') : $this->language->get('text_disabled'), 'install' => $this->url->link('extension/openbay/install', 'token=' . $this->session->data['token'] . '&extension=' . $extension, 'SSL'), 'uninstall' => $this->url->link('extension/openbay/uninstall', 'token=' . $this->session->data['token'] . '&extension=' . $extension, 'SSL'), 'installed' => in_array($extension, $extensions),
Fixed missmatched group name for status check on openbay.
opencart_opencart
train
e5ef3abdd2336c34cd853a1f845f79b8b19fbb1b
diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/scoping.rb +++ b/activerecord/lib/active_record/scoping.rb @@ -36,7 +36,7 @@ module ActiveRecord # to get the current_scope for the +Board+ model, then you would use the # following code: # - # registry = ActiveRecord::Scoping::ScopeRegistry.instance + # registry = ActiveRecord::Scoping::ScopeRegistry # registry.set_value_for(:current_scope, "Board", some_new_scope) # # Now when you run: @@ -52,10 +52,6 @@ module ActiveRecord class ScopeRegistry # :nodoc: extend ActiveSupport::PerThreadRegistry - class << self - delegate :value_for, :set_value_for, to: :instance - end - VALID_SCOPE_TYPES = [:current_scope, :ignore_default_scope] def initialize diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1377,9 +1377,9 @@ class BasicsTest < ActiveRecord::TestCase UnloadablePost.send(:current_scope=, UnloadablePost.all) UnloadablePost.unloadable - assert_not_nil ActiveRecord::Scoping::ScopeRegistry.instance.value_for(:current_scope, "UnloadablePost") + assert_not_nil ActiveRecord::Scoping::ScopeRegistry.value_for(:current_scope, "UnloadablePost") ActiveSupport::Dependencies.remove_unloadable_constants! - assert_nil ActiveRecord::Scoping::ScopeRegistry.instance.value_for(:current_scope, "UnloadablePost") + assert_nil ActiveRecord::Scoping::ScopeRegistry.value_for(:current_scope, "UnloadablePost") ensure Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost) end diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -193,10 +193,6 @@ module ActiveSupport class InstrumentationRegistry # :nodoc: extend ActiveSupport::PerThreadRegistry - class << self - delegate :instrumenter_for, to: :instance - end - def initialize @registry = {} end diff --git a/activesupport/lib/active_support/per_thread_registry.rb b/activesupport/lib/active_support/per_thread_registry.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/per_thread_registry.rb +++ b/activesupport/lib/active_support/per_thread_registry.rb @@ -1,7 +1,11 @@ module ActiveSupport # This module is used to encapsulate access to thread local variables. # - # Given + # Instead of polluting the thread locals namespace: + # + # Thread.current[:connection_handler] + # + # you define a class that extends this module: # # module ActiveRecord # class RuntimeRegistry @@ -11,34 +15,40 @@ module ActiveSupport # end # end # - # <tt>ActiveRecord::RuntimeRegistry</tt> gets an +instance+ class method - # that returns an instance of the class unique to the current thread. Thus, - # instead of polluting +Thread.current+ - # - # Thread.current[:connection_handler] - # - # you write + # and invoke the declared instance accessors as class methods. So # - # ActiveRecord::RuntimeRegistry.instance.connection_handler + # ActiveRecord::RuntimeRegistry.connection_handler = connection_handler # - # A +method_missing+ handler that proxies to the thread local instance is - # installed in the extended class so the call above can be shortened to + # sets a connection handler local to the current thread, and # # ActiveRecord::RuntimeRegistry.connection_handler # - # The instance is stored as a thread local keyed by the name of the class, - # that is the string "ActiveRecord::RuntimeRegistry" in the example above. + # returns a connection handler local to the current thread. + # + # This feature is accomplished by instantiating the class and storing the + # instance as a thread local keyed by the class name. In the example above + # a key "ActiveRecord::RuntimeRegistry" is stored in <tt>Thread.current</tt>. + # The class methods proxy to said thread local instance. # # If the class has an initializer, it must accept no arguments. module PerThreadRegistry - def instance - Thread.current[self.name] ||= new - end - protected - def method_missing(*args, &block) - instance.public_send(*args, &block) + def method_missing(name, *args, &block) + # Caches the method definition as a singleton method of the receiver. + singleton_class.class_eval do + define_method(name) do |*a, &b| + per_thread_registry_instance.public_send(name, *a, &b) + end + end + + send(name, *args, &block) + end + + private + + def per_thread_registry_instance + Thread.current[name] ||= new end end end
hides the per thread registry instance, and caches singleton methods Existing code was delegating to the instance with delegate macro calls, or invoking the instance method to reach the object and call its instance methods. But the point is to have a clean class-level interface where the thread local instance is hidden in the implementation. References #<I>c<I>. References #<I>.
rails_rails
train
12d501479f667c1fbeb01ebea6a5c734db04a797
diff --git a/src/Northern/Common/Util/ArrayUtil.php b/src/Northern/Common/Util/ArrayUtil.php index <HASH>..<HASH> 100644 --- a/src/Northern/Common/Util/ArrayUtil.php +++ b/src/Northern/Common/Util/ArrayUtil.php @@ -426,10 +426,10 @@ abstract class ArrayUtil { } /** - * This method tests for the existance of $needle in $haystack. If $needle is a + * This method tests for the existence of $needle in $haystack. If $needle is a * non-array type this method will function exaclty like the build in PHP in_array * function, however, if $needle is an array this method will iterate over each - * of the items in the $needle array and checks for the existance of each of the + * of the items in the $needle array and checks for the existence of each of the * values in $haystack. * * @param mixed $needle @@ -467,7 +467,7 @@ abstract class ArrayUtil { * @param string $delimiter * @return mixed */ - public static function extract( &$arr, $path, $default = NULL, $delimiter = '.' ) + public static function extract( array &$arr, $path, $default = NULL, $delimiter = '.' ) { $value = static::get( $arr, $path, $default, $delimiter ); @@ -476,4 +476,17 @@ abstract class ArrayUtil { return $value; } + /** + * Performs a "deep" compare on two given arrays. This method returns TRUE if both + * arrays are exactly the same, otherwise this method will return FALSE. + * + * @param array $a + * @param array $b + * @return boolean + */ + public static function compare( array $a, array $b ) + { + return serialize($a) === serialize($b); + } + } diff --git a/tests/src/Northern/Test/Common/Util/ArrayUtilTest.php b/tests/src/Northern/Test/Common/Util/ArrayUtilTest.php index <HASH>..<HASH> 100644 --- a/tests/src/Northern/Test/Common/Util/ArrayUtilTest.php +++ b/tests/src/Northern/Test/Common/Util/ArrayUtilTest.php @@ -407,6 +407,20 @@ class ArrayUtilTest extends \PHPUnit_Framework_TestCase { $this->assertFalse( $value ); } + public function testCompare() + { + $data1 = $this->getTestData(); + $data2 = $this->getTestData(); + + $value = Arr::compare( $data1, $data2 ); + $this->assertTrue( $value ); + + $data2 = array_reverse( $data1, TRUE ); + + $value = Arr::compare( $data1, $data2 ); + $this->assertFalse( $value ); + } + public function getTestData() { $data = array( @@ -421,5 +435,5 @@ class ArrayUtilTest extends \PHPUnit_Framework_TestCase { return $data; } - + }
Added compare method to the ArrayUtil class.
northern_PHP-Common
train
12096ace6b53be56839afb53df8d46037fc9e2d7
diff --git a/lib/OpenLayers/Feature/Vector.js b/lib/OpenLayers/Feature/Vector.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Feature/Vector.js +++ b/lib/OpenLayers/Feature/Vector.js @@ -316,16 +316,11 @@ OpenLayers.Feature.Vector = OpenLayers.Class(OpenLayers.Feature, { * * - fillColor: "#ee9900", * - fillOpacity: 0.4, - * - hoverFillColor: "white", - * - hoverFillOpacity: 0.8, * - strokeColor: "#ee9900", * - strokeOpacity: 1, * - strokeWidth: 1, * - strokeLinecap: "round", [butt | round | square] * - strokeDashstyle: "solid", [dot | dash | dashdot | longdash | longdashdot | solid] - * - hoverStrokeColor: "red", - * - hoverStrokeOpacity: 1, - * - hoverStrokeWidth: 0.2, * - pointRadius: 6, * - hoverPointRadius: 1, * - hoverPointUnit: "%",
Remove hover* properties from documentation. Leaving in code for now, but so far as I can tell, these would depend on support from some specification, and the only code on the web which mentions them are duplicate copies of OpenLayers documentation. We should probably remove these from the corresponding style blocks as well. git-svn-id: <URL>
openlayers_openlayers
train
867b889935563ea33bfd69ca28fe5fb7e4df9c01
diff --git a/test_flask_ldapconn.py b/test_flask_ldapconn.py index <HASH>..<HASH> 100644 --- a/test_flask_ldapconn.py +++ b/test_flask_ldapconn.py @@ -68,7 +68,7 @@ class LDAPConnSearchTestCase(LDAPConnTestCase): with self.app.test_request_context(): conn = self.ldap.connection whoami = conn.extend.standard.who_am_i() - self.assertEqual(whoami.decode('utf-8'), + self.assertEqual(whoami, 'dn:{}'.format(self.app.config['LDAP_BINDDN'])) @@ -256,6 +256,7 @@ class LDAPConnModelTestCase(unittest.TestCase): self.assertTrue(mod_user.save()) user = self.user.query.filter(query_filter).first() self.assertEqual(user.givenname.value, 'Rafael') + self.assertEqual(user.surname.value, u'Römhild') self.assertEqual(user.title.value, 'SysAdmin') self.assertTrue('it@planetexpress.co' in user.email) @@ -351,7 +352,7 @@ class LDAPConnSSLTestCase(unittest.TestCase): with self.app.test_request_context(): conn = self.ldap.connection whoami = conn.extend.standard.who_am_i() - self.assertEqual(whoami.decode('utf-8'), + self.assertEqual(whoami, 'dn:{}'.format(self.app.config['LDAP_BINDDN'])) @@ -411,7 +412,7 @@ class LDAPConnDeprecatedTestCAse(LDAPConnTestCase): def test_whoami_deprecated(self): with self.app.test_request_context(): whoami = self.ldap.whoami() - self.assertEqual(whoami.decode('utf-8'), + self.assertEqual(whoami, 'dn:{}'.format(self.app.config['LDAP_BINDDN']))
who_am_i() now try to decode the authzid as unicode
rroemhild_flask-ldapconn
train
29a508691aebfa8c23531cc4e55297d1c6a14a9b
diff --git a/tangy-form-reducer.js b/tangy-form-reducer.js index <HASH>..<HASH> 100644 --- a/tangy-form-reducer.js +++ b/tangy-form-reducer.js @@ -18,14 +18,11 @@ const tangyFormReducer = function (state = initialState, action) { case 'FORM_OPEN': newState = Object.assign({}, action.response) - newState.items = action.itemsInDom.map(itemInDom => { - const matchingItemInResponse = newState.items.find(item => item.id === itemInDom.id) - if (matchingItemInResponse) { - return { ...itemInDom, ...matchingItemInResponse } - } else { - return itemInDom - } - }) + // Ensure that the only items we have in the response are those that are in the DOM but maintain state of the existing items in the response. + newState.items = action.itemsInDom.map(itemInDom => newState.items.find(item => item.id === itemInDom.id) + ? { ...itemInDom, ...newState.items.find(item => item.id === itemInDom.id) } + : itemInDom + ) firstNotDisabled = newState.items.findIndex(item => item.disabled === false) newState.items[firstNotDisabled].hideBackButton = true const indexOfSummaryItem = newState.items.findIndex(item => item.summary === true)
Make pruning of response items more compact and document
Tangerine-Community_tangy-form
train
71f1d039b8ad7d5862eefc9e46ba889e6cc4f0ca
diff --git a/Db/DAL.php b/Db/DAL.php index <HASH>..<HASH> 100644 --- a/Db/DAL.php +++ b/Db/DAL.php @@ -173,7 +173,7 @@ class DAL implements \Iterator { /** * Remove a FROM table. * @param string $what - * @return DALm $this + * @return DAL $this * @api */ public function removeFrom($what) { @@ -1106,7 +1106,7 @@ class DAL implements \Iterator { /** * Update rows. * @param array $values - * @return Query + * @return integer * @api */ public function update(array $values) { @@ -1118,7 +1118,7 @@ class DAL implements \Iterator { /** * Insert rows. * @param array $values - * @return Query + * @return integer * @api */ public function insert(array $values) { @@ -1130,8 +1130,8 @@ class DAL implements \Iterator { /** * Delete rows. - * @param array $tables - * @return Query + * @param string[] $tables + * @return integer * @api */ public function delete(array $tables=[]) { @@ -1175,7 +1175,8 @@ class DAL implements \Iterator { /** * Count number of rows. - * @param string $group_by + * @param string $group_by + * @param string $what * @return string * @api */
Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on <URL>
asgardphp_asgard
train
4d9348e1d5f1c895b3e96318de9c894187f2e2e7
diff --git a/core/eolearn/core/__init__.py b/core/eolearn/core/__init__.py index <HASH>..<HASH> 100644 --- a/core/eolearn/core/__init__.py +++ b/core/eolearn/core/__init__.py @@ -27,7 +27,7 @@ from .eotask import EOTask from .eoworkflow import EOWorkflow, WorkflowResults from .eoworkflow_tasks import OutputTask from .utils.common import deep_eq -from .utils.fs import get_filesystem, load_s3_filesystem +from .utils.fs import get_filesystem, load_s3_filesystem, pickle_fs, unpickle_fs from .utils.parallelize import execute_with_mp_lock, join_futures, join_futures_iter, parallelize from .utils.parsing import FeatureParser diff --git a/core/eolearn/tests/test_utils/test_fs.py b/core/eolearn/tests/test_utils/test_fs.py index <HASH>..<HASH> 100644 --- a/core/eolearn/tests/test_utils/test_fs.py +++ b/core/eolearn/tests/test_utils/test_fs.py @@ -25,8 +25,8 @@ from moto import mock_s3 from sentinelhub import SHConfig -from eolearn.core import get_filesystem, load_s3_filesystem -from eolearn.core.utils.fs import get_aws_credentials, get_full_path, join_path, pickle_fs, unpickle_fs +from eolearn.core import get_filesystem, load_s3_filesystem, pickle_fs, unpickle_fs +from eolearn.core.utils.fs import get_aws_credentials, get_full_path, join_path def test_get_local_filesystem(tmp_path): diff --git a/io/eolearn/io/geometry_io.py b/io/eolearn/io/geometry_io.py index <HASH>..<HASH> 100644 --- a/io/eolearn/io/geometry_io.py +++ b/io/eolearn/io/geometry_io.py @@ -19,8 +19,8 @@ from fs_s3fs import S3FS from sentinelhub import CRS, GeopediaFeatureIterator, SHConfig -from eolearn.core import EOPatch, EOTask, FeatureTypeSet -from eolearn.core.utils.fs import get_base_filesystem_and_path, get_full_path, pickle_fs, unpickle_fs +from eolearn.core import EOPatch, EOTask, FeatureTypeSet, pickle_fs, unpickle_fs +from eolearn.core.utils.fs import get_base_filesystem_and_path, get_full_path LOGGER = logging.getLogger(__name__)
Imported pickle_fs and unpickle_fs into eolearn.core.__init__
sentinel-hub_eo-learn
train
5d4e3c86d170d5a811fb610427b3e80b5a37ac9d
diff --git a/respite/middleware.py b/respite/middleware.py index <HASH>..<HASH> 100644 --- a/respite/middleware.py +++ b/respite/middleware.py @@ -21,9 +21,12 @@ class HttpMethodOverrideMiddleware: request.POST.get('_method') ).upper() - # Discard the "_method" key in the interest of keeping the request pristine. - if '_method' in request.POST: - request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data) + # In the interest of keeping the request pristine, we discard the "_method" key + # and set its "POST" attribute to an empty QueryDict. + if '_method' in request.POST: + request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data) + + request.POST = QueryDict('') class HttpPutMiddleware: """ diff --git a/tests/test_middleware.py b/tests/test_middleware.py index <HASH>..<HASH> 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -32,3 +32,4 @@ def test_http_method_override_middleware(): HttpMethodOverrideMiddleware().process_request(request) assert_equal(request.method, 'PUT') + assert_equal(request.POST, {})
Reset "request.POST" upon method override. Fixes #<I>
jgorset_django-respite
train
6f5b1936ab08adc7389ab7cd91b091ae5d1c1e34
diff --git a/pytradfri/device.py b/pytradfri/device.py index <HASH>..<HASH> 100644 --- a/pytradfri/device.py +++ b/pytradfri/device.py @@ -12,7 +12,8 @@ from .const import ( ATTR_LIGHT_DIMMER, ATTR_LIGHT_COLOR_X, ATTR_LIGHT_COLOR_Y, - ATTR_LIGHT_COLOR + ATTR_LIGHT_COLOR, + ATTR_TRANSITION_TIME ) from .resource import ApiResource @@ -145,14 +146,19 @@ class LightControl: ATTR_LIGHT_STATE: int(state) }, index=index) - def set_dimmer(self, dimmer, *, index=0): + def set_dimmer(self, dimmer, *, index=0, transition_time=None): """Set dimmer value of a light. - Integer between 0..255 + dimmer: Integer between 0..255 + transition_time: Integer representing tenth of a second (default None) """ - self.set_values({ - ATTR_LIGHT_DIMMER: dimmer, - }, index=index) + values = { + ATTR_LIGHT_DIMMER: dimmer + } + if transition_time is not None: + values[ATTR_TRANSITION_TIME] = transition_time + + self.set_values(values, index=index) def set_hex_color(self, color, *, index=0): """Set xy color of the light.""" diff --git a/pytradfri/group.py b/pytradfri/group.py index <HASH>..<HASH> 100644 --- a/pytradfri/group.py +++ b/pytradfri/group.py @@ -3,6 +3,7 @@ from .const import ( ATTR_LIGHT_STATE, ATTR_LIGHT_DIMMER, ATTR_ID, + ATTR_TRANSITION_TIME ) from .resource import ApiResource @@ -66,14 +67,18 @@ class Group(ApiResource): ATTR_LIGHT_STATE: int(state) }) - def set_dimmer(self, dimmer): + def set_dimmer(self, dimmer, transition_time=None): """Set dimmer value of a group. - Integer between 0..255 + dimmer: Integer between 0..255 + transition_time: Integer representing tenth of a second (default None) """ - self.set_values({ + values = { ATTR_LIGHT_DIMMER: dimmer, - }) + } + if transition_time is not None: + values[ATTR_TRANSITION_TIME] = transition_time + self.set_values(values) def __repr__(self): state = 'on' if self.state else 'off'
Added support for transition time (#<I>) * Added support for transition time * remove white space * Transition time as optional keyword argument to set_dimmer * comment line shorter to pass the build
ggravlingen_pytradfri
train
ed64507d938d7f41cf21f9104db275927a0729f4
diff --git a/tests/Mongolid/Cursor/EmbeddedCursorTest.php b/tests/Mongolid/Cursor/EmbeddedCursorTest.php index <HASH>..<HASH> 100644 --- a/tests/Mongolid/Cursor/EmbeddedCursorTest.php +++ b/tests/Mongolid/Cursor/EmbeddedCursorTest.php @@ -50,7 +50,7 @@ class EmbeddedCursorTest extends TestCase $cursor = $this->getCursor(stdClass::class, $items); // Assert - $cursor->sort(['age' => 1, 'name' - 1]); + $cursor->sort(['age' => 1, 'name' -1]); $this->assertAttributeEquals( [ (object) ['age' => 24],
Try to fix a test on php <I>
leroy-merlin-br_mongolid
train
0dc5d27dff72141108c9042abd9325325f6fa082
diff --git a/bakery/project/views.py b/bakery/project/views.py index <HASH>..<HASH> 100644 --- a/bakery/project/views.py +++ b/bakery/project/views.py @@ -81,6 +81,8 @@ def project_required(f): return f(user, p, *args, **kwargs) else: flash(_('Project is being synchronized, wait until it is done')) + if request.path == url_for('project.queue', username=user.login, project_id=p.id): + return f(user, p, *args, **kwargs) return redirect(url_for('project.queue', username=user.login, project_id=p.id)) return decorated_function diff --git a/checker-cli.py b/checker-cli.py index <HASH>..<HASH> 100755 --- a/checker-cli.py +++ b/checker-cli.py @@ -27,8 +27,9 @@ if __name__ == '__main__': parser.add_argument('action', help="Action or target test suite", choices=['list', 'result', 'upstream', 'upstream-ttx', 'metadata', - 'description'],) + 'description', 'upstream-repo'],) parser.add_argument('file', nargs="*", help="Test files, can be a list") + parser.add_argument('--test', help="Test files, can be a list") parser.add_argument('--verbose', '-v', action='count', help="Verbosity level", default=1) @@ -42,7 +43,7 @@ if __name__ == '__main__': sys.exit(1) for x in args.file: - result = run_set(x, args.action) + result = run_set(x, args.action, test_method=args.test) failures = map(lambda x: (x._testMethodName, x._err_msg), result.get('failure', [])) error = map(lambda x: (x._testMethodName, x._err_msg), result.get('error', [])) if not bool(failures + error): diff --git a/checker/tests/upstream/test_prepolation.py b/checker/tests/upstream/test_prepolation.py index <HASH>..<HASH> 100644 --- a/checker/tests/upstream/test_prepolation.py +++ b/checker/tests/upstream/test_prepolation.py @@ -15,6 +15,8 @@ # # See AUTHORS.txt for the list of Authors and LICENSE.txt for the License. import fontforge +import lxml.etree +import os import os.path as op from checker.base import BakeryTestCase as TestCase @@ -46,10 +48,47 @@ class FontTestPrepolation(TestCase): glyphs = [] for f in directory.get_fonts(): - if f[-4:] in ['.ufo', '.sfd']: - glyphs_ = self.get_ufo_glyphs(f) - else: - glyphs_ = self.get_ttf_glyphs(f) + glyphs_ = self.get_glyphs(f) if glyphs and glyphs != glyphs_: self.fail('Family has different glyphs across fonts') + + def get_glyphs(self, f): + if f[-4:] in ['.ufo', '.sfd']: + return self.get_ufo_glyphs(f) + return self.get_ttf_glyphs(f) + + def get_contours(self, f, g): + file_extension = f[-4:] + if file_extension == '.ufo': + for k in os.listdir(op.join(self.path, f, 'glyphs')): + doc = lxml.etree.parse(op.join(self.path, f, 'glyphs', k)) + if not doc.xpath('//glyph[@name="%s"]' % g): + continue + + value = len(doc.xpath('//outline/contour')) + + components = doc.xpath('//outline/component/@base') + for component in components: + value += self.get_contours(f, component) + + return value + + if file_extension in ['.ttf', '.ttx', '.otf']: + pass + + def test_font_prepolation_glyph_contours(self): + """ Check that glyphs has same number of contours across family """ + directory = UpstreamDirectory(self.path) + + glyphs = {} + for f in directory.get_fonts(): + glyphs_ = self.get_glyphs(f) + + for g in glyphs_: + number_contours = self.get_contours(f, g) + if g in glyphs and glyphs[g] != number_contours: + msg = ('Number of contours of glyph "%s" does not match' + 'Expected %s contours, but actual is %s contours') + self.fail(msg % (g, glyphs[g], number_contours)) + glyphs[g] = number_contours
Test to check prepolation of contours number #<I>
googlefonts_fontbakery
train
a17f20183e789e2cd6068f2cdc68091e67ba42b2
diff --git a/enrol/authorize/index.php b/enrol/authorize/index.php index <HASH>..<HASH> 100644 --- a/enrol/authorize/index.php +++ b/enrol/authorize/index.php @@ -17,18 +17,18 @@ } /// Load strings. All strings should be defined here. locallib.php uses these strings. - $strs = get_strings(array('user','status','action','delete','time','course','confirm','yes','no','all','none','error')); - $authstrs = get_strings(array('paymentmanagement','orderid','void','capture','refund','delete', + $strs = get_strings(array('user','status','action','time','course','confirm','yes','no','all','none','error')); + $authstrs = get_strings(array('orderid','void','capture','refund','delete', 'authcaptured','authorizedpendingcapture','capturedpendingsettle','capturedsettled', 'settled','refunded','cancelled','expired','tested','new', - 'transid','settlementdate','notsettled','amount', - 'howmuch','captureyes','unenrolstudent'), 'enrol_authorize'); + 'transid','settlementdate','notsettled','amount','unenrolstudent'), 'enrol_authorize'); /// Print header + $strpaymentmanagement = get_string('paymentmanagement', 'enrol_authorize'); if (!$course = get_record('course', 'id', $courseid)) { error('Could not find that course'); } - print_header_simple("$authstrs->paymentmanagement", "", "<a href=\"index.php\">$authstrs->paymentmanagement</a>"); + print_header_simple("$strpaymentmanagement", "", "<a href=\"index.php\">$strpaymentmanagement</a>"); /// If orderid is empty, user wants to see all orders diff --git a/enrol/authorize/locallib.php b/enrol/authorize/locallib.php index <HASH>..<HASH> 100644 --- a/enrol/authorize/locallib.php +++ b/enrol/authorize/locallib.php @@ -215,8 +215,9 @@ function authorize_print_order_details($orderno) } if (empty($confirm)) { + $strcaptureyes = get_string('captureyes', 'enrol_authorize'); $table->data[] = array("<b>$strs->confirm:</b>", - "$authstrs->captureyes<br /><a href='index.php?order=$orderno&amp;sesskey=$USER->sesskey&amp;".ORDER_CAPTURE."=y&amp;confirm=1'>$strs->yes</a> + "$strcaptureyes<br /><a href='index.php?order=$orderno&amp;sesskey=$USER->sesskey&amp;".ORDER_CAPTURE."=y&amp;confirm=1'>$strs->yes</a> &nbsp;&nbsp;&nbsp;&nbsp;<a href='index.php?order=$orderno'>$strs->no</a>"); } else { @@ -286,9 +287,10 @@ function authorize_print_order_details($orderno) $a = new stdClass; $a->upto = $upto; $strcanbecredit = get_string('canbecredit', 'enrol_authorize', $a); + $strhowmuch = get_string('howmuch', 'enrol_authorize'); $cbunenrol = print_checkbox('unenrol', '1', !empty($unenrol), '', '', '', true); $table->data[] = array("<b>$authstrs->unenrolstudent</b>", $cbunenrol); - $table->data[] = array("<b>$authstrs->howmuch</b>", + $table->data[] = array("<b>$strhowmuch</b>", "<input type='hidden' name='confirm' value='1'> <input type='text' size='5' name='amount' value='$amount'> $strcanbecredit<br /><input type='submit' name='".ORDER_REFUND."' value='$authstrs->refund'>");
Unnecesary strings removed. Merged from MOODLE_<I>_MERGED
moodle_moodle
train
626f3df8f139485c8f14fbe5fd796d28bd2ef264
diff --git a/packages/node_modules/@ciscospark/plugin-people/test/integration/spec/people.js b/packages/node_modules/@ciscospark/plugin-people/test/integration/spec/people.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@ciscospark/plugin-people/test/integration/spec/people.js +++ b/packages/node_modules/@ciscospark/plugin-people/test/integration/spec/people.js @@ -3,7 +3,7 @@ * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ -import '../..'; +import '../../..'; import {assert} from '@ciscospark/test-helper-chai'; import CiscoSpark from '@ciscospark/spark-core'; diff --git a/packages/node_modules/@ciscospark/plugin-people/test/unit/spec/people.js b/packages/node_modules/@ciscospark/plugin-people/test/unit/spec/people.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@ciscospark/plugin-people/test/unit/spec/people.js +++ b/packages/node_modules/@ciscospark/plugin-people/test/unit/spec/people.js @@ -4,7 +4,7 @@ */ import {assert} from '@ciscospark/test-helper-chai'; -import People from '../..'; +import People from '../../..'; import MockSpark from '@ciscospark/test-helper-mock-spark'; describe(`plugin-people`, () => { diff --git a/packages/node_modules/@ciscospark/plugin-phone/test/unit/spec/web-rtc-media.js b/packages/node_modules/@ciscospark/plugin-phone/test/unit/spec/web-rtc-media.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@ciscospark/plugin-phone/test/unit/spec/web-rtc-media.js +++ b/packages/node_modules/@ciscospark/plugin-phone/test/unit/spec/web-rtc-media.js @@ -1,5 +1,5 @@ import sinon from '@ciscospark/test-helper-sinon'; -import handleErrorEvent from '../../../integration/lib/handle-error-event'; +import handleErrorEvent from '../../integration/lib/handle-error-event'; import {assert} from '@ciscospark/test-helper-chai'; import {WebRTCMedia} from '../../..'; import {parse} from 'sdp-transform'; diff --git a/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/ephemeral.js b/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/ephemeral.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/ephemeral.js +++ b/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/ephemeral.js @@ -6,7 +6,7 @@ import {assert} from '@ciscospark/test-helper-chai'; import MockSpark from '@ciscospark/test-helper-mock-spark'; import sinon from '@ciscospark/test-helper-sinon'; -import Device, {config} from '../..'; +import Device, {config} from '../../..'; import {cloneDeep} from 'lodash'; import lolex from 'lolex'; import {skipInBrowser} from '@ciscospark/test-helper-mocha'; diff --git a/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/interceptors/embargo.js b/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/interceptors/embargo.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/interceptors/embargo.js +++ b/packages/node_modules/@ciscospark/plugin-wdm/test/unit/spec/interceptors/embargo.js @@ -8,7 +8,7 @@ import {assert} from '@ciscospark/test-helper-chai'; import {defaults, HttpStatusInterceptor} from '@ciscospark/http-core'; import MockSpark from '@ciscospark/test-helper-mock-spark'; import Device, {EmbargoInterceptor} from '../../../..'; -import deviceFixture from '../../../lib/device-fixture'; +import deviceFixture from '../../lib/device-fixture'; import sinon from '@ciscospark/test-helper-sinon'; describe(`plugin-wdm`, function() {
test(all): deal with moved package locations
webex_spark-js-sdk
train
85fc18e7bc5dafafeaf2e96927700fdd7176ece9
diff --git a/library/src/main/java/com/dd/CircularProgressButton.java b/library/src/main/java/com/dd/CircularProgressButton.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/dd/CircularProgressButton.java +++ b/library/src/main/java/com/dd/CircularProgressButton.java @@ -266,6 +266,7 @@ public class CircularProgressButton extends Button { @Override public void onAnimationEnd() { if (mIconComplete != 0) { + setText(null); setIcon(mIconComplete); } else { setText(mCompleteText); @@ -347,6 +348,7 @@ public class CircularProgressButton extends Button { @Override public void onAnimationEnd() { if (mIconComplete != 0) { + setText(null); setIcon(mIconError); } else { setText(mErrorText); @@ -396,7 +398,7 @@ public class CircularProgressButton extends Button { public void setProgress(int progress) { mProgress = progress; - if (mMorphingInProgress) { + if (mMorphingInProgress || getWidth() == 0) { return; } @@ -432,4 +434,12 @@ public class CircularProgressButton extends Button { public int getProgress() { return mProgress; } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + if(changed) { + setProgress(mProgress); + } + } }
Fixed issue #<I> Setting progress before view was drawn cause unexpected results
dmytrodanylyk_circular-progress-button
train
1ee7dce453e4f5e1246b591e0cba6603c18aa3ef
diff --git a/src/SQL/Connection.php b/src/SQL/Connection.php index <HASH>..<HASH> 100644 --- a/src/SQL/Connection.php +++ b/src/SQL/Connection.php @@ -9,26 +9,28 @@ use pulledbits\ActiveRecord\SQL\Query\Result; class Connection { private $connection; + private $targetDirectory; - public function __construct(\PDO $connection) + public function __construct(\PDO $connection, string $targetDirectory) { $this->connection = $connection; + $this->targetDirectory = $targetDirectory; } - static function fromDatabaseURL(string $url) : self + static function fromDatabaseURL(string $url, string $targetDirectory) : self { $parsedUrl = parse_url($url); - return new \pulledbits\ActiveRecord\SQL\Connection(new \PDO($parsedUrl['scheme'] . ':dbname=' . substr($parsedUrl['path'], 1), $parsedUrl['user'], $parsedUrl['pass'], array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''))); + return new self(new \PDO($parsedUrl['scheme'] . ':dbname=' . substr($parsedUrl['path'], 1), $parsedUrl['user'], $parsedUrl['pass'], array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'')), $targetDirectory); } - public function schema(string $targetDirectory) + public function schema() { - return new Schema($this->recordConfigurator($targetDirectory), new QueryFactory($this)); + return new Schema($this->recordConfigurator(), new QueryFactory($this)); } - private function recordConfigurator($targetDirectory) + private function recordConfigurator() { $sourceSchema = Meta\Schema::fromPDO($this->connection); - return new RecordFactory($sourceSchema, $targetDirectory); + return new RecordFactory($sourceSchema, $this->targetDirectory); } public function execute(string $query, array $namedParameters) : Result diff --git a/tests/activerecord.php b/tests/activerecord.php index <HASH>..<HASH> 100644 --- a/tests/activerecord.php +++ b/tests/activerecord.php @@ -15,8 +15,8 @@ if (file_exists($targetDirectory) === false) { // test activiteit require __DIR__ . '/bootstrap.php'; -$connection = \pulledbits\ActiveRecord\SQL\Connection::fromDatabaseURL($_SERVER['argv'][1]); -$schema = $connection->schema($targetDirectory); +$connection = \pulledbits\ActiveRecord\SQL\Connection::fromDatabaseURL($_SERVER['argv'][1], $targetDirectory); +$schema = $connection->schema(); $starttijd = date('Y-m-d ') . '23:00:00'; diff --git a/tests/src/SQL/SchemaTest.php b/tests/src/SQL/SchemaTest.php index <HASH>..<HASH> 100644 --- a/tests/src/SQL/SchemaTest.php +++ b/tests/src/SQL/SchemaTest.php @@ -92,7 +92,7 @@ class SchemaTest extends \PHPUnit_Framework_TestCase '/^INSERT INTO activiteit \(name. foo2\) VALUES \(:\w+, :\w+\)$/' => 1, '/^INSERT INTO activiteit \(name. foo3, foo4\) VALUES \(:\w+, :\w+, :\w+\)$/' => 1, '/^CALL missing_procedure\(:\w+, :\w+\)/' => false - ])); + ]), sys_get_temp_dir()); $queryFactory = new QueryFactory($connection); $this->object = new Schema($recordConfiguration, $queryFactory); }
require targetdirectory in activerecord connection
pulledbits_activerecord
train
1d914f8c79d1d55853dcb67d64b1cdf9553b38b5
diff --git a/src/toil/test/cwl/cwlTest.py b/src/toil/test/cwl/cwlTest.py index <HASH>..<HASH> 100644 --- a/src/toil/test/cwl/cwlTest.py +++ b/src/toil/test/cwl/cwlTest.py @@ -124,7 +124,7 @@ class CWLTest(ToilTest): pass @slow - @pytest.mark.timeout(1500) + @pytest.mark.timeout(1800) def test_run_conformance(self, batchSystem=None): rootDir = self._projectRootPath() cwlSpec = os.path.join(rootDir, 'src/toil/test/cwl/spec')
Increase cwl test timeout further.
DataBiosphere_toil
train
a7a771e06c644afa565d62269494990136a99d47
diff --git a/modules/es/es.TransactionProcessor.js b/modules/es/es.TransactionProcessor.js index <HASH>..<HASH> 100644 --- a/modules/es/es.TransactionProcessor.js +++ b/modules/es/es.TransactionProcessor.js @@ -217,10 +217,14 @@ es.TransactionProcessor.prototype.applyAnnotations = function( to, update ) { changes++; } if ( update && changes ) { - var from = this.model.getNodeFromOffset( this.cursor ); + var fromNode = this.model.getNodeFromOffset( this.cursor ), + toNode = this.model.getNodeFromOffset( to ); this.model.traverseLeafNodes( function( node ) { node.emit( 'update' ); - }, from ); + if ( node === toNode ) { + return false; + } + }, fromNode ); } };
Another major performance improvement for updated annotated retentions
wikimedia_parsoid
train
ef0f0f42402573581943cc4b36f6dda33ffd9298
diff --git a/anyconfig/__init__.py b/anyconfig/__init__.py index <HASH>..<HASH> 100644 --- a/anyconfig/__init__.py +++ b/anyconfig/__init__.py @@ -28,7 +28,7 @@ On loading multiple config files, you can choose strategy to merge configs from the followings: * anyconfig.MS_REPLACE: Replace all configuration parameters provided in former - config files are simply replaced w/ the ones in later config files. + config files w/ the ones in later config files. For example, if a.yml and b.yml are like followings: @@ -57,6 +57,36 @@ the followings: {'a': 1, 'b': [{'c': 3}], 'd': {'e': "bbb"}} +* anyconfig.MS_NO_REPLACE: Do not replace configuration parameters provided in + former config files. + + For example, if a.yml and b.yml are like followings: + + a.yml:: + + b: + - c: 0 + - c: 2 + d: + e: "aaa" + f: 3 + + b.yml:: + + a: 1 + b: + - c: 3 + d: + e: "bbb" + + then:: + + load(["a.yml", "b.yml"], merge=anyconfig.MS_NO_REPLACE) + + will give object such like:: + + {'a': 1, 'b': [{'c': 0}, {'c': 2}], 'd': {'e': "bbb", 'f': 3}} + * anyconfig.MS_DICTS: Merge dicts recursively. That is, the following :: @@ -78,7 +108,8 @@ the followings: """ from .api import single_load, multi_load, load, loads, dump, dumps, \ - list_types, MS_REPLACE, MS_DICTS, MS_DICTS_AND_LISTS + list_types, find_parser, \ + MS_REPLACE, MS_NO_REPLACE, MS_DICTS, MS_DICTS_AND_LISTS VERSION = "0.0.3.6" @@ -88,9 +119,10 @@ VERSION = "0.0.3.6" __version__ = VERSION __all__ = [ + "list_types", "find_parser", "single_load", "multi_load", "load", "loads", "dump", "dumps", "list_types", - "MS_REPLACE", "MS_DICTS", "MS_DICTS_AND_LISTS", + "MS_REPLACE", "MS_NO_REPLACE", "MS_DICTS", "MS_DICTS_AND_LISTS", ] __author__ = 'Satoru SATOH <ssat@redhat.com>' diff --git a/anyconfig/api.py b/anyconfig/api.py index <HASH>..<HASH> 100644 --- a/anyconfig/api.py +++ b/anyconfig/api.py @@ -13,6 +13,7 @@ import os.path MS_REPLACE = "replace" +MS_NO_REPLACE = "noreplace" MS_DICTS = "merge_dicts" MS_DICTS_AND_LISTS = "merge_dicts_and_lists"
exported list_types, find_parser and MS_NO_REPLACE, and added usage example of MS_NO_REPLACE
ssato_python-anyconfig
train
141da94538bd5677a042b189bd74fa3a54dc7d7c
diff --git a/endpoints.go b/endpoints.go index <HASH>..<HASH> 100644 --- a/endpoints.go +++ b/endpoints.go @@ -1,8 +1,8 @@ package discordgo -// Constants of all known Discord API Endpoints +// All known Discord endpoints. // Please let me know if you know of any others. -const ( +var ( STATUS = "https://status.discordapp.com/api/v2/" SM = STATUS + "scheduled-maintenances/" SM_ACTIVE = SM + "active.json" @@ -35,10 +35,7 @@ const ( SSO = API + "sso" REPORT = API + "report" INTEGRATIONS = API + "integrations" -) -// Almost like the constants above :) Except can't be constants -var ( USER = func(uID string) string { return USERS + uID } USER_AVATAR = func(uID, aID string) string { return USERS + uID + "/avatars/" + aID + ".jpg" } USER_SETTINGS = func(uID string) string { return USERS + uID + "/settings" }
Don't really need seperate const block
bwmarrin_discordgo
train
be65e43c4a8b0870039791f0ae59f7c83ac88726
diff --git a/server/app/models/host_node_stat.rb b/server/app/models/host_node_stat.rb index <HASH>..<HASH> 100644 --- a/server/app/models/host_node_stat.rb +++ b/server/app/models/host_node_stat.rb @@ -221,7 +221,7 @@ class HostNodeStat created_at: { '$first': '$created_at' }, cpu_num_cores: { '$sum': '$cpu_num_cores' }, - cpu_percent_used: { '$avg': '$cpu_percent_used' }, + cpu_percent_used: { '$sum': '$cpu_percent_used' }, memory_used: { '$sum': '$memory_used' }, memory_total: { '$sum': '$memory_total' }, diff --git a/server/spec/models/host_node_stat_spec.rb b/server/spec/models/host_node_stat_spec.rb index <HASH>..<HASH> 100644 --- a/server/spec/models/host_node_stat_spec.rb +++ b/server/spec/models/host_node_stat_spec.rb @@ -434,7 +434,7 @@ describe HostNodeStat do # Records #2, #4 and #5. expect(results[0]["cpu"]).to eq({ "num_cores" => 3.0, # avg(1,1) + 2 - "percent_used" => 0.25, #avg( avg(.1, .7) + .1 ) + "percent_used" => 0.5, # avg(.1, .7) + .1 }) expect(results[0]["memory"]).to eq({ "used" => 800.0, # avg(500, 100) + 500
Fix grid metrics CPU calculation (#<I>) * Adding CPU to node usage. Adding more memory stats to metrics API responses. Adding more unit tests, updating docs. * Changing grid metrics to use sum of node CPU instead of average * Updating grid metrics unit test to match new rules regarding CPU percent aggregation.
kontena_kontena
train
228327c0ca82437e4376e1922d807468342e4d5e
diff --git a/lib/vagrant/commands/suspend.rb b/lib/vagrant/commands/suspend.rb index <HASH>..<HASH> 100644 --- a/lib/vagrant/commands/suspend.rb +++ b/lib/vagrant/commands/suspend.rb @@ -11,8 +11,33 @@ module Vagrant description "Suspends the currently running vagrant environment" def execute(args=[]) - env.require_persisted_vm - env.vm.suspend + args = parse_options(args) + + if args[0] + suspend_single(args[0]) + else + suspend_all + end + end + + def suspend_single(name) + vm = env.vms[name.to_sym] + if vm.nil? + error_and_exit(:unknown_vm, :vm => name) + return # for tests + end + + if vm.created? + vm.suspend + else + logger.info "VM '#{name}' not created. Ignoring." + end + end + + def suspend_all + env.vms.keys.each do |name| + suspend_single(name) + end end def options_spec(opts) @@ -20,4 +45,4 @@ module Vagrant end end end -end \ No newline at end of file +end diff --git a/test/vagrant/commands/suspend_test.rb b/test/vagrant/commands/suspend_test.rb index <HASH>..<HASH> 100644 --- a/test/vagrant/commands/suspend_test.rb +++ b/test/vagrant/commands/suspend_test.rb @@ -4,30 +4,64 @@ class CommandsSuspendTest < Test::Unit::TestCase setup do @klass = Vagrant::Commands::Suspend - @persisted_vm = mock("persisted_vm") - @persisted_vm.stubs(:execute!) - @env = mock_environment - @env.stubs(:require_persisted_vm) - @env.stubs(:vm).returns(@persisted_vm) - @instance = @klass.new(@env) end context "executing" do + should "call on all if no name is given" do + @instance.expects(:suspend_all).once + @instance.execute + end + + should "call on single if a name is given" do + @instance.expects(:suspend_single).with("foo").once + @instance.execute(["foo"]) + end + end + + context "suspending all" do + should "suspend each VM" do + vms = { :foo => nil, :bar => nil, :baz => nil } + @env.stubs(:vms).returns(vms) + + vms.each do |name, value| + @instance.expects(:suspend_single).with(name).once + end + + @instance.suspend_all + end + end + + context "suspending a single VM" do setup do - @persisted_vm.stubs(:suspend) - @persisted_vm.stubs(:saved?).returns(false) + @foo_vm = mock("vm") + vms = { :foo => @foo_vm } + @env.stubs(:vms).returns(vms) end - should "require a persisted VM" do - @env.expects(:require_persisted_vm).once - @instance.execute + should "error and exit if the VM doesn't exist" do + @env.stubs(:vms).returns({}) + @instance.expects(:error_and_exit).with(:unknown_vm, :vm => :foo).once + @instance.suspend_single(:foo) end - should "suspend the VM" do - @persisted_vm.expects(:suspend).once - @instance.execute + should "halt if its created" do + @foo_vm.stubs(:created?).returns(true) + @foo_vm.expects(:suspend).once + @instance.execute(["foo"]) + end + + should "halt and force if specified" do + @foo_vm.stubs(:created?).returns(true) + @foo_vm.expects(:suspend).once + @instance.execute(["foo"]) + end + + should "do nothing if its not created" do + @foo_vm.stubs(:created?).returns(false) + @foo_vm.expects(:suspend).never + @instance.suspend_single(:foo) end end end
`vagrant suspend` works with multi-vms
hashicorp_vagrant
train
a68066eb475ed806934797fd47185c4e1dd690be
diff --git a/claripy/frontends/replacement_frontend.py b/claripy/frontends/replacement_frontend.py index <HASH>..<HASH> 100644 --- a/claripy/frontends/replacement_frontend.py +++ b/claripy/frontends/replacement_frontend.py @@ -184,19 +184,24 @@ class ReplacementFrontend(ConstrainedFrontend): if not isinstance(rc, Base) or not rc.symbolic: continue - if rc.op == 'Not': - self.add_replacement(c.args[0], false, replace=False, promote=True, invalidate_cache=True) - elif rc.op == '__eq__' and rc.args[0].symbolic ^ rc.args[1].symbolic: - old, new = rc.args if rc.args[0].symbolic else rc.args[::-1] - self.add_replacement(old, new, promote=True, invalidate_cache=True) - elif self._complex_auto_replace: + if not self._complex_auto_replace: + if rc.op == 'Not': + self.add_replacement(c.args[0], false, replace=False, promote=True, invalidate_cache=True) + elif rc.op == '__eq__' and rc.args[0].symbolic ^ rc.args[1].symbolic: + old, new = rc.args if rc.args[0].symbolic else rc.args[::-1] + self.add_replacement(old, new, promote=True, invalidate_cache=True) + else: satisfiable, replacements = self._balancer.constraint_to_si(rc) if not satisfiable: self.add_replacement(rc, false) for old, new in replacements: if old.cardinality == 1: continue + rold = self._replacement(old) + if rold.cardinality == 1: + continue + self.add_replacement(old, rold.intersection(new)) ConstrainedFrontend._add_constraints(self, constraints, **kwargs)
reorganize constraint replacement code
angr_claripy
train
d4df45fd2ecf31f0d5e0360f1b7e818bb180dc8d
diff --git a/src/Assetic/AssetManager.php b/src/Assetic/AssetManager.php index <HASH>..<HASH> 100644 --- a/src/Assetic/AssetManager.php +++ b/src/Assetic/AssetManager.php @@ -78,4 +78,12 @@ class AssetManager { return array_keys($this->assets); } + + /** + * Clears all assets. + */ + public function clear() + { + $this->assets = array(); + } } diff --git a/tests/Assetic/Test/AssetManagerTest.php b/tests/Assetic/Test/AssetManagerTest.php index <HASH>..<HASH> 100644 --- a/tests/Assetic/Test/AssetManagerTest.php +++ b/tests/Assetic/Test/AssetManagerTest.php @@ -50,4 +50,12 @@ class AssetManagerTest extends \PHPUnit_Framework_TestCase $this->am->set('@foo', $this->getMock('Assetic\\Asset\\AssetInterface')); } + + public function testClear() + { + $this->am->set('foo', $this->getMock('Assetic\Asset\AssetInterface')); + $this->am->clear(); + + $this->assertFalse($this->am->has('foo')); + } }
added AssetManager::clear()
kriswallsmith_assetic
train
61da4a1001355875382817cb94df3cdd0bf882db
diff --git a/cmd/pilosa/main.go b/cmd/pilosa/main.go index <HASH>..<HASH> 100644 --- a/cmd/pilosa/main.go +++ b/cmd/pilosa/main.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "math/rand" + "net/http" "os" "os/signal" "path/filepath" @@ -34,6 +35,7 @@ const ( ) func main() { + http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 64 m := NewMain() fmt.Fprintf(m.Stderr, "Pilosa %s\n", Build)
limit the number of connections to single host
pilosa_pilosa
train
3773ed55bf6b777b074ffbc9f8f0887519eb6417
diff --git a/aws/resource_aws_elasticache_replication_group_test.go b/aws/resource_aws_elasticache_replication_group_test.go index <HASH>..<HASH> 100644 --- a/aws/resource_aws_elasticache_replication_group_test.go +++ b/aws/resource_aws_elasticache_replication_group_test.go @@ -3,6 +3,7 @@ package aws import ( "fmt" "log" + "os" "regexp" "strings" "testing" @@ -58,6 +59,10 @@ func testSweepElasticacheReplicationGroups(region string) error { } func TestAccAWSElasticacheReplicationGroup_basic(t *testing.T) { + oldvar := os.Getenv("AWS_DEFAULT_REGION") + os.Setenv("AWS_DEFAULT_REGION", "us-east-1") + defer os.Setenv("AWS_DEFAULT_REGION", oldvar) + var rg elasticache.ReplicationGroup rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_elasticache_replication_group.test" @@ -120,6 +125,10 @@ func TestAccAWSElasticacheReplicationGroup_Uppercase(t *testing.T) { } func TestAccAWSElasticacheReplicationGroup_updateDescription(t *testing.T) { + oldvar := os.Getenv("AWS_DEFAULT_REGION") + os.Setenv("AWS_DEFAULT_REGION", "us-east-1") + defer os.Setenv("AWS_DEFAULT_REGION", oldvar) + var rg elasticache.ReplicationGroup rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_elasticache_replication_group.test" @@ -164,6 +173,10 @@ func TestAccAWSElasticacheReplicationGroup_updateDescription(t *testing.T) { } func TestAccAWSElasticacheReplicationGroup_updateMaintenanceWindow(t *testing.T) { + oldvar := os.Getenv("AWS_DEFAULT_REGION") + os.Setenv("AWS_DEFAULT_REGION", "us-east-1") + defer os.Setenv("AWS_DEFAULT_REGION", oldvar) + var rg elasticache.ReplicationGroup rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_elasticache_replication_group.test" @@ -200,6 +213,10 @@ func TestAccAWSElasticacheReplicationGroup_updateMaintenanceWindow(t *testing.T) } func TestAccAWSElasticacheReplicationGroup_updateNodeSize(t *testing.T) { + oldvar := os.Getenv("AWS_DEFAULT_REGION") + os.Setenv("AWS_DEFAULT_REGION", "us-east-1") + defer os.Setenv("AWS_DEFAULT_REGION", oldvar) + var rg elasticache.ReplicationGroup rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_elasticache_replication_group.test" @@ -475,6 +492,10 @@ func TestAccAWSElasticacheReplicationGroup_clusteringAndCacheNodesCausesError(t } func TestAccAWSElasticacheReplicationGroup_enableSnapshotting(t *testing.T) { + oldvar := os.Getenv("AWS_DEFAULT_REGION") + os.Setenv("AWS_DEFAULT_REGION", "us-east-1") + defer os.Setenv("AWS_DEFAULT_REGION", oldvar) + var rg elasticache.ReplicationGroup rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_elasticache_replication_group.test"
Put the region back for tests that need it
terraform-providers_terraform-provider-aws
train
2d505d5ba0ca22da5041822a4f20d73b4b725b5d
diff --git a/reliure/types.py b/reliure/types.py index <HASH>..<HASH> 100644 --- a/reliure/types.py +++ b/reliure/types.py @@ -236,7 +236,7 @@ class Boolean(GenericType): super(Boolean, self).__init__(**kwargs) def parse(self, value): - if type(value) == unicode: + if isinstance(value, six.string_types): value = value.lower() return value in Boolean.TRUE_VALUES
bug parsing boolean use of six.string_types
kodexlab_reliure
train
d2cc81c02365b52da4e446a89a0b94d1954b1ad1
diff --git a/libnetwork/ipvs/ipvs.go b/libnetwork/ipvs/ipvs.go index <HASH>..<HASH> 100644 --- a/libnetwork/ipvs/ipvs.go +++ b/libnetwork/ipvs/ipvs.go @@ -59,10 +59,10 @@ func New(path string) (*Handle, error) { return nil, err } } + defer n.Close() sock, err := nl.GetNetlinkSocketAt(n, netns.None(), syscall.NETLINK_GENERIC) if err != nil { - n.Close() return nil, err }
Make sure to close nshandle in ipvs.New
moby_moby
train
b0ff765e3c8b7b04d42a3af9f6771dad5aff1e50
diff --git a/cluster/src/main/java/io/atomix/cluster/protocol/PhiMembershipProtocol.java b/cluster/src/main/java/io/atomix/cluster/protocol/PhiMembershipProtocol.java index <HASH>..<HASH> 100644 --- a/cluster/src/main/java/io/atomix/cluster/protocol/PhiMembershipProtocol.java +++ b/cluster/src/main/java/io/atomix/cluster/protocol/PhiMembershipProtocol.java @@ -223,7 +223,7 @@ public class PhiMembershipProtocol private CompletableFuture<Void> sendHeartbeat(GossipMember member) { return bootstrapService.getMessagingService().sendAndReceive(member.address(), HEARTBEAT_MESSAGE, SERIALIZER.encode(localMember)) .whenCompleteAsync((response, error) -> { - if (error != null) { + if (error == null) { GossipMember remoteMember = SERIALIZER.decode(response); updateMember(remoteMember); } else {
Fix improper null check in phi protocol heartbeats.
atomix_atomix
train
4820ae07a910b8613a894480590782f079447530
diff --git a/mill/__init__.py b/mill/__init__.py index <HASH>..<HASH> 100644 --- a/mill/__init__.py +++ b/mill/__init__.py @@ -112,22 +112,10 @@ class Mill: self._user_id = user_id return True - def sync_connect(self): - """Close the Mill connection.""" - loop = asyncio.get_event_loop() - task = loop.create_task(self.connect()) - loop.run_until_complete(task) - async def close_connection(self): """Close the Mill connection.""" await self.websession.close() - def sync_close_connection(self): - """Close the Mill connection.""" - loop = asyncio.get_event_loop() - task = loop.create_task(self.close_connection()) - loop.run_until_complete(task) - async def request(self, command, payload, retry=3): """Request data.""" # pylint: disable=too-many-return-statements @@ -243,12 +231,6 @@ class Mill: data = json.loads(result) return data - def sync_request(self, command, payload, retry=2): - """Request data.""" - loop = asyncio.get_event_loop() - task = loop.create_task(self.request(command, payload, retry)) - return loop.run_until_complete(task) - async def get_home_list(self): """Request data.""" resp = await self.request("selectHomeList", "{}") @@ -299,12 +281,6 @@ class Mill: if heater.home_id is None: heater.home_id = home.get("homeId") - def sync_update_rooms(self): - """Request data.""" - loop = asyncio.get_event_loop() - task = loop.create_task(self.update_rooms()) - return loop.run_until_complete(task) - async def set_room_temperatures_by_name( self, room_name, sleep_temp=None, comfort_temp=None, away_temp=None ): @@ -376,12 +352,6 @@ class Mill: await self.request("changeRoomMode", payload) self.rooms[room_id] = room - def sync_set_room_mode(self, room_id, mode=None, hour=0, minute=0): - """Request data.""" - loop = asyncio.get_event_loop() - task = loop.create_task(self.set_room_mode(room_id, mode, hour, minute)) - return loop.run_until_complete(task) - async def fetch_heater_data(self): """Request data.""" if not self.heaters: @@ -472,12 +442,6 @@ class Mill: heater.year_consumption = float(cons.get("valueTotal")) heater.last_consumption_update = dt.datetime.now() - def sync_update_heaters(self): - """Request data.""" - loop = asyncio.get_event_loop() - task = loop.create_task(self.update_heaters()) - loop.run_until_complete(task) - async def throttle_update_heaters(self): """Throttle update device.""" if ( @@ -532,14 +496,6 @@ class Mill: } await self.request("deviceControl", payload) - def sync_heater_control(self, device_id, fan_status=None, power_status=None): - """Set heater temps.""" - loop = asyncio.get_event_loop() - task = loop.create_task( - self.heater_control(device_id, fan_status, power_status) - ) - loop.run_until_complete(task) - async def set_heater_temp(self, device_id, set_temp): """Set heater temp.""" payload = { @@ -551,12 +507,6 @@ class Mill: } await self.request("changeDeviceInfo", payload) - def sync_set_heater_temp(self, device_id, set_temp): - """Set heater temps.""" - loop = asyncio.get_event_loop() - task = loop.create_task(self.set_heater_temp(device_id, set_temp)) - loop.run_until_complete(task) - async def find_all_heaters(self): """Find all heaters.""" await self.update_rooms()
Remove sync functions (#<I>)
Danielhiversen_pymill
train
9d67c932a266a9c5333f74bb61af5f587ae73cde
diff --git a/mode/css/css.js b/mode/css/css.js index <HASH>..<HASH> 100644 --- a/mode/css/css.js +++ b/mode/css/css.js @@ -37,7 +37,7 @@ CodeMirror.defineMode("css", function(config, parserConfig) { stream.match(/^\s*\w*/); return ret("keyword", "important"); } - else if (/\d/.test(ch)) { + else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); }
[css mode] Recognize numbers with leading dot Closes #<I> Closes #<I>
codemirror_CodeMirror
train
e5b116283af8388210cd77d2db53d5eda1ac7c58
diff --git a/tests/test_skyscanner.py b/tests/test_skyscanner.py index <HASH>..<HASH> 100755 --- a/tests/test_skyscanner.py +++ b/tests/test_skyscanner.py @@ -123,12 +123,11 @@ class TestHotels(unittest.TestCase): market='UK', currency='GBP', locale='en-GB', - pickupplace='LHR-sky', - dropoffplace='LHR-sky', - pickupdatetime='2015-05-28T12:00', - dropoffdatetime='2015-05-31T12:00', - driverage='30', - userip='175.156.244.174') + entityid=27543923, + checkindate='2015-05-26', + checkoutdate='2015-05-30', + guests=1, + rooms=1) print(poll_url) @@ -228,46 +227,49 @@ class TestFlights(unittest.TestCase): pass - def test_poll_session(self): - flights_service = Flights(self.api_key) + # def test_poll_session(self): + # flights_service = Flights(self.api_key) - poll_url = flights_service.create_session( - country='UK', - currency='GBP', - locale='en-GB', - originplace='SIN-sky', - destinationplace='KUL-sky', - outbounddate='2015-05-28', - inbounddate='2015-05-31', - adults=1) + # poll_url = flights_service.create_session( + # country='UK', + # currency='GBP', + # locale='en-GB', + # originplace='SIN-sky', + # destinationplace='KUL-sky', + # outbounddate='2015-05-28', + # inbounddate='2015-05-31', + # adults=1) - result = flights_service.poll_session(poll_url, sorttype='carrier') + # result = flights_service.poll_session(poll_url, sorttype='carrier') - self.assertTrue(len(result['Itineraries']) > 0) + # self.assertTrue(len(result['Itineraries']) > 0) - pass + # pass - def test_request_booking_details(self): - flights_service = Flights(self.api_key) + # def test_request_booking_details(self): + # flights_service = Flights(self.api_key) - poll_url = flights_service.create_session( - country='UK', - currency='GBP', - locale='en-GB', - originplace='SIN-sky', - destinationplace='KUL-sky', - outbounddate='2015-05-28', - inbounddate='2015-05-31', - adults=1) + # poll_url = flights_service.create_session( + # country='UK', + # currency='GBP', + # locale='en-GB', + # originplace='SIN-sky', + # destinationplace='KUL-sky', + # outbounddate='2015-05-28', + # inbounddate='2015-05-31', + # adults=1) - flights_results = flights_service.poll_session(poll_url, sorttype='carrier') - itinerary = flights_results['Itineraries'][0] + # flights_results = flights_service.poll_session(poll_url, sorttype='carrier') - result = flights_service.request_booking_details(poll_url, outboundlegid=itinerary['OutboundLegId'], inboundlegid=itinerary['InboundLegId']) + # print(flights_results) - print(result) + # itinerary = flights_results['Itineraries'][0] + + # result = flights_service.request_booking_details(poll_url, outboundlegid=itinerary['OutboundLegId'], inboundlegid=itinerary['InboundLegId']) + + # print(result) - pass + # pass def test_get_result(self): flights_service = Flights(self.api_key)
remove unit tests that we don't need
Skyscanner_skyscanner-python-sdk
train
fe6e6e2e0cd27974cb074bf6b49320e5cdf020e3
diff --git a/asciimatics/widgets.py b/asciimatics/widgets.py index <HASH>..<HASH> 100644 --- a/asciimatics/widgets.py +++ b/asciimatics/widgets.py @@ -52,13 +52,14 @@ def _enforce_width(text, width, unicode_aware=True): return text -def _find_min_start(text, max_width, unicode_aware=True): +def _find_min_start(text, max_width, unicode_aware=True, at_end=False): """ Find the starting point in the string that will reduce it to be less than or equal to the specified width when displayed on screen. :param text: The text to analyze. :param max_width: The required maximum width + :param at_end: At the end of the editable line, so allow spaced for cursor. :return: The offset within `text` to start at to reduce it to the required length. """ @@ -66,10 +67,12 @@ def _find_min_start(text, max_width, unicode_aware=True): string_len = wcswidth if unicode_aware else len char_len = wcwidth if unicode_aware else lambda x: 1 display_end = string_len(text) - while display_end >= max_width: + while display_end > max_width: result += 1 display_end -= char_len(text[0]) text = text[1:] + if at_end and display_end == max_width: + result += 1 return result @@ -1630,7 +1633,8 @@ class Text(Widget): # Calculate new visible limits if needed. self._start_column = min(self._start_column, self._column) self._start_column += _find_min_start(self._value[self._start_column:self._column + 1], - self.width, self._frame.canvas.unicode_aware) + self.width, self._frame.canvas.unicode_aware, + self._column >= self.string_len(self._value)) # Render visible portion of the text. (colour, attr, bg) = self._pick_colours("edit_text") @@ -1958,7 +1962,10 @@ class TextBox(Widget): min(self._start_line, self._line))) self._start_column = min(self._start_column, self._column) self._start_column += _find_min_start( - self._value[self._line][self._start_column:self._column + 1], self.width, self._frame.canvas.unicode_aware) + self._value[self._line][self._start_column:self._column + 1], + self.width, + self._frame.canvas.unicode_aware, + self._column >= self.string_len(self._value[self._line])) # Clear out the existing box content (colour, attr, bg) = self._pick_colours("edit_text") @@ -2015,8 +2022,7 @@ class TextBox(Widget): " " if display_column >= len(display_value[display_line]) else display_value[display_line][display_column], frame_no, - self._x + self._offset + dx + self.string_len( - display_value[display_line][display_start_column:display_column]), + self._x + self._offset + dx + text_width, self._y + display_line + dy - display_start_line) def reset(self):
Fix logic for cursor positioning in text editors
peterbrittain_asciimatics
train
b3ea3dddf2657d258fc797b6e119c593297bc51a
diff --git a/src/Silex/Console/Command/CacheClearCommand.php b/src/Silex/Console/Command/CacheClearCommand.php index <HASH>..<HASH> 100644 --- a/src/Silex/Console/Command/CacheClearCommand.php +++ b/src/Silex/Console/Command/CacheClearCommand.php @@ -29,7 +29,7 @@ namespace Lokhman\Silex\Console\Command; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -41,41 +41,92 @@ use Symfony\Component\Console\Output\OutputInterface; */ class CacheClearCommand extends Command { - protected static $TARGETS = [ - 'apcu', - ]; - /** * {@inheritdoc} */ protected function configure() { + foreach ((new \ReflectionClass($this))->getMethods() as $method) { + if ($method->class == self::class || is_subclass_of($method->class, self::class)) { + if (strpos($method->name, '_') === 0) { + $targets[] = substr($method->name, 1); + } + } + } + sort($targets); + $this ->setName('cache:clear') ->setDescription('Clears cache') - ->addArgument('targets', InputArgument::IS_ARRAY, 'Target cache to clear'); + ->addOption('target', 't', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + 'Target cache to clear', $targets); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { - $targets = $input->getArgument('targets') ? : static::$TARGETS; - if ($unknown = array_diff($targets, static::$TARGETS)) { - $output->writeln(sprintf('<error>Unknown target "%s"</error>', $unknown[0])); + foreach ($input->getOption('target') as $target) { + if (method_exists($this, '_' . $target)) { + call_user_func([$this, '_' . $target], $input, $output); + } else { + $output->writeln(sprintf('<error>Unknown target "%s"</error>', $target)); + return; + } + } + + $output->writeln('<info>Cache cleared<info>'); + } + + /** + * @see \Symfony\Component\Filesystem\Filesystem + */ + private function fsEmpty($path) { + $iterator = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS); + foreach (new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST) as $fileInfo) { + $file = $fileInfo->getPathname(); + if (is_link($file)) { + if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) { + $error = error_get_last(); + throw new \RuntimeException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message'])); + } + } elseif (is_dir($file)) { + if (!@rmdir($file) && file_exists($file)) { + $error = error_get_last(); + throw new \RuntimeException(sprintf('Failed to remove directory "%s": %s.', $file, $error['message'])); + } + } elseif (!@unlink($file) && file_exists($file)) { + $error = error_get_last(); + throw new \RuntimeException(sprintf('Failed to remove file "%s": %s.', $file, $error['message'])); + } + } + } + + private function _apc(InputInterface $input, OutputInterface $output) { + if (!function_exists('apc_clear_cache')) { return; } - foreach (array_unique($targets) as $target) { - call_user_func([$this, '_'.$target], $input, $output); + apc_clear_cache(); + $output->writeln('<comment>APC cache cleared</comment>'); + } + + private function _apcu(InputInterface $input, OutputInterface $output) { + if (!function_exists('apcu_clear_cache')) { + return; } - $output->writeln('<info>Cache cleared<info>'); + apcu_clear_cache(); + $output->writeln('<comment>APCu cache cleared</comment>'); } - protected function _apcu() { - if (function_exists('apcu_clear_cache')) { - apcu_clear_cache(); + private function _twig(InputInterface $input, OutputInterface $output) { + $app = $this->getApplication()->getContainer(); + if (!isset($app['twig.options']['cache'])) { + return; } + + $this->fsEmpty($app['twig.options']['cache']); + $output->writeln('<comment>Twig cache cleared</comment>'); } }
Add more targets to cache-clear command
lokhman_silex-console
train
4b1cb06f955ad6f7db06314db84766d699fef105
diff --git a/openstack_dashboard/dashboards/settings/user/views.py b/openstack_dashboard/dashboards/settings/user/views.py index <HASH>..<HASH> 100644 --- a/openstack_dashboard/dashboards/settings/user/views.py +++ b/openstack_dashboard/dashboards/settings/user/views.py @@ -32,6 +32,7 @@ class UserSettingsView(forms.ModalFormView): template_name = 'settings/user/settings.html' def get_initial(self): + default_tz = getattr(settings, 'TIME_ZONE', 'UTC') return { 'language': self.request.session.get( settings.LANGUAGE_COOKIE_NAME, @@ -39,7 +40,7 @@ class UserSettingsView(forms.ModalFormView): self.request.LANGUAGE_CODE)), 'timezone': self.request.session.get( 'django_timezone', - self.request.COOKIES.get('django_timezone', 'UTC')), + self.request.COOKIES.get('django_timezone', default_tz)), 'pagesize': utils.get_page_size(self.request), 'instance_log_length': utils.get_log_length(self.request)}
take time zone into account Previously, settings fell back to UTC rather than using what was configured in local_settings. Change-Id: I<I>b<I>fb<I>b3a<I>b2f0ad<I>a<I>fee<I> Closes-Bug: #<I>
openstack_horizon
train
08fdb0e0c1a0512576314ce382eb3ca7fb567952
diff --git a/src/Runner/index.js b/src/Runner/index.js index <HASH>..<HASH> 100644 --- a/src/Runner/index.js +++ b/src/Runner/index.js @@ -59,7 +59,7 @@ class TestRunner { * @private */ _runTraits (suite) { - debug('running %d trait(s) for %s suite', suite.traits.length, suite.group.title) + debug('running %d trait(s) for %s suite', suite.traits.length, suite.group._title) suite.traits.forEach((trait) => { const resolvedTrait = typeof (trait.action) === 'function' ? trait.action diff --git a/templates/vowfile.js b/templates/vowfile.js index <HASH>..<HASH> 100644 --- a/templates/vowfile.js +++ b/templates/vowfile.js @@ -24,7 +24,7 @@ module.exports = (cli, runner) => { | line, if http server is not required | */ - use('Adonis/Src/Server').listen() + use('Adonis/Src/Server').listen(process.env.HOST, process.env.PORT) /* |--------------------------------------------------------------------------
fix(runner,vowfile): fix typos
adonisjs_adonis-vow
train
4892443f9b90b82c6dc61669b1a787c65efbb6a0
diff --git a/js/runner.go b/js/runner.go index <HASH>..<HASH> 100644 --- a/js/runner.go +++ b/js/runner.go @@ -28,7 +28,6 @@ import ( "net/http" "net/http/cookiejar" "strconv" - "sync" "time" "github.com/dop251/goja" @@ -197,7 +196,6 @@ func (r *Runner) newVU(id int64, samplesOut chan<- stats.SampleContainer) (*VU, Console: r.console, BPool: bpool.NewBufferPool(100), Samples: samplesOut, - runMutex: sync.Mutex{}, } vu.Runtime.Set("__VU", vu.ID) vu.Runtime.Set("console", common.Bind(vu.Runtime, vu.Console, vu.Context)) @@ -368,18 +366,20 @@ type VU struct { Samples chan<- stats.SampleContainer - runMutex sync.Mutex setupData goja.Value } // Verify that interfaces are implemented -var _ lib.ActiveVU = &ActiveVU{} -var _ lib.InitializedVU = &VU{} +var ( + _ lib.ActiveVU = &ActiveVU{} + _ lib.InitializedVU = &VU{} +) // ActiveVU holds a VU and its activation parameters type ActiveVU struct { *VU *lib.VUActivationParams + busy chan struct{} } // Activate the VU so it will be able to run code. @@ -387,21 +387,40 @@ func (u *VU) Activate(params *lib.VUActivationParams) lib.ActiveVU { u.Runtime.ClearInterrupt() // u.Env = params.Env + avu := &ActiveVU{ + VU: u, + VUActivationParams: params, + busy: make(chan struct{}, 1), + } + go func() { + // Wait for the run context to be over <-params.RunContext.Done() + // Interrupt the JS runtime u.Runtime.Interrupt(errInterrupt) + // Wait for the VU to stop running, if it was, and prevent it from + // running again for this activation + avu.busy <- struct{}{} + if params.DeactivateCallback != nil { params.DeactivateCallback() } }() - return &ActiveVU{u, params} + return avu } // RunOnce runs the default function once. func (u *ActiveVU) RunOnce() error { - u.runMutex.Lock() - defer u.runMutex.Unlock() + select { + case <-u.RunContext.Done(): + return u.RunContext.Err() // we are done, return + case u.busy <- struct{}{}: + // nothing else can run now, and the VU cannot be deactivated + } + defer func() { + <-u.busy // unlock deactivation again + }() // Unmarshall the setupData only the first time for each VU so that VUs are isolated but we // still don't use too much CPU in the middle test diff --git a/js/runner_test.go b/js/runner_test.go index <HASH>..<HASH> 100644 --- a/js/runner_test.go +++ b/js/runner_test.go @@ -32,7 +32,6 @@ import ( "net" "net/http" "os" - "strings" "sync" "testing" "time" @@ -559,7 +558,7 @@ func TestVURunInterrupt(t *testing.T) { for name, r := range testdata { name, r := name, r t.Run(name, func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() samples := make(chan stats.SampleContainer, 100) defer close(samples) @@ -574,7 +573,7 @@ func TestVURunInterrupt(t *testing.T) { activeVU := vu.Activate(&lib.VUActivationParams{RunContext: ctx}) err = activeVU.RunOnce() assert.Error(t, err) - assert.True(t, strings.HasPrefix(err.Error(), "context cancelled at ")) + assert.Contains(t, err.Error(), "context cancelled") }) } } @@ -625,8 +624,8 @@ func TestVURunInterruptDoesntPanic(t *testing.T) { <-ch time.Sleep(time.Millisecond * 1) // NOTE: increase this in case of problems ;) newCancel() + wg.Wait() } - wg.Wait() }) } }
Properly synchronize VU deactivation and fix some tests (#<I>)
loadimpact_k6
train
f90a2a96e8cd2baa18fe56d7b62bcc3b19ea933a
diff --git a/pcef/core/panels/folding.py b/pcef/core/panels/folding.py index <HASH>..<HASH> 100644 --- a/pcef/core/panels/folding.py +++ b/pcef/core/panels/folding.py @@ -14,7 +14,7 @@ This module contains the marker panel from pcef.qt import QtCore, QtGui from pcef.core import constants from pcef.core.panel import Panel - +from pcef.core.system import mergedColors class FoldingIndicator(object): @@ -83,12 +83,31 @@ class FoldingPanel(Panel): return indic return None + def drawArrow(self, arrowRect, active, expanded, painter): + opt = QtGui.QStyleOptionViewItemV2() + opt.rect = arrowRect + opt.state = (QtGui.QStyle.State_Active | + QtGui.QStyle.State_Item | + QtGui.QStyle.State_Children) + if expanded: + opt.state |= QtGui.QStyle.State_Open + if active: + opt.state |= (QtGui.QStyle.State_MouseOver | + QtGui.QStyle.State_Enabled | + QtGui.QStyle.State_Selected) + opt.palette.setBrush(QtGui.QPalette.Window, + self.palette().highlight()) + opt.rect.translate(-2, 0) + self.style().drawPrimitive(QtGui.QStyle.PE_IndicatorBranch, + opt, painter, self) + def paintEvent(self, event): Panel.paintEvent(self, event) painter = QtGui.QPainter(self) for top, blockNumber in self.editor.visibleBlocks: indic = self.getIndicatorForLine(blockNumber) if indic: + # compute rectangles arrowRect = QtCore.QRect( 0, top, self.sizeHint().width(), self.sizeHint().height()) if indic.state == FoldingIndicator.UNFOLDED: @@ -98,14 +117,43 @@ class FoldingPanel(Panel): foldZoneRect = QtCore.QRect( 0, top, self.sizeHint().width(), h) # Draw Foldable zone rect + active = False + expanded = indic.state == FoldingIndicator.UNFOLDED if indic == self.__mouseOveredIndic: - painter.setBrush(QtCore.Qt.red) - painter.fillRect(foldZoneRect, self.editor.style.value("panelHighlight")) - if indic.state == FoldingIndicator.UNFOLDED: - self.__downArrowIcon.paint(painter, arrowRect) - else: - self.__rightArrowIcon.paint(painter, arrowRect) - + active = True + pal = self.palette() + b = pal.base().color() + h = pal.highlight().color() + b.setAlpha(180) + h.setAlpha(180) + c = mergedColors(b, h, 50) # ubuntu value = #f7bba2 + + grad = QtGui.QLinearGradient(foldZoneRect.topLeft(), + foldZoneRect.topRight()) + grad.setColorAt(0, c.lighter(100)) + grad.setColorAt(1, c.lighter(110)) + outline = c + painter.fillRect(foldZoneRect, grad) + painter.setPen(QtGui.QPen(outline)) + painter.drawLine(foldZoneRect.topLeft() + + QtCore.QPoint(1, 0), + foldZoneRect.topRight() - + QtCore.QPoint(1, 0)) + painter.drawLine(foldZoneRect.bottomLeft() + + QtCore.QPoint(1, 0), + foldZoneRect.bottomRight() - + QtCore.QPoint(1, 0)) + painter.drawLine(foldZoneRect.topRight() + + QtCore.QPoint(0, 1), + foldZoneRect.bottomRight() - + QtCore.QPoint(0, 1)) + painter.drawLine(foldZoneRect.topLeft() + + QtCore.QPoint(0, 1), + foldZoneRect.bottomLeft() - + QtCore.QPoint(0, 1)) + + # draw arrow + self.drawArrow(arrowRect, active, expanded, painter) def mouseMoveEvent(self, event): line = self.editor.lineNumber(event.pos().y()) @@ -133,9 +181,9 @@ if __name__ == '__main__': self.openFile(__file__) self.resize(QtCore.QSize(1000, 600)) self.installPanel(FoldingPanel()) - self.foldingPanel.addIndicator(FoldingIndicator(18, 27)) - self.foldingPanel.addIndicator(FoldingIndicator(22, 25)) - fi = FoldingIndicator(28, 45) + self.foldingPanel.addIndicator(FoldingIndicator(20, 29)) + self.foldingPanel.addIndicator(FoldingIndicator(24, 27)) + fi = FoldingIndicator(30, 45) fi.state = fi.FOLDED self.foldingPanel.addIndicator(fi) self.foldingPanel.zoneOrder = -1
Fold panel: good rendering achieved on linux
pyQode_pyqode.core
train
3e0ad9fd4855a66d52492ad3a19ef3c7db83a0d2
diff --git a/src/symbols.js b/src/symbols.js index <HASH>..<HASH> 100644 --- a/src/symbols.js +++ b/src/symbols.js @@ -301,16 +301,16 @@ defineSymbol(math, ams, close, "\u2518", "\\lrcorner", true); // AMS Binary Relations defineSymbol(math, ams, rel, "\u2266", "\\leqq", true); -defineSymbol(math, ams, rel, "\u2a7d", "\\leqslant"); +defineSymbol(math, ams, rel, "\u2a7d", "\\leqslant", true); defineSymbol(math, ams, rel, "\u2a95", "\\eqslantless", true); -defineSymbol(math, ams, rel, "\u2272", "\\lesssim"); -defineSymbol(math, ams, rel, "\u2a85", "\\lessapprox"); +defineSymbol(math, ams, rel, "\u2272", "\\lesssim", true); +defineSymbol(math, ams, rel, "\u2a85", "\\lessapprox", true); defineSymbol(math, ams, rel, "\u224a", "\\approxeq", true); defineSymbol(math, ams, bin, "\u22d6", "\\lessdot"); defineSymbol(math, ams, rel, "\u22d8", "\\lll", true); -defineSymbol(math, ams, rel, "\u2276", "\\lessgtr"); -defineSymbol(math, ams, rel, "\u22da", "\\lesseqgtr"); -defineSymbol(math, ams, rel, "\u2a8b", "\\lesseqqgtr"); +defineSymbol(math, ams, rel, "\u2276", "\\lessgtr", true); +defineSymbol(math, ams, rel, "\u22da", "\\lesseqgtr", true); +defineSymbol(math, ams, rel, "\u2a8b", "\\lesseqqgtr", true); defineSymbol(math, ams, rel, "\u2251", "\\doteqdot"); defineSymbol(math, ams, rel, "\u2253", "\\risingdotseq", true); defineSymbol(math, ams, rel, "\u2252", "\\fallingdotseq", true); diff --git a/test/katex-spec.js b/test/katex-spec.js index <HASH>..<HASH> 100644 --- a/test/katex-spec.js +++ b/test/katex-spec.js @@ -2889,7 +2889,7 @@ describe("Unicode", function() { }); it("should build more relations", function() { - expect("⊂⊃⊆⊇⊏⊐⊑⊒⊢⊣⊩⊪⊸⋈⋍⋐⋑⋔⋛⋞⋟⌢⌣⩾⪆⪌⪕⪖⪯⪰⪷⪸⫅⫆≘≙≚≛≝≞≟").toBuild(strictSettings); + expect("⊂⊃⊆⊇⊏⊐⊑⊒⊢⊣⊩⊪⊸⋈⋍⋐⋑⋔⋛⋞⋟⌢⌣⩾⪆⪌⪕⪖⪯⪰⪷⪸⫅⫆≘≙≚≛≝≞≟≲⩽⪅≶⋚⪋").toBuild(strictSettings); }); it("should parse symbols", function() {
Support Unicode ≲ ⩽ ⪅ ≶ ⋚ ⪋ (#<I>) Add six more Unicode relation characters to `symbols.js`. Fixes issue #<I>.
KaTeX_KaTeX
train
9bc66a048ac094f92ef32d41adebc48b1f34173d
diff --git a/lib/scsocket.js b/lib/scsocket.js index <HASH>..<HASH> 100644 --- a/lib/scsocket.js +++ b/lib/scsocket.js @@ -21,6 +21,7 @@ var SCSocket = function (options) { var opts = { port: null, autoReconnect: true, + autoProcessSubscriptions: true, ackTimeout: 10000, hostname: global.location && location.hostname, path: '/socketcluster/', @@ -339,6 +340,8 @@ SCSocket.prototype._tryReconnect = function (initialDelay) { }; SCSocket.prototype._onSCOpen = function (status) { + var self = this; + if (status) { this.id = status.id; this.pingTimeout = status.pingTimeout; @@ -346,9 +349,16 @@ SCSocket.prototype._onSCOpen = function (status) { } this._connectAttempts = 0; - this._resubscribe(); + if (this.options.autoProcessSubscriptions) { + this.processPendingSubscriptions(); + } + + // If the user invokes the callback while in autoProcessSubscriptions mode, it + // won't break anything - The processPendingSubscriptions() call will be a no-op. + SCEmitter.prototype.emit.call(this, 'connect', status, function () { + self.processPendingSubscriptions(); + }); - SCEmitter.prototype.emit.call(this, 'connect', status); this._flushEmitBuffer(); }; @@ -679,7 +689,7 @@ SCSocket.prototype.isSubscribed = function (channel, includePending) { return !!channel && channel.state == channel.SUBSCRIBED; }; -SCSocket.prototype._resubscribe = function () { +SCSocket.prototype.processPendingSubscriptions = function () { var self = this; var channels = [];
Can now disable auto resubscribe and control that flow manually
SocketCluster_socketcluster-client
train
e6238e30b9414c8b6c0b2ff53c0ee425c7813813
diff --git a/visidata/unfurl.py b/visidata/unfurl.py index <HASH>..<HASH> 100644 --- a/visidata/unfurl.py +++ b/visidata/unfurl.py @@ -42,6 +42,7 @@ class UnfurledSheet(Sheet): self.addRow([row, TypedExceptionWrapper(None, exception=e), TypedExceptionWrapper(None, exception=e)]) else: vd.exceptionCaught(e) + continue if not isinstance(val, Iterable) or isinstance(val, str): val = [ val ]
[unfurl-col-] fix unfurl-col with exceptions (thanks @jsvine) Closes #<I>
saulpw_visidata
train
5b4b41a7fc9797799cbeb11f31d4e8f4147a69d2
diff --git a/src/resource.js b/src/resource.js index <HASH>..<HASH> 100644 --- a/src/resource.js +++ b/src/resource.js @@ -225,25 +225,30 @@ class Resource { descriptor.name = this._sourceInspection.name } - // Format - if (!descriptor.format) { - descriptor.format = this._sourceInspection.format - } + // Only for non inline + if (!this.inline) { - // Mediatype - if (!descriptor.mediatype) { - descriptor.mediatype = this._sourceInspection.mediatype - } + // Format + if (!descriptor.format) { + descriptor.format = this._sourceInspection.format + } - // Encoding - if (descriptor.encoding === config.DEFAULT_RESOURCE_ENCODING) { - if (!config.IS_BROWSER) { - const jschardet = require('jschardet') - const iterator = await this.rawIter() - const bytes = (await iterator.next()).value - const encoding = jschardet.detect(bytes).encoding.toLowerCase() - descriptor.encoding = (encoding === 'ascii') ? 'utf-8' : encoding + // Mediatype + if (!descriptor.mediatype) { + descriptor.mediatype = this._sourceInspection.mediatype } + + // Encoding + if (descriptor.encoding === config.DEFAULT_RESOURCE_ENCODING) { + if (!config.IS_BROWSER) { + const jschardet = require('jschardet') + const iterator = await this.rawIter() + const bytes = (await iterator.next()).value + const encoding = jschardet.detect(bytes).encoding.toLowerCase() + descriptor.encoding = (encoding === 'ascii') ? 'utf-8' : encoding + } + } + } // Schema
Don't infer format etc for inline
frictionlessdata_datapackage-js
train
cdfb739339a2a92a0f31c0de150e21ed7e1d879d
diff --git a/RELEASE-NOTES b/RELEASE-NOTES index <HASH>..<HASH> 100644 --- a/RELEASE-NOTES +++ b/RELEASE-NOTES @@ -4,6 +4,13 @@ Extension page on mediawiki.org: https://www.mediawiki.org/wiki/Extension:Diff Latest version of the release notes: https://gerrit.wikimedia.org/r/gitweb?p=mediawiki/extensions/Diff.git;a=blob;f=RELEASE-NOTES +=== Version 0.5 === +(dev) + +; Removals + +* Removed Diff::getApplicableDiff + === Version 0.4 === 2013-01-08 diff --git a/includes/diffop/diff/Diff.php b/includes/diffop/diff/Diff.php index <HASH>..<HASH> 100644 --- a/includes/diffop/diff/Diff.php +++ b/includes/diffop/diff/Diff.php @@ -258,21 +258,6 @@ class Diff extends \GenericArrayObject implements IDiff { } /** - * @see Diff::getApplicableDiff - * - * @since 0.1 - * @deprecated since 0.4, use Patcher::getApplicableDiff - * - * @param array $currentObject - * - * @return Diff - */ - public function getApplicableDiff( array $currentObject ) { - $patcher = new MapPatcher( false ); - return $patcher->getApplicableDiff( $currentObject, $this ); - } - - /** * @see DiffOp::isAtomic * * @since 0.1 diff --git a/includes/diffop/diff/IDiff.php b/includes/diffop/diff/IDiff.php index <HASH>..<HASH> 100644 --- a/includes/diffop/diff/IDiff.php +++ b/includes/diffop/diff/IDiff.php @@ -47,18 +47,6 @@ interface IDiff extends DiffOp, Appendable, \ArrayAccess, \Traversable { public function addOperations( array $operations ); /** - * Filters the diff for operations that can be applied to the provided object. - * - * @since 0.1 - * @deprecated since 0.4, use Patcher::getApplicableDiff - * - * @param array $currentObject - * - * @return Diff - */ - public function getApplicableDiff( array $currentObject ); - - /** * Removes empty Diff DiffOps from the diff. * * @since 0.3
Removed deprecated Removed Diff::getApplicableDiff Change-Id: I<I>bfe<I>cdb<I>d<I>eee9d<I>b<I>ea<I>ee<I>e
wmde_Diff
train
5cef77bdf49b2372981cd518c4f3dc168ddd3275
diff --git a/bulbs/videos/models.py b/bulbs/videos/models.py index <HASH>..<HASH> 100644 --- a/bulbs/videos/models.py +++ b/bulbs/videos/models.py @@ -15,7 +15,6 @@ import six class VideohubVideo(Indexable): """A reference to a video on the onion videohub.""" - id = models.IntegerField(primary_key=True) title = models.CharField(max_length=512) description = models.TextField(blank=True, default="") keywords = models.TextField(blank=True, default="")
Let Django provide `id` field by default
theonion_django-bulbs
train
65f453a813c4493c508154a56cc74b6397190b5f
diff --git a/drools-core/src/main/java/org/drools/core/util/StringUtils.java b/drools-core/src/main/java/org/drools/core/util/StringUtils.java index <HASH>..<HASH> 100644 --- a/drools-core/src/main/java/org/drools/core/util/StringUtils.java +++ b/drools-core/src/main/java/org/drools/core/util/StringUtils.java @@ -1016,7 +1016,7 @@ public class StringUtils { return codeAwareSplitOnChar(string, trimArgs, ','); } - private static List<String> codeAwareSplitOnChar(CharSequence string, boolean trimArgs, char... chs) { + public static List<String> codeAwareSplitOnChar(CharSequence string, boolean trimArgs, char... chs) { List<String> args = new ArrayList<String>(); int lastStart = 0; int nestedParam = 0; diff --git a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PropertyReactivityTest.java b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PropertyReactivityTest.java index <HASH>..<HASH> 100644 --- a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PropertyReactivityTest.java +++ b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PropertyReactivityTest.java @@ -1307,4 +1307,25 @@ public class PropertyReactivityTest extends BaseModelTest { assertEquals(43, p.getAge()); } + + @Test + public void testMvelModifyBlockWithComma() { + // RHDM-1552 + final String str = + "import " + Person.class.getCanonicalName() + ";\n" + + "\n" + + "rule R dialect \"mvel\" when\n" + + " $p : Person( age < 50 )\n" + + "then\n" + + " modify($p) { setName(\"Mario\"), age = $p.age + 1 };\n" + + "end\n"; + + KieSession ksession = getKieSession( str ); + + Person p = new Person("Mario", 40); + ksession.insert( p ); + ksession.fireAllRules(3); + + assertEquals(43, p.getAge()); + } } diff --git a/drools-mvel/src/main/java/org/drools/mvel/builder/MVELConsequenceBuilder.java b/drools-mvel/src/main/java/org/drools/mvel/builder/MVELConsequenceBuilder.java index <HASH>..<HASH> 100644 --- a/drools-mvel/src/main/java/org/drools/mvel/builder/MVELConsequenceBuilder.java +++ b/drools-mvel/src/main/java/org/drools/mvel/builder/MVELConsequenceBuilder.java @@ -42,6 +42,7 @@ import org.mvel2.MacroProcessor; import static org.drools.core.reteoo.PropertySpecificUtil.getEmptyPropertyReactiveMask; import static org.drools.core.reteoo.PropertySpecificUtil.setPropertyOnMask; +import static org.drools.core.util.StringUtils.codeAwareSplitOnChar; import static org.drools.core.util.StringUtils.findEndOfBlockIndex; import static org.drools.core.util.StringUtils.findEndOfMethodArgsIndex; import static org.drools.core.util.StringUtils.splitStatements; @@ -226,7 +227,7 @@ public class MVELConsequenceBuilder String modifyBlock = text.substring( modifyBlockStart+1, modifyBlockEnd ).trim(); StringBuilder sb = new StringBuilder(); - for (String statement : splitStatements(modifyBlock)) { + for (String statement : codeAwareSplitOnChar(modifyBlock, true, ';', ',', '\n')) { sb.append( modified ).append( "." ).append( statement.trim() ).append( ";\n" ); } sb.append( "drools.update(" ).append( modified ).append( ");\n" );
[DROOLS-<I>][RHDM-<I>] allow comma to be used as statements separator in mvel modify block (#<I>)
kiegroup_drools
train
6facc27a705fd1b7c1980a65501223f010186aa5
diff --git a/.travis.yml b/.travis.yml index <HASH>..<HASH> 100644 --- a/.travis.yml +++ b/.travis.yml @@ -42,6 +42,9 @@ matrix: - os: osx osx_image: xcode8.3 go: master + - os: osx + env: SKIP_BINUTILS=1 + go: master addons: apt: @@ -51,7 +54,7 @@ addons: before_install: - go get -u github.com/golang/lint/golint honnef.co/go/tools/cmd/... - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew update ; fi - - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew install binutils ; fi + - if [[ "$TRAVIS_OS_NAME" == "osx" && -z $SKIP_BINUTILS ]]; then brew install binutils ; fi - if [[ "$TRAVIS_OS_NAME" == "osx" && -z $SKIP_GRAPHVIZ ]]; then brew install graphviz; fi script: diff --git a/internal/binutils/binutils.go b/internal/binutils/binutils.go index <HASH>..<HASH> 100644 --- a/internal/binutils/binutils.go +++ b/internal/binutils/binutils.go @@ -81,6 +81,26 @@ func (bu *Binutils) update(fn func(r *binrep)) { bu.rep = r } +// String returns string representation of the binutils state for debug logging. +func (bu *Binutils) String() string { + r := bu.get() + var llvmSymbolizer, addr2line, nm, objdump string + if r.llvmSymbolizerFound { + llvmSymbolizer = r.llvmSymbolizer + } + if r.addr2lineFound { + addr2line = r.addr2line + } + if r.nmFound { + nm = r.nm + } + if r.objdumpFound { + objdump = r.objdump + } + return fmt.Sprintf("llvm-symbolizer=%q addr2line=%q nm=%q objdump=%q fast=%t", + llvmSymbolizer, addr2line, nm, objdump, r.fast) +} + // SetFastSymbolization sets a toggle that makes binutils use fast // symbolization (using nm), which is much faster than addr2line but // provides only symbol name information (no file/line). diff --git a/internal/binutils/binutils_test.go b/internal/binutils/binutils_test.go index <HASH>..<HASH> 100644 --- a/internal/binutils/binutils_test.go +++ b/internal/binutils/binutils_test.go @@ -298,6 +298,13 @@ func TestMachoFiles(t *testing.T) { if err != nil { t.Fatalf("Open: unexpected error %v", err) } + t.Logf("binutils: %v", bu) + if runtime.GOOS == "darwin" && !bu.rep.addr2lineFound && !bu.rep.llvmSymbolizerFound { + // On OSX user needs to install gaddr2line or llvm-symbolizer with + // Homebrew, skip the test when the environment doesn't have it + // installed. + t.Skip("couldn't find addr2line or gaddr2line") + } defer f.Close() syms, err := f.Symbols(nil, 0) if err != nil {
Detect when binutils are not installed on OSX and skip the test. (#<I>) Fixes #<I>.
google_pprof
train
a8a0fb25aa3b879fe51421a8376c52c8347f1cf3
diff --git a/hazelcast/src/test/java/com/hazelcast/test/HazelcastTestSupport.java b/hazelcast/src/test/java/com/hazelcast/test/HazelcastTestSupport.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/test/java/com/hazelcast/test/HazelcastTestSupport.java +++ b/hazelcast/src/test/java/com/hazelcast/test/HazelcastTestSupport.java @@ -40,6 +40,9 @@ import com.hazelcast.spi.impl.operationservice.impl.OperationServiceImpl; import com.hazelcast.spi.partition.IPartition; import com.hazelcast.util.EmptyStatement; import com.hazelcast.util.ExceptionUtil; +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.junit.After; import org.junit.ComparisonFailure; @@ -49,6 +52,7 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -79,7 +83,7 @@ public abstract class HazelcastTestSupport { public static final int ASSERT_TRUE_EVENTUALLY_TIMEOUT; - private static org.apache.log4j.Level logLevel; + private static Level logLevel; static { ASSERT_TRUE_EVENTUALLY_TIMEOUT = Integer.getInteger("hazelcast.assertTrueEventually.timeout", 120); @@ -249,21 +253,33 @@ public abstract class HazelcastTestSupport { System.setProperty("hazelcast.logging.type", "log4j"); } - public static void setLogLevel(org.apache.log4j.Level level) { + public static void setLogLevel(Level level) { if (isLog4jLoaded() && logLevel == null) { - org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger(); - logLevel = rootLogger.getLevel(); - rootLogger.setLevel(level); + logLevel = setLogLevelOnAllLoggers(level); } } public static void resetLogLevel() { if (isLog4jLoaded() && logLevel != null) { - org.apache.log4j.Logger.getRootLogger().setLevel(logLevel); + setLogLevelOnAllLoggers(logLevel); logLevel = null; } } + @SuppressWarnings("unchecked") + private static Level setLogLevelOnAllLoggers(Level level) { + Logger rootLogger = Logger.getRootLogger(); + Level oldLevel = rootLogger.getLevel(); + rootLogger.setLevel(level); + + Enumeration<Logger> currentLoggers = LogManager.getCurrentLoggers(); + while (currentLoggers.hasMoreElements()) { + currentLoggers.nextElement().setLevel(level); + } + + return oldLevel; + } + private static boolean isLog4jLoaded() { setLoggingLog4j(); try {
Fixed setting of log level in HazelcastTestSupport.
hazelcast_hazelcast
train