hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
3baad2a2cadc249ed0e8cf8fa890b10998168f0a
diff --git a/Model/Service/TransactionHandlerService.php b/Model/Service/TransactionHandlerService.php index <HASH>..<HASH> 100755 --- a/Model/Service/TransactionHandlerService.php +++ b/Model/Service/TransactionHandlerService.php @@ -519,12 +519,14 @@ class TransactionHandlerService // Refund $this->creditMemoService->refund($creditMemo); - if ($this->order->getStatus() == 'closed') { - $status = 'closed'; - } else { - $status = $this->config->getValue('order_status_refunded'); - } - + $isPartialRefund = $this->isPartialRefund( + $amount, + true, + $this->order, + true + ); + + $status = $isPartialRefund ? $this->config->getValue('order_status_refunded') : 'closed'; $orderComment->setData('status', $status)->save(); // Remove the core credit memo comment @@ -536,16 +538,7 @@ class TransactionHandlerService } // Amend the order status set by magento when refunding the credit memo - $isPartialRefund = $this->isPartialRefund( - $amount, - true, - $this->order, - true - ); - - $status = $isPartialRefund ? $this->config->getValue('order_status_refunded') : 'closed'; $this->order->setStatus($status); - $this->order->setTotalRefunded($currentTotal + $amount); } }
chore: order status comment fixed for final partial refund from hub
checkout_checkout-magento2-plugin
train
5de8fe05f39a5ada05c633f31b378d403b26aad6
diff --git a/src/main/java/net/snowflake/client/core/SFStatement.java b/src/main/java/net/snowflake/client/core/SFStatement.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/snowflake/client/core/SFStatement.java +++ b/src/main/java/net/snowflake/client/core/SFStatement.java @@ -21,8 +21,6 @@ import net.snowflake.client.log.SFLoggerFactory; import net.snowflake.client.util.SecretDetector; import net.snowflake.common.core.SqlState; import org.apache.http.client.methods.HttpRequestBase; - -import java.io.IOException; import java.sql.SQLException; import java.sql.Statement; import java.util.Collections; diff --git a/src/main/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableV1.java b/src/main/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableV1.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableV1.java +++ b/src/main/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableV1.java @@ -843,6 +843,15 @@ public class SnowflakeResultSetSerializableV1 implements SnowflakeResultSetSeria this.memoryLimit = initMemoryLimit(this.parameters); } + if (queryResultFormat == QueryResultFormat.ARROW + && memoryLimit * 2 > Runtime.getRuntime().maxMemory()) + { + memoryLimit = Runtime.getRuntime().maxMemory()/2; + logger.debug("To avoid OOM for arrow buffer allocation, " + + "memoryLimit should be equal to half of maxMemory {}", + memoryLimit); + } + // Parse chunk header JsonNode chunkHeaders = rootNode.path("data").path("chunkHeaders"); if (chunkHeaders != null && !chunkHeaders.isMissingNode())
SNOW-<I>: make sure memoryLimit can avoid OOM for Arrow buffer
snowflakedb_snowflake-jdbc
train
2278677d2d3789c7e251755bd2d1c63af531dd76
diff --git a/tests/mocha-reporter.js b/tests/mocha-reporter.js index <HASH>..<HASH> 100644 --- a/tests/mocha-reporter.js +++ b/tests/mocha-reporter.js @@ -60,7 +60,7 @@ module.exports = class ServerlessSpec extends Spec { // Mocha ignores uncaught exceptions if they happen in conext of skipped test, expose them // https://github.com/mochajs/mocha/issues/3938 - if (runner.currentRunnable.isPending()) throw err; + if (runner.currentRunnable.isPending() || runner._abort) throw err; // eslint-disable-line no-underscore-dangle return; } // If there's an uncaught exception after rest runner wraps up
Expose errors during suite abort phase
serverless_serverless
train
7cc72af508f149bc86df5b3ac5c6de3836579e70
diff --git a/modules/engine.py b/modules/engine.py index <HASH>..<HASH> 100644 --- a/modules/engine.py +++ b/modules/engine.py @@ -83,7 +83,7 @@ class PygletLoop (object): def play(self, frames_per_sec=50): import pyglet - self.window = pyglet.window.Window() + self.window = pyglet.window.Window(visible=False) self.stage = self.get_initial_stage() self.stage.set_master(self)
Make the pyglet window hidden on construction.
kxgames_kxg
train
388f2dcf8dad1f4e6881911393ca30c898fd33c1
diff --git a/http/sys_auth.go b/http/sys_auth.go index <HASH>..<HASH> 100644 --- a/http/sys_auth.go +++ b/http/sys_auth.go @@ -13,9 +13,7 @@ func handleSysAuth(core *vault.Core) http.Handler { switch r.Method { case "GET": handleSysListAuth(core).ServeHTTP(w, r) - case "POST": - fallthrough - case "DELETE": + case "POST", "PUT", "DELETE": handleSysEnableDisableAuth(core, w, r) default: respondError(w, http.StatusMethodNotAllowed, nil) @@ -58,7 +56,7 @@ func handleSysEnableDisableAuth(core *vault.Core, w http.ResponseWriter, r *http } switch r.Method { - case "POST": + case "PUT", "POST": handleSysEnableAuth(core, w, r, path) case "DELETE": handleSysDisableAuth(core, w, r, path)
http: PUT to sys/auth should be the same as POST
hashicorp_vault
train
c35316f1582de2c25b9e3c0ec99ba356b444806a
diff --git a/socketIO_client/__init__.py b/socketIO_client/__init__.py index <HASH>..<HASH> 100644 --- a/socketIO_client/__init__.py +++ b/socketIO_client/__init__.py @@ -3,7 +3,10 @@ import json import requests import time from collections import namedtuple -from urlparse import urlparse +try: + from urlparse import urlparse +except: + from urllib.parse import urlparse from .exceptions import ConnectionError, TimeoutError, PacketError from .transports import _get_response, _negotiate_transport, TRANSPORTS @@ -254,13 +257,13 @@ class SocketIO(object): # Initialize heartbeat_pacemaker self.heartbeat_pacemaker = self._make_heartbeat_pacemaker( heartbeat_interval=socketIO_session.heartbeat_timeout / 2) - self.heartbeat_pacemaker.next() + next(self.heartbeat_pacemaker) # Negotiate transport transport = _negotiate_transport( self.client_supported_transports, socketIO_session, self.is_secure, self.base_url, **self.kw) # Update namespaces - for path, namespace in self._namespace_by_path.iteritems(): + for path, namespace in self._namespace_by_path.items(): namespace._transport = transport transport.connect(path) return transport diff --git a/socketIO_client/transports.py b/socketIO_client/transports.py index <HASH>..<HASH> 100644 --- a/socketIO_client/transports.py +++ b/socketIO_client/transports.py @@ -6,7 +6,10 @@ import six import socket import time import websocket -from itertools import izip +try: + from itertools import izip +except: + izip = zip from .exceptions import SocketIOError, ConnectionError, TimeoutError
Run under Python 3 This will make the code I wrote in : <URL>
invisibleroads_socketIO-client
train
2e9403b047d926d39d5b299abc071f3c29627fc6
diff --git a/buildfile.go b/buildfile.go index <HASH>..<HASH> 100644 --- a/buildfile.go +++ b/buildfile.go @@ -313,10 +313,11 @@ func (b *buildFile) Build(dockerfile, context io.Reader) (string, error) { for { line, err := file.ReadString('\n') if err != nil { - if err == io.EOF { + if err == io.EOF && line == "" { break + } else if err != io.EOF { + return "", err } - return "", err } line = strings.Replace(strings.TrimSpace(line), " ", " ", 1) // Skip comments and empty line diff --git a/buildfile_test.go b/buildfile_test.go index <HASH>..<HASH> 100644 --- a/buildfile_test.go +++ b/buildfile_test.go @@ -15,58 +15,69 @@ run sh -c 'echo root:testpass > /tmp/passwd' run mkdir -p /var/run/sshd ` +const DockerfileNoNewLine = ` +# VERSION 0.1 +# DOCKER-VERSION 0.2 + +from ` + unitTestImageName + ` +run sh -c 'echo root:testpass > /tmp/passwd' +run mkdir -p /var/run/sshd` + func TestBuild(t *testing.T) { - runtime, err := newTestRuntime() - if err != nil { - t.Fatal(err) - } - defer nuke(runtime) + dockerfiles := []string{Dockerfile, DockerfileNoNewLine} + for _, Dockerfile := range dockerfiles { + runtime, err := newTestRuntime() + if err != nil { + t.Fatal(err) + } + defer nuke(runtime) - srv := &Server{runtime: runtime} + srv := &Server{runtime: runtime} - buildfile := NewBuildFile(srv, &utils.NopWriter{}) + buildfile := NewBuildFile(srv, &utils.NopWriter{}) - imgID, err := buildfile.Build(strings.NewReader(Dockerfile), nil) - if err != nil { - t.Fatal(err) - } + imgID, err := buildfile.Build(strings.NewReader(Dockerfile), nil) + if err != nil { + t.Fatal(err) + } - builder := NewBuilder(runtime) - container, err := builder.Create( - &Config{ - Image: imgID, - Cmd: []string{"cat", "/tmp/passwd"}, - }, - ) - if err != nil { - t.Fatal(err) - } - defer runtime.Destroy(container) + builder := NewBuilder(runtime) + container, err := builder.Create( + &Config{ + Image: imgID, + Cmd: []string{"cat", "/tmp/passwd"}, + }, + ) + if err != nil { + t.Fatal(err) + } + defer runtime.Destroy(container) - output, err := container.Output() - if err != nil { - t.Fatal(err) - } - if string(output) != "root:testpass\n" { - t.Fatalf("Unexpected output. Read '%s', expected '%s'", output, "root:testpass\n") - } + output, err := container.Output() + if err != nil { + t.Fatal(err) + } + if string(output) != "root:testpass\n" { + t.Fatalf("Unexpected output. Read '%s', expected '%s'", output, "root:testpass\n") + } - container2, err := builder.Create( - &Config{ - Image: imgID, - Cmd: []string{"ls", "-d", "/var/run/sshd"}, - }, - ) - if err != nil { - t.Fatal(err) - } - defer runtime.Destroy(container2) + container2, err := builder.Create( + &Config{ + Image: imgID, + Cmd: []string{"ls", "-d", "/var/run/sshd"}, + }, + ) + if err != nil { + t.Fatal(err) + } + defer runtime.Destroy(container2) - output, err = container2.Output() - if err != nil { - t.Fatal(err) - } - if string(output) != "/var/run/sshd\n" { - t.Fatal("/var/run/sshd has not been created") + output, err = container2.Output() + if err != nil { + t.Fatal(err) + } + if string(output) != "/var/run/sshd\n" { + t.Fatal("/var/run/sshd has not been created") + } } }
build: don't ignore last line in Dockerfile when it doesn't end with \n
containers_storage
train
da8734a6f9213cfdcf92b63fe8d014989e0ced18
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ServerDowngrader.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ServerDowngrader.java index <HASH>..<HASH> 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ServerDowngrader.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ServerDowngrader.java @@ -24,8 +24,12 @@ import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpObject; +import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; +import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.ReferenceCountUtil; @@ -78,9 +82,12 @@ public class Http2ServerDowngrader extends MessageToMessageCodec<Http2StreamFram out.add(full); } } else { - out.add(HttpConversionUtil.toHttpRequest(id, headersFrame.headers(), validateHeaders)); + HttpRequest req = HttpConversionUtil.toHttpRequest(id, headersFrame.headers(), validateHeaders); + if (!HttpUtil.isContentLengthSet(req)) { + req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); + } + out.add(req); } - } else if (frame instanceof Http2DataFrame) { Http2DataFrame dataFrame = (Http2DataFrame) frame; if (dataFrame.isEndStream()) { diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ServerDowngraderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ServerDowngraderTest.java index <HASH>..<HASH> 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ServerDowngraderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ServerDowngraderTest.java @@ -32,6 +32,7 @@ import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.CharsetUtil; @@ -255,6 +256,28 @@ public class Http2ServerDowngraderTest { assertThat(request.method(), is(HttpMethod.GET)); assertThat(request.protocolVersion(), is(HttpVersion.HTTP_1_1)); assertFalse(request instanceof FullHttpRequest); + assertTrue(HttpUtil.isTransferEncodingChunked(request)); + + assertThat(ch.readInbound(), is(nullValue())); + assertFalse(ch.finish()); + } + + @Test + public void testDowngradeHeadersWithContentLength() throws Exception { + EmbeddedChannel ch = new EmbeddedChannel(new Http2ServerDowngrader()); + Http2Headers headers = new DefaultHttp2Headers(); + headers.path("/"); + headers.method("GET"); + headers.setInt("content-length", 0); + + assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers))); + + HttpRequest request = ch.readInbound(); + assertThat(request.uri(), is("/")); + assertThat(request.method(), is(HttpMethod.GET)); + assertThat(request.protocolVersion(), is(HttpVersion.HTTP_1_1)); + assertFalse(request instanceof FullHttpRequest); + assertFalse(HttpUtil.isTransferEncodingChunked(request)); assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.finish()); @@ -276,6 +299,7 @@ public class Http2ServerDowngraderTest { assertThat(request.protocolVersion(), is(HttpVersion.HTTP_1_1)); assertThat(request.content().readableBytes(), is(0)); assertTrue(request.trailingHeaders().isEmpty()); + assertFalse(HttpUtil.isTransferEncodingChunked(request)); } finally { request.release(); }
codec-http2: Mark requests as chunked in Http2ServerDowngrader Motivation: Http2ServerDowngrader doesn't mark chunked requests as chunked, even though the natural conversion from http/2 requests to http/<I> requests is to chunked ones. Modifications: Mark requests that aren't already complete as chunked. Result: Requests will be chunked, and can later be aggregated if necessary.
netty_netty
train
20e5a4c557879d674dcdce2a671cd5fcd098bbfd
diff --git a/notify_js.go b/notify_js.go index <HASH>..<HASH> 100644 --- a/notify_js.go +++ b/notify_js.go @@ -36,7 +36,7 @@ func Notify(title, message, appIcon string) (err error) { n.New(js.ValueOf(title), opts) } else { var f js.Func - f = js.FuncOf(func(this js.Value, args []js.Value) any { + f = js.FuncOf(func(this js.Value, args []js.Value) interface{} { if args[0].String() == "granted" { n.New(js.ValueOf(title), opts) }
s/any/interface{}
gen2brain_beeep
train
62c09895afd72ec9620031cd9dfb8ca9823d1287
diff --git a/src/Service/Client/Cache/ExpireResolver.php b/src/Service/Client/Cache/ExpireResolver.php index <HASH>..<HASH> 100644 --- a/src/Service/Client/Cache/ExpireResolver.php +++ b/src/Service/Client/Cache/ExpireResolver.php @@ -41,12 +41,14 @@ class ExpireResolver */ public function getExpire($request, \DateTime $date) { - if (!empty($this->requests[$request])) { - return $date->modify($this->requests[$request]); - } elseif (!isset($this->requests[$request])) { + if (!array_key_exists($request, $this->requests)) { return $date->modify(self::DEFAULT_MODIFY); } + if ($this->requests[$request]) { + return $date->modify($this->requests[$request]); + } + return null; } } diff --git a/tests/Service/Client/Cache/ExpireResolverTest.php b/tests/Service/Client/Cache/ExpireResolverTest.php index <HASH>..<HASH> 100644 --- a/tests/Service/Client/Cache/ExpireResolverTest.php +++ b/tests/Service/Client/Cache/ExpireResolverTest.php @@ -60,7 +60,7 @@ class ExpireResolverTest extends \PHPUnit_Framework_TestCase $date = new \DateTime('28-06-2016 16:30:00'); $expected = clone $date; - if (!isset($this->requests[$request])) { + if (!array_key_exists($request, $this->requests)) { $expected->modify(ExpireResolver::DEFAULT_MODIFY); } elseif ($this->requests[$request]) { $expected->modify($this->requests[$request]);
correct resolver empty modify value for request
anime-db_ani-db-browser-bundle
train
4dcb23cfe521f344ac1412c8831b92585bce3695
diff --git a/instaloader/structures.py b/instaloader/structures.py index <HASH>..<HASH> 100644 --- a/instaloader/structures.py +++ b/instaloader/structures.py @@ -75,13 +75,13 @@ class Post: """Create a post object from a given mediaid""" return cls.from_shortcode(context, mediaid_to_shortcode(mediaid)) - def get_node(self): + def _asdict(self): if self._full_metadata_dict: node = self._full_metadata_dict else: node = self._node if self._owner_profile: - node['owner'] = self.owner_profile.get_node() + node['owner'] = self.owner_profile._asdict() if self._location: node['location'] = self._location._asdict() return node @@ -399,7 +399,7 @@ class Profile: username = Post.from_mediaid(context, int(data['edges'][0]["node"]["id"])).owner_username return cls(context, {'username': username.lower(), 'id': profile_id}) - def get_node(self): + def _asdict(self): json_node = self._node.copy() # remove posts json_node.pop('edge_media_collections', None) @@ -578,10 +578,10 @@ class StoryItem: self._node = node self._owner_profile = owner_profile - def get_node(self): + def _asdict(self): node = self._node if self._owner_profile: - node['owner'] = self._owner_profile.get_node() + node['owner'] = self._owner_profile._asdict() return node @property @@ -776,7 +776,7 @@ def save_structure_to_file(structure: JsonExportable, filename: str) -> None: :param structure: :class:`Post`, :class:`Profile` or :class:`StoryItem` :param filename: Filename, ends in '.json' or '.json.xz' """ - json_structure = {'node': structure.get_node(), + json_structure = {'node': structure._asdict(), 'instaloader': {'version': __version__, 'node_type': structure.__class__.__name__}} compress = filename.endswith('.xz') if compress:
{Post,Profile,StoryItem}.get_node() -> ._as_dict() This is consistend with namedtuple._as_dict() and marks it as a protected member, which is good as it should be only accessed by save_structure_to_file().
instaloader_instaloader
train
ccb8966321a27a8340a6fa48ab414b8f78d559e0
diff --git a/pyinfra_cli/prints.py b/pyinfra_cli/prints.py index <HASH>..<HASH> 100644 --- a/pyinfra_cli/prints.py +++ b/pyinfra_cli/prints.py @@ -38,12 +38,18 @@ def _get_group_combinations(inventory): return group_combinations -def _jsonify(data, *args, **kwargs): - data = { - key.name if isinstance(key, Host) else key: value - for key, value in six.iteritems(data) - } +def _stringify_host_keys(data): + if isinstance(data, dict): + return { + key.name if isinstance(key, Host) else key: _stringify_host_keys(value) + for key, value in six.iteritems(data) + } + + return data + +def _jsonify(data, *args, **kwargs): + data = _stringify_host_keys(data) return json.dumps(data, *args, **kwargs)
Handle JSONifying of `Host` objects.
Fizzadar_pyinfra
train
245ec739ca9b574f367e1201b02079e7737a78d4
diff --git a/cmd/minikube/cmd/start.go b/cmd/minikube/cmd/start.go index <HASH>..<HASH> 100644 --- a/cmd/minikube/cmd/start.go +++ b/cmd/minikube/cmd/start.go @@ -322,7 +322,7 @@ func prepareNone() { console.OutLn("") console.OutStyle("command", "sudo mv %s/.kube %s/.minikube $HOME", home, home) - console.OutStyle("command", "sudo chown -R $USER %s/.kube %s/.minikube", home, home) + console.OutStyle("command", "sudo chown -R $USER $HOME/.kube $HOME/.minikube") console.OutLn("") console.OutStyle("tip", "This can also be done automatically by setting the env var CHANGE_MINIKUBE_NONE_USER=true")
chown command should be against user $HOME, not roots home directory.
kubernetes_minikube
train
df333caaa3764a962ecc926a1255f94d4831af4b
diff --git a/app/controllers/releaf/base_controller.rb b/app/controllers/releaf/base_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/releaf/base_controller.rb +++ b/app/controllers/releaf/base_controller.rb @@ -104,14 +104,17 @@ module Releaf def edit raise FeatureDisabled unless @features[:edit] - @resource = resource_class.includes(relations_for_includes).find(params[:id]) + # load resource only if is not loaded yet + @resource = resource_class.includes(relations_for_includes).find(params[:id]) if @resource.nil? end def validate if params[:id].nil? + # load resource only if is not loaded yet @resource = resource_class.new else - @resource = resource_class.includes(relations_for_includes).find(params[:id]) + # load resource only if is not loaded yet + @resource = resource_class.includes(relations_for_includes).find(params[:id]) if @resource.nil? end @resource.assign_attributes required_params.permit(*resource_params) @@ -125,13 +128,11 @@ module Releaf def create raise FeatureDisabled unless @features[:create] - @resource = resource_class.new save_and_respond :create end def update raise FeatureDisabled unless @features[:edit] - @resource = resource_class.find(params[:id]) save_and_respond :update end @@ -612,11 +613,15 @@ module Releaf def save_and_respond request_type if request_type == :create + # load resource only if is not loaded yet + @resource = resource_class.new if @resource.nil? @resource.assign_attributes required_params.permit(*resource_params) result = @resource.save html_render_action = "new" elsif request_type == :update + # load resource only if is not loaded yet + @resource = resource_class.find(params[:id]) if @resource.nil? result = @resource.update_attributes required_params.permit(*resource_params) html_render_action = "edit"
Load @resource only if it's not existing before
cubesystems_releaf
train
1b5ff1102c179c1940dc3f4bd57839dc1c559cdd
diff --git a/libzfs/zpool.py b/libzfs/zpool.py index <HASH>..<HASH> 100644 --- a/libzfs/zpool.py +++ b/libzfs/zpool.py @@ -1,6 +1,7 @@ -from .bindings import manager +from .bindings import manager, enums from .handle import LibZFSHandle -from . import enums + +from .nvpair import NVList c_libzfs = manager.libzfs ffi_libzfs = manager.libzfs_ffi @@ -9,6 +10,7 @@ ffi_libzfs = manager.libzfs_ffi class ZPool(object): _name = None _state = None + _config = None def __init__(self, handle): self._handle = handle @@ -26,6 +28,15 @@ class ZPool(object): self._state = enums.pool_state(state) return self._state + @property + def config(self): + if self._config is None: + config = c_libzfs.zpool_get_config(self._handle, ffi_libzfs.new_handle(None)) + config_list = NVList.from_nvlist_ptr(config) + with config_list: + self._config = config_list.to_dict(skip_unknown = True) + return self._config + def __repr__(self): return "<ZPool: %s: %s>" % (self.name, self.state.name)
-Add: ZPool.config settings. skipping unknown, for now, as we lack a fair few converters still.
Xaroth_libzfs-python
train
2adf0b02be3c422b204a4f8914697efb78d250f7
diff --git a/cocaine/proxy/proxy.py b/cocaine/proxy/proxy.py index <HASH>..<HASH> 100644 --- a/cocaine/proxy/proxy.py +++ b/cocaine/proxy/proxy.py @@ -649,7 +649,8 @@ class LogLevel(web.RequestHandler): # pylint: disable=W0223 self.write("No such level %s" % lvlname) return - logging.getLogger().setLevel(lvl) + for name in ("cocaine.proxy.general", "cocaine.proxy.access", "cocaine.baseservice"): + logging.getLogger(name).setLevel(lvl) self.write("level %s has been set" % logging.getLevelName(lvl))
fix(proxy): change loglevel for all loggers
cocaine_cocaine-tools
train
7b0d039fb0f611076236a975e0931f236daa18ee
diff --git a/lib/logger.js b/lib/logger.js index <HASH>..<HASH> 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -34,7 +34,7 @@ logger.setLevel = function (level) { /* Verbose and debug have not exactly the same semantic in Mailin and * Winston, so handle that. */ if (logger.transports.console.level === 'verbose' && - level === 'debug') { + level === 'debug') { return; } @@ -47,7 +47,9 @@ logger.error = function (err) { if (err.stack) { this._error(err.stack); } else if (!_.isString(err)) { - this._error(util.inspect(err, {depth: 5})); + this._error(util.inspect(err, { + depth: 5 + })); } else { this._error.apply(this, arguments); } diff --git a/lib/mailUtilities.js b/lib/mailUtilities.js index <HASH>..<HASH> 100644 --- a/lib/mailUtilities.js +++ b/lib/mailUtilities.js @@ -3,6 +3,7 @@ var child_process = require('child_process'); var shell = require('shelljs'); var logger = require('./logger'); +var path = require('path'); var Spamc = require('spamc'); var spamc = new Spamc(); @@ -28,7 +29,8 @@ module.exports = { return callback(null, false); } - var verifyDkim = child_process.spawn('python', ['python/verifydkim.py']); + var verifyDkimPath = path.join(__dirname, 'python/verifydkim.py'); + var verifyDkim = child_process.spawn('python', [verifyDkimPath]); verifyDkim.stdout.on('data', function (data) { logger.verbose(data.toString()); @@ -49,7 +51,8 @@ module.exports = { return callback(null, false); } - var cmd = 'python python/verifyspf.py ' + ip + ' ' + address + ' ' + host; + var verifySpfPath = path.join(__dirname, 'python/verifyspf.py'); + var cmd = 'python ' + verifySpfPath + ' ' + ip + ' ' + address + ' ' + host; child_process.exec(cmd, function (err, stdout) { logger.verbose(stdout); var code = 0; @@ -71,7 +74,6 @@ module.exports = { } spamc.report(rawEmail, function (err, result) { - debugger; if (err) logger.error(err); if (err) return callback(new Error('Unable to compute spam score.')); callback(null, result.spamScore); diff --git a/lib/mailin.js b/lib/mailin.js index <HASH>..<HASH> 100644 --- a/lib/mailin.js +++ b/lib/mailin.js @@ -79,7 +79,7 @@ Mailin.prototype.start = function (options, callback) { var memoryUsage = process.memoryUsage(); var ram = memoryUsage.rss + memoryUsage.heapUsed; var million = 1000000; - logger.info('Ram Usage: ' + ram / million + 'mb | rss: ' + memoryUsage.rss / million + + logger.info('Ram Usage: ' + ram / million + 'mb | rss: ' + memoryUsage.rss / million + 'mb | heapTotal: ' + memoryUsage.heapTotal / million + 'mb | heapUsed: ' + memoryUsage.heapUsed / million); }, 500); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mailin", - "version": "0.0.8", + "version": "0.0.9", "description": "Artisanal inbound emails for every web app", "main": "index.js", "bin": {
Fix python scripts paths
Flolagale_mailin
train
722d8562f046fcf58791ce0f679999425a57e11f
diff --git a/src/test/java/org/mariadb/jdbc/integration/Common.java b/src/test/java/org/mariadb/jdbc/integration/Common.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/mariadb/jdbc/integration/Common.java +++ b/src/test/java/org/mariadb/jdbc/integration/Common.java @@ -140,13 +140,12 @@ public class Common { public static boolean haveSsl() throws SQLException { Statement stmt = sharedConn.createStatement(); ResultSet rs = stmt.executeQuery("show variables like '%ssl%'"); - while (rs.next()) { - System.out.println(rs.getString(1) + ":" + rs.getString(2)); - } + // while (rs.next()) { + // System.out.println(rs.getString(1) + ":" + rs.getString(2)); + // } rs = stmt.executeQuery("select @@have_ssl"); assertTrue(rs.next()); - System.out.println("have ssl:" + rs.getString(1)); return "YES".equals(rs.getString(1)); }
[misc] removing ssl status from test
MariaDB_mariadb-connector-j
train
3e6e63b70ebab0f02ec555721ec69e74f1d8cc2d
diff --git a/bdata/bmerged.py b/bdata/bmerged.py index <HASH>..<HASH> 100644 --- a/bdata/bmerged.py +++ b/bdata/bmerged.py @@ -27,6 +27,7 @@ class bmerged(bdata): idx = np.argsort(runs) bdata_list = np.array(bdata_list)[idx] runs = np.array(runs)[idx] + years = np.array([b.year for b in bdata_list]) # set some common parameters for key in ('apparatus','area','das','description','duration','end_date', @@ -36,10 +37,9 @@ class bmerged(bdata): x = np.array([getattr(b,key) for b in bdata_list]) setattr(self,key,self._combine_values(key,x)) - # set the run number and year self.run = int(''.join(map(str,runs))) - self.year = max([b.year for b in bdata_list]) + self.year = int(''.join(map(str,years))) # set ppg, camp, and epics for top in ('ppg','epics','camp'):
bmerged.py: updated years to be appended
dfujim_bdata
train
886ac48dc26f949f6379822347527085c983b2d6
diff --git a/tests/scripts/selenium/fuzzer.rb b/tests/scripts/selenium/fuzzer.rb index <HASH>..<HASH> 100644 --- a/tests/scripts/selenium/fuzzer.rb +++ b/tests/scripts/selenium/fuzzer.rb @@ -1,4 +1,3 @@ -require 'debugger' require 'selenium-webdriver' require_relative 'selenium_adapter' @@ -116,8 +115,11 @@ if replay doc_delta, rand_delta = read_deltas_from_file(replay) js_set_delta_replay(driver, doc_delta, 'docDelta') js_set_delta_replay(driver, rand_delta, 'randomDelta') + doc_delta = js_get_doc_delta(driver) js_set_scribe_delta(driver) + adapter.doc_length = doc_delta['endLength'] random_delta = js_get_random_delta(driver) + random_delta_str = js_get_random_delta_as_str(driver) adapter.apply_delta(random_delta) check_consistency(driver, replay) else diff --git a/tests/scripts/selenium/selenium_adapter.rb b/tests/scripts/selenium/selenium_adapter.rb index <HASH>..<HASH> 100644 --- a/tests/scripts/selenium/selenium_adapter.rb +++ b/tests/scripts/selenium/selenium_adapter.rb @@ -5,6 +5,7 @@ # - Some of this code is not the Ruby way; fix that. ################################################################################ class SeleniumAdapter + attr_accessor :doc_length def initialize(driver, editor) @cursor_pos = 0 @driver = driver @@ -22,8 +23,14 @@ class SeleniumAdapter type_text(op['value']) # Remove off any prexisting formatting that Scribe applied move_cursor(index) - highlight(op['value'].length) - remove_active_formatting + runs = op['value'].split "\n" + runs.each do |run| + highlight(run.length) + remove_active_formatting + move_cursor(0) # Kludge to remove highlighting + move_cursor(index + run.length + 1) # +1 to account for \n + index += run.length + 1 + end move_cursor(0) # Kludge to remove the highlighting break elsif op['start'] > index
Bug fixes. Need to initialize doc_length of adapter when we set the delta on scribe in preparation of a replay. In cases where multiple lines are inserted, need to highlight each line individually to correctly remove the automatically applied formatting.
quilljs_quill
train
e58c4b345126aa19fd7c6dd4a63a5c4222e78507
diff --git a/css_to_inline_styles.php b/css_to_inline_styles.php index <HASH>..<HASH> 100755 --- a/css_to_inline_styles.php +++ b/css_to_inline_styles.php @@ -12,7 +12,8 @@ * If you report a bug, make sure you give me enough information (include your code). * * Changelog since 1.0.3 - * - fixed some code-styling issues. + * - fixed some code-styling issues + * - added support for multiple values * * Changelog since 1.0.2 * - .class are matched from now on. @@ -311,7 +312,13 @@ class CSSToInlineStyles $propertyChunks = array(); // build chunks - foreach($properties as $key => $value) $propertyChunks[] = $key .': '. $value .';'; + foreach($properties as $key => $values) + { + foreach((array) $values as $value) + { + $propertyChunks[] = $key .': '. $value .';'; + } + } // build properties string $propertiesString = implode(' ', $propertyChunks); @@ -461,8 +468,12 @@ class CSSToInlineStyles // validate if(!isset($chunks[1])) continue; + // cleanup + $chunks[0] = trim($chunks[0]); + $chunks[1] = trim($chunks[1]); + // add to pairs array - $pairs[trim($chunks[0])] = trim($chunks[1]); + if(!isset($pairs[$chunks[0]]) || !in_array($chunks[1], $pairs[$chunks[0]])) $pairs[$chunks[0]][] = $chunks[1]; } // sort the pairs
Added support for multiple values for the same property
tijsverkoyen_CssToInlineStyles
train
667325db43962f4e20ddaaa7f89de2dfbbf8edfd
diff --git a/pyontutils/docs.py b/pyontutils/docs.py index <HASH>..<HASH> 100644 --- a/pyontutils/docs.py +++ b/pyontutils/docs.py @@ -56,7 +56,7 @@ def renderMarkdown(path, title=None, authors=None, date=None, **kwargs): mdfile = path.as_posix() # TODO fix relative links to point to github - pandoc = ['pandoc', '-f', md_read_format, '-t', 'org', mdfile] + pandoc = ['pandoc', '--columns', '300', '-f', md_read_format, '-t', 'org', mdfile] sed = ['sed', r's/\[\[\(.\+\)\]\[\[\[\(.\+\)\]\]\]\]/[[img:\2][\1]]/g'] p = subprocess.Popen(pandoc,
docs pandoc up column width to prevent spurious line splits
tgbugs_pyontutils
train
91342a0430119d3884ac7d6bf4078fcf38e401fa
diff --git a/ethereum/pow/chain.py b/ethereum/pow/chain.py index <HASH>..<HASH> 100644 --- a/ethereum/pow/chain.py +++ b/ethereum/pow/chain.py @@ -76,8 +76,12 @@ class Chain(object): initialize(self.state) self.new_head_cb = new_head_cb - - assert self.state.block_number == self.state.prev_headers[0].number + + if self.state.block_number == 0: + assert self.state.block_number == self.state.prev_headers[0].number + else: + assert self.state.block_number - 1 == self.state.prev_headers[0].number + if reset_genesis: if isinstance(self.state.prev_headers[0], FakeHeader): header = self.state.prev_headers[0].to_block_header()
fixed off by one error for genesis with state in chain init
ethereum_pyethereum
train
e9afe9168ef04fcf172b1298cde15bf3d011cf5a
diff --git a/tests/unit/modules/test_netmiko_mod.py b/tests/unit/modules/test_netmiko_mod.py index <HASH>..<HASH> 100644 --- a/tests/unit/modules/test_netmiko_mod.py +++ b/tests/unit/modules/test_netmiko_mod.py @@ -2,7 +2,6 @@ import logging import salt.modules.netmiko_mod as netmiko_mod -from salt.utils.args import get_function_argspec from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import patch from tests.support.unit import TestCase @@ -34,8 +33,8 @@ def mock_file_apply_template_on_contents(*args): return args[0] -def mock_config_get(key, default): - return default +def mock_prepare_connection(**kwargs): + return MockNetmikoConnection(**kwargs), {} class NetmikoTestCase(TestCase, LoaderModuleMockMixin): @@ -44,14 +43,12 @@ class NetmikoTestCase(TestCase, LoaderModuleMockMixin): netmiko_mod: { "__salt__": { "file.apply_template_on_contents": mock_file_apply_template_on_contents, - "config.get": mock_config_get, }, "__proxy__": { "netmiko.conn": mock_netmiko_conn, "netmiko.args": mock_netmiko_args, }, - "__utils__": {"args.get_function_argspec": get_function_argspec}, - "ConnectHandler": MockNetmikoConnection, + "_prepare_connection": mock_prepare_connection, } }
saltstack/salt#<I> mock prepare_connection since it depends on netmiko
saltstack_salt
train
faf5c4b47aa8a013b62e10b66e5c1d5224638240
diff --git a/colorz.py b/colorz.py index <HASH>..<HASH> 100755 --- a/colorz.py +++ b/colorz.py @@ -312,7 +312,7 @@ def main(): # Open local file or online file try: - img_fd = open(args.image) if os.path.isfile(args.image) else \ + img_fd = open(args.image, 'rb') if os.path.isfile(args.image) else \ BytesIO(urlopen(args.image).read()) except ValueError: print("%s was not a valid URL." % args.image) diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ with codecs.open(path.join(here, 'README.rst'), encoding='utf-8') as f: setup( name='colorz', - version='1.0.1', + version='1.0.2', description='Color scheme generator.', long_description=long_description, url='https://github.com/metakirby5/colorz',
hotfix: open file in binary mode to prevent Pillow bug
metakirby5_colorz
train
bfa01848e2d68947d098da11255b60787a012979
diff --git a/rest/src/main/java/org/jboss/pnc/rest/provider/ArtifactProvider.java b/rest/src/main/java/org/jboss/pnc/rest/provider/ArtifactProvider.java index <HASH>..<HASH> 100644 --- a/rest/src/main/java/org/jboss/pnc/rest/provider/ArtifactProvider.java +++ b/rest/src/main/java/org/jboss/pnc/rest/provider/ArtifactProvider.java @@ -58,17 +58,19 @@ public class ArtifactProvider extends AbstractProvider<Artifact, ArtifactRest> { public CollectionInfo<ArtifactRest> getAllForBuildRecord(int pageIndex, int pageSize, String sortingRsql, String query, int buildRecordId) { BuildRecord buildRecord = buildRecordRepository.queryById(buildRecordId); - List<Artifact> artifactList = buildRecord.getDependencies(); - if (artifactList == null) { - artifactList = new ArrayList<Artifact>(); + + List<Artifact> fullArtifactList = new ArrayList<Artifact>(); + for (Artifact artifact : buildRecord.getBuiltArtifacts()) { + fullArtifactList.add(artifact); } - for (BuiltArtifact artifact : buildRecord.getBuiltArtifacts()) { - artifactList.add(artifact); + for (Artifact artifact : buildRecord.getDependencies()) { + fullArtifactList.add(artifact); } - return nullableStreamOf(artifactList).map(artifact -> new ArtifactRest(artifact)).skip(pageIndex * pageSize) - .limit(pageSize).collect(new CollectionInfoCollector<>(pageIndex, pageSize, artifactList.size())); + return nullableStreamOf(fullArtifactList).map(artifact -> new ArtifactRest(artifact)).skip(pageIndex * pageSize) + .limit(pageSize).collect(new CollectionInfoCollector<>(pageIndex, pageSize, fullArtifactList.size())); } + public CollectionInfo<ArtifactRest> getBuiltArtifactsForBuildRecord(int pageIndex, int pageSize, String sortingRsql, String query, int buildRecordId) { BuildRecord buildRecord = buildRecordRepository.queryById(buildRecordId);
Fix bug causing duplicate entries for build record dependencies
project-ncl_pnc
train
a90040adbdedef2c6e1de998169d26a25b839f2f
diff --git a/src/Model/Write/Products/CollectionDecorator/StockData.php b/src/Model/Write/Products/CollectionDecorator/StockData.php index <HASH>..<HASH> 100644 --- a/src/Model/Write/Products/CollectionDecorator/StockData.php +++ b/src/Model/Write/Products/CollectionDecorator/StockData.php @@ -214,6 +214,9 @@ class StockData implements DecoratorInterface private function getCombinedStock(ExportEntity $entity, int $storeId): float { $stockQuantities = $this->getStockQuantities($entity); + if (empty($stockQuantities)) { + return 0; + } switch ($this->config->getStockCalculation($storeId)) { case StockCalculation::OPTION_MAX:
Added check on empty array to prevent Exception on executing max on empty array
EmicoEcommerce_Magento2TweakwiseExport
train
6a8d4a0359d5c898301fcac0da785e9b59675dd8
diff --git a/rack-protection/lib/rack/protection/json_csrf.rb b/rack-protection/lib/rack/protection/json_csrf.rb index <HASH>..<HASH> 100644 --- a/rack-protection/lib/rack/protection/json_csrf.rb +++ b/rack-protection/lib/rack/protection/json_csrf.rb @@ -10,7 +10,7 @@ module Rack # JSON GET APIs are volnurable to being embedded as JavaScript while the # Array prototype has been patched to track data. Checks the referrer # even on GET requests if the content type is JSON. - class JsonCsrf < AuthenticityToken + class JsonCsrf < Base default_reaction :deny def call(env)
fix superclass this didn't matter, since it overrides call
sinatra_sinatra
train
b3005af1e8d5fa32259bdb9d394401f96dbac862
diff --git a/odl/operator/pspace_ops.py b/odl/operator/pspace_ops.py index <HASH>..<HASH> 100644 --- a/odl/operator/pspace_ops.py +++ b/odl/operator/pspace_ops.py @@ -277,12 +277,46 @@ class ProductSpaceOperator(Operator): def derivative(self, x): """Derivative of the product space operator. + + Parameters + ---------- + x : domain element + The point to take the derivative in + + Returns + ------- + adjoint : linear`ProductSpaceOperator` + The derivative + + Examples + -------- + >>> import odl + >>> r3 = odl.Rn(3) + >>> X = odl.ProductSpace(r3, r3) + >>> I = odl.IdentityOperator(r3) + >>> x = X.element([[1, 2, 3], [4, 5, 6]]) + + Example with linear operator (derivative is itself) + + >>> prod_op = ProductSpaceOperator([[0, I], [0, 0]], + ... dom=X, ran=X) + >>> prod_op(x) + ProductSpace(Rn(3), 2).element([ + [4.0, 5.0, 6.0], + [0.0, 0.0, 0.0] + ]) + >>> prod_op.derivative(x)(x) + ProductSpace(Rn(3), 2).element([ + [4.0, 5.0, 6.0], + [0.0, 0.0, 0.0] + ]) """ - deriv_ops = [op.derivative(x[col]) for op, col in zip(self.ops.data, self.ops.col)] + deriv_ops = [op.derivative(x[col]) for op, col in zip(self.ops.data, + self.ops.col)] indices = [self.ops.row, self.ops.col] - shape = (self.ops.shape[0], self.ops.shape[1]) - adj_matrix = sp.sparse.coo_matrix((deriv_ops, indices), shape) - return ProductSpaceOperator(adj_matrix, self.domain, self.range) + shape = self.ops.shape + deriv_matrix = sp.sparse.coo_matrix((deriv_ops, indices), shape) + return ProductSpaceOperator(deriv_matrix, self.domain, self.range) @property def adjoint(self):
ENH: improve style of derivative doc
odlgroup_odl
train
68ed581134ef762aa039253c16b8f3b020f7d74f
diff --git a/apiary2postman/apiary2postman.py b/apiary2postman/apiary2postman.py index <HASH>..<HASH> 100755 --- a/apiary2postman/apiary2postman.py +++ b/apiary2postman/apiary2postman.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from sys import stdin, stdout, argv, exit +from sys import stdin, stderr, stdout, argv, exit import argparse import subprocess import os @@ -7,6 +7,16 @@ import platform from converter import write from blueprint import blueprint2json,fetch_blueprint +class bcolors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + def readInput(): content = "" for line in stdin: @@ -16,18 +26,24 @@ def readInput(): def check_drafter(): try: - if platform.system().lower().startswith('win'): - subprocess.call(['drafter', '-v'], stdout=subprocess.PIPE) == 0 - else: - subprocess.check_output(['which', 'drafter']) + assert subprocess.check_output(['drafter', '-v']).startswith('v0.1') except: - print 'Please install drafter:' - print '' - print 'By using brew:' - print '\tbrew install --HEAD https://raw.github.com/apiaryio/drafter/master/tools/homebrew/drafter.rb' - print '' - print 'By source, see:' - print '\thttps://github.com/apiaryio/drafter' + print >> stderr, '' + print >> stderr, bcolors.BOLD +'Please install Drafter < v2' + bcolors.ENDC + print >> stderr, 'Drafter is used to convert Blueprint API to JSON. The preferred version is v0.1.9.' + print >> stderr, 'Drafter v2 changed the JSON output format to be incomptabile with apiary2postman.' + print >> stderr, 'Feel free to submit a pull request at GitHub which fixes this at https://github.com/thecopy/apiary2postman' + print >> stderr, '' + print >> stderr, 'By using ' + bcolors.BOLD + 'brew:' + bcolors.ENDC + print >> stderr, '\tbrew install --HEAD https://raw.githubusercontent.com/apiaryio/drafter/b3dce8dda5d48b36e963abeffe5b0de7afecac3d/tools/homebrew/drafter.rb' + print >> stderr, '' + print >> stderr, 'By ' + bcolors.BOLD + 'source:' + bcolors.ENDC + print >> stderr, '\tgit clone https://github.com/apiaryio/drafter' + print >> stderr, '\tcd drafter' + print >> stderr, '\tgit checkout b3dce8d ' + bcolors.HEADER + '# This is the commit for release 0.1.9' + bcolors.ENDC + print >> stderr, '\t./configure' + print >> stderr, '\tmake' + print >> stderr, '\tsudo make install' exit(3) def main(): diff --git a/apiary2postman/blueprint.py b/apiary2postman/blueprint.py index <HASH>..<HASH> 100644 --- a/apiary2postman/blueprint.py +++ b/apiary2postman/blueprint.py @@ -12,6 +12,6 @@ def fetch_blueprint(name, key): def blueprint2json(blueprint): p = Popen(['drafter', '--format', 'json'], stdin=PIPE, stdout=PIPE, stderr=PIPE) - out, err = p.communicate(blueprint) + out, err = p.communicate(blueprint.encode('utf8')) return out \ No newline at end of file
Check drafter version, not only that it is installed. Amend error message (fixes #<I>). Fix PIPE encoding issue.
thecopy_apiary2postman
train
23eb5f8cb44bedf090cfcacbe1c5315703235a38
diff --git a/esptool.py b/esptool.py index <HASH>..<HASH> 100755 --- a/esptool.py +++ b/esptool.py @@ -1902,7 +1902,7 @@ def elf2image(args): e = ELFFile(args.input) if args.chip == 'auto': # Default to ESP8266 for backwards compatibility print("Creating image for ESP8266...") - args.chip == 'esp8266' + args.chip = 'esp8266' if args.chip == 'esp32': image = ESP32FirmwareImage()
Fix assignment to args.chip.
espressif_esptool
train
9f2ebe742de448f296150a0f59fc590fdc55833a
diff --git a/lib/context.js b/lib/context.js index <HASH>..<HASH> 100644 --- a/lib/context.js +++ b/lib/context.js @@ -103,6 +103,12 @@ class Context { this.res.status(err.status); + let contentType = this.res.get('Content-Type'); + if ('string' === typeof contentType) { + this.req.headers.accept = contentType; + } + + let self = this; this.res.format({ 'text/plain': function() { @@ -113,18 +119,16 @@ class Context { let config = sand.Http.config; if (config[err.status]) { - self.render(config[err.status], data); + self.render(config[err.status], err); } else if (_.isPlainObject(config[err.status])) { - self.render(config[status].file, config[err.status].data); + self.render(config[err.status].file, config[err.status].data); } else { self.send(message); } }, 'application/json': function() { - self.json({ - error: message - }); + self.json(_.merge({ error: message }, err)); } }) } @@ -201,7 +205,7 @@ delegate(Context.prototype, 'response') .method('render') .method('json') .method('status') - .method('type') + .access('type') .access('length') .access('lastModified') .access('etag')
fixed json error messages, also override accept if specified earlier
SandJS_http
train
411c51358a86769877f30877d415ae8d1ddf4688
diff --git a/src/InfoViz/Native/ParallelCoordinates/index.js b/src/InfoViz/Native/ParallelCoordinates/index.js index <HASH>..<HASH> 100644 --- a/src/InfoViz/Native/ParallelCoordinates/index.js +++ b/src/InfoViz/Native/ParallelCoordinates/index.js @@ -69,6 +69,7 @@ export function toColorArray(colorString) { function parallelCoordinate(publicAPI, model) { // Private internal const scoreToColor = []; + let lastAnnotationPushed = null; function updateSizeInformation() { if (!model.canvas) { @@ -852,13 +853,20 @@ function parallelCoordinate(publicAPI, model) { publicAPI.render(); })); model.subscriptions.push(model.provider.onAnnotationChange(annotation => { + if (lastAnnotationPushed && annotation.selection.type === 'range' && annotation.generation === lastAnnotationPushed.generation + 1) { + // Assume that it is still ours but edited by someone else + lastAnnotationPushed = annotation; + + // Capture the score and update our default + model.defaultScore = lastAnnotationPushed.score[0]; + } model.axes.resetSelections(annotation.selection, false, annotation.score, scoreToColor); publicAPI.render(); })); model.subscriptions.push(model.axes.onSelectionChange(() => { if (model.useAnnotation) { - const annotation = AnnotationBuilder.annotation(model.axes.getSelection(), [model.defaultScore], model.defaultWeight); - model.provider.setAnnotation(annotation); + lastAnnotationPushed = AnnotationBuilder.annotation(model.axes.getSelection(), [model.defaultScore], model.defaultWeight); + model.provider.setAnnotation(lastAnnotationPushed); } else { model.provider.setSelection(model.axes.getSelection()); }
fix(ParallelCoordinates): Add support for annotation edit and defaultScore update
Kitware_paraviewweb
train
85dcdf21a8c7522c3296c3c928e16b207b609161
diff --git a/src/main/java/org/codehaus/groovy/control/customizers/SecureASTCustomizer.java b/src/main/java/org/codehaus/groovy/control/customizers/SecureASTCustomizer.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/codehaus/groovy/control/customizers/SecureASTCustomizer.java +++ b/src/main/java/org/codehaus/groovy/control/customizers/SecureASTCustomizer.java @@ -700,7 +700,7 @@ public class SecureASTCustomizer extends CompilationCustomizer { // we should now check if the import is in the star imports String packageName = getWildCardImport(className); if (!staticStarImportsWhitelist.contains(className + ".*") - && !staticStarImportsWhitelist.stream().filter(it -> it.endsWith(".")).anyMatch(packageName::startsWith)) { + && staticStarImportsWhitelist.stream().filter(it -> it.endsWith(".")).noneMatch(packageName::startsWith)) { throw new SecurityException("Importing [" + fqn + "] is not allowed"); } } else { diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/PluginDefaultGroovyMethods.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/PluginDefaultGroovyMethods.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/codehaus/groovy/vmplugin/v8/PluginDefaultGroovyMethods.java +++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/PluginDefaultGroovyMethods.java @@ -601,7 +601,7 @@ public class PluginDefaultGroovyMethods extends DefaultGroovyMethodsSupport { * @since 2.5.0 */ public static Stream<Integer> stream(final int[] self) { - return Arrays.stream(self).mapToObj(Integer::valueOf); + return Arrays.stream(self).boxed(); } /** @@ -614,7 +614,7 @@ public class PluginDefaultGroovyMethods extends DefaultGroovyMethodsSupport { * @since 2.5.0 */ public static Stream<Long> stream(final long[] self) { - return Arrays.stream(self).mapToObj(Long::valueOf); + return Arrays.stream(self).boxed(); } /** @@ -627,7 +627,7 @@ public class PluginDefaultGroovyMethods extends DefaultGroovyMethodsSupport { * @since 2.5.0 */ public static Stream<Double> stream(final double[] self) { - return Arrays.stream(self).mapToObj(Double::valueOf); + return Arrays.stream(self).boxed(); } /**
Trivial refactoring: Simplify the code
apache_groovy
train
d5d0b05f704ef5121dab3b9220df2a5f48b963fa
diff --git a/treeinterpreter/treeinterpreter.py b/treeinterpreter/treeinterpreter.py index <HASH>..<HASH> 100644 --- a/treeinterpreter/treeinterpreter.py +++ b/treeinterpreter/treeinterpreter.py @@ -10,7 +10,7 @@ from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import RandomForestClassifier -def get_tree_paths(tree, node_id, parent=None, depth=0): +def get_tree_paths(tree, node_id, depth=0): """ Returns all paths through the tree as list of node_ids """ @@ -21,15 +21,13 @@ def get_tree_paths(tree, node_id, parent=None, depth=0): right_child = tree.children_right[node_id] if left_child != _tree.TREE_LEAF: - left_paths = get_tree_paths(tree, left_child, parent=node_id, - depth=depth + 1) - right_paths = get_tree_paths(tree, right_child, parent=node_id, - depth=depth + 1) - - for p in left_paths: - p.append(node_id) - for p in right_paths: - p.append(node_id) + left_paths = get_tree_paths(tree, left_child, depth=depth + 1) + right_paths = get_tree_paths(tree, right_child, depth=depth + 1) + + for path in left_paths: + path.append(node_id) + for path in right_paths: + path.append(node_id) paths = left_paths + right_paths else: paths = [[node_id]] @@ -63,7 +61,7 @@ def predict_tree(model, X): contributions[row] = contribs direct_prediction = model.tree_.value.take( leaves, axis=0, mode='clip').reshape(X.shape[0], 1)[:, 0] - elif type(model) == DecisionTreeClassifier: + elif type(model) == DecisionTreeClassifier: # remove the single-dimensional inner arrays values = model.tree_.value.squeeze() # scikit stores category counts, we turn them into probabilities @@ -97,6 +95,19 @@ def predict_tree(model, X): def predict_forest(model, X): + """ Returns a tripe (prediction, bias, contributions) + Parameters + ---------- + X : array-like, shape = (n_samples, n_features) + Test samples. + model : RandomForestRegressor or RandomForestClassifier + Sckit learn forest model on which the prediction should be decomposed + + Returns + ------- + decomposed prediction : tuple + + """ biases = [] contributions = [] predictions = [] @@ -107,3 +118,24 @@ def predict_forest(model, X): predictions.append(pred) return (np.mean(predictions, axis=0), np.mean(biases, axis=0), np.mean(contributions, axis=0)) + + +def predict(model, X): + pass + +if __name__ == "__main__": + # test + from sklearn.datasets import load_iris + iris = load_iris() + idx = range(len(iris.data)) + np.random.shuffle(idx) + X = iris.data[idx] + Y = iris.target[idx] + dt = RandomForestClassifier(max_depth=3) + dt.fit(X[:len(X)/2], Y[:len(X)/2]) + testX = X[len(X)/2:len(X)/2+5] + base_prediction = dt.predict_proba(testX) + pred, bias, contrib = predict_forest(dt, testX) + + assert(np.allclose(base_prediction, pred)) + assert(np.allclose(pred, bias + np.sum(contrib, axis=1))) \ No newline at end of file
Pep improvements, main method for quick test
andosa_treeinterpreter
train
78718fffefd96399952c706b034c86d4b1020783
diff --git a/cloudfoundry-operations/src/main/java/org/cloudfoundry/operations/applications/DefaultApplications.java b/cloudfoundry-operations/src/main/java/org/cloudfoundry/operations/applications/DefaultApplications.java index <HASH>..<HASH> 100644 --- a/cloudfoundry-operations/src/main/java/org/cloudfoundry/operations/applications/DefaultApplications.java +++ b/cloudfoundry-operations/src/main/java/org/cloudfoundry/operations/applications/DefaultApplications.java @@ -149,6 +149,10 @@ public final class DefaultApplications implements Applications { private static final int CF_STAGING_TIME_EXPIRED = 170007; + private static final String[] ENTRY_FIELDS_CRASH = {"index", "reason", "exit_description"}; + + private static final String[] ENTRY_FIELDS_NORMAL = {"instances", "memory", "state", "environment_json"}; + private static final Comparator<LogMessage> LOG_MESSAGE_COMPARATOR = Comparator.comparing(LogMessage::getTimestamp); private static final Duration LOG_MESSAGE_TIMESPAN = Duration.ofMillis(500); @@ -665,7 +669,7 @@ public final class DefaultApplications implements Applications { } return ApplicationEvent.builder() .actor(entity.getActorName()) - .description(eventDescription(getMetadataRequest(entity), "instances", "memory", "state", "environment_json")) + .description(eventDescription(getMetadataRequest(entity), getEntryNames(entity.getType()))) .id(ResourceUtils.getId(resource)) .event(entity.getType()) .time(timestamp) @@ -851,6 +855,10 @@ public final class DefaultApplications implements Applications { .orElseThrow(() -> new IllegalArgumentException(String.format("Domain %s not found", domainName))); } + private static String[] getEntryNames(String type) { + return type.contains("crash") ? ENTRY_FIELDS_CRASH : ENTRY_FIELDS_NORMAL; + } + private static Map<String, Object> getEnvironment(AbstractApplicationResource resource) { return ResourceUtils.getEntity(resource).getEnvironmentJsons(); } @@ -880,6 +888,9 @@ public final class DefaultApplications implements Applications { return metadata.get("request") .map(m -> (Map<String, Object>) m) .orElse(Collections.emptyMap()); + } else if (metadata.get("instance") != null) { + return metadata.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().orElse(""))); } else { return Collections.emptyMap(); }
Handle Crash Events Previously application events were limited to 'happy path' events such as state changes. We discarded other events most notably application crashes. This commit adds reporting for the supporting information around crashes. [resolves #<I>]
cloudfoundry_cf-java-client
train
9ea0d8f0e9a9cff65ab34a54dd5f797402983aa3
diff --git a/src/oauth2server/Server.php b/src/oauth2server/Server.php index <HASH>..<HASH> 100644 --- a/src/oauth2server/Server.php +++ b/src/oauth2server/Server.php @@ -179,7 +179,7 @@ class Server return $params; } - function newAuthoriseRequest(string $typeId, array $authoriseParams) + public function newAuthoriseRequest(string $typeId, array $authoriseParams) { // Check if the user already has an access token $accessToken = $this->db->hasAccessToken($userId,
Added scope to newAuthoriseRequst function
thephpleague_oauth2-server
train
69a8bf404a08690e9d0d8a92a3913522b239b1b0
diff --git a/publify_core/spec/factories.rb b/publify_core/spec/factories.rb index <HASH>..<HASH> 100644 --- a/publify_core/spec/factories.rb +++ b/publify_core/spec/factories.rb @@ -58,7 +58,7 @@ FactoryGirl.define do extended 'extended content for fun' guid permalink 'a-big-article' - published_at DateTime.new(2005, 1, 1, 2, 0, 0) + published_at { Time.now } user allow_comments true state :published @@ -203,9 +203,7 @@ FactoryGirl.define do author 'Bob Foo' url 'http://fakeurl.com' body 'Comment body' - created_at '2005-01-01 02:00:00' - updated_at '2005-01-01 02:00:00' - published_at '2005-01-01 02:00:00' + published_at { Time.now } guid state 'ham' @@ -242,9 +240,7 @@ FactoryGirl.define do name { FactoryGirl.generate(:name) } title 'Page One Title' body { FactoryGirl.generate(:body) } - created_at '2005-05-05 01:00:01' - published_at '2005-05-05 01:00:01' - updated_at '2005-05-05 01:00:01' + published_at { Time.now } user blog { Blog.first || create(:blog) } state 'published' @@ -252,9 +248,7 @@ FactoryGirl.define do factory :note do body 'this is a note' - created_at '2013-07-14 01:00:01' - published_at '2013-07-14 01:00:01' - updated_at '2013-07-14 01:00:01' + published_at { Time.now } user state 'published' association :text_filter, factory: :markdown @@ -274,8 +268,6 @@ FactoryGirl.define do url 'http://www.example.com' excerpt 'This is an excerpt' guid 'dsafsadffsdsf' - created_at Time.now - updated_at Time.now end factory :sidebar do diff --git a/publify_core/spec/models/article_spec.rb b/publify_core/spec/models/article_spec.rb index <HASH>..<HASH> 100644 --- a/publify_core/spec/models/article_spec.rb +++ b/publify_core/spec/models/article_spec.rb @@ -915,7 +915,7 @@ describe Article, type: :model do end it 'does not allow comments for an old article' do - art = build :article, created_at: Time.now - 31.days, blog: blog + art = build :article, published_at: Time.now - 31.days, blog: blog assert art.comments_closed? end end diff --git a/publify_core/spec/models/comment_spec.rb b/publify_core/spec/models/comment_spec.rb index <HASH>..<HASH> 100644 --- a/publify_core/spec/models/comment_spec.rb +++ b/publify_core/spec/models/comment_spec.rb @@ -23,9 +23,6 @@ describe Comment, type: :model do end describe '#save' do - before(:each) do - allow(blog).to receive(:sp_article_auto_close) { 300 } - end it 'should save good comment' do c = build(:comment, url: 'http://www.google.de') assert c.save @@ -38,10 +35,12 @@ describe Comment, type: :model do assert_equal 'http://fakeurl.com', c.url end - it 'should not save in invalid article' do - c = valid_comment(author: 'Old Spammer', body: 'Old trackback body', article: build(:article, state: 'draft', blog: blog)) - assert !c.save - assert c.errors['article_id'].any? + it 'does not save when article comment window is closed' do + article = build :article, published_at: 1.year.ago + article.blog.sp_article_auto_close = 30 + comment = build(:comment, author: 'Old Spammer', body: 'Old trackback body', article: article) + expect(comment.save).to be_falsey + expect(comment.errors[:article_id]).not_to be_empty end it 'should change old comment' do @@ -57,8 +56,6 @@ describe Comment, type: :model do end it 'should not save with article not allow comment' do - allow(blog).to receive(:sp_article_auto_close) { 1 } - c = build(:comment, article: build_stubbed(:article, allow_comments: false)) expect(c.save).not_to be_truthy expect(c.errors).not_to be_empty diff --git a/publify_core/spec/models/feedback_spec.rb b/publify_core/spec/models/feedback_spec.rb index <HASH>..<HASH> 100644 --- a/publify_core/spec/models/feedback_spec.rb +++ b/publify_core/spec/models/feedback_spec.rb @@ -40,14 +40,14 @@ describe Feedback, type: :model do end describe 'published_since' do - let(:time) { DateTime.new(2011, 11, 1, 13, 45) } + let(:time) { 1.year.ago } it 'returns nothing with no feedback' do - create(:ham_comment) + create(:ham_comment, published_at: 2.years.ago) expect(Feedback.published_since(time)).to be_empty end it 'returns feedback when one published since last visit' do - FactoryGirl.create(:ham_comment) + FactoryGirl.create(:ham_comment, published_at: 2.years.ago) feedback = FactoryGirl.create(:ham_comment, published_at: time + 2.hours) expect(Feedback.published_since(time)).to eq [feedback] end
Don't set system timestamps in factories
publify_publify
train
a9f056067e065dabc6868614b3abacf8b483f427
diff --git a/example/index/app.js b/example/index/app.js index <HASH>..<HASH> 100644 --- a/example/index/app.js +++ b/example/index/app.js @@ -59,6 +59,9 @@ require(['../../IDBStore.js'], function(IDBStore){ ['customerid','firstname','lastname', 'age'].forEach(function(key){ var value = nodeCache[key].value.trim(); if(value.length){ + if(key == 'customerid'){ + value = parseInt(value, 10); + } data[key] = value; } }); @@ -88,7 +91,7 @@ require(['../../IDBStore.js'], function(IDBStore){ lastname: lastnames[Math.floor(Math.random()*5)], firstname: firstnames[Math.floor(Math.random()*4)], age: Math.floor(Math.random() * (100 - 20)) + 20, - customerid: ( "" + ( Date.now() * Math.random() ) ).substring(0, 6) + customerid: parseInt( ( "" + ( Date.now() * Math.random() ) ).substring(0, 6), 10) }; return entry;
Go back to numeric ids
jensarps_IDBWrapper
train
d8a10a391953102552902c6c511aaa347a88eb18
diff --git a/src/validator.js b/src/validator.js index <HASH>..<HASH> 100644 --- a/src/validator.js +++ b/src/validator.js @@ -921,15 +921,6 @@ if ( 'undefined' === typeof value ) throw new Violation( this, value ); - try { - if ( 'string' === typeof value ) - new Assert().NotNull().validate( value ) && new Assert().NotBlank().validate( value ); - else if ( true === _isArray( value ) ) - new Assert().Length( { min: 1 } ).validate( value ); - } catch ( violation ) { - throw new Violation( this, value ); - } - return true; }; diff --git a/tests/tests.js b/tests/tests.js index <HASH>..<HASH> 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -563,13 +563,12 @@ var Suite = function ( validatorjs, expect, AssertExtra ) { it( 'Required', function () { assert = new Assert().Required(); - var result = validate( '', assert ); + var result = validate( undefined, assert ); expect( result ).not.to.be( true ); expect( result.assert.__class__ ).to.be("Required"); - expect( validate( 'bar', assert ) ).to.be( true ); - expect( validate( [], assert ) ).not.to.be( true ); - expect( validate( [ 'foo' ], assert ) ).to.be( true ); + expect( validate( '', assert ) ).to.be( true ); + expect( validate( [], assert ) ).to.be( true ); } ) it( 'Collection', function () {
Simplify Required assert This commit updates the Required assert to check only if the property is defined.
guillaumepotier_validator.js
train
cef7b0f6000e48e0d837ee0127d9283f7ea697b8
diff --git a/src/base/PopupButton.js b/src/base/PopupButton.js index <HASH>..<HASH> 100644 --- a/src/base/PopupButton.js +++ b/src/base/PopupButton.js @@ -9,7 +9,7 @@ import { raiseChangeEvents, render, state, - template, + template } from "./internal.js"; import KeyboardMixin from "./KeyboardMixin.js"; import PopupDragSelectMixin from "./PopupDragSelectMixin.js"; @@ -57,6 +57,16 @@ class PopupButton extends Base { handled = true; } break; + + // If popup is open, pressing Esc should close popup. + case "Escape": + if (this.opened) { + this.close({ + canceled: "Escape" + }); + handled = true; + } + break; } // Give superclass a chance to handle. @@ -150,10 +160,13 @@ class PopupButton extends Base { // focused element (i.e., this element) when opening, and restore focus to // it when the popup closes. }); +<<<<<<< HEAD } if (changed.popupPartType) { this[ids].popup.removeAttribute("tabindex"); +======= +>>>>>>> Use DelegateFocusMixin to keep focus on inner button. } } diff --git a/src/base/TooltipSource.js b/src/base/TooltipSource.js index <HASH>..<HASH> 100644 --- a/src/base/TooltipSource.js +++ b/src/base/TooltipSource.js @@ -8,10 +8,8 @@ import PopupButton from "./PopupButton.js"; */ class TooltipSource extends PopupButton { get [internal.defaultState]() { - // HACK return Object.assign(super[internal.defaultState], { - role: "none", - tabIndex: -1 + role: "none" }); } @@ -33,18 +31,15 @@ class TooltipSource extends PopupButton { }); // HACK - source.tabIndex = 0; - - // HACK - source.addEventListener("keydown", event => { - this[internal.raiseChangeEvents] = true; - if (event.key === "Escape") { - this.close({ - canceled: "Escape" - }); - } - this[internal.raiseChangeEvents] = false; - }); + // source.addEventListener("keydown", event => { + // this[internal.raiseChangeEvents] = true; + // if (event.key === "Escape") { + // this.close({ + // canceled: "Escape" + // }); + // } + // this[internal.raiseChangeEvents] = false; + // }); } // Suppress popup's backdrop, which would interfere with tracking @@ -59,7 +54,8 @@ class TooltipSource extends PopupButton { /** @type {any} */ (popup).autoFocus = Hidden; } - // HACK + // Even if the popup declares itself focusable, we want to keep focus on + // the source. popup.tabIndex = -1; } }
Use DelegateFocusMixin to keep focus on inner button.
elix_elix
train
5073999a014d3e4e6ce6eee6f94e353b27708cb3
diff --git a/aws_syncr/amazon/iam.py b/aws_syncr/amazon/iam.py index <HASH>..<HASH> 100644 --- a/aws_syncr/amazon/iam.py +++ b/aws_syncr/amazon/iam.py @@ -137,7 +137,7 @@ class Iam(AmazonMixin, object): current_attached_policies = [] with self.ignore_missing(): - current_attached_policies = self.client.list_attached_role_policies(RoleName=name, PathPrefix=prefix) + current_attached_policies = self.client.list_attached_role_policies(RoleName=name) current_attached_policies = [p['PolicyArn'] for p in current_attached_policies["AttachedPolicies"]] new_attached_policies = ["arn:aws:iam::aws:policy/{0}".format(p) for p in new_policies]
Seems the PathPrefix isn't needed and it makes it come up with empty results
delfick_aws_syncr
train
d6483529b2b1f8ae8d626bd71b068cf3d226b62f
diff --git a/app/controllers/kuhsaft/cms/admin_controller.rb b/app/controllers/kuhsaft/cms/admin_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/kuhsaft/cms/admin_controller.rb +++ b/app/controllers/kuhsaft/cms/admin_controller.rb @@ -1,7 +1,6 @@ module Kuhsaft module Cms class AdminController < ActionController::Base - inherit_resources respond_to :html layout 'kuhsaft/cms/application' before_filter :set_content_locale diff --git a/kuhsaft.gemspec b/kuhsaft.gemspec index <HASH>..<HASH> 100644 --- a/kuhsaft.gemspec +++ b/kuhsaft.gemspec @@ -51,5 +51,4 @@ Gem::Specification.new do |s| s.add_dependency 'simple_form', '3.0.0' s.add_dependency 'jquery-ui-rails' s.add_dependency 'bourbon' - s.add_dependency 'inherited_resources' end diff --git a/lib/kuhsaft.rb b/lib/kuhsaft.rb index <HASH>..<HASH> 100644 --- a/lib/kuhsaft.rb +++ b/lib/kuhsaft.rb @@ -15,5 +15,4 @@ module Kuhsaft require 'bootstrap-sass' require 'haml' require 'ckeditor_rails' - require 'inherited_resources' end
do not use inherited_resources in kuhsaft
brandleadership_kuhsaft
train
ac7cc1a9c69ae618107284deb4e3ae80c90fd47b
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from distutils.core import setup setup(name='trans-notify', - version='0.1', + version='0.2', description='Mobile Notifications for Transmission Downloads', author='Micah Ransdell', author_email='mjr578@gmail.com',
bumped to version <I>
micahr_herald
train
0ed30ce5a02e4c8a9a54d7ee51d256377a65ee7e
diff --git a/lib/discourse/oneboxer/handlebars_onebox.rb b/lib/discourse/oneboxer/handlebars_onebox.rb index <HASH>..<HASH> 100644 --- a/lib/discourse/oneboxer/handlebars_onebox.rb +++ b/lib/discourse/oneboxer/handlebars_onebox.rb @@ -44,10 +44,10 @@ module Discourse args[:host] = nice_host HandlebarsOnebox.generate_onebox(template,args) - rescue => ex - # If there's an exception, just embed the link - raise ex if Rails.env.development? - default_url + # rescue => ex + # # If there's an exception, just embed the link + # raise ex if defined?(Rails) && Rails.env.development? + # default_url end def self.generate_onebox(template, args)
This is a really bad idea, it causes exceptions to go silent
discourse_onebox
train
8574e5de3642313cc0da098c5cd328fe4a3e22bd
diff --git a/lib/chef/provider/package/portage.rb b/lib/chef/provider/package/portage.rb index <HASH>..<HASH> 100644 --- a/lib/chef/provider/package/portage.rb +++ b/lib/chef/provider/package/portage.rb @@ -92,7 +92,7 @@ class Chef @candidate_version = pkginfo.stdout.split(/(?<=-)/).last(2).join else # Latest/Best version of the package is NOT a revision (-rX). - @candidate_version = pkginfo.stdout.split('-').last + @candidate_version = pkginfo.stdout.split("-").last end @candidate_version diff --git a/spec/unit/provider/package/portage_spec.rb b/spec/unit/provider/package/portage_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/package/portage_spec.rb +++ b/spec/unit/provider/package/portage_spec.rb @@ -113,7 +113,7 @@ describe Chef::Provider::Package::Portage, "load_current_resource" do end it "should throw an exception if the exitstatus is not 0" do - status = double(:stdout => "", :stderr =>"", :exitstatus => 1) + status = double(:stdout => "", :stderr => "", :exitstatus => 1) allow(@provider).to receive(:shell_out).and_return(status) expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package) end
Fix style issues reported by travis-ci.
chef_chef
train
465a424cc318617953b5712719a1b393b6108540
diff --git a/PHPGangsta/GoogleAuthenticator.php b/PHPGangsta/GoogleAuthenticator.php index <HASH>..<HASH> 100644 --- a/PHPGangsta/GoogleAuthenticator.php +++ b/PHPGangsta/GoogleAuthenticator.php @@ -77,7 +77,7 @@ class PHPGangsta_GoogleAuthenticator public function getQRCodeGoogleUrl($name, $secret, $title = null) { $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.''); if(isset($title)) { - $urlencoded .= urlencode('&issuer='.$title); + $urlencoded .= urlencode('&issuer='.urlencode($title)); } return 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl='.$urlencoded.''; }
urlencode title Otherwise we might occur problems when using things like whitespaces.
PHPGangsta_GoogleAuthenticator
train
5c9d1dbb5c89ad6e685a5b20f89e97b2030ed282
diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -1,10 +1,10 @@ module ActiveRecord module NamedScope - # All subclasses of ActiveRecord::Base have two named_scopes: + # All subclasses of ActiveRecord::Base have two named \scopes: # * <tt>all</tt> - which is similar to a <tt>find(:all)</tt> query, and - # * <tt>scoped</tt> - which allows for the creation of anonymous scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt> + # * <tt>scoped</tt> - which allows for the creation of anonymous \scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt> # - # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing + # These anonymous \scopes tend to be useful when procedurally generating complex queries, where passing # intermediate values (scopes) around as first-class objects is convenient. def self.included(base) base.class_eval do @@ -32,14 +32,14 @@ module ActiveRecord # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it resembles the association object # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>, # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just - # as with the association objects, named scopes act like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>, + # as with the association objects, named \scopes act like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>, # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really was an Array. # - # These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only. + # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only. # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. # - # All scopes are available as class methods on the ActiveRecord::Base descendent upon which the scopes were defined. But they are also available to + # All \scopes are available as class methods on the ActiveRecord::Base descendent upon which the \scopes were defined. But they are also available to # <tt>has_many</tt> associations. If, # # class Person < ActiveRecord::Base @@ -49,7 +49,7 @@ module ActiveRecord # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean # only shirts. # - # Named scopes can also be procedural. + # Named \scopes can also be procedural: # # class Shirt < ActiveRecord::Base # named_scope :colored, lambda { |color| @@ -59,7 +59,7 @@ module ActiveRecord # # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. # - # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations: + # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: # # class Shirt < ActiveRecord::Base # named_scope :red, :conditions => {:color => 'red'} do @@ -70,7 +70,7 @@ module ActiveRecord # end # # - # For testing complex named scopes, you can examine the scoping options using the + # For testing complex named \scopes, you can examine the scoping options using the # <tt>proxy_options</tt> method on the proxy itself. # # class Shirt < ActiveRecord::Base
escaping otherwise autolinked "scopes" in named_scope.rb (we can now assume rdoc is <I>)
rails_rails
train
0957568d3ac5f01fa5958c42db1b00efdf17c51f
diff --git a/question/type/ddimageortext/edit_ddimageortext_form.php b/question/type/ddimageortext/edit_ddimageortext_form.php index <HASH>..<HASH> 100644 --- a/question/type/ddimageortext/edit_ddimageortext_form.php +++ b/question/type/ddimageortext/edit_ddimageortext_form.php @@ -298,8 +298,8 @@ class qtype_ddimageortext_edit_form extends question_edit_form { $PAGE->requires->yui_module('moodle-qtype_ddimageortext-form', 'M.qtype_ddimageortext.init_form', array($params)); - $PAGE->requires->css('/lib/yui/3.4.0/build/cssfonts-context/fonts-context-min.css'); - $PAGE->requires->css('/lib/yui/3.4.0/build/cssreset-context/cssreset-context-min.css'); + $PAGE->requires->css('/lib/yui/3.2.0/build/cssfonts/fonts-context-min.css'); + $PAGE->requires->css('/lib/yui/3.2.0/build/cssreset/reset-context-min.css'); return $question; } diff --git a/question/type/ddimageortext/renderer.php b/question/type/ddimageortext/renderer.php index <HASH>..<HASH> 100755 --- a/question/type/ddimageortext/renderer.php +++ b/question/type/ddimageortext/renderer.php @@ -38,9 +38,8 @@ require_once($CFG->dirroot . '/question/type/gapselect/rendererbase.php'); class qtype_ddimageortext_renderer extends qtype_with_combined_feedback_renderer { public function head_code(question_attempt $qa) { - $this->page->requires->css('/lib/yui/3.4.0/build/cssfonts-context/fonts-context-min.css'); - $this->page->requires->css( - '/lib/yui/3.4.0/build/cssreset-context/cssreset-context-min.css'); + $this->page->requires->css('/lib/yui/3.2.0/build/cssfonts/fonts-context-min.css'); + $this->page->requires->css('/lib/yui/3.2.0/build/cssreset/reset-context-min.css'); return parent::head_code($qa); } public function clear_wrong(question_attempt $qa) {
MDL-<I> ddimageortext: NOBUG need to use <I> yui url to access <I> yui which is the latest available in MOODLE_<I>_STABLE
moodle_moodle
train
a2fe113558d14379b72e4c3353e6b83c833f8906
diff --git a/tests/test_core.py b/tests/test_core.py index <HASH>..<HASH> 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -161,3 +161,16 @@ def test_resample_matched(): assert y.flags['OWNDATA'] # x and y are distinct objects assert y is not x + + +def test_resample_axis(): + # derived from https://github.com/bmcfee/resampy/issues/73 + + rand_arr = np.abs(np.random.rand(3, 4, 5, 100)) + + resampled_arr = resampy.resample(rand_arr, 100, 24, axis=3) + + resampled_t_arr = resampy.resample(np.transpose(rand_arr), 100, 24, axis=0) + + assert np.allclose(resampled_arr, np.transpose(resampled_t_arr)) + assert (resampled_arr**2).sum() > 0
adding a high-dimension resampling test
bmcfee_resampy
train
bcd8d41048cfd5755459707da1731280a9678861
diff --git a/lib/kamaze/project/tasks/gem.rb b/lib/kamaze/project/tasks/gem.rb index <HASH>..<HASH> 100644 --- a/lib/kamaze/project/tasks/gem.rb +++ b/lib/kamaze/project/tasks/gem.rb @@ -6,19 +6,16 @@ # This is free software: you are free to change and redistribute it. # There is NO WARRANTY, to the extent permitted by law. +# @type [Kamaze::Project::Tools::Gemspec::Writer] writer tools.fetch(:gemspec_writer).tap do |writer| - writer.write unless writer.generated.file? -end + writer.write(preserve_mtime: true) unless writer.generated.file? -# Require base tasks ------------------------------------------------ -[:gemspec, :build].each { |req| require_relative "gem/#{req}" } + # Require base tasks ---------------------------------------------- + [:gemspec, :build].each { |req| require_relative "gem/#{req}" } -lambda do |method, *args| - tools.fetch(:gemspec_writer).public_send(*[method].push(*args)) -end.tap do |writer| # Default task ---------------------------------------------------- desc 'Build all the packages' - task gem: [writer.call(:to_s), :'gem:build'] do |task| # rubocop:disable Style/SymbolProc + task gem: [writer.to_s, :'gem:build'] do |task| # rubocop:disable Style/SymbolProc task.reenable end end diff --git a/lib/kamaze/project/tasks/gem/gemspec.rb b/lib/kamaze/project/tasks/gem/gemspec.rb index <HASH>..<HASH> 100644 --- a/lib/kamaze/project/tasks/gem/gemspec.rb +++ b/lib/kamaze/project/tasks/gem/gemspec.rb @@ -6,19 +6,16 @@ # This is free software: you are free to change and redistribute it. # There is NO WARRANTY, to the extent permitted by law. -lambda do |method, *args, **kwargs| - tools.fetch(:gemspec_writer).yield_self do |writer| - RUBY_VERSION >= '2.7' ? writer.public_send(method, *args, **kwargs) : writer.public_send(method, *args) - end -end.tap do |writer| - task "#{writer.call(:to_s)}": [:'gem:gemspec'] do |task| # rubocop:disable Style/SymbolProc +# @type [Kamaze::Project::Tools::Gemspec::Writer] writer +tools.fetch(:gemspec_writer).tap do |writer| + task writer.to_s => [:'gem:gemspec'] do |task| # rubocop:disable Style/SymbolProc task.reenable end desc 'Update gemspec' task 'gem:gemspec' do |task| task.reenable.tap do - writer.call(:write, preserve_mtime: true) + writer.write(preserve_mtime: true) end end end
gem (tasks) bugfix + unclutter
SwagDevOps_kamaze-project
train
4498fd79da2058b83e5b3caa8b7e60223112a245
diff --git a/shield/utils.py b/shield/utils.py index <HASH>..<HASH> 100644 --- a/shield/utils.py +++ b/shield/utils.py @@ -2,7 +2,7 @@ from __future__ import absolute_import, unicode_literals, division import operator from six.moves import map, reduce -from ._registry import registry, expression +from ._registry import registry, target_registry, bearer_registry, expression def register(function, *permissions, **kwargs): @@ -21,14 +21,20 @@ def register(function, *permissions, **kwargs): The entity that the bearer is being granted the permissions for (optional). """ - target, bearer = kwargs.get('target'), kwargs['bearer'] - if permissions and not permissions[0] is None: - for permission in permissions: - key = bearer, target, permission - registry[key] = function + # Generic USER HAS ALL PERMISSIONS ON TARGET type permision + if not len(permissions): + target_registry[kwargs['bearer'], kwargs['target']] = function + + # Generic USER CAN X permission. + elif not 'target' in kwargs: + for perm in permissions: + bearer_registry[kwargs['bearer'], perm] = function + + # Specific USER CAN X ON TARGET permission. else: - registry[bearer, target] = function + for perm in permissions: + registry[kwargs['bearer'], kwargs['target'], perm] = function def has(*permissions, **kwargs):
Fix registration function to use new registry definition
concordusapps_python-shield
train
e40e07a7997a97f542b4243a73ff4583018f3ad5
diff --git a/intranet/apps/search/views.py b/intranet/apps/search/views.py index <HASH>..<HASH> 100644 --- a/intranet/apps/search/views.py +++ b/intranet/apps/search/views.py @@ -1,6 +1,7 @@ import elasticsearch from django.contrib.auth.decorators import login_required from django.shortcuts import render +from intranet.apps.users.models import User from intranet import settings @@ -8,8 +9,11 @@ from intranet import settings def search_view(request): q = request.GET.get("q", "").strip() if q: - if q.isdigit() and len(q) == settings.FCPS_STUDENT_ID_LENGTH: - pass + if q.isdigit(): + u = User.objects.user_with_student_id(q) + if u is not None: + return u + es = elasticsearch.Elasticsearch() results = es.search(index="ion", body={ "query": {
Add search by student id (not functional yet)
tjcsl_ion
train
d0223ef41aa4a0fe44565daa83e31eff3069555b
diff --git a/Kwc/Directories/Item/Directory/FormController.php b/Kwc/Directories/Item/Directory/FormController.php index <HASH>..<HASH> 100644 --- a/Kwc/Directories/Item/Directory/FormController.php +++ b/Kwc/Directories/Item/Directory/FormController.php @@ -42,7 +42,7 @@ class Kwc_Directories_Item_Directory_FormController extends Kwf_Controller_Actio foreach ($forms as $key => $form) { $card = $cards->add(); $card->add($form); - $card->setTitle(Kwc_Abstract::getSetting($form->getClass(), 'componentName')); + $card->setTitle(Kwf_Trl::getInstance()->trlStaticExecute(Kwc_Abstract::getSetting($form->getClass(), 'componentName'))); $card->setName($key); $card->setNamePrefix($key); }
add missing trlStaticExecute
koala-framework_koala-framework
train
bdd015c6ef20cd0b952403ad5afe21d1d8864668
diff --git a/src/Factory/Mail/ConfirmationFactory.php b/src/Factory/Mail/ConfirmationFactory.php index <HASH>..<HASH> 100644 --- a/src/Factory/Mail/ConfirmationFactory.php +++ b/src/Factory/Mail/ConfirmationFactory.php @@ -23,7 +23,7 @@ use Laminas\ServiceManager\Factory\FactoryInterface; */ class ConfirmationFactory implements FactoryInterface { - public function __invoke(ContainerInterface $container, $requestedName, array $options = []) + public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null) { $router = $container->get('Router'); $options['router'] = $router;
fix(Applications): Confirmation mail factory is incompatible with Factory Interface.
yawik_applications
train
0aaac84a42f6af11d2c0d70ea378f0bf25d254b7
diff --git a/lxd/cluster/upgrade.go b/lxd/cluster/upgrade.go index <HASH>..<HASH> 100644 --- a/lxd/cluster/upgrade.go +++ b/lxd/cluster/upgrade.go @@ -65,6 +65,10 @@ func MaybeUpdate(state *state.State) error { return nil } + if state.Cluster == nil { + return fmt.Errorf("Failed checking cluster update, state not initialised yet") + } + err = state.Cluster.Transaction(func(tx *db.ClusterTx) error { outdated, err := tx.NodeIsOutdated() if err != nil {
lxd/cluster/upgrade: Prevents crash if heartbeat occurs before dqlite init
lxc_lxd
train
a6cc4b3c03601affe7d36b4fde45f6bf48de04d1
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,9 @@ from setuptools import setup, find_packages with open('.project_metadata.json') as meta_file: project_metadata = json.loads(meta_file.read()) +with open('README.rst') as readme_file: + long_description = readme_file.read() + long_description_content_type = 'text/x-rst' setup( name=project_metadata['name'], @@ -14,6 +17,8 @@ setup( author=project_metadata['author'], author_email=project_metadata['author_email'], description=project_metadata['description'], + long_description=long_description, + long_description_content_type=long_description_content_type, license=project_metadata['license'], install_requires=[ 'flask',
Issue #<I> Updated long description
dusktreader_flask-praetorian
train
2623b636a9667e28ee585b0d757a414b293e8999
diff --git a/packages/react/src/components/Select/Select.js b/packages/react/src/components/Select/Select.js index <HASH>..<HASH> 100644 --- a/packages/react/src/components/Select/Select.js +++ b/packages/react/src/components/Select/Select.js @@ -21,20 +21,20 @@ const Select = React.forwardRef(function Select( { className, id, - inline, + inline = false, labelText, - disabled, + disabled = false, children, // reserved for use with <Pagination> component - noLabel, + noLabel = false, // eslint-disable-next-line no-unused-vars - hideLabel, - invalid, + hideLabel = false, + invalid = false, invalidText, helperText, - light, + light = false, size, - warn, + warn = false, warnText, ...other }, diff --git a/packages/react/src/components/Select/Select.stories.js b/packages/react/src/components/Select/Select.stories.js index <HASH>..<HASH> 100644 --- a/packages/react/src/components/Select/Select.stories.js +++ b/packages/react/src/components/Select/Select.stories.js @@ -14,15 +14,48 @@ import { Layer } from '../Layer'; export default { title: 'Components/Select', component: Select, - argTypes: { - size: { - options: ['sm', 'md', 'lg'], - control: { type: 'select' }, - }, - }, args: { + disabled: false, + inline: false, + noLabel: false, + hideLabel: false, + invalid: false, + warn: false, size: 'md', }, + argTypes: { + onChange: { + action: 'onChange', + table: { + disable: true, + }, + }, + children: { + table: { + disable: true, + }, + }, + className: { + table: { + disable: true, + }, + }, + defaultValue: { + table: { + disable: true, + }, + }, + id: { + table: { + disable: true, + }, + }, + light: { + table: { + disable: true, + }, + }, + }, decorators: [(story) => <div style={{ width: '400px' }}>{story()}</div>], subcomponents: { SelectItem, @@ -31,11 +64,10 @@ export default { }, }; -export const _Default = (args) => { +export const Default = () => { return ( <div> <Select - {...args} id="select-1" defaultValue="placeholder-item" labelText="Select an option" @@ -59,11 +91,10 @@ export const _Default = (args) => { ); }; -export const Inline = (args) => { +export const Inline = () => { return ( <div> <Select - {...args} inline id="select-1" defaultValue="placeholder-item" @@ -88,7 +119,7 @@ export const Inline = (args) => { ); }; -export const _Skeleton = () => ( +export const Skeleton = () => ( <div aria-label="loading select" aria-live="assertive" @@ -99,11 +130,10 @@ export const _Skeleton = () => ( </div> ); -export const WithLayer = (args) => { +export const WithLayer = () => { return ( <> <Select - {...args} id="select-1" defaultValue="placeholder-item" labelText="" @@ -119,7 +149,6 @@ export const WithLayer = (args) => { </Select> <Layer> <Select - {...args} id="select-1" defaultValue="placeholder-item" labelText="" @@ -137,7 +166,6 @@ export const WithLayer = (args) => { </Select> <Layer> <Select - {...args} id="select-1" defaultValue="placeholder-item" labelText="" @@ -158,3 +186,40 @@ export const WithLayer = (args) => { </> ); }; + +export const Playground = (args) => { + return ( + <div> + <Select + id="select-1" + defaultValue="placeholder-item" + labelText="Select an option" + helperText="Optional helper text" + {...args}> + <SelectItem + disabled + hidden + value="placeholder-item" + text="Choose an option" + /> + <SelectItemGroup label="Category 1"> + <SelectItem value="option-1" text="Option 1" /> + <SelectItem value="option-2" text="Option 2" /> + </SelectItemGroup> + <SelectItemGroup label="Category 2"> + <SelectItem value="option-3" text="Option 3" /> + <SelectItem value="option-4" text="Option 4" /> + </SelectItemGroup> + </Select> + </div> + ); +}; + +Playground.argTypes = { + helperText: { + control: 'text', + }, + invalidText: { control: 'text' }, + labelText: { control: 'text' }, + warnText: { control: 'text' }, +};
docs(select): add playground story, controls (#<I>) * docs(select): add playground story, controls * fix(select): remove unused playground argtypes * fix(select): ensure string controls work, remove unecessary props from controls
carbon-design-system_carbon-components
train
5771da7a0b19eeaeac1a87f1d66ea0339f912ea0
diff --git a/model/ZipExporter.php b/model/ZipExporter.php index <HASH>..<HASH> 100644 --- a/model/ZipExporter.php +++ b/model/ZipExporter.php @@ -136,8 +136,6 @@ class ZipExporter implements tao_models_classes_export_ExportHandler } if ($zip->numFiles === 0) { - $nbFiles = 0; - foreach ($exportFiles as $label => $files) { $archivePath = ''; @@ -146,11 +144,8 @@ class ZipExporter implements tao_models_classes_export_ExportHandler $archivePath = $exportClasses[$label] . '/'; $zip->addEmptyDir($archivePath); - - $nbFiles++; } - $nbFiles += count($files); //create the directory /** @var core_kernel_classes_Resource $fileResource */ @@ -158,8 +153,7 @@ class ZipExporter implements tao_models_classes_export_ExportHandler $link = $this->getResourceLink($fileResource); $fileContent = $this->getFileManagement() - ->getFileStream($link) - ->getContents(); + ->getFileStream($link); $preparedFileContent = $this->getMediaResourcePreparer()->prepare($fileResource, $fileContent); diff --git a/model/export/service/MediaResourcePreparer.php b/model/export/service/MediaResourcePreparer.php index <HASH>..<HASH> 100644 --- a/model/export/service/MediaResourcePreparer.php +++ b/model/export/service/MediaResourcePreparer.php @@ -33,6 +33,7 @@ use oat\tao\model\media\TaoMediaResolver; use oat\taoMediaManager\model\fileManagement\FileManagement; use oat\taoMediaManager\model\MediaSource; use oat\taoMediaManager\model\sharedStimulus\specification\SharedStimulusResourceSpecification; +use Psr\Http\Message\StreamInterface; use qtism\data\content\BodyElement; use qtism\data\content\xhtml\Img; use qtism\data\content\xhtml\QtiObject; @@ -50,14 +51,14 @@ class MediaResourcePreparer extends ConfigurableService /** @var TaoMediaResolver */ private $mediaResolver; - public function prepare(core_kernel_classes_Resource $mediaResource, string $contents): string + public function prepare(core_kernel_classes_Resource $mediaResource, StreamInterface $contents): string { if (!$this->getSharedStimulusResourceSpecification()->isSatisfiedBy($mediaResource)) { - return $contents; + return (string)$contents; } $xmlDocument = new XmlDocument(); - $xmlDocument->loadFromString($contents); + $xmlDocument->loadFromString((string)$contents); foreach ($this->getComponents($xmlDocument) as $component) { $mediaAsset = $this->getMediaAsset($component);
Switching to stream instead of plain string
oat-sa_extension-tao-mediamanager
train
b3f6363c418eb280fb78c216f10cb50b93a330b2
diff --git a/thermo/utils.py b/thermo/utils.py index <HASH>..<HASH> 100644 --- a/thermo/utils.py +++ b/thermo/utils.py @@ -2139,11 +2139,12 @@ class TDependentProperty(object): @method.setter def method(self, method): if method not in self.all_methods and method != POLY_FIT and method is not None: - raise ValueError("The given methods is not available for this chemical") + raise ValueError("The given method is not available for this chemical") self.T_cached = None self._method = method extrapolation = getattr(self, '_extrapolation', None) - if extrapolation is not None: self.extrapolation = extrapolation + if extrapolation is not None and method is not None: + self._load_extrapolation_coeffs(method) def valid_methods(self, T=None): r'''Method to obtain a sorted list of methods that have data @@ -3536,12 +3537,13 @@ class TPDependentProperty(TDependentProperty): for name, (Ts, Ps, properties) in kwargs['tabular_data_P'].items(): self.add_tabular_data_P(Ts, Ps, properties, name=name, check_properties=False) - method_P = kwargs.get('method_P', None) - all_methods_P = self.all_methods_P - for i in self.ranked_methods_P: - if i in all_methods_P: - method_P = i - break + method_P = kwargs.get('method_P', getattr(self, '_method_P', None)) + if method_P is None: + all_methods_P = self.all_methods_P + for i in self.ranked_methods_P: + if i in all_methods_P: + method_P = i + break self.method_P = method_P @property
finallize changes to work with tests
CalebBell_thermo
train
770d43443a7554b0953e1c2f0d272dfb163f7b02
diff --git a/lib/cabiri.rb b/lib/cabiri.rb index <HASH>..<HASH> 100644 --- a/lib/cabiri.rb +++ b/lib/cabiri.rb @@ -11,6 +11,8 @@ module Cabiri # - self_pipe: a pipe that is used by the main process to implement a blocking wait for the # wait_until_finished method. Both endpoints have sync set to true to prevent the # kernel from buffering any messages. + # - mutex: a mutex that is used to treat the code that deals with extracting results from + # finished processes and spawning new processes as a critical section # - logger: a logger to help log errors def initialize @remaining_jobs = [] @@ -24,6 +26,7 @@ module Cabiri @self_pipe[0].sync = true @self_pipe[1].sync = true + @mutex = Mutex.new @logger = Logger.new($stdout) end @@ -53,22 +56,8 @@ module Cabiri end end - # here we start by creating a uid to index mapping. We also add an entry for each - # job to the jobs_info array. - # Next we define a signal handler that deals with SIGCHLD signals - # (a signal that indicates that a child process has terminated). When we receive - # such a signal we get the pid and make sure that the child process was one of - # the jobs belonging to the job queue. - # This needs to be done inside a while loop as two or more child processes exiting - # in quick succession might only generate one signal. For example, the first dead - # child process will generate a SIGCHLD. However, when a second process dies quickly - # afterwards and the previous SIGCHLD signal has not yet been handled, this second - # process won't send a second SIGCHLD signal, but will instead assume that the - # SIGCHLD handler knows to look for multiple dead processes. - # You might also notice that old_handler is being used to redirect this signal to - # a possible other previously defined SIGCHLD signal handler. - # Also note that we close the write end of the self_pipe when there are no jobs left. - # See the comments on the wait_until_finished method for why this is important. + # here we start by creating a uid to index mapping and add an entry for each + # job to the jobs_info array. We then schedule the first batch of jobs. def start(max_active_jobs) # create job mappings and initialize job info @remaining_jobs.each_with_index do |job, index| @@ -79,23 +68,8 @@ module Cabiri @jobs_info[index][:pid] = nil @jobs_info[index][:pipe] = nil @jobs_info[index][:error] = nil - @jobs_info[index][:state] = :waiting @jobs_info[index][:result] = nil - end - - # define signal handler - old_handler = trap(:CLD) do - begin - while pid = Process.wait(-1, Process::WNOHANG) - if(@active_jobs_pids.include?(pid)) - handle_finished_job(pid) - fill_job_slots(max_active_jobs) - @self_pipe[1].close if finished? - end - old_handler.call if old_handler.respond_to?(:call) - end - rescue Errno::ECHILD - end + @jobs_info[index][:state] = :waiting end # start scheduling first batch of jobs @@ -109,7 +83,7 @@ module Cabiri def fill_job_slots(max_active_jobs) while(@active_jobs_pids.length < max_active_jobs and !@remaining_jobs.empty?) begin - start_next_job + start_next_job(max_active_jobs) rescue => ex handle_error(ex) ensure @@ -130,8 +104,18 @@ module Cabiri # a hash - we don't know) into a byte stream, put this information inside an array, and then convert this # array into a special string designed for transporting binary data as text. This text can now be send # through the write endpoint of the pipe. Back outside the job process we close the write endpoint of the - # pipe and set sync to true. The rest of the code here should require no comments. - def start_next_job + # pipe and set sync to true. The next few lines hould require no comment. + # We finish by creating a thread that waits for the newly created job to end. This thread is responsible + # for extracting information from the finished job and spawning new jobs. Also note that we close the + # write end of the self_pipe when there are no jobs left. See the comments on the wait_until_finished + # method for why this is important. + # Notice how the inside of the thread is wrapped inside a mutex. This is required to prevent a race + # condition from occurring when two or more jobs return in quick succession. When the first job + # returns, its thread will start scheduling new processes, but this can take some time. If a second + # job returns before the thread of the first job is done scheduling, it will start doing scheduling + # work as well. So now you have two threads simultaneously doing scheduling work, and the end result + # will be unpredictable. + def start_next_job(max_active_jobs) pipe = IO.pipe() job = @remaining_jobs.first @@ -151,6 +135,15 @@ module Cabiri @jobs_info[index][:pid] = pid @jobs_info[index][:pipe] = pipe @jobs_info[index][:state] = :running + + Thread.new(pid) do |my_pid| + Process.waitpid(my_pid) + @mutex.synchronize do + handle_finished_job(my_pid) + fill_job_slots(max_active_jobs) + @self_pipe[1].close if finished? + end + end end # when a job finishes, we remove its pid from the array that keeps track of active processes.
fix how processes are scheduled to prevent race conditions
vaneyckt_Cabiri
train
ff0dd280fc383798e41719c88df3661fbb71986a
diff --git a/src/AwsS3V3/AwsS3V3Adapter.php b/src/AwsS3V3/AwsS3V3Adapter.php index <HASH>..<HASH> 100644 --- a/src/AwsS3V3/AwsS3V3Adapter.php +++ b/src/AwsS3V3/AwsS3V3Adapter.php @@ -195,6 +195,7 @@ class AwsS3V3Adapter implements FilesystemAdapter private function createOptionsFromConfig(Config $config): array { + $config = $config->withDefaults($this->options); $options = ['params' => []]; if ($mimetype = $config->get('mimetype')) { @@ -217,7 +218,7 @@ class AwsS3V3Adapter implements FilesystemAdapter } } - return $options + $this->options; + return $options; } public function writeStream(string $path, $contents, Config $config): void diff --git a/src/AwsS3V3/AwsS3V3AdapterTest.php b/src/AwsS3V3/AwsS3V3AdapterTest.php index <HASH>..<HASH> 100644 --- a/src/AwsS3V3/AwsS3V3AdapterTest.php +++ b/src/AwsS3V3/AwsS3V3AdapterTest.php @@ -288,6 +288,19 @@ class AwsS3V3AdapterTest extends FilesystemAdapterTestCase /** * @test + * @dataProvider casesWhereHttpStreamingInfluencesSeekability + */ + public function use_globally_configured_options(bool $streaming): void + { + $adapter = $this->useAdapter($this->createFilesystemAdapter($streaming, ['ContentType' => 'text/plain+special'])); + $this->givenWeHaveAnExistingFile('path.txt'); + + $mimeType = $adapter->mimeType('path.txt')->mimeType(); + $this->assertSame('text/plain+special', $mimeType); + } + + /** + * @test */ public function moving_with_updated_metadata(): void {
[AWS S3] Use globally configured options.
thephpleague_flysystem
train
b7bc83e1172f26b36f22d54e30c2eb04a6645170
diff --git a/openpnm/models/geometry/conduit_hydraulic_coefficient.py b/openpnm/models/geometry/conduit_hydraulic_coefficient.py index <HASH>..<HASH> 100644 --- a/openpnm/models/geometry/conduit_hydraulic_coefficient.py +++ b/openpnm/models/geometry/conduit_hydraulic_coefficient.py @@ -2,19 +2,6 @@ import numpy as _np from numpy import pi from numpy import arctanh as _atanh - -def cylinders_in_series(target, - pore_diameter='pore.diameter', - throat_diameter='throat.diameter', - n_cylinders=5, - throat_length=None, - return_elements=False): - r""" - - """ - network = target.network - - def spheres_and_cylinders(target, pore_diameter='pore.diameter', throat_diameter='throat.diameter', @@ -110,6 +97,92 @@ def spheres_and_cylinders(target, return vals +def spheres_and_cylinders_2D(target, + pore_diameter='pore.diameter', + throat_diameter='throat.diameter', + conduit_lengths=None, + throat_length=None, + return_elements=False): + r""" + Compute hydraulic shape coefficient for conduits of spheres and cylinders + + Parameter + --------- + target: OpenPNM object + + Notes + ----- + The hydraulic shape coefficient is the geometrical part of the pre-factor + in Stoke's flow: + + .. math:: + + + Thus :math:`S_{hydraulic}` represents the combined effect of the area and + length of the *conduit*, which consists of a throat and 1/2 of the pore + on each end. + + """ + network = target.project.network + throats = network.map_throats(throats=target.Ts, origin=target) + cn = network['throat.conns'][throats] + # Get pore diameter + D1 = network[pore_diameter][cn[:, 0]] + D2 = network[pore_diameter][cn[:, 1]] + Dt = network[throat_diameter][throats] + # Get conduit lengths + L1 = network[conduit_lengths + '.pore1'][throats] + L2 = network[conduit_lengths + '.pore2'][throats] + Lt = network[conduit_lengths + '.throat'][throats] + # Get pore/throat baseline areas (the one used in generic conductance) + A1 = D1 + A2 = D2 + At = network[throat_diameter][throats] + # Preallocating F, SF + # F is INTEGRAL(1/A^2) dx , x : 0 --> L + F1, F2, Ft = _np.zeros((3, len(Lt))) + SF1, SF2, SFt = _np.ones((3, len(Lt))) + # Setting SF to 1 when Li = 0 (ex. boundary pores) + # INFO: This is needed since area could also be zero, which confuses NumPy + m1, m2, mt = [Li != 0 for Li in [L1, L2, Lt]] + SF1[~m1] = SF2[~m2] = SFt[~mt] = 1 + F1[m1] = (_atanh(2*L1/D1) / (2*D1))[m1] + F2[m2] = (_atanh(2*L2/D2) / (2*D2))[m2] + Ft[mt] = (Lt / At**2)[mt] + # Calculate conduit shape factors + SF1[m1] = (L1 / (A1**2 * F1))[m1] + SF2[m2] = (L2 / (A2**2 * F2))[m2] + SFt[mt] = (Lt / (At**2 * Ft))[mt] + # Find g for half of pore 1, throat, and half of pore 2 + g1 = D1 ** 3 / (12 * L1) + g2 = D2 ** 3 / (12 * L2) + gt = Dt ** 3 / (12 * Lt) + # Apply shape factors to individual g + g1, g2, gt = g1*SF1, g2*SF2, gt*SFt + # Ensure infinite conductance for elements with zero length + g1[L1 == 0] = _np.inf + g2[L2 == 0] = _np.inf + gt[Lt == 0] = _np.inf + if return_elements: + vals = {'pore1': g1, 'throat': gt, 'pore2': g2} + else: + vals = (1/gt + 1/g1 + 1/g2)**(-1) + return vals + + + +def cylinders_in_series(target, + pore_diameter='pore.diameter', + throat_diameter='throat.diameter', + n_cylinders=5, + throat_length=None, + return_elements=False): + r""" + + """ + network = target.network + + def pyramids_and_cuboids(target, pore_diameter='pore.diameter', throat_diameter='throat.diameter',
[ci skip] add spheres_and_cylinders_2D to hydraulic coeff
PMEAL_OpenPNM
train
757d284759549d1efc0e0539643d1ec72c6f2cf4
diff --git a/opts/opts.go b/opts/opts.go index <HASH>..<HASH> 100644 --- a/opts/opts.go +++ b/opts/opts.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/docker/docker/pkg/blkiodev" + "github.com/docker/docker/api/types/blkiodev" "github.com/docker/go-units" ) diff --git a/opts/throttledevice.go b/opts/throttledevice.go index <HASH>..<HASH> 100644 --- a/opts/throttledevice.go +++ b/opts/throttledevice.go @@ -3,7 +3,7 @@ package opts import ( "fmt" - "github.com/docker/docker/pkg/blkiodev" + "github.com/docker/docker/api/types/blkiodev" ) // ThrottledeviceOpt defines a map of ThrottleDevices diff --git a/opts/weightdevice.go b/opts/weightdevice.go index <HASH>..<HASH> 100644 --- a/opts/weightdevice.go +++ b/opts/weightdevice.go @@ -3,7 +3,7 @@ package opts import ( "fmt" - "github.com/docker/docker/pkg/blkiodev" + "github.com/docker/docker/api/types/blkiodev" ) // WeightdeviceOpt defines a map of WeightDevices
Move blkiodev package to types.
docker_cli
train
473236ca9f3a0d5435c1c28c0125af919e544047
diff --git a/easybatch-core/src/main/java/org/easybatch/core/util/Utils.java b/easybatch-core/src/main/java/org/easybatch/core/util/Utils.java index <HASH>..<HASH> 100644 --- a/easybatch-core/src/main/java/org/easybatch/core/util/Utils.java +++ b/easybatch-core/src/main/java/org/easybatch/core/util/Utils.java @@ -25,6 +25,7 @@ package org.easybatch.core.util; import org.easybatch.core.api.Engine; +import org.easybatch.core.api.Record; import org.easybatch.core.api.Report; import org.easybatch.core.jmx.Monitor; @@ -132,4 +133,8 @@ public abstract class Utils { } return getters; } + + public static boolean isRecord(final Object record) { + return Record.class.isAssignableFrom(record.getClass()); + } } diff --git a/easybatch-core/src/main/java/org/easybatch/core/writer/OutputStreamRecordWriter.java b/easybatch-core/src/main/java/org/easybatch/core/writer/OutputStreamRecordWriter.java index <HASH>..<HASH> 100644 --- a/easybatch-core/src/main/java/org/easybatch/core/writer/OutputStreamRecordWriter.java +++ b/easybatch-core/src/main/java/org/easybatch/core/writer/OutputStreamRecordWriter.java @@ -31,8 +31,7 @@ import java.io.IOException; import java.io.OutputStreamWriter; import static java.lang.String.format; -import static org.easybatch.core.util.Utils.LINE_SEPARATOR; -import static org.easybatch.core.util.Utils.checkNotNull; +import static org.easybatch.core.util.Utils.*; /** * Convenient processor to write the <strong>payload</strong> of a {@link Record} to an output stream. @@ -61,8 +60,7 @@ public class OutputStreamRecordWriter extends AbstractRecordWriter { @Override public void writeRecord(final Object record) throws RecordProcessingException { - boolean isRecord = Record.class.isAssignableFrom(record.getClass()); - Object payload = isRecord ? ((Record) record).getPayload() : record; + Object payload = isRecord(record) ? ((Record) record).getPayload() : record; try { outputStreamWriter.write(payload + LINE_SEPARATOR); outputStreamWriter.flush();
add utility method to check if an Object is a Record
j-easy_easy-batch
train
42bdbccac2a8f9e63f1fa8f12316db191215e040
diff --git a/lib/active_merchant/billing/gateways/micropayment.rb b/lib/active_merchant/billing/gateways/micropayment.rb index <HASH>..<HASH> 100644 --- a/lib/active_merchant/billing/gateways/micropayment.rb +++ b/lib/active_merchant/billing/gateways/micropayment.rb @@ -80,7 +80,6 @@ module ActiveMerchant #:nodoc: post[:amount] = amount(money) post[:currency] = options[:currency] || currency(money) end - post[:project] = options[:project] || "sprdly" end def add_payment_method(post, payment_method, options={}) diff --git a/test/remote/gateways/remote_micropayment_test.rb b/test/remote/gateways/remote_micropayment_test.rb index <HASH>..<HASH> 100644 --- a/test/remote/gateways/remote_micropayment_test.rb +++ b/test/remote/gateways/remote_micropayment_test.rb @@ -34,7 +34,7 @@ class RemoteMicropaymentTest < Test::Unit::TestCase end def test_successful_authorize_and_capture - response = @gateway.authorize(@amount, @credit_card, @options.merge(recurring: false)) + response = @gateway.authorize(@amount, @credit_card) assert_success response assert_equal "Succeeded", response.message assert_match %r(^\w+\|.+$), response.authorization @@ -44,7 +44,8 @@ class RemoteMicropaymentTest < Test::Unit::TestCase assert_equal "Succeeded", capture.message end - def test_successful_authorize_and_capture_with_recurring + def test_successful_authorize_and_capture_with_recurring + @credit_card.verification_value = "" response = @gateway.authorize(@amount, @credit_card, @options.merge(recurring: true)) assert_success response assert_equal "Succeeded", response.message @@ -93,8 +94,6 @@ class RemoteMicropaymentTest < Test::Unit::TestCase assert_match %r(^\w+\|.+$), response.authorization capture = @gateway.capture(@amount, response.authorization) - puts response.authorization - puts capture.authorization assert_success capture assert_equal "Succeeded", capture.message
Micropayment: Cleanup a little
activemerchant_active_merchant
train
57c276c80aba6cb13a859369f4f194470df594d7
diff --git a/src/trumbowyg.js b/src/trumbowyg.js index <HASH>..<HASH> 100644 --- a/src/trumbowyg.js +++ b/src/trumbowyg.js @@ -1376,10 +1376,25 @@ Object.defineProperty(jQuery.trumbowyg, 'defaultOptions', { var t = this, prefix = t.o.prefix, fullscreenCssClass = prefix + 'fullscreen', - isFullscreen; + fullscreenPlaceholderClass = fullscreenCssClass + '-placeholder', + isFullscreen, + editorHeight = t.$box.outerHeight(); t.$box.toggleClass(fullscreenCssClass); isFullscreen = t.$box.hasClass(fullscreenCssClass); + + if (isFullscreen) { + t.$box.before( + $('<div/>', { + class: fullscreenPlaceholderClass + }).css({ + height: editorHeight + 'px' + }) + ); + } else { + $('.' + fullscreenPlaceholderClass).remove(); + } + $('body').toggleClass(prefix + 'body-fullscreen', isFullscreen); $(window).trigger('scroll'); t.$c.trigger('tbw' + (isFullscreen ? 'open' : 'close') + 'fullscreen');
fix: add a placeholder while fullscreen to keep editor space fix #<I>
Alex-D_Trumbowyg
train
a2286a6d6d9aa9c251a272fbe9dbcf77669ce51f
diff --git a/test/action_view_extensions/builder_test.rb b/test/action_view_extensions/builder_test.rb index <HASH>..<HASH> 100644 --- a/test/action_view_extensions/builder_test.rb +++ b/test/action_view_extensions/builder_test.rb @@ -49,8 +49,7 @@ class BuilderTest < ActionView::TestCase end test "collection radio checks the correct value to local variables" do - user = User.new - user.active = false + user = User.build(active: false) with_collection_radio_buttons user, :active, [true, false], :to_s, :to_s assert_select 'form input[type=radio][value=true]' @@ -297,9 +296,9 @@ class BuilderTest < ActionView::TestCase end test "collection check box checks the correct value to local variables" do - user = User.new - user.tag_ids = [1, 3] + user = User.build(tag_ids: [1, 3]) collection = (1..3).map { |i| [i, "Tag #{i}"] } + with_collection_check_boxes user, :tag_ids, collection, :first, :last assert_select 'form input[type=checkbox][value=1][checked=checked]' diff --git a/test/form_builder/general_test.rb b/test/form_builder/general_test.rb index <HASH>..<HASH> 100644 --- a/test/form_builder/general_test.rb +++ b/test/form_builder/general_test.rb @@ -88,14 +88,7 @@ class FormBuilderTest < ActionView::TestCase end test 'builder allow to use numbers in the model name' do - user = UserNumber1And2.new({ - id: 1, - name: 'New in SimpleForm!', - description: 'Hello!', - created_at: Time.now - }) - - user.tags = [Tag.new(nil, 'Tag1')] + user = UserNumber1And2.build(tags: [Tag.new(nil, 'Tag1')]) with_concat_form_for(user, url: '/') do |f| f.simple_fields_for(:tags) do |tags| diff --git a/test/inputs/collection_select_input_test.rb b/test/inputs/collection_select_input_test.rb index <HASH>..<HASH> 100644 --- a/test/inputs/collection_select_input_test.rb +++ b/test/inputs/collection_select_input_test.rb @@ -112,7 +112,7 @@ class CollectionSelectInputTest < ActionView::TestCase end test 'input should detect label and value on collections' do - users = [ setup_new_user(id: 1, name: "Jose"), setup_new_user(id: 2, name: "Carlos") ] + users = [User.build(id: 1, name: "Jose"), User.build(id: 2, name: "Carlos")] with_input_for @user, :description, :select, collection: users assert_select 'select option[value=1]', 'Jose' assert_select 'select option[value=2]', 'Carlos' diff --git a/test/support/models.rb b/test/support/models.rb index <HASH>..<HASH> 100644 --- a/test/support/models.rb +++ b/test/support/models.rb @@ -55,6 +55,17 @@ class User :post_count, :lock_version, :amount, :attempts, :action, :credit_card, :gender, :extra_special_company_id + def self.build(extra_attributes = {}) + attributes = { + id: 1, + name: 'New in SimpleForm!', + description: 'Hello!', + created_at: Time.now + }.merge! extra_attributes + + new attributes + end + def initialize(options={}) @new_record = false options.each do |key, value| diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -35,40 +35,27 @@ class ActionView::TestCase include SimpleForm::ActionViewExtensions::FormHelper setup :set_controller - setup :setup_new_user + setup :setup_users def set_controller @controller = MockController.new end - def setup_new_user(options={}) - @user = User.new({ - id: 1, - name: 'New in SimpleForm!', - description: 'Hello!', - created_at: Time.now - }.merge(options)) - - @validating_user = ValidatingUser.new({ - id: 1, - name: 'New in SimpleForm!', - description: 'Hello!', + def setup_users(extra_attributes = {}) + @user = User.build(extra_attributes) + + @validating_user = ValidatingUser.build({ home_picture: 'Home picture', - created_at: Time.now, age: 19, amount: 15, attempts: 1, company: [1] - }.merge(options)) + }.merge!(extra_attributes)) - @other_validating_user = OtherValidatingUser.new({ - id: 1, - name: 'New in SimpleForm!', - description: 'Hello!', - created_at: Time.now, + @other_validating_user = OtherValidatingUser.build({ age: 19, company: 1 - }.merge(options)) + }.merge!(extra_attributes)) end def protect_against_forgery?
Cleanup user building a little bit
plataformatec_simple_form
train
13dee96b293c1b60d10035eee2ac7f6f36108a61
diff --git a/tests/Plugins/Autolink/ParserTest.php b/tests/Plugins/Autolink/ParserTest.php index <HASH>..<HASH> 100644 --- a/tests/Plugins/Autolink/ParserTest.php +++ b/tests/Plugins/Autolink/ParserTest.php @@ -100,6 +100,14 @@ class ParserTest extends Test '[url=http://example.com]Non-existent URL tag[/url]', '<rt>[url=<URL url="http://example.com">http://example.com</URL>]Non-existent URL tag[/url]</rt>' ), + array( + 'Link in brackets: [http://example.com/foo] --', + '<rt>Link in brackets: [<URL url="http://example.com/foo">http://example.com/foo</URL>] --</rt>' + ), + array( + 'Link in brackets: [http://example.com/foo?a[]=1] --', + '<rt>Link in brackets: [<URL url="http://example.com/foo?a[]=1">http://example.com/foo?a[]=1</URL>] --</rt>' + ), ); }
Added Autolink test for links in brackets. Turns out it groks them
s9e_TextFormatter
train
e25d82a03d8a45058e183244edde85f98b815145
diff --git a/sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java b/sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java index <HASH>..<HASH> 100644 --- a/sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java +++ b/sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java @@ -99,7 +99,7 @@ public class PostgresDialect extends BaseSqlDialect { @Override public Set<String> getSpacialRefTable() { - return ImmutableSet.copyOf(Collections.singletonList("spatial_ref_sys")); + return ImmutableSet.copyOf(Arrays.asList("spatial_ref_sys", "us_gaz", "us_lex", "us_rules")); } @Override
added more postgis spacial tables to ignore
pietermartin_sqlg
train
5f36f79b55b1be07f3e363b7e3c3a307ab1fda04
diff --git a/tests/test_client.py b/tests/test_client.py index <HASH>..<HASH> 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -52,10 +52,16 @@ def test_connect(corenlp_client): def test_context_manager(): - with corenlp.CoreNLPClient(annotators="tokenize,ssplit") as context_client: + with corenlp.CoreNLPClient(annotators="tokenize,ssplit", + endpoint="http://localhost:9001") as context_client: ann = context_client.annotate(TEXT) assert corenlp.to_text(ann.sentence[0]) == TEXT[:-1] +def test_no_duplicate_servers(): + """We expect a second server on the same port to fail""" + with pytest.raises(corenlp.PermanentlyFailedException): + with corenlp.CoreNLPClient(annotators="tokenize,ssplit") as duplicate_server: + raise RuntimeError("This should have failed") def test_annotate(corenlp_client): ann = corenlp_client.annotate(TEXT)
Add a test for duplicate servers failing, move the context manager test to a different port
stanfordnlp_stanza
train
d2cc5a048a37e1abc23a50c259cd1fe2e16ada63
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/LoadDataFixturesDoctrineCommand.php @@ -24,6 +24,7 @@ use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Internal\CommitOrderCalculator; use Doctrine\ORM\Mapping\ClassMetadata; +use InvalidArgumentException; /** * Load data fixtures from bundles. @@ -62,6 +63,16 @@ EOT $emName = $input->getOption('em'); $emName = $emName ? $emName : 'default'; $emServiceName = sprintf('doctrine.orm.%s_entity_manager', $emName); + + if (!$this->container->has($emServiceName)) { + throw new InvalidArgumentException( + sprintf( + 'Could not find an entity manager configured with the name "%s". Check your '. + 'application configuration to configure your Doctrine entity managers.', $emName + ) + ); + } + $em = $this->container->get($emServiceName); $dirOrFile = $input->getOption('fixtures'); if ($dirOrFile) { @@ -80,6 +91,11 @@ EOT } } $fixtures = $loader->getFixtures(); + if (!$fixtures) { + throw new InvalidArgumentException( + sprintf('Could not find any fixtures to load in: %s', "\n\n- ".implode("\n- ", $paths)) + ); + } $purger = new ORMPurger($em); $executor = new ORMExecutor($em, $purger); $executor->setLogger(function($message) use ($output) {
[DoctrineBundle] Improving error exceptions thrown when loading data fixtures.
symfony_symfony
train
bb2f6ae824661b4c65da82001a78a6b5561685ea
diff --git a/definitions/npm/history_v5.x.x/flow_v0.104.x-/history_v5.x.x.js b/definitions/npm/history_v5.x.x/flow_v0.104.x-/history_v5.x.x.js index <HASH>..<HASH> 100644 --- a/definitions/npm/history_v5.x.x/flow_v0.104.x-/history_v5.x.x.js +++ b/definitions/npm/history_v5.x.x/flow_v0.104.x-/history_v5.x.x.js @@ -20,8 +20,8 @@ declare module 'history' { replace: ((path: string, state?: { ... }) => void) & ((location: $Shape<HistoryLocation>) => void), go(n: number): void, - goBack(): void, - goForward(): void, + back(): void, + forward(): void, listen(({| location: HistoryLocation, action: Action |}) => void): Unregister, block( blocker: (transition: {|
[history_v5.x.x] Fix back() and forward() type definitions (#<I>)
flow-typed_flow-typed
train
6d75c3a4324fcc968ec26c986dcdcb4ec2f8c2ff
diff --git a/test/clientTests.js b/test/clientTests.js index <HASH>..<HASH> 100644 --- a/test/clientTests.js +++ b/test/clientTests.js @@ -1,24 +1,45 @@ var async = require('async'); var util = require('util'); var Client = require('../index.js').Client; +var Connection = require('../index.js').Connection; var types = require('../lib/types.js'); var keyspace = new types.QueryLiteral('unittestkp1_2'); var client = null; module.exports = { 'setup keyspace': function(test) { - client = new Client({hosts: ['localhost:9042', 'localhost:9042'], keyspace: keyspace}); - client.execute("DROP KEYSPACE ?;", [keyspace], function () { - createKeySpace(); + setup(function () { + client = new Client({hosts: ['localhost:9042', 'localhost:9042'], keyspace: keyspace}); + createTable(); }); - function createKeySpace() { - client.execute("CREATE KEYSPACE ? WITH replication = {'class': 'SimpleStrategy','replication_factor': '1'};", [keyspace], function (err) { + + //recreates a keyspace, using a connection object + function setup(callback) { + var con = new Connection({host:'localhost'}); + con.open(function (err) { if (err) { - test.fail(err); - test.done(); - return; + con.close(function () { + fail(test, err); + }); + } + else { + con.execute("DROP KEYSPACE ?;", [keyspace], function () { + createKeyspace(con, callback); + }); + } + }); + } + + function createKeyspace(con, callback) { + con.execute("CREATE KEYSPACE ? WITH replication = {'class': 'SimpleStrategy','replication_factor': '1'};", [keyspace], function (err) { + if (err) { + con.close(function () { + fail(test, err); + }); } - createTable(); + con.close(function () { + callback(); + }); }); } @@ -40,9 +61,9 @@ module.exports = { "int_sample int," + "inet_sample inet," + "text_sample text);", [], function (err) { - if (err) test.fail(err); + if (err) return fail(test, err); test.done(); - }); + }); } }, 'execute params': function (test) { @@ -294,4 +315,14 @@ function shutDownEnd(test, client) { client.shutdown(function(){ test.done(); }); +} + +function fail(test, err, client) { + test.fail(err); + if (client) { + shutDownEnd(test, client); + } + else { + test.done(); + } } \ No newline at end of file
Client tests: Use a Connection to setup the test keyspace
jorgebay_node-cassandra-cql
train
f8e0e008cdb32f929050ef8311e293499df1d7b0
diff --git a/src/connectors/price-ranges/connectPriceRanges.js b/src/connectors/price-ranges/connectPriceRanges.js index <HASH>..<HASH> 100644 --- a/src/connectors/price-ranges/connectPriceRanges.js +++ b/src/connectors/price-ranges/connectPriceRanges.js @@ -158,13 +158,15 @@ export default function connectPriceRanges(renderFn, unmountFn) { }, init({ helper, instantSearchInstance }) { - this._refine = this._refine.bind(this, helper); + this.refine = opts => { + this._refine(helper, opts); + }; renderFn( { instantSearchInstance, items: [], - refine: this._refine, + refine: this.refine, widgetParams, }, true @@ -209,7 +211,7 @@ export default function connectPriceRanges(renderFn, unmountFn) { renderFn( { items: facetValues, - refine: this._refine, + refine: this.refine, widgetParams, instantSearchInstance, }, diff --git a/src/connectors/toggle/connectToggle.js b/src/connectors/toggle/connectToggle.js index <HASH>..<HASH> 100644 --- a/src/connectors/toggle/connectToggle.js +++ b/src/connectors/toggle/connectToggle.js @@ -128,7 +128,7 @@ export default function connectToggle(renderFn, unmountFn) { }; }, - toggleRefinement(helper, { isRefined } = {}) { + _toggleRefinement(helper, { isRefined } = {}) { // Checking if (!isRefined) { if (hasAnOffValue) { @@ -160,7 +160,9 @@ export default function connectToggle(renderFn, unmountFn) { ) ); - this.toggleRefinement = this.toggleRefinement.bind(this, helper); + this.toggleRefinement = opts => { + this._toggleRefinement(helper, opts); + }; const isRefined = state.isDisjunctiveFacetRefined(attributeName, on); diff --git a/src/widgets/price-ranges/__tests__/price-ranges-test.js b/src/widgets/price-ranges/__tests__/price-ranges-test.js index <HASH>..<HASH> 100644 --- a/src/widgets/price-ranges/__tests__/price-ranges-test.js +++ b/src/widgets/price-ranges/__tests__/price-ranges-test.js @@ -146,7 +146,7 @@ describe('priceRanges()', () => { }); it('refines on the lower bound', () => { - widget._refine({ from: 10, to: undefined }); + widget.refine({ from: 10, to: undefined }); expect(helper.clearRefinements.calledOnce).toBe( true, 'helper.clearRefinements called once' @@ -159,7 +159,7 @@ describe('priceRanges()', () => { }); it('refines on the upper bound', () => { - widget._refine({ fromt: undefined, to: 10 }); + widget.refine({ fromt: undefined, to: 10 }); expect(helper.clearRefinements.calledOnce).toBe( true, 'helper.clearRefinements called once' @@ -168,7 +168,7 @@ describe('priceRanges()', () => { }); it('refines on the 2 bounds', () => { - widget._refine({ from: 10, to: 20 }); + widget.refine({ from: 10, to: 20 }); expect(helper.clearRefinements.calledOnce).toBe( true, 'helper.clearRefinements called once' diff --git a/src/widgets/toggle/__tests__/currentToggle-test.js b/src/widgets/toggle/__tests__/currentToggle-test.js index <HASH>..<HASH> 100644 --- a/src/widgets/toggle/__tests__/currentToggle-test.js +++ b/src/widgets/toggle/__tests__/currentToggle-test.js @@ -400,10 +400,10 @@ describe('currentToggle()', () => { let helper; function toggleOn() { - widget.toggleRefinement(helper, { isRefined: false }); + widget.toggleRefinement({ isRefined: false }); } function toggleOff() { - widget.toggleRefinement(helper, { isRefined: true }); + widget.toggleRefinement({ isRefined: true }); } beforeEach(() => { @@ -424,6 +424,11 @@ describe('currentToggle()', () => { userValues, }); widget.getConfiguration(); + const state = { + isDisjunctiveFacetRefined: sinon.stub().returns(false), + }; + const createURL = () => '#'; + widget.init({ state, helper, createURL, instantSearchInstance }); // When toggleOn(); @@ -443,6 +448,11 @@ describe('currentToggle()', () => { userValues, }); widget.getConfiguration(); + const state = { + isDisjunctiveFacetRefined: sinon.stub().returns(true), + }; + const createURL = () => '#'; + widget.init({ state, helper, createURL, instantSearchInstance }); // When toggleOff(); @@ -468,6 +478,11 @@ describe('currentToggle()', () => { values: userValues, }); widget.getConfiguration(); + const state = { + isDisjunctiveFacetRefined: sinon.stub().returns(false), + }; + const createURL = () => '#'; + widget.init({ state, helper, createURL, instantSearchInstance }); // When toggleOn(); @@ -494,6 +509,11 @@ describe('currentToggle()', () => { values: userValues, }); widget.getConfiguration(); + const state = { + isDisjunctiveFacetRefined: sinon.stub().returns(true), + }; + const createURL = () => '#'; + widget.init({ state, helper, createURL, instantSearchInstance }); // When toggleOff();
fix(connectors): prefer wrappers over bind (#<I>) * fix(connectors): prefer wrappers over bind Previously we were using bind, which will be applied at each init. This is ok for one time mount, but since we can mount and unmount dynamically now, it's a problem. * chore: fix test for price-range and toggle widgets * refactor: remove unnecessary spread
algolia_instantsearch.js
train
ab2badb8e3e5439a327f1d778ea875148520e355
diff --git a/lib/components/narrative/line-itin/connected-itinerary-body.js b/lib/components/narrative/line-itin/connected-itinerary-body.js index <HASH>..<HASH> 100644 --- a/lib/components/narrative/line-itin/connected-itinerary-body.js +++ b/lib/components/narrative/line-itin/connected-itinerary-body.js @@ -68,7 +68,11 @@ class ConnectedItineraryBody extends Component { TransitLegSubheader={TransitLegSubheader} TransitLegSummary={TransitLegSummary} /> - <TripDetails itinerary={itinerary} /> + <TripDetails + itinerary={itinerary} + longDateFormat={config.dateTime.longDateFormat} + timeOptions={timeOptions} + /> <TripTools itinerary={itinerary} /> </ItineraryBodyContainer> )
fix(ItineraryBody): Pass time/date format to TripDetails component.
opentripplanner_otp-react-redux
train
1fe2c9886f76f51e1e459fe97f2ac360869deb19
diff --git a/daemons/startstop/simple.py b/daemons/startstop/simple.py index <HASH>..<HASH> 100644 --- a/daemons/startstop/simple.py +++ b/daemons/startstop/simple.py @@ -16,6 +16,11 @@ from ..interfaces import startstop LOG = logging.getLogger(__name__) +SUCCESS_MSG = "an integer is required" + +if sys.version_info >= (3, 10, 0): + SUCCESS_MSG = "object cannot be interpreted as an integer" + class SimpleStartStopManager(startstop.StartStopManager): @@ -78,7 +83,7 @@ class SimpleStartStopManager(startstop.StartStopManager): except TypeError as err: - if "an integer is required" in str(err): + if SUCCESS_MSG in str(err): LOG.info("Succesfully stopped the process.") return None
Python <I>'s os.kill() throws a TypeError with a different message than older Python versions
kevinconway_daemons
train
b2423f4cce50689ce0430211869f62470a963fd6
diff --git a/lib/xclarity_client/xclarity_base.rb b/lib/xclarity_client/xclarity_base.rb index <HASH>..<HASH> 100644 --- a/lib/xclarity_client/xclarity_base.rb +++ b/lib/xclarity_client/xclarity_base.rb @@ -16,7 +16,11 @@ module XClarityClient def connection_builder(conf, uri) $lxca_log.info "XClarityClient::XClarityBase connection_builder", "Creating connection to #{conf.host + uri}" #Building configuration - @conn = Faraday.new(url: conf.host + uri) do |faraday| + host = conf.host; + if !host.start_with?('https://') && !host.start_with?('http://') + host = 'https://' + host + end + @conn = Faraday.new(url: host + uri) do |faraday| faraday.request :url_encoded # form-encode POST params faraday.response :logger # log requests to STDOUT -- This line, should be uncommented if you wanna inspect the URL Request faraday.adapter Faraday.default_adapter # make requests with Net::HTTP diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -4,7 +4,7 @@ require 'apib/mock_server' require 'webmock/rspec' -base_url = "http://example.com" +base_url = "https://example.com" # These environment variables must be defined ENV['LXCA_USERNAME'] ||= '' ENV['LXCA_PASSWORD'] ||= '' diff --git a/spec/xclarity_client_node_spec.rb b/spec/xclarity_client_node_spec.rb index <HASH>..<HASH> 100644 --- a/spec/xclarity_client_node_spec.rb +++ b/spec/xclarity_client_node_spec.rb @@ -7,12 +7,13 @@ describe XClarityClient do conf = XClarityClient::Configuration.new( username: ENV['LXCA_USERNAME'], password: ENV['LXCA_PASSWORD'], - host: ENV['LXCA_HOST'], + host: "example.com", auth_type: ENV['LXCA_AUTH_TYPE'], verify_ssl: ENV['LXCA_VERIFY_SSL'] ) @client = XClarityClient::Client.new(conf) + @host = ENV['LXCA_HOST'] @includeAttributes = %w(accessState activationKeys) @excludeAttributes = %w(accessState activationKeys) @@ -121,7 +122,7 @@ describe XClarityClient do context 'with state == "On" and name == "Identify"' do it 'turns on the location led' do @client.turn_on_loc_led(@uuidArray[0]) - uri = "http://example.com/nodes/#{@uuidArray[0]}" + uri = "#{@host}/nodes/#{@uuidArray[0]}" request_body = { 'body' => { 'leds' => [{ 'name' => 'Identify', 'state' => 'On' }] } } expect(a_request(:put, uri).with(request_body)).to have_been_made @@ -131,7 +132,7 @@ describe XClarityClient do context 'with state == "Off" and name == "Identify"' do it 'turns off the location led' do @client.turn_off_loc_led(@uuidArray[0]) - uri = "http://example.com/nodes/#{@uuidArray[0]}" + uri = "#{@host}/nodes/#{@uuidArray[0]}" request_body = { 'body' => { 'leds' => [{ 'name' => 'Identify', 'state' => 'Off' }] } } expect(a_request(:put, uri).with(request_body)).to have_been_made @@ -141,7 +142,7 @@ describe XClarityClient do context 'with state == "Blinking" and name == "Identify"' do it 'turns on the blinking location led' do @client.blink_loc_led(@uuidArray[0]) - uri = "http://example.com/nodes/#{@uuidArray[0]}" + uri = "#{@host}/nodes/#{@uuidArray[0]}" request_body = { 'body' => { 'leds' => [{ 'name' => 'Identify', 'state' => 'Blinking' }] } } expect(a_request(:put, uri).with(request_body)).to have_been_made
Adjust the connection url to append https:// if a prefix has not been given. If http:// has been added it will not be modified and the connection should fail gracefully
lenovo_xclarity_client
train
0481dff83f4a7a83ca1444cda5a9552788cf14e3
diff --git a/openquake/engine/calculators/hazard/event_based/core.py b/openquake/engine/calculators/hazard/event_based/core.py index <HASH>..<HASH> 100644 --- a/openquake/engine/calculators/hazard/event_based/core.py +++ b/openquake/engine/calculators/hazard/event_based/core.py @@ -163,14 +163,17 @@ def compute_ses_and_gmfs(job_id, src_seeds, gsims_by_rlz, task_no): # log calc_time per distinct rupture if ses_num_occ: + num_occ = sum(num for rup in ses_num_occ + for ses, num in ses_num_occ[rup]) logs.LOG.info( - 'job=%d, src=%s:%s, num_ruptures=%d, calc_time=%fs', - job_id, src.source_id, src.__class__.__name__, - len(ses_num_occ), time.time() - t0) + 'job=%d, src=%s:%s, num_ruptures=%d, num_sites=%d, ' + 'calc_time=%fs', job_id, src.source_id, src.__class__.__name__, + num_occ, len(s_sites), time.time() - t0) num_distinct_ruptures += len(ses_num_occ) - logs.LOG.info('job=%d, task %d generated %d/%d distinct ruptures', - job_id, task_no, num_distinct_ruptures, total_ruptures) + if num_distinct_ruptures: + logs.LOG.info('job=%d, task %d generated %d/%d ruptures', + job_id, task_no, num_distinct_ruptures, total_ruptures) mon1.flush() mon2.flush() mon3.flush() diff --git a/openquake/engine/input/source.py b/openquake/engine/input/source.py index <HASH>..<HASH> 100644 --- a/openquake/engine/input/source.py +++ b/openquake/engine/input/source.py @@ -543,6 +543,8 @@ def get_num_ruptures_weight(src): num_ruptures = src.count_ruptures() if isinstance(src, source.PointSource): weight = num_ruptures + elif isinstance(src, source.CharacteristicFaultSource): + weight = num_ruptures * 100 else: # giving more than linear weight to other sources weight = num_ruptures ** 1.5 return num_ruptures, weight
Special weight for characteristic sources and better logging
gem_oq-engine
train
b2a48efa9ec98275d0689c633b244e8a771da601
diff --git a/nameko/legacy/consuming.py b/nameko/legacy/consuming.py index <HASH>..<HASH> 100644 --- a/nameko/legacy/consuming.py +++ b/nameko/legacy/consuming.py @@ -38,5 +38,10 @@ def queue_iterator(queue, no_ack=False, timeout=None): yield msg except socket.timeout: if timeout is not None: + # we raise a different exception type here because we bubble out + # to our caller, but `socket.timeout` errors get caught if + # our connection is "ensured" with `kombu.Connection.ensure`; + # the reference to the connection is destroyed so it can't be + # closed later - see http://bit.ly/1nJz2Gm#L446 raise RpcTimeout(timeout) raise
add comment explaining re-raise of socket.timeout as a different error
nameko_nameko
train
606909cbe53d8b10c7aa7de8d78f686af5f4a498
diff --git a/go/vt/tabletmanager/after_action.go b/go/vt/tabletmanager/after_action.go index <HASH>..<HASH> 100644 --- a/go/vt/tabletmanager/after_action.go +++ b/go/vt/tabletmanager/after_action.go @@ -141,7 +141,8 @@ func (agent *ActionAgent) loadKeyspaceAndBlacklistRules(tablet *pbt.Tablet, blac return nil } -func (agent *ActionAgent) stopQueryService() { +func (agent *ActionAgent) stopQueryService(reason string) { + log.Infof("Agent is going to stop query service, reason: %v", reason) agent.QueryServiceControl.StopService() } @@ -160,24 +161,30 @@ func (agent *ActionAgent) changeCallback(ctx context.Context, oldTablet, newTabl var tabletControl *pbt.Shard_TabletControl var blacklistedTables []string var err error + var disallowQueryReason string if allowQuery { shardInfo, err = agent.TopoServer.GetShard(ctx, newTablet.Keyspace, newTablet.Shard) if err != nil { log.Errorf("Cannot read shard for this tablet %v, might have inaccurate SourceShards and TabletControls: %v", newTablet.Alias, err) } else { if newTablet.Type == pbt.TabletType_MASTER { - allowQuery = len(shardInfo.SourceShards) == 0 + if allowQuery = len(shardInfo.SourceShards) == 0; !allowQuery { + disallowQueryReason = "old master is still in shard info" + } } if tc := shardInfo.GetTabletControl(newTablet.Type); tc != nil { if topo.InCellList(newTablet.Alias.Cell, tc.Cells) { if tc.DisableQueryService { allowQuery = false + disallowQueryReason = "query service disabled by tablet control" } blacklistedTables = tc.BlacklistedTables tabletControl = tc } } } + } else { + disallowQueryReason = fmt.Sprintf("not a serving tablet type(%v)", newTablet.Type) } // Read the keyspace on masters to get ShardingColumnType, @@ -202,12 +209,12 @@ func (agent *ActionAgent) changeCallback(ctx context.Context, oldTablet, newTabl // anything to start working until either InitMaster or InitSlave. case agent.initReplication: agent.initReplication = false - agent.stopQueryService() + agent.stopQueryService("initialize replication") // Transitioning from replica to master, so clients that were already // connected don't keep on using the master as replica or rdonly. case newTablet.Type == pbt.TabletType_MASTER && oldTablet.Type != pbt.TabletType_MASTER: - agent.stopQueryService() + agent.stopQueryService("tablet promoted to master") // Having different parameters for the query service. // It needs to stop and restart with the new parameters. @@ -216,14 +223,14 @@ func (agent *ActionAgent) changeCallback(ctx context.Context, oldTablet, newTabl // - changing the BlacklistedTables list case (newTablet.KeyRange != oldTablet.KeyRange), !reflect.DeepEqual(blacklistedTables, agent.BlacklistedTables()): - agent.stopQueryService() + agent.stopQueryService("keyrange/blacklistedtables changed") } if err := agent.allowQueries(newTablet, blacklistedTables); err != nil { log.Errorf("Cannot start query service: %v", err) } } else { - agent.stopQueryService() + agent.stopQueryService(disallowQueryReason) } // save the tabletControl we've been using, so the background diff --git a/go/vt/tabletmanager/agent_rpc_actions.go b/go/vt/tabletmanager/agent_rpc_actions.go index <HASH>..<HASH> 100644 --- a/go/vt/tabletmanager/agent_rpc_actions.go +++ b/go/vt/tabletmanager/agent_rpc_actions.go @@ -472,7 +472,7 @@ func (agent *ActionAgent) DemoteMaster(ctx context.Context) (myproto.Replication // Now stop the query service, to make sure nobody is writing to the // database. This will in effect close the connection pools to the // database. - agent.stopQueryService() + agent.stopQueryService("DemoteMaster marks server rdonly") return agent.MysqlDaemon.DemoteMaster() // There is no serving graph update - the master tablet will diff --git a/go/vt/tabletmanager/healthcheck.go b/go/vt/tabletmanager/healthcheck.go index <HASH>..<HASH> 100644 --- a/go/vt/tabletmanager/healthcheck.go +++ b/go/vt/tabletmanager/healthcheck.go @@ -203,9 +203,9 @@ func (agent *ActionAgent) runHealthCheck(targetTabletType pbt.TabletType) { if isQueryServiceRunning { // we are not healthy or should not be running the // query service, shut it down. - // Log the error which causes QueryService to stop - log.Errorf("About to stop query service: <%v>", err) - agent.stopQueryService() + agent.stopQueryService( + fmt.Sprintf("health-check failure(%v)", err), + ) } }
log reasons for shutting down query service
vitessio_vitess
train
1efaff8f7f4a87daaff9636a426f22a14ce1574c
diff --git a/changeset/changeset.go b/changeset/changeset.go index <HASH>..<HASH> 100644 --- a/changeset/changeset.go +++ b/changeset/changeset.go @@ -31,3 +31,7 @@ func (changeset *Changeset) Changes() map[string]interface{} { func (changeset *Changeset) Values() map[string]interface{} { return changeset.values } + +func (changeset *Changeset) Types() map[string]reflect.Type { + return changeset.types +} diff --git a/changeset/changeset_test.go b/changeset/changeset_test.go index <HASH>..<HASH> 100644 --- a/changeset/changeset_test.go +++ b/changeset/changeset_test.go @@ -10,4 +10,5 @@ func TestChangeset(t *testing.T) { ch := Changeset{} assert.Nil(t, ch.Changes()) assert.Nil(t, ch.Values()) + assert.Nil(t, ch.Types()) } diff --git a/query.go b/query.go index <HASH>..<HASH> 100644 --- a/query.go +++ b/query.go @@ -1,7 +1,9 @@ package grimoire import ( + "reflect" "strings" + "time" "github.com/Fs02/go-paranoid" "github.com/Fs02/grimoire/c" @@ -142,34 +144,17 @@ func (query Query) MustAll(doc interface{}) { paranoid.Panic(query.All(doc)) } -func (query Query) mergeChanges(ch *changeset.Changeset) map[string]interface{} { - var changes map[string]interface{} - - if len(query.Changes) > 0 { - changes = make(map[string]interface{}) - - // copy changes - for k, v := range ch.Changes() { - changes[k] = v - } - - // apply query changes - for k, v := range query.Changes { - changes[k] = v - } - } else { - changes = ch.Changes() - } - - return changes -} - func (query Query) Insert(doc interface{}, chs ...*changeset.Changeset) error { var ids []interface{} if len(chs) > 0 { for _, ch := range chs { - changes := query.mergeChanges(ch) + changes := make(map[string]interface{}) + cloneChangeset(changes, ch.Changes()) + putTimestamp(changes, "created_at", ch.Types()) + putTimestamp(changes, "updated_at", ch.Types()) + cloneQuery(changes, query.Changes) + qs, args := query.repo.adapter.Insert(query, changes) id, _, err := query.repo.adapter.Exec(qs, args) @@ -203,15 +188,16 @@ func (query Query) MustInsert(doc interface{}, chs ...*changeset.Changeset) { } func (query Query) Update(doc interface{}, chs ...*changeset.Changeset) error { - var changes map[string]interface{} + changes := make(map[string]interface{}) // only take the first changeset if any if len(chs) != 0 { - changes = query.mergeChanges(chs[0]) - } else { - changes = query.Changes + cloneChangeset(changes, chs[0].Changes()) + putTimestamp(changes, "updated_at", chs[0].Types()) } + cloneQuery(changes, query.Changes) + // nothing to update if len(changes) == 0 { return nil @@ -245,3 +231,30 @@ func (query Query) Delete() error { func (query Query) MustDelete() { paranoid.Panic(query.Delete()) } + +func cloneChangeset(out map[string]interface{}, changes map[string]interface{}) { + for k, v := range changes { + // filter out changeset + if _, ok := v.(*changeset.Changeset); ok { + continue + } + + if _, ok := v.([]*changeset.Changeset); ok { + continue + } + + out[k] = v + } +} + +func cloneQuery(out map[string]interface{}, changes map[string]interface{}) { + for k, v := range changes { + out[k] = v + } +} + +func putTimestamp(out map[string]interface{}, field string, types map[string]reflect.Type) { + if typ, ok := types[field]; ok && typ == reflect.TypeOf(time.Time{}) { + out[field] = time.Now() + } +}
always clone changes, put created_at and updated_at
Fs02_grimoire
train
393a4d8d567fcaa1ab4334b22a0e80c8a13b76f6
diff --git a/regions/io/crtf/read.py b/regions/io/crtf/read.py index <HASH>..<HASH> 100644 --- a/regions/io/crtf/read.py +++ b/regions/io/crtf/read.py @@ -67,7 +67,7 @@ def read_crtf(filename, errors='strict'): raise CRTFRegionParserError('Every CRTF Region must start with "#CRTF" ') -class CRTFParser: +class CRTFParser(object): """ Parses a CRTF string.
explicitly inheriting from object for backward compatibility
astropy_regions
train
0e053a151d3455132b26151240936a1ca375f224
diff --git a/pkts-streams/src/main/java/io/pkts/streams/SipStream.java b/pkts-streams/src/main/java/io/pkts/streams/SipStream.java index <HASH>..<HASH> 100644 --- a/pkts-streams/src/main/java/io/pkts/streams/SipStream.java +++ b/pkts-streams/src/main/java/io/pkts/streams/SipStream.java @@ -7,7 +7,7 @@ import io.pkts.packet.sip.SipParseException; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; -import java.util.Collection; +import java.util.List; /** * Represents a stream of related SIP messages. @@ -22,7 +22,7 @@ public interface SipStream extends Stream<SipMessage> { * {@inheritDoc} */ @Override - Collection<SipMessage> getPackets(); + List<SipMessage> getPackets(); /** * Post Dial Delay (PDD) is defined as the time it takes between the INVITE diff --git a/pkts-streams/src/main/java/io/pkts/streams/Stream.java b/pkts-streams/src/main/java/io/pkts/streams/Stream.java index <HASH>..<HASH> 100644 --- a/pkts-streams/src/main/java/io/pkts/streams/Stream.java +++ b/pkts-streams/src/main/java/io/pkts/streams/Stream.java @@ -9,7 +9,7 @@ import io.pkts.packet.Packet; import java.io.IOException; import java.io.OutputStream; -import java.util.Collection; +import java.util.List; /** * A {@link Stream} represents a set of {@link Packet}s that belong together. @@ -25,7 +25,7 @@ public interface Stream<T extends Packet> { * * @return */ - Collection<T> getPackets(); + List<T> getPackets(); /** * Get the duration in microseconds of the stream. Note, see comment on diff --git a/pkts-streams/src/main/java/io/pkts/streams/impl/BasicSipStream.java b/pkts-streams/src/main/java/io/pkts/streams/impl/BasicSipStream.java index <HASH>..<HASH> 100644 --- a/pkts-streams/src/main/java/io/pkts/streams/impl/BasicSipStream.java +++ b/pkts-streams/src/main/java/io/pkts/streams/impl/BasicSipStream.java @@ -14,7 +14,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.util.Collection; +import java.util.List; /** * The {@link BasicSipStream} only does some very basic analysis of the SIP @@ -66,7 +66,7 @@ public class BasicSipStream implements SipStream { * {@inheritDoc} */ @Override - public Collection<SipMessage> getPackets() { + public List<SipMessage> getPackets() { return this.fsm.getMessages(); } diff --git a/pkts-streams/src/main/java/io/pkts/streams/impl/DefaultSipStream.java b/pkts-streams/src/main/java/io/pkts/streams/impl/DefaultSipStream.java index <HASH>..<HASH> 100644 --- a/pkts-streams/src/main/java/io/pkts/streams/impl/DefaultSipStream.java +++ b/pkts-streams/src/main/java/io/pkts/streams/impl/DefaultSipStream.java @@ -10,7 +10,7 @@ import io.pkts.streams.StreamId; import java.io.IOException; import java.io.OutputStream; -import java.util.Collection; +import java.util.List; /** * The {@link DefaultSipStream} implements a complete SIP state machine in order @@ -36,7 +36,7 @@ public final class DefaultSipStream implements SipStream { } @Override - public Collection<SipMessage> getPackets() { + public List<SipMessage> getPackets() { // TODO Auto-generated method stub return null; } diff --git a/pkts-streams/src/main/java/io/pkts/streams/impl/SimpleCallStateMachine.java b/pkts-streams/src/main/java/io/pkts/streams/impl/SimpleCallStateMachine.java index <HASH>..<HASH> 100644 --- a/pkts-streams/src/main/java/io/pkts/streams/impl/SimpleCallStateMachine.java +++ b/pkts-streams/src/main/java/io/pkts/streams/impl/SimpleCallStateMachine.java @@ -16,7 +16,6 @@ import io.pkts.streams.SipStream.CallState; import java.io.Serializable; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -517,8 +516,8 @@ public final class SimpleCallStateMachine { * * @return */ - public Collection<SipMessage> getMessages() { - return this.messages; + public List<SipMessage> getMessages() { + return new ArrayList<SipMessage>(this.messages); } /**
changed to List instead since the packets in a stream is ordered
aboutsip_pkts
train
1815bd7fbda932933fed604579e955a8c4d7c021
diff --git a/lark/exceptions.py b/lark/exceptions.py index <HASH>..<HASH> 100644 --- a/lark/exceptions.py +++ b/lark/exceptions.py @@ -97,10 +97,10 @@ class UnexpectedToken(ParseError, UnexpectedInput): super(UnexpectedToken, self).__init__(message) class VisitError(LarkError): - def __init__(self, tree, orig_exc): - self.tree = tree + def __init__(self, rule, obj, orig_exc): + self.obj = obj self.orig_exc = orig_exc - message = 'Error trying to process rule "%s":\n\n%s' % (tree.data, orig_exc) + message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc) super(VisitError, self).__init__(message) ###} diff --git a/lark/lark.py b/lark/lark.py index <HASH>..<HASH> 100644 --- a/lark/lark.py +++ b/lark/lark.py @@ -225,7 +225,16 @@ class Lark(Serialize): for rule in self.rules: if rule.options and rule.options.priority is not None: rule.options.priority = None - self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, self.options.lexer_callbacks) + + # TODO Deprecate lexer_callbacks? + lexer_callbacks = dict(self.options.lexer_callbacks) + if self.options.transformer: + t = self.options.transformer + for term in self.terminals: + if hasattr(t, term.name): + lexer_callbacks[term.name] = getattr(t, term.name) + + self.lexer_conf = LexerConf(self.terminals, self.ignore_tokens, self.options.postlex, lexer_callbacks) if self.options.parser: self.parser = self._build_parser() diff --git a/lark/lexer.py b/lark/lexer.py index <HASH>..<HASH> 100644 --- a/lark/lexer.py +++ b/lark/lexer.py @@ -108,6 +108,13 @@ class Token(Str): self.end_column = end_column return self + def update(self, type_=None, value=None): + return Token.new_borrow_pos( + type_ if type_ is not None else self.type, + value if value is not None else self.value, + self + ) + @classmethod def new_borrow_pos(cls, type_, value, borrow_t): return cls(type_, value, borrow_t.pos_in_stream, borrow_t.line, borrow_t.column, borrow_t.end_line, borrow_t.end_column) diff --git a/lark/visitors.py b/lark/visitors.py index <HASH>..<HASH> 100644 --- a/lark/visitors.py +++ b/lark/visitors.py @@ -48,7 +48,7 @@ class Transformer: except (GrammarError, Discard): raise except Exception as e: - raise VisitError(tree, e) + raise VisitError(tree.data, tree, e) def _call_userfunc_token(self, token): try: @@ -61,7 +61,7 @@ class Transformer: except (GrammarError, Discard): raise except Exception as e: - raise VisitError(token, e) + raise VisitError(token.type, token, e) def _transform_children(self, children): diff --git a/tests/test_parser.py b/tests/test_parser.py index <HASH>..<HASH> 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -99,16 +99,22 @@ class TestParsers(unittest.TestCase): def a(self, children): return children[0] + "!" def A(self, tok): - return tok.upper() + return tok.update(value=tok.upper()) # Test regular - g = Lark("""start: a - a : A - A: "x" - """, parser='lalr') - r = T().transform(g.parse("x")) + g = """start: a + a : A + A: "x" + """ + p = Lark(g, parser='lalr') + r = T(False).transform(p.parse("x")) self.assertEqual( r.children, ["x!"] ) - r = T(True).transform(g.parse("x")) + r = T().transform(p.parse("x")) + self.assertEqual( r.children, ["X!"] ) + + # Test internal transformer + p = Lark(g, parser='lalr', transformer=T()) + r = p.parse("x") self.assertEqual( r.children, ["X!"] )
Support for token visitation in internal transformers, as an alternative mechanism for lexer_callbacks
lark-parser_lark
train
60e794664ae6b31f1552f181131be19febc59d14
diff --git a/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java b/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java index <HASH>..<HASH> 100644 --- a/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java +++ b/aeron-archive/src/main/java/io/aeron/archive/ArchiveConductor.java @@ -58,6 +58,7 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa private final EpochClock epochClock; private final File archiveDir; private final FileChannel archiveDirChannel; + private final Subscription controlSubscription; private final Catalog catalog; private final RecordingEventsProxy recordingEventsProxy; @@ -87,7 +88,8 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa maxConcurrentRecordings = ctx.maxConcurrentRecordings(); maxConcurrentReplays = ctx.maxConcurrentReplays(); - aeron.addSubscription(ctx.controlChannel(), ctx.controlStreamId(), this, null); + controlSubscription = aeron.addSubscription( + ctx.controlChannel(), ctx.controlStreamId(), this, null); recordingEventsProxy = new RecordingEventsProxy( ctx.idleStrategy(), @@ -122,10 +124,13 @@ abstract class ArchiveConductor extends SessionWorker<Session> implements Availa protected void postSessionsClose() { + if (!ctx.ownsAeronClient()) + { + CloseHelper.close(controlSubscription); + } + CloseHelper.quietClose(catalog); CloseHelper.quietClose(archiveDirChannel); - CloseHelper.quietClose(aeronAgentInvoker); - CloseHelper.quietClose(driverAgentInvoker); } protected int preWork()
[Java] Fix lifecycle tracking of Aeron resources in Archive on close.
real-logic_aeron
train
0ca7e6b0c4450fe6614826a925243f92d19be659
diff --git a/parsl/dataflow/dflow.py b/parsl/dataflow/dflow.py index <HASH>..<HASH> 100644 --- a/parsl/dataflow/dflow.py +++ b/parsl/dataflow/dflow.py @@ -443,6 +443,7 @@ class DataFlowKernel(object): executor = self.executors[executor_label] except Exception: logger.exception("Task {} requested invalid executor {}: config is\n{}".format(task_id, executor_label, self._config)) + raise ValueError("Task {} requested invalid executor {}".format(task_id, executor_label)) if self.monitoring is not None and self.monitoring.resource_monitoring_enabled: executable = self.monitoring.monitor_wrapper(executable, task_id, @@ -626,6 +627,8 @@ class DataFlowKernel(object): choices = list(e for e in self.executors if e != 'data_manager') elif isinstance(executors, list): choices = executors + else: + raise ValueError("Task {} supplied invalid type for executors: {}".format(task_id, type(executors))) executor = random.choice(choices) # Transform remote input files to data futures
Better error handling when app 'executors' parameter is wrong (#<I>) With these changes, exceptions still happen in the same circumstances as before (when a user supplies an incorrect executors value to an app definition) but with better explanations: they are reported as the type being wrong, rather than some later piece of code breaking.
Parsl_parsl
train
0f9411f5f359145abed595f42a011bd8bc680924
diff --git a/lib/moog.js b/lib/moog.js index <HASH>..<HASH> 100644 --- a/lib/moog.js +++ b/lib/moog.js @@ -134,7 +134,7 @@ module.exports = function(options) { self.options.sections = self.options.sections || []; self.options.unparsedSections = self.options.unparsedSections || []; - const validKeys = [ '__meta', 'options', 'cascades', 'beforeSuperClass', 'init', 'afterAllSections', 'extend', 'improve', 'methods', 'extendMethods' ] + const validKeys = [ '__meta', 'options', 'cascades', 'beforeSuperClass', 'init', 'afterAllSections', 'extend', 'improve', 'methods', 'extendMethods', 'instantiate' ] .concat(self.options.sections) .concat(self.options.sections.map(getExtendKey)) .concat(self.options.unparsedSections)
instantiate was inadvertently left off the valid keys list for modules
apostrophecms_apostrophe
train
1bf888cb126871f8bb55deae830e19125fbac989
diff --git a/ldap_sync/management/commands/syncldap.py b/ldap_sync/management/commands/syncldap.py index <HASH>..<HASH> 100644 --- a/ldap_sync/management/commands/syncldap.py +++ b/ldap_sync/management/commands/syncldap.py @@ -19,10 +19,12 @@ class Command(NoArgsCommand): def handle_noargs(self, **options): ldap_groups = self.get_ldap_groups() - ldap_users = self.get_ldap_users() + if ldap_groups: + self.sync_ldap_groups(ldap_groups) - self.sync_ldap_groups(ldap_groups) - self.sync_ldap_users(ldap_users) + ldap_users = self.get_ldap_users() + if ldap_users: + self.sync_ldap_users(ldap_users) def get_ldap_users(self): """ @@ -30,9 +32,9 @@ class Command(NoArgsCommand): """ user_filter = getattr(settings, 'LDAP_SYNC_USER_FILTER', None) if not user_filter: - error_msg = ("LDAP_SYNC_USER_FILTER must be specified in your " - "Django settings file") - raise ImproperlyConfigured(error_msg) + msg = "LDAP_SYNC_USER_FILTER not configured, skipping user sync" + logger.info(msg) + return None attributes = getattr(settings, 'LDAP_SYNC_USER_ATTRIBUTES', None) if not attributes: @@ -104,9 +106,9 @@ class Command(NoArgsCommand): """ group_filter = getattr(settings, 'LDAP_SYNC_GROUP_FILTER', None) if not group_filter: - error_msg = ("LDAP_SYNC_GROUP_FILTER must be specified in your " - "Django settings file") - raise ImproperlyConfigured(error_msg) + msg = "LDAP_SYNC_GROUP_FILTER not configured, skipping group sync" + logger.info(msg) + return None attributes = getattr(settings, 'LDAP_SYNC_GROUP_ATTRIBUTES', None) if not attributes:
Skip user/group sync if the filter is not configured
jbittel_django-ldap-sync
train
c7f2cd0211fa09cba52b9483f221fa92f421c17c
diff --git a/api/http_lifecycle.go b/api/http_lifecycle.go index <HASH>..<HASH> 100644 --- a/api/http_lifecycle.go +++ b/api/http_lifecycle.go @@ -19,6 +19,9 @@ type HttpLifecycle struct { root *url.URL // client is the *http.Client used to execute these requests. client *http.Client + // authenticateRequests stores whether or not the HttpLifecycle should + // authenticate its HTTP requests + authenticateRequests bool } var _ Lifecycle = new(HttpLifecycle) @@ -43,26 +46,33 @@ func NewHttpLifecycle(root *url.URL) *HttpLifecycle { // serializing it into JSON, then that error will be returned and the // *http.Request will not be generated. // +// In all cases, credentials are attached to the HTTP request as described in +// the `auth` package (see github.com/github/git-lfs/auth#GetCreds). +// // Finally, all of these components are combined together and the resulting // request is returned. func (l *HttpLifecycle) Build(schema *RequestSchema) (*http.Request, error) { - path, err := l.AbsolutePath(schema.Path) + path, err := l.absolutePath(schema.Path) if err != nil { return nil, err } - body, err := l.Body(schema) + body, err := l.body(schema) if err != nil { return nil, err } - // TODO(taylor): attach creds! req, err := http.NewRequest(schema.Method, path.String(), body) if err != nil { return nil, err } - req.URL.RawQuery = l.QueryParameters(schema).Encode() + // ASK(@sinbad): is this the correct usage? + // if _, err = auth.GetCreds(req); err != nil { + // return nil, err + // } + + req.URL.RawQuery = l.queryParameters(schema).Encode() return req, nil } @@ -98,15 +108,15 @@ func (l *HttpLifecycle) Execute(req *http.Request, into interface{}) (Response, } // Cleanup implements the Lifecycle.Cleanup function by closing the Body -// attached to the repsonse. +// attached to the response. func (l *HttpLifecycle) Cleanup(resp Response) error { return resp.Body().Close() } -// AbsolutePath returns the absolute path made by combining a given relative +// absolutePath returns the absolute path made by combining a given relative // path with the owned "base" path. If there was an error in parsing the // relative path, then that error will be returned. -func (l *HttpLifecycle) AbsolutePath(path string) (*url.URL, error) { +func (l *HttpLifecycle) absolutePath(path string) (*url.URL, error) { rel, err := url.Parse(path) if err != nil { return nil, err @@ -116,13 +126,13 @@ func (l *HttpLifecycle) AbsolutePath(path string) (*url.URL, error) { return l.root.ResolveReference(rel), nil } -// Body returns an io.Reader which reads out a JSON-encoded copy of the payload +// body returns an io.Reader which reads out a JSON-encoded copy of the payload // attached to a given *RequestSchema, if it is present. If no body is present // in the request, then nil is returned instead. // // If an error was encountered while attempting to marshal the body, then that // will be returned instead, along with a nil io.Reader. -func (l *HttpLifecycle) Body(schema *RequestSchema) (io.ReadCloser, error) { +func (l *HttpLifecycle) body(schema *RequestSchema) (io.ReadCloser, error) { if schema.Body == nil { return nil, nil } @@ -135,7 +145,10 @@ func (l *HttpLifecycle) Body(schema *RequestSchema) (io.ReadCloser, error) { return ioutil.NopCloser(bytes.NewReader(body)), nil } -func (l *HttpLifecycle) QueryParameters(schema *RequestSchema) url.Values { +// queryParameters returns a url.Values containing all of the provided query +// parameters as given in the *RequestSchema. If no query parameters were given, +// then an empty url.Values is returned instead. +func (l *HttpLifecycle) queryParameters(schema *RequestSchema) url.Values { vals := url.Values{} if schema.Query != nil { for k, v := range schema.Query {
api/http_lifecycle: make internal methods, add an ASK for @sinbad
git-lfs_git-lfs
train
dfe7a55c1032521c1c3817a10fd2c8e51b8b4cbd
diff --git a/RELEASE.rst b/RELEASE.rst index <HASH>..<HASH> 100644 --- a/RELEASE.rst +++ b/RELEASE.rst @@ -192,6 +192,8 @@ pandas 0.9.0 - Various fixes by upcasting of date -> datetime (#1395) - Raise better exception when passing multiple functions with the same name, such as lambdas, to GroupBy.aggregate + - Fix DataFrame.apply with axis=1 on a non-unique index (#1878) + - Proper handling of Index subclasses in pandas.unique (#1759) pandas 0.8.1 ============ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index <HASH>..<HASH> 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -856,6 +856,7 @@ class DataFrame(NDFrame): if (isinstance(index, basestring) or not hasattr(index, "__iter__")): result_index = sdict.pop(index) + result_index = Index(result_index, name=index) columns.remove(index) else: try: @@ -865,7 +866,7 @@ class DataFrame(NDFrame): for field in index: del sdict[field] columns.remove(field) - result_index = MultiIndex.from_arrays(arrays) + result_index = MultiIndex.from_arrays(arrays, names=index) except Exception: result_index = index elif isinstance(data, dict) and len(data) > 0: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index <HASH>..<HASH> 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -2448,6 +2448,22 @@ class TestDataFrame(unittest.TestCase, CheckIndexing, self.assertRaises(ValueError, DataFrame.from_records, [(1,2,3), (4,5,6)], columns=['a','b','a']) + def test_from_records_set_index_name(self): + def create_dict(order_id): + return {'order_id': order_id, 'quantity': np.random.randint(1, 10), + 'price': np.random.randint(1, 10)} + documents = [create_dict(i) for i in range(10)] + # demo missing data + documents.append({'order_id': 10, 'quantity': 5}) + + result = DataFrame.from_records(documents, index='order_id') + self.assert_(result.index.name == 'order_id') + + # MultiIndex + result = DataFrame.from_records(documents, + index=['order_id', 'quantity']) + self.assert_(result.index.names == ['order_id', 'quantity']) + def test_to_records_floats(self): df = DataFrame(np.random.rand(10,10)) df.to_records()
BUG: set index name/names in DataFrame.from_records. close #<I>
pandas-dev_pandas
train
c8be6cc65124773c28c83d3881e468e2c0ddd137
diff --git a/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java b/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java index <HASH>..<HASH> 100644 --- a/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java +++ b/aeron-archiver/src/test/java/io/aeron/archiver/ReplaySessionTest.java @@ -48,7 +48,7 @@ public class ReplaySessionTest private static final int MTU_LENGTH = 4096; private static final long TIME = 0; private static final int REPLAY_SESSION_ID = 0; - public static final int FRAME_LENGTH = 1024; + private static final int FRAME_LENGTH = 1024; private File archiveDir; private int messageCounter = 0;
[Java] constant should be private
real-logic_aeron
train
ba554d49c9aa5ecfa6d123e1b3baa3871926d98c
diff --git a/raiden/network/rpc/client.py b/raiden/network/rpc/client.py index <HASH>..<HASH> 100644 --- a/raiden/network/rpc/client.py +++ b/raiden/network/rpc/client.py @@ -252,7 +252,6 @@ class JSONRPCClient: if self.nonce_last_update > query_time: # Python's 2.7 time is not monotonic and it's affected by clock # resets, force an update. - self.nonce_update_interval = query_time - self.nonce_update_interval needs_update = True else: @@ -274,7 +273,7 @@ class JSONRPCClient: # we may have hammered the server and not all tx are # registered as `pending` yet if initialized: - while nonce < self.nonce_current_value: + while nonce <= self.nonce_current_value: log.debug( 'nonce on server too low; retrying', server=nonce,
bugfix: nonce queried from server Raiden must wait until all the sent transactions are registered as pending, therefor the condition should include the latest used nonce:: nonce <= self.nonce_current_value
raiden-network_raiden
train
3e9714a932a9e01d43fba89590ffb27a67c9612c
diff --git a/packages/ember-metal/lib/array.js b/packages/ember-metal/lib/array.js index <HASH>..<HASH> 100644 --- a/packages/ember-metal/lib/array.js +++ b/packages/ember-metal/lib/array.js @@ -70,6 +70,12 @@ var arrayIndexOf = isNativeFunc(Array.prototype.indexOf) ? Array.prototype.index return -1; }; +/** + Array polyfills to support ES5 features in older browsers. + + @namespace Ember + @property ArrayPolyfills +*/ Ember.ArrayPolyfills = { map: arrayMap, forEach: arrayForEach,
adding docs for Ember.ArrayPolyfills
emberjs_ember.js
train
6f15ac85df1ab1e3855c5066ab63ea8832171a93
diff --git a/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java b/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java index <HASH>..<HASH> 100644 --- a/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java +++ b/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java @@ -1064,6 +1064,9 @@ public abstract class RSBRemoteService<M extends GeneratedMessage> implements RS // only print message if not already gone to connecting ExceptionPrinter.printVerboseMessage("Remote connection to Controller[" + ScopeTransformer.transform(getScope()) + "] was detached because the controller shutdown was initiated.", logger); + + // reset transaction id because controller will start at 0 again after reconnect. + transactionId = 0; setConnectionState(CONNECTING); return dataUpdate; @@ -1170,8 +1173,10 @@ public abstract class RSBRemoteService<M extends GeneratedMessage> implements RS throw ex; } finally { long newTransactionId = (Long) getDataField(TransactionIdProvider.TRANSACTION_ID_FIELD_NAME); - if (newTransactionId < transactionId) { - logger.error("RemoteService {} received a data object with an older transaction id {} than {}", this, newTransactionId, transactionId); + + // warn if the transaction id is outdated, additionally the 0 transaction is accepted which is broadcast during the controller startup after. + if (newTransactionId < transactionId && transactionId != 0) { + logger.warn("RemoteService {} received a data object with an older transaction id {} than {}", this, newTransactionId, transactionId); } transactionId = newTransactionId; } @@ -1697,6 +1702,13 @@ public abstract class RSBRemoteService<M extends GeneratedMessage> implements RS long timeout = METHOD_CALL_START_TIMEOUT; while (true) { + + if (Thread.interrupted()) { + throw new InterruptedException(); + } + + Thread.yield(); + // if reconnecting wait until activated again if (getConnectionState() == ConnectionState.RECONNECTING) { waitForConnectionState(ConnectionState.CONNECTING); @@ -1748,7 +1760,7 @@ public abstract class RSBRemoteService<M extends GeneratedMessage> implements RS internalFuture = internalRequestStatus(); event = internalFuture.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); } catch (CouldNotPerformException ex) { - logger.warn("Something went wrong during data request, maybe the connection or activation state has just changed so all checks will be performed again...", ex); + ExceptionPrinter.printHistory("Something went wrong during data request, maybe the connection or activation state has just changed so all checks will be performed again...", ex, logger, LogLevel.WARN); continue; }
made sync task more nice and optimized logging, reset transaction id on reconnect.
openbase_jul
train
4fce18cfe0248072bd17b222cb33aabdf1f3731f
diff --git a/src/MarkerClusterGroup.js b/src/MarkerClusterGroup.js index <HASH>..<HASH> 100644 --- a/src/MarkerClusterGroup.js +++ b/src/MarkerClusterGroup.js @@ -527,7 +527,7 @@ L.MarkerClusterGroup = L.FeatureGroup.extend({ if (layer._icon && this._map.getBounds().contains(layer.getLatLng())) { //Layer is visible ond on screen, immediate return callback(); - } else if (layer.__parent._zoom < this._map.getZoom()) { + } else if (layer.__parent._zoom < Math.round(this._map._zoom)) { //Layer should be visible at this zoom level. It must not be on screen so just pan over to it this._map.on('moveend', showMarker, this); this._map.panTo(layer.getLatLng()); @@ -574,7 +574,7 @@ L.MarkerClusterGroup = L.FeatureGroup.extend({ this._needsRemoving = []; //Remember the current zoom level and bounds - this._zoom = this._map.getZoom(); + this._zoom = Math.round(this._map._zoom); this._currentShownBounds = this._getExpandedVisibleBounds(); this._map.on('zoomend', this._zoomEnd, this);
Added missing rounding to map._zoom and replaced map.getZoom() by map._zoom direct access for consistency.
Leaflet_Leaflet.markercluster
train
c143a7d30d569ede3d5204378ad66b96de785d1c
diff --git a/src/Models/Traits/SupportsCertificateCheck.php b/src/Models/Traits/SupportsCertificateCheck.php index <HASH>..<HASH> 100644 --- a/src/Models/Traits/SupportsCertificateCheck.php +++ b/src/Models/Traits/SupportsCertificateCheck.php @@ -9,7 +9,6 @@ use Spatie\UptimeMonitor\Events\CertificateCheckFailed; use Spatie\UptimeMonitor\Events\CertificateExpiresSoon; use Spatie\UptimeMonitor\Models\Enums\CertificateStatus; use Spatie\UptimeMonitor\Events\CertificateCheckSucceeded; -use Spatie\SslCertificate\Exceptions\CouldNotDownloadCertificate; trait SupportsCertificateCheck { @@ -19,7 +18,7 @@ trait SupportsCertificateCheck $certificate = SslCertificate::createForHostName($this->url->getHost()); $this->setCertificate($certificate); - } catch (CouldNotDownloadCertificate $exception) { + } catch (Exception $exception) { $this->setCertificateException($exception); } } diff --git a/tests/Integration/Commands/DisableMonitorCommandTest.php b/tests/Integration/Commands/DisableMonitorCommandTest.php index <HASH>..<HASH> 100644 --- a/tests/Integration/Commands/DisableMonitorCommandTest.php +++ b/tests/Integration/Commands/DisableMonitorCommandTest.php @@ -2,6 +2,7 @@ namespace Spatie\UptimeMonitor\Test\Integration\Commands; +use Artisan; use Spatie\UptimeMonitor\Test\TestCase; use Spatie\UptimeMonitor\Models\Monitor; @@ -25,7 +26,7 @@ class DisableMonitorCommandTest extends TestCase /** @test */ public function it_displays_a_message_if_the_monitor_is_not_found() { - $this->artisan('monitor:disable', ['url' => 'http://mysite.com']); + Artisan::call('monitor:disable', ['url' => 'https://mysite.com']); $this->seeInConsoleOutput('There is no monitor configured for url'); } diff --git a/tests/Integration/Commands/EnableMonitorCommandTest.php b/tests/Integration/Commands/EnableMonitorCommandTest.php index <HASH>..<HASH> 100644 --- a/tests/Integration/Commands/EnableMonitorCommandTest.php +++ b/tests/Integration/Commands/EnableMonitorCommandTest.php @@ -2,6 +2,7 @@ namespace Spatie\UptimeMonitor\Test\Integration\Commands; +use Artisan; use Spatie\UptimeMonitor\Test\TestCase; use Spatie\UptimeMonitor\Models\Monitor; @@ -48,7 +49,7 @@ class EnableMonitorCommandTest extends TestCase /** @test */ public function it_displays_a_message_if_the_monitor_is_not_found() { - $this->artisan('monitor:enable', ['url' => 'https://mysite.com']); + Artisan::call('monitor:enable', ['url' => 'https://mysite.com']); $this->seeInConsoleOutput('There is no monitor configured for url'); }
Fix: "SSL check fails if an invalid domain is detected" (#<I>) * Catch any exception on checkCertificate() * remove unused import * [OT] tests fail on php <I>/<I> - as mentioned here: <URL>
spatie_laravel-uptime-monitor
train
b231530f9de127c58c2b010f92fd2c7763cd3b49
diff --git a/src/geo/cartodb-layer-group-base.js b/src/geo/cartodb-layer-group-base.js index <HASH>..<HASH> 100644 --- a/src/geo/cartodb-layer-group-base.js +++ b/src/geo/cartodb-layer-group-base.js @@ -17,22 +17,14 @@ var CartoDBLayerGroupBase = Backbone.Model.extend({ this.layers = new Backbone.Collection(options.layers || []); - this._layersCollection.bind('reset', function () { - var cartoDBLayers = this._layersCollection.select(function (layerModel) { return layerModel.get('type') === 'CartoDB'; }); - this.layers.reset(cartoDBLayers); - }, this); - - this._layersCollection.bind('add', function (layerModel) { - if (layerModel.get('type') === 'CartoDB') { - this.layers.add(layerModel); - } - }, this); + this._layersCollection.bind('reset', this._resetLayers, this); + this._layersCollection.bind('add', this._resetLayers, this); + this._layersCollection.bind('remove', this._resetLayers, this); + }, - this._layersCollection.bind('remove', function (layerModel) { - if (layerModel.get('type') === 'CartoDB') { - this.layers.remove(layerModel); - } - }, this); + _resetLayers: function () { + var cartoDBLayers = this._layersCollection.getCartoDBLayers(); + this.layers.reset(cartoDBLayers); }, getIndexOf: function (layerModel) { diff --git a/src/geo/map/layers.js b/src/geo/map/layers.js index <HASH>..<HASH> 100644 --- a/src/geo/map/layers.js +++ b/src/geo/map/layers.js @@ -51,6 +51,24 @@ var Layers = Backbone.Collection.extend({ } this.sort(); + }, + + getCartoDBLayers: function () { + return this._getLayersByType(CARTODB_LAYER_TYPE); + }, + + getTiledLayers: function () { + return this._getLayersByType(TILED_LAYER_TYPE); + }, + + getTorqueLayers: function () { + return this._getLayersByType(TORQUE_LAYER_TYPE); + }, + + _getLayersByType: function (layerType) { + return this.select(function (layerModel) { + return layerModel.get('type') === layerType; + }); } }); diff --git a/test/spec/geo/cartodb-layer-group-anonymous-map.spec.js b/test/spec/geo/cartodb-layer-group-anonymous-map.spec.js index <HASH>..<HASH> 100644 --- a/test/spec/geo/cartodb-layer-group-anonymous-map.spec.js +++ b/test/spec/geo/cartodb-layer-group-anonymous-map.spec.js @@ -1,11 +1,11 @@ var $ = require('jquery'); -var Backbone = require('backbone'); +var Layers = require('../../../src/geo/map/layers'); var CartoDBLayer = require('../../../src/geo/map/cartodb-layer'); var CartoDBLayerGroupAnonymousMap = require('../../../src/geo/cartodb-layer-group-anonymous-map'); describe('geo/layer-group-anonymous-map', function () { beforeEach(function () { - this.layersCollection = new Backbone.Collection(); + this.layersCollection = new Layers(); }); // TODO: This test is a bit useless diff --git a/test/spec/geo/cartodb-layer-group-base.spec.js b/test/spec/geo/cartodb-layer-group-base.spec.js index <HASH>..<HASH> 100644 --- a/test/spec/geo/cartodb-layer-group-base.spec.js +++ b/test/spec/geo/cartodb-layer-group-base.spec.js @@ -1,6 +1,7 @@ var $ = require('jquery'); var Backbone = require('backbone'); var CartoDBLayer = require('../../../src/geo/map/cartodb-layer'); +var Layers = require('../../../src/geo/map/layers'); var CartoDBLayerGroupBase = require('../../../src/geo/cartodb-layer-group-base'); var MyCartoDBLayerGroup = CartoDBLayerGroupBase.extend({ @@ -9,7 +10,7 @@ var MyCartoDBLayerGroup = CartoDBLayerGroupBase.extend({ describe('geo/cartodb-layer-group-base', function () { beforeEach(function () { - this.layersCollection = new Backbone.Collection(); + this.layersCollection = new Layers(); }); describe('internal collection of CartoDB layers', function () { diff --git a/test/spec/geo/cartodb-layer-group-named-map.spec.js b/test/spec/geo/cartodb-layer-group-named-map.spec.js index <HASH>..<HASH> 100644 --- a/test/spec/geo/cartodb-layer-group-named-map.spec.js +++ b/test/spec/geo/cartodb-layer-group-named-map.spec.js @@ -1,11 +1,11 @@ var $ = require('jquery'); -var Backbone = require('backbone'); +var Layers = require('../../../src/geo/map/layers'); var CartoDBLayer = require('../../../src/geo/map/cartodb-layer'); var CartoDBLayerGroupNamed = require('../../../src/geo/cartodb-layer-group-named-map'); describe('geo/cartodb-layer-group-named-map', function () { beforeEach(function () { - this.layersCollection = new Backbone.Collection(); + this.layersCollection = new Layers(); }); // TODO: This test is a bit useless
Reset internal collection of CartoDB layers when layers change (to keep them in the right order).
CartoDB_carto.js
train
b096e548775093ee35e56887a2c641af752e4644
diff --git a/lib/nuggets/cli.rb b/lib/nuggets/cli.rb index <HASH>..<HASH> 100644 --- a/lib/nuggets/cli.rb +++ b/lib/nuggets/cli.rb @@ -25,10 +25,10 @@ ############################################################################### #++ +require 'safe_yaml/load' require 'optparse' -require 'yaml' -require 'zlib' require 'highline' +require 'zlib' module Nuggets class CLI @@ -188,7 +188,7 @@ module Nuggets return unless file if ::File.readable?(file) - @config = ::YAML.load_file(file) + @config = ::SafeYAML.load_file(file, :deserialize_symbols => true) else quit "No such file: #{file}" unless default end
lib/nuggets/cli.rb (load_config): Use SafeYAML.
blackwinter_nuggets
train
52ed790560419874ea3bca7063cc4919624c444e
diff --git a/alerta/webhooks/custom.py b/alerta/webhooks/custom.py index <HASH>..<HASH> 100644 --- a/alerta/webhooks/custom.py +++ b/alerta/webhooks/custom.py @@ -16,7 +16,7 @@ def custom(webhook): try: incomingAlert = custom_webhooks.webhooks[webhook].incoming( query_string=request.args, - payload=request.get_json() or request.get_data(as_text=True) or request.values + payload=request.get_json() or request.get_data(as_text=True) or request.form ) except ValueError as e: raise ApiError(str(e), 400) diff --git a/tests/test_webhooks.py b/tests/test_webhooks.py index <HASH>..<HASH> 100644 --- a/tests/test_webhooks.py +++ b/tests/test_webhooks.py @@ -1,9 +1,12 @@ import json import unittest +from io import BytesIO from uuid import uuid4 -from alerta.app import create_app, db +from alerta.app import create_app, db, custom_webhooks +from alerta.models.alert import Alert +from alerta.webhooks import WebhookBase class WebhooksTestCase(unittest.TestCase): @@ -17,6 +20,7 @@ class WebhooksTestCase(unittest.TestCase): self.app = create_app(test_config) self.client = self.app.test_client() + # alert templates self.trigger_alert = { 'event': 'node_down', 'resource': str(uuid4()).upper()[:8], @@ -691,3 +695,87 @@ class WebhooksTestCase(unittest.TestCase): # graylog alert response = self.client.post('/webhooks/graylog', data=self.graylog_notification, headers=self.headers) self.assertEqual(response.status_code, 201) + + def test_custom_webhook(self): + + # setup custom webhook + custom_webhooks.webhooks['json'] = TestJsonWebhook() + custom_webhooks.webhooks['text'] = TestTextWebhook() + custom_webhooks.webhooks['form'] = TestFormWebhook() + custom_webhooks.webhooks['multipart'] = TestMultiPartFormWebhook() + + # test json payload + response = self.client.post('/webhooks/json?foo=bar', json={'baz': 'quux'}, content_type='application/json') + self.assertEqual(response.status_code, 201) + data = json.loads(response.data.decode('utf-8')) + self.assertEqual(data['alert']['resource'], 'bar') + self.assertEqual(data['alert']['event'], 'quux') + + # test text data + response = self.client.post('/webhooks/text?foo', data='this is raw data', content_type='text/plain') + self.assertEqual(response.status_code, 201) + data = json.loads(response.data.decode('utf-8')) + self.assertEqual(data['alert']['resource'], 'nofoo') + self.assertEqual(data['alert']['event'], 'this is raw data') + + # test form data + response = self.client.post('/webhooks/form?foo=1', data='say=Hi&to=Mom', content_type='application/x-www-form-urlencoded') + self.assertEqual(response.status_code, 201) + data = json.loads(response.data.decode('utf-8')) + self.assertEqual(data['alert']['resource'], '1') + self.assertEqual(data['alert']['event'], 'Say Hi to Mom', response.data) + + # test multipart form data + form_data1 = dict( + field1='value1', + file1=(BytesIO(b'my file contents'), "file1.txt"), + ) + response = self.client.post('/webhooks/multipart?foo=1', data=form_data1, content_type='multipart/form-data;boundary="boundary"') + self.assertEqual(response.status_code, 201) + data = json.loads(response.data.decode('utf-8')) + self.assertEqual(data['alert']['resource'], '1') + self.assertEqual(data['alert']['event'], 'value1') + + +class TestJsonWebhook(WebhookBase): + + def incoming(self, query_string, payload): + return Alert( + resource=query_string['foo'], + event=payload['baz'], + environment='Production', + service=['Foo'] + ) + + +class TestTextWebhook(WebhookBase): + + def incoming(self, query_string, payload): + return Alert( + resource=query_string.get('foo') or 'nofoo', + event=payload, + environment='Production', + service=['Foo'] + ) + + +class TestFormWebhook(WebhookBase): + + def incoming(self, query_string, payload): + return Alert( + resource=query_string['foo'], + event='Say {} to {}'.format(payload['say'], payload['to']), + environment='Production', + service=['Foo'] + ) + + +class TestMultiPartFormWebhook(WebhookBase): + + def incoming(self, query_string, payload): + return Alert( + resource=query_string['foo'], + event=payload['field1'], + environment='Production', + service=['Foo'] + )
Use 'request.form' method instead of 'request.values' to simplify returned data structure (#<I>)
alerta_alerta
train