hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
5a949e0596de194bcc84b22e01f65801a4962c02
|
diff --git a/bosh-director/spec/unit/deployment_plan/manual_network_spec.rb b/bosh-director/spec/unit/deployment_plan/manual_network_spec.rb
index <HASH>..<HASH> 100644
--- a/bosh-director/spec/unit/deployment_plan/manual_network_spec.rb
+++ b/bosh-director/spec/unit/deployment_plan/manual_network_spec.rb
@@ -107,7 +107,17 @@ describe Bosh::Director::DeploymentPlan::ManualNetwork do
'reserved' => [],
'cloud_properties' => {},
'availability_zone' => 'az-2',
+ },
+ {
+ 'range' => '192.168.3.0/30',
+ 'gateway' => '192.168.3.1',
+ 'dns' => ['192.168.3.1', '192.168.3.2'],
+ 'static' => [],
+ 'reserved' => [],
+ 'cloud_properties' => {},
+ 'availability_zone' => 'az-2',
}
+
]
}
}
@@ -140,11 +150,19 @@ describe Bosh::Director::DeploymentPlan::ManualNetwork do
expect(NetAddr::CIDR.create(reservation.ip).to_s).to eq('192.168.1.2/32')
end
- context 'when failing to allocate dynamic IP' do
+ it 'allocates dynamic IPs across multiple subnets for a single AZ' do
+ allow(instance).to receive(:availability_zone).and_return(BD::DeploymentPlan::AvailabilityZone.new('az-2', {}))
+ manual_network.reserve(BD::DynamicNetworkReservation.new(instance, manual_network))
+
+ manual_network.reserve(reservation)
+ expect(NetAddr::CIDR.create(reservation.ip).to_s).to eq('192.168.3.2/32')
+ end
+
+ context 'when no subnet has enough capacity to allocate a dynamic IP' do
it 'raises NetworkReservationNotEnoughCapacity' do
allow(instance).to receive(:availability_zone).and_return(nil)
- manual_network.reserve(BD::DynamicNetworkReservation.new(instance, manual_network))
- manual_network.reserve(BD::DynamicNetworkReservation.new(instance, manual_network)) # reserve last ip
+ # Trying to reserve 1 more IP than the available
+ 3.times {manual_network.reserve(BD::DynamicNetworkReservation.new(instance, manual_network))}
expect {
manual_network.reserve(reservation)
|
Add explicit test coverage for overflowing subnet ranges within an AZ
[#<I>](<URL>)
|
cloudfoundry_bosh
|
train
|
d485493baf1bf4910879d7ddb1ce564156284f5e
|
diff --git a/lib/dynode/request.js b/lib/dynode/request.js
index <HASH>..<HASH> 100644
--- a/lib/dynode/request.js
+++ b/lib/dynode/request.js
@@ -25,7 +25,8 @@ Request.prototype.send = function(action, messageBody, cb) {
"x-amz-date" : new Date().toGMTString(),
"x-amz-security-token" : credentials.sessionToken,
"x-amz-target" : self.config.prefix + action,
- "content-type" : "application/x-amz-json-1.0"
+ "content-type" : "application/x-amz-json-1.0",
+ "Connection" : "Keep-Alive"
};
var opts = {
|
adding a connection keep alive to reduce latency
|
Wantworthy_dynode
|
train
|
44763c5afed050fc61f9d9c01498c806cacb89c3
|
diff --git a/src/Storefront/Controller/CmsController.php b/src/Storefront/Controller/CmsController.php
index <HASH>..<HASH> 100644
--- a/src/Storefront/Controller/CmsController.php
+++ b/src/Storefront/Controller/CmsController.php
@@ -52,7 +52,7 @@ class CmsController extends StorefrontController
* Route for cms data (used in XmlHttpRequest)
*
* @HttpCache()
- * @Route("/widgets/cms/{id}", name="frontend.cms.page", methods={"GET", "POST"}, defaults={"id"=null, "XmlHttpRequest"=true})
+ * @Route("/widgets/cms/{id}", name="frontend.cms.page", methods={"GET", "POST"}, defaults={"XmlHttpRequest"=true})
*
* @throws InconsistentCriteriaIdsException
* @throws MissingRequestParameterException
@@ -60,10 +60,6 @@ class CmsController extends StorefrontController
*/
public function page(string $id, Request $request, SalesChannelContext $salesChannelContext): Response
{
- if (!$id) {
- throw new MissingRequestParameterException('Parameter id missing');
- }
-
$cmsPage = $this->cmsRoute->load($id, $request, $salesChannelContext)->getCmsPage();
return $this->renderStorefront('@Storefront/storefront/page/content/detail.html.twig', ['cmsPage' => $cmsPage]);
@@ -73,7 +69,7 @@ class CmsController extends StorefrontController
* Route to load a cms page which assigned to the provided navigation id.
* Navigation id is required to load the slot config for the navigation
*
- * @Route("/widgets/cms/navigation/{navigationId}", name="frontend.cms.navigation.page", methods={"GET", "POST"}, defaults={"navigationId"=null, "XmlHttpRequest"=true})
+ * @Route("/widgets/cms/navigation/{navigationId}", name="frontend.cms.navigation.page", methods={"GET", "POST"}, defaults={"XmlHttpRequest"=true})
*
* @throws CategoryNotFoundException
* @throws MissingRequestParameterException
@@ -82,10 +78,6 @@ class CmsController extends StorefrontController
*/
public function category(string $navigationId, Request $request, SalesChannelContext $salesChannelContext): Response
{
- if (!$navigationId) {
- throw new MissingRequestParameterException('Parameter navigationId missing');
- }
-
$category = $this->categoryRoute->load($navigationId, $request, $salesChannelContext)->getCategory();
if (!$category->getCmsPageId()) {
|
NEXT-<I> - Amend route default to match attributed methods
Fixes #<I>
|
shopware_platform
|
train
|
4d0d0fffc720967585b63a732caa35bdc03d8f79
|
diff --git a/src/python_pachyderm/spout.py b/src/python_pachyderm/spout.py
index <HASH>..<HASH> 100644
--- a/src/python_pachyderm/spout.py
+++ b/src/python_pachyderm/spout.py
@@ -1,4 +1,5 @@
import io
+import os
import tarfile
import contextlib
@@ -16,16 +17,26 @@ class SpoutManager:
```
"""
- def __init__(self, marker_filename=None):
+ def __init__(self, marker_filename=None, pfs_directory="/pfs"):
"""
Creates a new spout manager.
+
+ Params:
+
+ * `marker_filename`: The name of the file for storing markers. If
+ unspecified, marker-related operations will fail.
+ * `pfs_directory`: The directory for PFS content. Usually this
+ shouldn't be explicitly specified, unless the spout manager is being
+ tested outside of a real Pachyderm pipeline.
"""
self.f = None
self.marker_filename = marker_filename
+ self.pfs_directory = pfs_directory
def __enter__(self):
- self.f = tarfile.open(fileobj=open("/pfs/out", "wb"), mode="w|", encoding="utf-8")
+ f = open(os.path.join(self.pfs_directory, "out"), "wb")
+ self.f = tarfile.open(fileobj=f, mode="w|", encoding="utf-8")
return self
def __exit__(self, type, value, traceback):
@@ -39,7 +50,7 @@ class SpoutManager:
if self.marker_filename is None:
raise Exception("no marker filename set")
- with open("/pfs/{}".format(self.marker_filename), "r") as f:
+ with open(os.path.join(self.pfs_directory, self.marker_filename), "r") as f:
yield f
def add_from_fileobj(self, path, size, fileobj):
|
Customize output directory in spout managers
|
pachyderm_python-pachyderm
|
train
|
28f917eabb0ebfe29cf7efd082720d1a4bbaa0db
|
diff --git a/lib/generators/double_entry/install/templates/migration.rb b/lib/generators/double_entry/install/templates/migration.rb
index <HASH>..<HASH> 100644
--- a/lib/generators/double_entry/install/templates/migration.rb
+++ b/lib/generators/double_entry/install/templates/migration.rb
@@ -16,9 +16,10 @@ class CreateDoubleEntryTables < ActiveRecord::Migration<%= migration_version %>
t.string "code", :null => false
t.integer "amount", :null => false
t.integer "balance", :null => false
- t.integer "partner_id"
+ t.references "partner", :index => false
t.string "partner_account", :null => false
t.string "partner_scope"
+ t.references "detail", :index => false, :polymorphic => true
t.integer "detail_id"
t.string "detail_type"
t.timestamps :null => false
@@ -48,7 +49,7 @@ class CreateDoubleEntryTables < ActiveRecord::Migration<%= migration_version %>
add_index "double_entry_line_aggregates", ["function", "account", "code", "year", "month", "week", "day"], :name => "line_aggregate_idx"
create_table "double_entry_line_checks", :force => true do |t|
- t.integer "last_line_id", :null => false
+ t.references "last_line", :null => false, :index => false
t.boolean "errors_found", :null => false
t.text "log"
t.timestamps :null => false
@@ -57,7 +58,7 @@ class CreateDoubleEntryTables < ActiveRecord::Migration<%= migration_version %>
add_index "double_entry_line_checks", ["created_at", "last_line_id"], :name => "line_checks_created_at_last_line_id_idx"
create_table "double_entry_line_metadata", :force => true do |t|
- t.integer "line_id", :null => false
+ t.references "line", :null => false, :index => false
t.string "key", :null => false
t.string "value", :null => false
t.timestamps :null => false
diff --git a/spec/support/schema.rb b/spec/support/schema.rb
index <HASH>..<HASH> 100644
--- a/spec/support/schema.rb
+++ b/spec/support/schema.rb
@@ -17,11 +17,10 @@ ActiveRecord::Schema.define do
t.string "code", :null => false
t.integer "amount", :null => false
t.integer "balance", :null => false
- t.integer "partner_id"
+ t.references "partner", :index => false
t.string "partner_account", :null => false
t.string "partner_scope"
- t.integer "detail_id"
- t.string "detail_type"
+ t.references "detail", :index => false, :polymorphic => true
t.timestamps :null => false
end
@@ -50,7 +49,7 @@ ActiveRecord::Schema.define do
add_index "double_entry_line_aggregates", ["function", "account", "code", "partner_account", "year", "month", "week", "day"], :name => "line_aggregate_idx"
create_table "double_entry_line_checks", :force => true do |t|
- t.integer "last_line_id", :null => false
+ t.references "last_line", :null => false, :index => false
t.boolean "errors_found", :null => false
t.text "log"
t.timestamps :null => false
@@ -59,7 +58,7 @@ ActiveRecord::Schema.define do
add_index "double_entry_line_checks", ["created_at", "last_line_id"], :name => "line_checks_created_at_last_line_id_idx"
create_table "double_entry_line_metadata", :force => true do |t|
- t.integer "line_id", :null => false
+ t.references "line", :null => false, :index => false
t.string "key", :null => false
t.string "value", :null => false
t.timestamps :null => false
|
Use `references` to use Rails default id column type
In Rails <I> the default type for row ids changed from integer to
bigint.
|
envato_double_entry
|
train
|
e0b126d7c1daefea52b71c73f2fb247a5f8f00dc
|
diff --git a/test/SavedSearches/Command/SubscribeToSavedSearchJSONDeserializerTest.php b/test/SavedSearches/Command/SubscribeToSavedSearchJSONDeserializerTest.php
index <HASH>..<HASH> 100644
--- a/test/SavedSearches/Command/SubscribeToSavedSearchJSONDeserializerTest.php
+++ b/test/SavedSearches/Command/SubscribeToSavedSearchJSONDeserializerTest.php
@@ -8,7 +8,8 @@ namespace CultuurNet\UDB3\SavedSearches\Command;
use CultuurNet\Deserializer\MissingValueException;
use ValueObjects\String\String;
-class SubscribeToSavedSearchJSONDeserializerTest extends \PHPUnit_Framework_TestCase {
+class SubscribeToSavedSearchJSONDeserializerTest extends \PHPUnit_Framework_TestCase
+{
/**
* @var string
|
III-7: Fix coding standard violation
|
cultuurnet_udb3-php
|
train
|
55076a9350ab7986b5fae2a0c0f8761db0399b73
|
diff --git a/python/run_xmpp.py b/python/run_xmpp.py
index <HASH>..<HASH> 100755
--- a/python/run_xmpp.py
+++ b/python/run_xmpp.py
@@ -49,7 +49,8 @@ import logging
# ------------------------------------------------------------------------------
-def main(xmpp_server, xmpp_port, peer_name, node_name, app_id):
+def main(xmpp_server, xmpp_port, peer_name, node_name, app_id,
+ xmpp_jid=None, xmpp_password=None):
"""
Runs the framework
@@ -58,6 +59,8 @@ def main(xmpp_server, xmpp_port, peer_name, node_name, app_id):
:param peer_name: Name of the peer
:param node_name: Name (also, UID) of the node hosting the peer
:param app_id: Application ID
+ :param xmpp_jid: XMPP JID, None for Anonymous login
+ :param xmpp_password: XMPP account password
"""
# Create the framework
framework = pelix.framework.create_framework(
@@ -96,7 +99,9 @@ def main(xmpp_server, xmpp_port, peer_name, node_name, app_id):
ipopo.add(herald.transports.xmpp.FACTORY_TRANSPORT,
"herald-xmpp-transport",
{herald.transports.xmpp.PROP_XMPP_SERVER: xmpp_server,
- herald.transports.xmpp.PROP_XMPP_PORT: xmpp_port})
+ herald.transports.xmpp.PROP_XMPP_PORT: xmpp_port,
+ herald.transports.xmpp.PROP_XMPP_JID: xmpp_jid,
+ herald.transports.xmpp.PROP_XMPP_PASSWORD: xmpp_password})
# Start the framework and wait for it to stop
framework.wait_for_stop()
@@ -115,6 +120,12 @@ if __name__ == "__main__":
group.add_argument("-p", "--port", action="store", type=int, default=5222,
dest="xmpp_port", help="Port of the XMPP server")
+ # XMPP login
+ group.add_argument("-j", "--jid", action="store", default=None,
+ dest="xmpp_jid", help="JID to login with")
+ group.add_argument("--password", action="store", default=None,
+ dest="xmpp_password", help="Password for authentication")
+
# Peer info
group = parser.add_argument_group("Peer Configuration",
"Identity of the Peer")
@@ -130,8 +141,9 @@ if __name__ == "__main__":
args = parser.parse_args()
# Configure the logging package
- logging.basicConfig(level=logging.INFO)
+ logging.basicConfig(level=logging.DEBUG)
logging.getLogger('herald').setLevel(logging.DEBUG)
# Run the framework
- main(args.xmpp_server, args.xmpp_port, args.name, args.node, args.app_id)
+ main(args.xmpp_server, args.xmpp_port, args.name, args.node, args.app_id,
+ args.xmpp_jid, args.xmpp_password)
|
run_xmpp.py can be given a JID and a password
|
cohorte_cohorte-herald
|
train
|
43d96bfb8bdde8c588e9a659652d5acd93cb84bf
|
diff --git a/mopidy_musicbox_webclient/static/js/functionsvars.js b/mopidy_musicbox_webclient/static/js/functionsvars.js
index <HASH>..<HASH> 100644
--- a/mopidy_musicbox_webclient/static/js/functionsvars.js
+++ b/mopidy_musicbox_webclient/static/js/functionsvars.js
@@ -402,8 +402,8 @@ function getPlaylistTracks (uri) {
return Mopidy.when(playlists[uri].tracks)
} else {
showLoading(true)
- return mopidy.playlists.getItems({'uri': uri}).then(function (refs) {
- return processPlaylistItems({'uri': uri, 'items': refs})
+ return mopidy.playlists.lookup({'uri': uri}).then(function (playlist) {
+ return processPlaylistItems({'uri': uri, 'playlist': playlist})
}, console.error)
}
}
diff --git a/mopidy_musicbox_webclient/static/js/process_ws.js b/mopidy_musicbox_webclient/static/js/process_ws.js
index <HASH>..<HASH> 100644
--- a/mopidy_musicbox_webclient/static/js/process_ws.js
+++ b/mopidy_musicbox_webclient/static/js/process_ws.js
@@ -180,27 +180,36 @@ function processGetPlaylists (resultArr) {
* process results of a returned list of playlist track refs
*********************************************************/
function processPlaylistItems (resultDict) {
- if (resultDict.items.length === 0) {
- console.log('Playlist', resultDict.uri, 'is empty')
+ var playlist = resultDict.playlist
+ if (!playlist || playlist === '') {
+ console.log('Playlist', resultDict.uri, 'is invalid')
showLoading(false)
return
}
- var trackUris = []
- for (i = 0; i < resultDict.items.length; i++) {
- trackUris.push(resultDict.items[i].uri)
- }
- return mopidy.library.lookup({'uris': trackUris}).then(function (tracks) {
- // Transform from dict to list and cache result
- var newplaylisturi = resultDict.uri
- var track
- playlists[newplaylisturi] = {'uri': newplaylisturi, 'tracks': []}
- for (i = 0; i < trackUris.length; i++) {
- track = tracks[trackUris[i]][0] || resultDict.items[i] // Fall back to using track Ref if lookup failed.
- playlists[newplaylisturi].tracks.push(track)
+ var playlistUri = resultDict.uri
+ playlists[playlistUri] = {'uri': playlistUri, 'tracks': []}
+ if (playlistUri.startsWith('m3u')) {
+ console.log('Playlist', playlistUri, 'requires tracks lookup')
+ var trackUris = []
+ for (i = 0; i < playlist.tracks.length; i++) {
+ trackUris.push(playlist.tracks[i].uri)
+ }
+ return mopidy.library.lookup({'uris': trackUris}).then(function (tracks) {
+ for (i = 0; i < trackUris.length; i++) {
+ var track = tracks[trackUris[i]][0] || playlist.tracks[i] // Fall back to using track Ref if lookup failed.
+ playlists[playlistUri].tracks.push(track)
+ }
+ showLoading(false)
+ return playlists[playlistUri].tracks
+ })
+ } else {
+ for (i = 0; i < playlist.tracks.length; i++) {
+ var track = playlist.tracks[i]
+ playlists[playlistUri].tracks.push(track)
}
showLoading(false)
- return playlists[newplaylisturi].tracks
- })
+ return playlists[playlistUri].tracks
+ }
}
/** ******************************************************
|
Use playlists.lookup where possible.
Fallback to mass track lookups only for m3u playlists. This is much faster.
|
pimusicbox_mopidy-musicbox-webclient
|
train
|
2241213f6677eef9a2c0dd7d90ac0f4fd7d6acd5
|
diff --git a/lib/mongoid/reloading.rb b/lib/mongoid/reloading.rb
index <HASH>..<HASH> 100644
--- a/lib/mongoid/reloading.rb
+++ b/lib/mongoid/reloading.rb
@@ -54,7 +54,7 @@ module Mongoid
#
# @since 2.3.2
def reload_root_document
- {}.merge(collection.find(_id: id).one || {})
+ {}.merge(with(consistency: :strong).collection.find(_id: id).one || {})
end
# Reload the embedded document.
@@ -67,7 +67,7 @@ module Mongoid
# @since 2.3.2
def reload_embedded_document
extract_embedded_attributes({}.merge(
- _root.collection.find(_id: _root.id).one
+ _root.with(consistency: :strong).collection.find(_id: _root.id).one
))
end
|
Perform reloads with strong consistency
|
mongodb_mongoid
|
train
|
201919abaeb40ed80f7a47a41fb7380dc25167a4
|
diff --git a/test/performance/base/PerfTimer.java b/test/performance/base/PerfTimer.java
index <HASH>..<HASH> 100644
--- a/test/performance/base/PerfTimer.java
+++ b/test/performance/base/PerfTimer.java
@@ -1,6 +1,6 @@
/*
Calimero 2 - A library for KNX network access
- Copyright (c) 2006, 2011 B. Malinowsky
+ Copyright (c) 2006, 2017 B. Malinowsky
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -59,7 +59,7 @@ public class PerfTimer
*/
public void start()
{
- start.add(new Long(System.currentTimeMillis()));
+ start.add(System.currentTimeMillis());
}
/**
@@ -67,7 +67,7 @@ public class PerfTimer
*/
public void stop()
{
- stop.add(new Long(System.currentTimeMillis()));
+ stop.add(System.currentTimeMillis());
}
/**
@@ -93,7 +93,7 @@ public class PerfTimer
final List<Integer> buf = new ArrayList<>();
final int size = Math.min(start.size(), stop.size());
for (int i = 0; i < size; ++i)
- buf.add(new Integer((int) (stop.get(i).longValue() - start.get(i).longValue())));
+ buf.add((int) (stop.get(i).longValue() - start.get(i).longValue()));
for (int i = 0; i < omitExtremes; ++i)
if (i % 2 == 0)
buf.remove(Collections.max(buf));
diff --git a/test/tuwien/auto/calimero/buffer/cache/performance/QueueTest.java b/test/tuwien/auto/calimero/buffer/cache/performance/QueueTest.java
index <HASH>..<HASH> 100644
--- a/test/tuwien/auto/calimero/buffer/cache/performance/QueueTest.java
+++ b/test/tuwien/auto/calimero/buffer/cache/performance/QueueTest.java
@@ -1,6 +1,6 @@
/*
Calimero 2 - A library for KNX network access
- Copyright (c) 2006, 2011 B. Malinowsky
+ Copyright (c) 2006, 2017 B. Malinowsky
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -133,7 +133,7 @@ public class QueueTest extends PerfTestCase
listFilled = new ArrayList<>(capacity);
for (int i = 0; i < capacity; ++i) {
primitiveFilled.add(System.currentTimeMillis());
- listFilled.add(new Long(System.currentTimeMillis()));
+ listFilled.add(System.currentTimeMillis());
}
}
@@ -167,10 +167,10 @@ public class QueueTest extends PerfTestCase
public void testArrayListSet()
{
for (int i = 0; i < capacity; ++i)
- list.add(new Long(System.currentTimeMillis()));
+ list.add(System.currentTimeMillis());
for (int i = capacity; i < iterations; ++i) {
- final Long time = new Long(System.currentTimeMillis());
+ final Long time = System.currentTimeMillis();
list.set(i % capacity, time);
list.set(i % capacity, time);
list.set(i % capacity, time);
diff --git a/test/tuwien/auto/calimero/dptxlator/PropertyTypesTest.java b/test/tuwien/auto/calimero/dptxlator/PropertyTypesTest.java
index <HASH>..<HASH> 100644
--- a/test/tuwien/auto/calimero/dptxlator/PropertyTypesTest.java
+++ b/test/tuwien/auto/calimero/dptxlator/PropertyTypesTest.java
@@ -73,8 +73,8 @@ public class PropertyTypesTest extends TestCase
public final void testGetAllPropertyTypes()
{
final Map<Integer, DPTID> m = PropertyTypes.getAllPropertyTypes();
- m.put(new Integer(1000), new DPTID(1000, "1000.001"));
- m.remove(new Integer(1000));
+ m.put(1000, new DPTID(1000, "1000.001"));
+ m.remove(Integer.valueOf(1000));
for (final Iterator<Integer> i = m.keySet().iterator(); i.hasNext();) {
final Integer type = i.next();
assertTrue(type > 0);
diff --git a/test/tuwien/auto/calimero/dptxlator/TranslatorTypesTest.java b/test/tuwien/auto/calimero/dptxlator/TranslatorTypesTest.java
index <HASH>..<HASH> 100644
--- a/test/tuwien/auto/calimero/dptxlator/TranslatorTypesTest.java
+++ b/test/tuwien/auto/calimero/dptxlator/TranslatorTypesTest.java
@@ -82,7 +82,7 @@ public class TranslatorTypesTest extends TestCase
{
for (int i = 0; i < 100; ++i) {
if (TranslatorTypes.getMainType(i) == null
- && TranslatorTypes.getAllMainTypes().containsKey(new Integer(i)))
+ && TranslatorTypes.getAllMainTypes().containsKey(Integer.valueOf(i)))
fail("not found but in type list");
}
@@ -130,7 +130,7 @@ public class TranslatorTypesTest extends TestCase
//newMainTypeFail(2000, Object.class);
newMainTypeFail(2000, DPTXlator.class);
final MainType mt = new MainType(2000, DPTXlatorBoolean.class, "DPTXlatorBoolean.class");
- TranslatorTypes.getAllMainTypes().put(new Integer(2000), mt);
+ TranslatorTypes.getAllMainTypes().put(2000, mt);
assertEquals(TranslatorTypes.getMainType(2000).createTranslator(
DPTXlatorBoolean.DPT_ENABLE).getClass(), DPTXlatorBoolean.class);
}
|
Replace Integer/Long constructor calls deprecated in java 9
|
calimero-project_calimero-core
|
train
|
0b217b8863de27e1110848f0547fb986e8c2e8e6
|
diff --git a/lib/slim/compiler.rb b/lib/slim/compiler.rb
index <HASH>..<HASH> 100644
--- a/lib/slim/compiler.rb
+++ b/lib/slim/compiler.rb
@@ -79,7 +79,7 @@ module Slim
if delimiter = options[:attr_delimiter][name]
"#{tmp}.respond_to?(:join) ? #{tmp}.flatten.compact.join(#{delimiter.inspect}) : #{tmp}"
else
- code
+ tmp
end
]]]]
end
diff --git a/test/slim/helper.rb b/test/slim/helper.rb
index <HASH>..<HASH> 100644
--- a/test/slim/helper.rb
+++ b/test/slim/helper.rb
@@ -72,7 +72,7 @@ class TestSlim < MiniTest::Unit::TestCase
end
class Env
- attr_reader :var
+ attr_reader :var, :x
class ::HtmlSafeString < String
def html_safe?
@@ -88,6 +88,7 @@ class Env
def initialize
@var = 'instance'
+ @x = 0
end
def id_helper
@@ -144,6 +145,11 @@ class Env
def output_number
1337
end
+
+ def succ_x
+ @x = @x.succ
+ end
+
end
class ViewEnv
diff --git a/test/slim/test_html_structure.rb b/test/slim/test_html_structure.rb
index <HASH>..<HASH> 100644
--- a/test/slim/test_html_structure.rb
+++ b/test/slim/test_html_structure.rb
@@ -459,4 +459,13 @@ html: body: .content
}
assert_html %{<html><body><div class=\"content\">Text</div></body></html>}, source
end
+
+ def test_eval_attributes_once
+ source = %q{
+input[value=succ_x]
+input[value=succ_x]
+}
+ assert_html %{<input value="1" /><input value="2" />}, source
+ end
+
end
|
Evaling a html attribute now happens only once. Fixed #<I>
|
slim-template_slim
|
train
|
f6ca4a3d5ec7d3e559073a5f54f7c43a615b9a63
|
diff --git a/CHANGELOG-2.3.md b/CHANGELOG-2.3.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG-2.3.md
+++ b/CHANGELOG-2.3.md
@@ -21,6 +21,7 @@
* Remove `:port` for cookie domain;
* `->amOnPage('/');` executed when running code coverage with WebDriver
* Fixed running single test with `include` config parameter. Fixes #4733 by @ppetpadriew
+* Fixed running single test when a custom suite path is configured (For instance, in single-suite setups).
* `generate:test` command won't include `tester` property if actor is not set for this config.
diff --git a/src/Codeception/Command/Run.php b/src/Codeception/Command/Run.php
index <HASH>..<HASH> 100644
--- a/src/Codeception/Command/Run.php
+++ b/src/Codeception/Command/Run.php
@@ -3,6 +3,7 @@ namespace Codeception\Command;
use Codeception\Codecept;
use Codeception\Configuration;
+use Codeception\Util\PathResolver;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
@@ -389,6 +390,24 @@ class Run extends Command
$suite = './' . $suite;
}
+ // running a single test when suite has a configured path
+ if (isset($config['suites'])) {
+ foreach ($config['suites'] as $s => $suiteConfig) {
+ if (!isset($suiteConfig['path'])) {
+ continue;
+ }
+ $testsPath = $config['paths']['tests'] . DIRECTORY_SEPARATOR . $suiteConfig['path'];
+ if ($suiteConfig['path'] === '.') {
+ $testsPath = $config['paths']['tests'];
+ }
+ if (preg_match("~^$testsPath/(.*?)$~", $suite, $matches)) {
+ $matches[2] = $matches[1];
+ $matches[1] = $s;
+ return $matches;
+ }
+ }
+ }
+
// Run single test without included tests
if (! Configuration::isEmpty() && strpos($suite, $config['paths']['tests']) === 0) {
return $this->matchTestFromFilename($suite, $config['paths']['tests']);
diff --git a/tests/cli/ConfigBundledSuitesCest.php b/tests/cli/ConfigBundledSuitesCest.php
index <HASH>..<HASH> 100644
--- a/tests/cli/ConfigBundledSuitesCest.php
+++ b/tests/cli/ConfigBundledSuitesCest.php
@@ -10,6 +10,13 @@ class ConfigBundledSuitesCest
$I->seeInShellOutput('OK (1 test');
}
+ public function runTestByPath(CliGuy $I)
+ {
+ $I->amInPath('tests/data/bundled_suites');
+ $I->executeCommand('run BasicTest.php');
+ $I->seeInShellOutput('OK (1 test');
+ }
+
public function generateTestsForBundledSuite(CliGuy $I)
{
$I->amInPath('tests/data/bundled_suites');
|
Fixed running single test when a custom suite path is configured (For instance, in single-suite setups)
|
Codeception_Codeception
|
train
|
6831dd28572f1e56906f83e849748f3fe0692ff4
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -63,7 +63,7 @@ if sys.version_info[0] == 2 and sys.version_info[1] <= 6:
setup(
name='fedmsg',
- version='0.3.3',
+ version='0.3.4',
description="Fedora Messaging Client API",
long_description=long_description,
author='Ralph Bean',
|
<I> with bugfixes to fedmsg-tail and new fedmsg.text items for bodhi.
|
fedora-infra_fedmsg
|
train
|
a75031c5afd6a0cd10d6e5e663d4624b09567d24
|
diff --git a/salt/grains/core.py b/salt/grains/core.py
index <HASH>..<HASH> 100644
--- a/salt/grains/core.py
+++ b/salt/grains/core.py
@@ -238,9 +238,9 @@ def os_data():
if os.path.isfile('/etc/lsb-release'):
for line in open('/etc/lsb-release').readlines():
# Matches any possible format:
- # DISTRIB_ID='Ubuntu'
+ # DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
- # DISTRIB_ID='Fedora'
+ # DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
|
Fix some comment formatting someone else "fixed"
|
saltstack_salt
|
train
|
8e56dc0464494bd2ccf9da25a743b711a171ce04
|
diff --git a/lib/kafka/protocol/decoder.rb b/lib/kafka/protocol/decoder.rb
index <HASH>..<HASH> 100644
--- a/lib/kafka/protocol/decoder.rb
+++ b/lib/kafka/protocol/decoder.rb
@@ -30,7 +30,7 @@ module Kafka
data = @io.read(offset + length)
return [] if data.nil?
@io.ungetc(data)
- data.bytes[offset, offset + length]
+ data.bytes[offset, offset + length] || []
end
# Decodes an 8-bit boolean from the IO object.
diff --git a/spec/protocol/decoder_spec.rb b/spec/protocol/decoder_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/protocol/decoder_spec.rb
+++ b/spec/protocol/decoder_spec.rb
@@ -1,6 +1,15 @@
describe Kafka::Protocol::Decoder do
describe '#peek' do
- let(:decoder) { Kafka::Protocol::Decoder.from_string(data) }
+ let(:io) { StringIO.new(data) }
+ let(:decoder) { Kafka::Protocol::Decoder.new(io) }
+
+ context 'io stream is shorter' do
+ let(:data) { 'he' }
+
+ it 'returns empty array' do
+ expect(decoder.peek(3, 1)).to eql([])
+ end
+ end
context 'io stream is empty' do
let(:data) { "" }
|
Handle the cases that the stream length is shorter
|
zendesk_ruby-kafka
|
train
|
ff5f8c386af6e85d09dac7b9ea964c72619cc236
|
diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php
index <HASH>..<HASH> 100644
--- a/modules/saml/lib/Auth/Source/SP.php
+++ b/modules/saml/lib/Auth/Source/SP.php
@@ -141,6 +141,8 @@ class sspmod_saml_Auth_Source_SP extends SimpleSAML_Auth_Source {
$idpEntityId = $idpMetadata->getString('entityid');
+ $state['saml:idp'] = $idpEntityId;
+
$ar = new SimpleSAML_XML_Shib13_AuthnRequest();
$ar->setIssuer($this->entityId);
diff --git a/modules/saml/www/sp/saml1-acs.php b/modules/saml/www/sp/saml1-acs.php
index <HASH>..<HASH> 100644
--- a/modules/saml/www/sp/saml1-acs.php
+++ b/modules/saml/www/sp/saml1-acs.php
@@ -23,6 +23,8 @@ if (!($source instanceof sspmod_saml_Auth_Source_SP)) {
throw new SimpleSAML_Error_Exception('Source type changed?');
}
+$idpEntityId = $state['saml:idp'];
+$idpMetadata = $source->getIdPMetadata($idpEntityId);
$responseXML = $_REQUEST['SAMLResponse'];
$responseXML = base64_decode($responseXML);
@@ -32,15 +34,19 @@ $response->setXML($responseXML);
$response->validate();
-$idp = $response->getIssuer();
+$responseIssuer = $response->getIssuer();
$attributes = $response->getAttributes();
+if ($responseIssuer !== $idpEntityId) {
+ throw new SimpleSAML_Error_Exception('The issuer of the response wasn\'t the destination of the request.');
+}
+
$logoutState = array(
'saml:logout:Type' => 'saml1'
);
$state['LogoutState'] = $logoutState;
-$source->handleResponse($state, $idp, $attributes);
+$source->handleResponse($state, $idpEntityId, $attributes);
assert('FALSE');
?>
\ No newline at end of file
|
saml: Check that the responder is the same as the one the request was sent to.
|
simplesamlphp_saml2
|
train
|
1e8cd91b661f2de9b23545afefe966594bca792a
|
diff --git a/specs/Bag.spec.php b/specs/Bag.spec.php
index <HASH>..<HASH> 100644
--- a/specs/Bag.spec.php
+++ b/specs/Bag.spec.php
@@ -2,6 +2,7 @@
namespace dirtsimple\imposer\tests;
use dirtsimple\imposer\Bag;
+use dirtsimple\fn;
describe("Bag", function() {
it("is an ArrayObject with prop-setting", function(){
@@ -68,4 +69,29 @@ describe("Bag", function() {
expect($this->bag['y'])->to->equal(99);
});
});
+
+ describe("select() returns an array that's", function() {
+ it("empty for an empty array", function(){
+ expect( $this->bag->select(array()) )->to->equal( array() );
+ });
+ it("empty for an array w/out overlapping keys", function(){
+ expect( $this->bag->select( array('q'=>fn::expr('$_')) ) )->to->equal( array() );
+ });
+ it("the result of calling the given function(s)", function(){
+ expect(
+ $this->bag->select( array('x'=>fn::expr('$_+1') ) )
+ )->to->equal( array('x'=>43) );
+ });
+ it("original values for non-callables", function() {
+ expect(
+ $this->bag->select( array('x'=>true ) )
+ )->to->equal( array('x'=>42) );
+ });
+ it("correct when given a key+value in place of an array", function(){
+ expect(
+ $this->bag->select( 'x', fn::expr('$_*3') )
+ )->to->equal( array('x'=>126) );
+ });
+ });
+
});
diff --git a/src/Bag.php b/src/Bag.php
index <HASH>..<HASH> 100644
--- a/src/Bag.php
+++ b/src/Bag.php
@@ -35,4 +35,14 @@ class Bag extends \ArrayObject {
return $this;
}
+ /* Apply function(s) to contents, return matching fields */
+ function select($funcs) {
+ if (func_num_args()>1) $funcs = array($funcs=>func_get_arg(1));
+ $res = array();
+ foreach ($funcs as $k => $v) {
+ if ( $this->offsetExists($k) ) $res[$k] = is_callable($v) ? $v($this[$k]) : $this[$k];
+ }
+ return $res;
+ }
+
}
|
Add Bag->select() method
|
dirtsimple_imposer
|
train
|
47ca4751e237943dd31d34e01568f6ff6f139668
|
diff --git a/ripe/atlas/cousteau/__init__.py b/ripe/atlas/cousteau/__init__.py
index <HASH>..<HASH> 100644
--- a/ripe/atlas/cousteau/__init__.py
+++ b/ripe/atlas/cousteau/__init__.py
@@ -102,6 +102,11 @@ class Measurement(EntityRepresentation):
"""Assing some measurement's raw meta data from API response to instance properties"""
if self.id is None:
self.id = self.meta_data.get("id")
+
+ stop_time = self.meta_data.get("stop_time")
+ if stop_time:
+ stop_time = datetime.fromtimestamp(stop_time)
+
self.protocol = self.meta_data.get("af")
self.destination_address = self.meta_data.get("dst_addr")
self.destination_asn = self.meta_data.get("dst_asn")
@@ -113,7 +118,7 @@ class Measurement(EntityRepresentation):
self.resolve_on_probe = self.meta_data.get("resolve_on_probe")
self.creation_time = datetime.fromtimestamp(self.meta_data.get("creation_time"))
self.start_time = datetime.fromtimestamp(self.meta_data.get("start_time"))
- self.stop_time = datetime.fromtimestamp(self.meta_data.get("stop_time"))
+ self.stop_time = stop_time
self.status = self.meta_data.get("status", {}).get("name")
self.type = self.meta_data.get("type", {}).get("name").upper()
self.result_url = self.meta_data.get("result")
|
Measurements without a stop time were exploding
|
RIPE-NCC_ripe-atlas-cousteau
|
train
|
a9372375e36788ca3ed37b3c1ba20bc3664a9a66
|
diff --git a/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdViolationRecorder.java b/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdViolationRecorder.java
index <HASH>..<HASH> 100644
--- a/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdViolationRecorder.java
+++ b/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdViolationRecorder.java
@@ -30,8 +30,6 @@ import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.rule.RuleKey;
-import java.net.URI;
-
@ScannerSide
public class PmdViolationRecorder {
@@ -72,9 +70,10 @@ public class PmdViolationRecorder {
}
private InputFile findResourceFor(RuleViolation violation) {
- final URI uri = URI.create(violation.getFilename());
return fs.inputFile(
- fs.predicates().hasURI(uri)
+ fs.predicates().hasAbsolutePath(
+ violation.getFilename()
+ )
);
}
diff --git a/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/ProjectDataSource.java b/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/ProjectDataSource.java
index <HASH>..<HASH> 100644
--- a/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/ProjectDataSource.java
+++ b/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/ProjectDataSource.java
@@ -24,6 +24,7 @@ import org.sonar.api.batch.fs.InputFile;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.file.Paths;
public class ProjectDataSource implements DataSource {
@@ -40,7 +41,9 @@ public class ProjectDataSource implements DataSource {
@Override
public String getNiceFileName(boolean shortNames, String inputFileName) {
- return inputFile.uri().toString();
+ return Paths.get(inputFile.uri())
+ .toAbsolutePath()
+ .toString();
}
@Override
diff --git a/sonar-pmd-plugin/src/test/java/org/sonar/plugins/pmd/PmdViolationRecorderTest.java b/sonar-pmd-plugin/src/test/java/org/sonar/plugins/pmd/PmdViolationRecorderTest.java
index <HASH>..<HASH> 100644
--- a/sonar-pmd-plugin/src/test/java/org/sonar/plugins/pmd/PmdViolationRecorderTest.java
+++ b/sonar-pmd-plugin/src/test/java/org/sonar/plugins/pmd/PmdViolationRecorderTest.java
@@ -19,11 +19,8 @@
*/
package org.sonar.plugins.pmd;
-import java.io.File;
-
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleViolation;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.TextRange;
@@ -37,6 +34,8 @@ import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.rule.RuleKey;
+import java.io.File;
+
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -138,7 +137,7 @@ class PmdViolationRecorderTest {
final RuleViolation pmdViolation = mock(RuleViolation.class);
when(rule.getName()).thenReturn(ruleName);
- when(pmdViolation.getFilename()).thenReturn(file.toURI().toString());
+ when(pmdViolation.getFilename()).thenReturn(file.getAbsolutePath());
when(pmdViolation.getBeginLine()).thenReturn(2);
when(pmdViolation.getDescription()).thenReturn("Description");
when(pmdViolation.getRule()).thenReturn(rule);
|
Switch from URI comparison to path comparison to deal with Windows Path structure
|
jensgerdes_sonar-pmd
|
train
|
0a37be3e3cf9289f63f1506bc31db409c2b46738
|
diff --git a/airflow/providers/snowflake/hooks/snowflake.py b/airflow/providers/snowflake/hooks/snowflake.py
index <HASH>..<HASH> 100644
--- a/airflow/providers/snowflake/hooks/snowflake.py
+++ b/airflow/providers/snowflake/hooks/snowflake.py
@@ -212,7 +212,7 @@ class SnowflakeHook(DbApiHook):
"""Override DbApiHook get_uri method for get_sqlalchemy_engine()"""
conn_config = self._get_conn_params()
uri = (
- 'snowflake://{user}:{password}@{account}/{database}/{schema}'
+ 'snowflake://{user}:{password}@{account}.{region}/{database}/{schema}'
'?warehouse={warehouse}&role={role}&authenticator={authenticator}'
)
return uri.format(**conn_config)
diff --git a/tests/providers/snowflake/hooks/test_snowflake.py b/tests/providers/snowflake/hooks/test_snowflake.py
index <HASH>..<HASH> 100644
--- a/tests/providers/snowflake/hooks/test_snowflake.py
+++ b/tests/providers/snowflake/hooks/test_snowflake.py
@@ -86,7 +86,8 @@ class TestSnowflakeHook(unittest.TestCase):
def test_get_uri(self):
uri_shouldbe = (
- 'snowflake://user:pw@airflow/db/public?warehouse=af_wh&role=af_role&authenticator=snowflake'
+ 'snowflake://user:pw@airflow.af_region/db/public?'
+ 'warehouse=af_wh&role=af_role&authenticator=snowflake'
)
assert uri_shouldbe == self.db_hook.get_uri()
@@ -243,7 +244,8 @@ class TestSnowflakeHookExtra(unittest.TestCase):
def test_get_uri_extra(self):
uri_shouldbe = (
- 'snowflake://user:pw@airflow/db/public?warehouse=af_wh&role=af_role&authenticator=snowflake'
+ 'snowflake://user:pw@airflow.af_region/db/public?'
+ 'warehouse=af_wh&role=af_role&authenticator=snowflake'
)
assert uri_shouldbe == self.db_hook_extra.get_uri()
|
Add region to Snowflake URI. (#<I>)
Without adding the AWS region to the URL, SQLAlchemy engines created by
Airflow can't write dataframes to snowflake using pd_writer. This PR
fixes this.
|
apache_airflow
|
train
|
d565df90ad85fd679f6507f0cff6b33ed364da8c
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -4,6 +4,8 @@ Changes between 2.3.5 and 2.4.DEV
- make "import pdb ; pdb.set_trace()" work natively wrt capturing (no "-s" needed
anymore), making ``pytest.set_trace()`` a mere shortcut.
+- fix issue333: fix a case of bad unittest/pytest hook interaction.
+
- fix issue181: --pdb now also works on collect errors (and
on internal errors) . This was implemented by a slight internal
refactoring and the introduction of a new hook
diff --git a/_pytest/unittest.py b/_pytest/unittest.py
index <HASH>..<HASH> 100644
--- a/_pytest/unittest.py
+++ b/_pytest/unittest.py
@@ -150,7 +150,10 @@ def pytest_runtest_makereport(item, call):
if isinstance(item, TestCaseFunction):
if item._excinfo:
call.excinfo = item._excinfo.pop(0)
- del call.result
+ try:
+ del call.result
+ except AttributeError:
+ pass
# twisted trial support
def pytest_runtest_protocol(item, __multicall__):
diff --git a/testing/test_unittest.py b/testing/test_unittest.py
index <HASH>..<HASH> 100644
--- a/testing/test_unittest.py
+++ b/testing/test_unittest.py
@@ -654,3 +654,21 @@ def test_no_teardown_if_setupclass_failed(testdir):
reprec = testdir.inline_run(testpath)
reprec.assertoutcome(passed=1, failed=1)
+
+def test_issue333_result_clearing(testdir):
+ testdir.makeconftest("""
+ def pytest_runtest_call(__multicall__, item):
+ __multicall__.execute()
+ assert 0
+ """)
+ testdir.makepyfile("""
+ import unittest
+ class TestIt(unittest.TestCase):
+ def test_func(self):
+ 0/0
+ """)
+
+ reprec = testdir.inline_run()
+ reprec.assertoutcome(failed=1)
+
+
|
fix issue<I>: fix a case of bad unittest/pytest hook interaction.
|
pytest-dev_pytest
|
train
|
e6e6380f6c226a98ab33d66d56b528f625191b91
|
diff --git a/src/Illuminate/View/Engines/EngineResolver.php b/src/Illuminate/View/Engines/EngineResolver.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/View/Engines/EngineResolver.php
+++ b/src/Illuminate/View/Engines/EngineResolver.php
@@ -30,6 +30,7 @@ class EngineResolver {
*/
public function register($engine, Closure $resolver)
{
+ unset($this->resolved[$engine]);
$this->resolvers[$engine] = $resolver;
}
|
allowing for resolved engines to be re-registered
|
laravel_framework
|
train
|
5776f66d1f423d25d0849b3a54f96e0bdbd4c2fd
|
diff --git a/src/pyrocore/scripts/pyroadmin.py b/src/pyrocore/scripts/pyroadmin.py
index <HASH>..<HASH> 100644
--- a/src/pyrocore/scripts/pyroadmin.py
+++ b/src/pyrocore/scripts/pyroadmin.py
@@ -19,12 +19,14 @@
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import with_statement
+import re
import sys
import glob
import shutil
import pprint
import fnmatch
import urllib2
+import xmlrpclib
from zipfile import ZipFile
from StringIO import StringIO
from contextlib import closing
@@ -47,6 +49,8 @@ class AdminTool(ScriptBaseWithConfig):
OPTIONAL_CFG_FILES = ["torque.ini"]
+ RC_CONTINUATION_THRESHOLD = 55
+
def add_options(self):
""" Add program options.
@@ -62,6 +66,8 @@ class AdminTool(ScriptBaseWithConfig):
self.add_value_option("--create-import", "GLOB-PATTERN",
action="append", default=[],
help="create import file for a '.d' directory")
+ self.add_bool_option("--dump-rc",
+ help="pretty-print dynamic commands defined in 'rtorrent.rc'")
self.add_value_option("-o", "--output", "KEY,KEY1.KEY2=DEFAULT,...",
action="append", default=[],
help="select fields to print, output is separated by TABs;"
@@ -205,6 +211,99 @@ class AdminTool(ScriptBaseWithConfig):
with open(os.path.expanduser(folder + '/.import.rc'), 'wt') as handle:
handle.write('\n'.join(conf_rc + ['']))
+ elif self.options.dump_rc:
+ # list all dynamic commands
+ proxy = config.engine.open()
+ methods = proxy.system.listMethods()
+
+ # XXX This is a heuristic and might break in newer rTorrent versions!
+ builtins = set(methods[:methods.index('view.sort_new')+1])
+ methods = set(methods)
+
+ def is_method(name):
+ 'Helper'
+ prefixes = ('d.', 'f.', 'p.', 't.', 'choke_group.', 'session.',
+ 'system.', 'throttle.', 'trackers.', 'ui.', 'view.')
+
+ return name in methods or any(name.startswith(x) for x in prefixes)
+
+ def rc_quoted(text, in_brace=False, plain=re.compile(r'^[a-zA-Z0-9_.]+$')):
+ 'Helper'
+ if isinstance(text, list):
+ fmt = '{%s}'
+ try:
+ method_name = text[0] + ""
+ except (TypeError, IndexError):
+ pass
+ else:
+ if is_method(method_name):
+ fmt = '(%s)' if in_brace else '((%s))'
+ if '.set' not in method_name and len(text) == 2 and text[1] == 0:
+ text = text[:1]
+ text = fmt % ', '.join([rc_quoted(x, in_brace=(fmt[0] == '{')) for x in text])
+ return text.replace('))))', ')) ))')
+ elif isinstance(text, int):
+ return '{:d}'.format(text)
+ elif plain.match(text):
+ return text
+ else:
+ return '"{}"'.format(text.replace('\\', '\\\\').replace('"', '\\"'))
+
+ group = None
+ for name in sorted(methods):
+ try:
+ value = proxy.method.get('', name, fail_silently=True)
+ const = bool(proxy.method.const('', name, fail_silently=True))
+ except xmlrpclib.Fault as exc:
+ if exc.faultCode == -503 and exc.faultString == 'Key not found.':
+ continue
+ raise
+ else:
+ group, old_group = name.split('.', 1)[0], group
+ if group == 'event':
+ group = name
+ if group != old_group:
+ print('')
+
+ definition = None
+ objtype = type(value)
+ if objtype is list:
+ value = [rc_quoted(x) for x in value]
+ fmt = '((%s))' if value and is_method(value[0]) else '{%s}'
+ definition = fmt % ', '.join(value)
+ elif objtype is dict:
+ print('method.insert = {}, multi|rlookup|static'.format(name))
+ for key, val in sorted(value.items()):
+ val = rc_quoted(val)
+ if len(val) > self.RC_CONTINUATION_THRESHOLD:
+ val = '\\\n ' + val
+ print('method.set_key = {}, {}, {}'.format(name, key, val))
+ elif objtype is str:
+ definition = rc_quoted(value)
+ elif objtype is int:
+ definition = '{:d}'.format(value)
+ else:
+ self.LOG.error("Cannot handle {!r} definition of method {}".format(objtype, name))
+ continue
+
+ if definition:
+ if name in builtins:
+ print('{}.set = {}'.format(name, definition))
+ else:
+ rctype = {str: 'string', int: 'value', long: 'value'}.get(objtype, 'simple')
+ if const:
+ rctype += '|const'
+ const = None
+ if len(definition) > self.RC_CONTINUATION_THRESHOLD:
+ definition = '\\\n ' + definition
+ definition = (definition
+ .replace(" ; ", " ;\\\n ")
+ .replace(", ", ",\\\n ")
+ )
+ print('method.insert = {}, {}, {}'.format(name, rctype, definition))
+ if const:
+ print('method.const.enable = {}'.format(name))
+
elif self.options.screenlet:
# Create screenlet stub
stub_dir = os.path.expanduser("~/.screenlets/PyroScope")
|
pyroadmin: added --dump-rc option
the output is certainly readable, the syntax might not work out
<I>% for roundtrips and need a few manual tweaks
|
pyroscope_pyrocore
|
train
|
792dbebef2ed8fb516960368b7e6ff0635b2614a
|
diff --git a/lib/fog/compute/requests/vcloud/login.rb b/lib/fog/compute/requests/vcloud/login.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/compute/requests/vcloud/login.rb
+++ b/lib/fog/compute/requests/vcloud/login.rb
@@ -13,7 +13,7 @@ module Fog
},
:method => 'POST',
:parse => true,
- :uri => login_uri
+ :uri => "#{base_url}/login"
})
end
diff --git a/lib/fog/compute/vcloud.rb b/lib/fog/compute/vcloud.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/compute/vcloud.rb
+++ b/lib/fog/compute/vcloud.rb
@@ -294,7 +294,7 @@ module Fog
def random_ip
usable_subnet_ips[rand(usable_subnet_ips.length)]
end
-
+
def usable_subnet_ips
subnet_ips[3..-2]
end
@@ -627,7 +627,7 @@ module Fog
include MockDataClasses
def self.base_url
- "https://fakey.com/api/v0.8b-ext2.6"
+ "https://fakey.com/api/v1.0"
end
def self.data_reset
@@ -750,10 +750,12 @@ module Fog
@connections = {}
@persistent = options[:persistent]
- @host = options[:vcloud_host] || Fog::Vcloud::Compute::HOST
- @path = options[:vcloud_path] || Fog::Vcloud::Compute::PATH
- @port = options[:vcloud_port] || Fog::Vcloud::Compute::PORT
- @scheme = options[:vcloud_scheme] || Fog::Vcloud::Compute::SCHEME
+ @username = options[:vcloud_username]
+ @password = options[:vcloud_password]
+ @host = options[:vcloud_host]
+ @path = options[:vcloud_path] || Fog::Vcloud::Compute::PATH
+ @port = options[:vcloud_port] || Fog::Vcloud::Compute::PORT
+ @scheme = options[:vcloud_scheme] || Fog::Vcloud::Compute::SCHEME
end
def default_organization_uri
@@ -806,6 +808,10 @@ module Fog
do_request(params)
end
+ def base_url
+ "#{@scheme}://#{@host}:#{@port}#{@path}"
+ end
+
# Use this to set the Authorization header for login
def authorization_header
"Basic #{Base64.encode64("#{@username}:#{@password}").chomp!}"
|
[vcloud|compute] make auth work
|
fog_fog
|
train
|
8839c9cb927b5876b10316a52aea03b06883feff
|
diff --git a/kentikapi/v5/tagging.py b/kentikapi/v5/tagging.py
index <HASH>..<HASH> 100644
--- a/kentikapi/v5/tagging.py
+++ b/kentikapi/v5/tagging.py
@@ -362,11 +362,11 @@ class Client:
# submit a populator batch
def submit_populator_batch(self, column_name, batch):
- url = 'https://api.kentik.com/api/v5/tagging/column/%s/populators' % column_name
+ url = 'https://api.kentik.com/api/v5/batch/customdimensions/%s/populators' % column_name
self._submit_batch(url, batch)
# submit a tag batch
def submit_tag_batch(self, batch):
- url = 'https://api.kentik.com/api/v5/tagging/tags'
+ url = 'https://api.kentik.com/api/v5/batch/tags'
self._submit_batch(url, batch)
|
Updated tagging URL endpoints to new 'batch' prefix
|
kentik_kentikapi-py
|
train
|
f7a01b4651541d1df2608f2b627044fabb7968cf
|
diff --git a/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/xtext/XtextValidationTest.java b/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/xtext/XtextValidationTest.java
index <HASH>..<HASH> 100644
--- a/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/xtext/XtextValidationTest.java
+++ b/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/xtext/XtextValidationTest.java
@@ -106,4 +106,19 @@ public class XtextValidationTest extends AbstractGeneratorTest {
assertEquals("diag.isWarning", diag.getSeverity(), Diagnostic.WARNING);
}
+ public void testEnumWithEmptyLiteral() throws Exception {
+ XtextResource resource = getResourceFromString(
+ "grammar org.foo.Bar with org.eclipse.xtext.common.Terminals\n" +
+ "generate testLanguage 'http://www.eclipse.org/2009/tmf/xtext/validation/literal/2'\n" +
+ "Model: enumValue=GeneratedEnum;\n" +
+ "enum GeneratedEnum: NoLiteral | ValidLiteral='literal' | EmptyLiteral='';");
+ assertTrue(resource.getErrors().toString(), resource.getErrors().isEmpty());
+ assertTrue(resource.getWarnings().toString(), resource.getWarnings().isEmpty());
+
+ Diagnostic diag = Diagnostician.INSTANCE.validate(resource.getContents().get(0));
+ assertNotNull("diag", diag);
+ assertEquals(diag.getChildren().toString(), 1, diag.getChildren().size());
+ assertEquals("diag.isError", diag.getSeverity(), Diagnostic.ERROR);
+ }
+
}
|
* feature: Check that refuses enum with explicit empty literals ("")
|
eclipse_xtext-core
|
train
|
c6704f4e97b2473472ecb8026cc1c9f2da5d161c
|
diff --git a/bugwarrior/services/bitbucket.py b/bugwarrior/services/bitbucket.py
index <HASH>..<HASH> 100644
--- a/bugwarrior/services/bitbucket.py
+++ b/bugwarrior/services/bitbucket.py
@@ -135,17 +135,31 @@ class BitbucketService(IssueService, ServiceClient):
return True
- def get_data(self, url, **kwargs):
- api = kwargs.get('api', self.BASE_API2)
-
+ def _get_json(self, url):
+ """ This function sets-up the authentication, perform a request to the
+ given url and return json-parsed data. """
kwargs = {}
if 'token' in self.auth:
kwargs['headers'] = {
'Authorization': 'Bearer ' + self.auth['token']}
elif 'basic' in self.auth:
kwargs['auth'] = self.auth['basic']
+ return self.json_response(requests.get(url, **kwargs))
- return self.json_response(requests.get(api + url, **kwargs))
+ def get_data(self, url, **kwargs):
+ api = kwargs.get('api', self.BASE_API2)
+ return self._get_json(api + url)
+
+ def get_collection(self, url):
+ """ Pages through an object collection from the bitbucket API.
+ Returns an iterator that lazily goes through all the 'values'
+ of all the pages in the collection. """
+ url = self.BASE_API2 + url
+ while url is not None:
+ response = self._get_json(url)
+ for value in response['values']:
+ yield value
+ url = response.get('next', None)
@classmethod
def validate_config(cls, config, target):
@@ -157,12 +171,13 @@ class BitbucketService(IssueService, ServiceClient):
IssueService.validate_config(config, target)
def fetch_issues(self, tag):
- response = self.get_data('/repositories/%s/issues/' % (tag))
- return [(tag, issue) for issue in response['values']]
+ response = self.get_collection('/repositories/%s/issues/' % (tag))
+ for issue in response:
+ yield (tag, issue)
def fetch_pull_requests(self, tag):
- response = self.get_data('/repositories/%s/pullrequests/' % tag)
- return [(tag, issue) for issue in response['values']]
+ response = self.get_collection('/repositories/%s/pullrequests/' % tag)
+ return [(tag, issue) for issue in response]
def get_annotations(self, tag, issue, issue_obj, url):
response = self.get_data(
@@ -177,14 +192,14 @@ class BitbucketService(IssueService, ServiceClient):
)
def get_annotations2(self, tag, issue, issue_obj, url):
- response = self.get_data(
+ response = self.get_collection(
'/repositories/%s/pullrequests/%i/comments' % (tag, issue['id'])
)
return self.build_annotations(
((
comment['user']['username'],
comment['content']['raw'],
- ) for comment in response['values']),
+ ) for comment in response),
issue_obj.get_processed_url(url)
)
@@ -194,13 +209,13 @@ class BitbucketService(IssueService, ServiceClient):
def issues(self):
user = self.config.get(self.target, 'bitbucket.username')
- response = self.get_data('/repositories/' + user + '/')
+ response = self.get_collection('/repositories/' + user + '/')
repo_tags = filter(self.filter_repos, [
- repo['full_name'] for repo in response.get('values')
+ repo['full_name'] for repo in response
if repo.get('has_issues')
])
- issues = sum([self.fetch_issues(repo) for repo in repo_tags], [])
+ issues = sum([list(self.fetch_issues(repo)) for repo in repo_tags], [])
log.name(self.target).debug(" Found {0} total.", len(issues))
closed = ['resolved', 'duplicate', 'wontfix', 'invalid', 'closed']
|
Bitbucket: Paginate through object collection returned by API call
Many endpoints in the version <I> of the bitbucket API return object
collection splint into pages, this change introduces a way to get all
the pages instead of just the first one.
See bitbucket documentation:
<URL>
|
ralphbean_bugwarrior
|
train
|
235604975a2e3aaba46fdd194e169c64fe30cc38
|
diff --git a/dwave/embedding/pegasus.py b/dwave/embedding/pegasus.py
index <HASH>..<HASH> 100644
--- a/dwave/embedding/pegasus.py
+++ b/dwave/embedding/pegasus.py
@@ -36,12 +36,18 @@ def find_clique_embedding(k, m=None, target_graph=None):
m = target_graph.graph['rows'] # We only support square Pegasus graphs
_, nodes = k
- # Get Pegasus nodes in terms of coordinates
+ # Deal with differences in ints vs coordinate target_graphs
if target_graph.graph['labels'] == 'int':
+ # Convert nodes in terms of Pegasus coordinates
coord_converter = pegasus_coordinates(m)
pegasus_coords = map(coord_converter.tuple, target_graph.nodes)
+
+ # A function to convert our final coordinate embedding to an ints embedding
+ back_translate = lambda emb: {key: list(coord_converter.ints(chain))
+ for key, chain in emb.items()}
else:
pegasus_coords = target_graph.nodes
+ back_translate = lambda emb: emb
# Break each Pegasus qubits into six Chimera fragments
# Note: By breaking the graph in this way, you end up with a K2,2 Chimera graph
@@ -65,6 +71,7 @@ def find_clique_embedding(k, m=None, target_graph=None):
defragment_tuple = get_tuple_defragmentation_fn(target_graph)
pegasus_clique_embedding = map(defragment_tuple, chimera_clique_embedding)
pegasus_clique_embedding = dict(zip(nodes, pegasus_clique_embedding))
+ pegasus_clique_embedding = back_translate(pegasus_clique_embedding)
if len(pegasus_clique_embedding) != len(nodes):
raise ValueError("No clique embedding found")
diff --git a/tests/unit/test_embedding_pegasus.py b/tests/unit/test_embedding_pegasus.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_embedding_pegasus.py
+++ b/tests/unit/test_embedding_pegasus.py
@@ -57,6 +57,16 @@ class TestFindClique(unittest.TestCase):
self.assertTrue(is_valid_embedding(embedding, nx.complete_graph(k), pg))
+ def test_valid_clique_ints(self):
+ k = nx.complete_graph(55)
+ m = 6
+
+ # Find embedding
+ pg = pegasus_graph(m)
+ embedding = find_clique_embedding(k, target_graph=pg)
+
+ self.assertTrue(is_valid_embedding(embedding, k, pg))
+
def test_valid_clique_coord(self):
k = nx.complete_graph(55)
m = 6
@@ -65,7 +75,7 @@ class TestFindClique(unittest.TestCase):
pg = pegasus_graph(m, coordinates=True)
embedding = find_clique_embedding(k, target_graph=pg)
- self.assertTrue(is_valid_embedding(embedding, nx.complete_graph(k), pg))
+ self.assertTrue(is_valid_embedding(embedding, k, pg))
def test_impossible_clique(self):
k = 55
|
Add back_translate lambda in order to deal with differences between ints and coordinates in the target_graph. Add unit test to check back translate
|
dwavesystems_dwave-system
|
train
|
96788bf275fdde0e1ebd47d4a00bef7be636f99f
|
diff --git a/spyderlib/plugins/inspector.py b/spyderlib/plugins/inspector.py
index <HASH>..<HASH> 100644
--- a/spyderlib/plugins/inspector.py
+++ b/spyderlib/plugins/inspector.py
@@ -9,6 +9,7 @@
from PyQt4.QtGui import (QHBoxLayout, QVBoxLayout, QLabel, QSizePolicy, QMenu,
QToolButton, QGroupBox, QFontComboBox, QActionGroup)
from PyQt4.QtCore import SIGNAL
+from PyQt4.QtWebKit import QWebView
import sys, re, os.path as osp, socket
@@ -85,7 +86,7 @@ class ObjectInspectorConfigPage(PluginConfigPage):
self.setLayout(vlayout)
-class ObjectInspector(ReadOnlyEditor):
+class ObjectInspector(ReadOnlyEditor, QWebView):
"""
Docstrings viewer widget
"""
@@ -95,6 +96,11 @@ class ObjectInspector(ReadOnlyEditor):
def __init__(self, parent):
self.set_default_color_scheme()
ReadOnlyEditor.__init__(self, parent)
+ QWebView.__init__(self, parent)
+
+ # Add a widget to render the rich (i.e. html) help
+ self.render_rich_text = QWebView(self)
+ self.render_rich_text.hide()
self.shell = None
@@ -115,22 +121,25 @@ class ObjectInspector(ReadOnlyEditor):
lambda valid: self.force_refresh())
# Plain text docstring option
+ self.docstring = True
plain_text = create_action(self, self.tr("Plain Text"),
toggled=self.toggle_plain_text)
plain_text.setChecked(True)
- self.docstring = True
# Source code option
show_source = create_action(self, self.tr("Show Source"),
toggled=self.toggle_show_source)
- show_source.setChecked(False)
+ # Rich text option
+ rich_text = create_action(self, self.tr("Rich Text"),
+ toggled=self.toggle_rich_text)
# Add the help actions to an exclusive QActionGroup
help_actions = QActionGroup(self)
help_actions.setExclusive(True)
help_actions.addAction(plain_text)
help_actions.addAction(show_source)
+ help_actions.addAction(rich_text)
# Automatic import option
auto_import = create_action(self, self.tr("Automatic import"),
@@ -149,7 +158,7 @@ class ObjectInspector(ReadOnlyEditor):
icon=get_icon('tooloptions.png'))
options_button.setPopupMode(QToolButton.InstantPopup)
menu = QMenu(self)
- add_actions(menu, [plain_text, show_source, auto_import])
+ add_actions(menu, [rich_text, plain_text, show_source, auto_import])
options_button.setMenu(menu)
layout_edit.addWidget(options_button)
@@ -157,6 +166,7 @@ class ObjectInspector(ReadOnlyEditor):
layout = QVBoxLayout()
layout.addLayout(layout_edit)
layout.addWidget(self.editor)
+ layout.addWidget(self.render_rich_text)
layout.addWidget(self.find_widget)
self.setLayout(layout)
@@ -263,11 +273,30 @@ class ObjectInspector(ReadOnlyEditor):
def toggle_plain_text(self, checked):
"""Toggle plain text docstring"""
self.docstring = checked
+
+ if self.editor.isHidden():
+ self.editor.show()
+ self.render_rich_text.hide()
+
self.force_refresh()
def toggle_show_source(self, checked):
"""Toggle show source code"""
self.docstring = not checked
+
+ if self.editor.isHidden():
+ self.editor.show()
+ self.render_rich_text.hide()
+
+ self.force_refresh()
+
+ def toggle_rich_text(self, checked):
+ """Toggle between sphinxified docstrings or plain ones"""
+
+ if self.render_rich_text.isHidden():
+ self.editor.hide()
+ self.render_rich_text.show()
+
self.force_refresh()
def toggle_auto_import(self, checked):
|
Add a QWebView widget to render the rich text help.
-. Add an action (rich_text) to show the widget. It will
hide the editor widget to show the QWebView one.
-. We prefer QWebView over QTextEdit or QTextBrowser because
they don't support full css styles.
|
spyder-ide_spyder
|
train
|
bbd0529f4bb71c7cd94995e87f92216de004284f
|
diff --git a/hack/update/github.go b/hack/update/github.go
index <HASH>..<HASH> 100644
--- a/hack/update/github.go
+++ b/hack/update/github.go
@@ -221,7 +221,7 @@ func GHReleases(ctx context.Context, owner, repo string) (stable, latest string,
return "", "", err
}
for _, rl := range rls {
- ver := rl.GetName()
+ ver := rl.GetTagName()
if !semver.IsValid(ver) {
continue
}
diff --git a/hack/update/update.go b/hack/update/update.go
index <HASH>..<HASH> 100644
--- a/hack/update/update.go
+++ b/hack/update/update.go
@@ -88,8 +88,7 @@ func (i *Item) apply(data interface{}) error {
if i.Content == nil {
return fmt.Errorf("unable to update content: nothing to update")
}
- org := string(i.Content)
- str := org
+ str := string(i.Content)
for src, dst := range i.Replace {
out, err := ParseTmpl(dst, data, "")
if err != nil {
|
fix GHReleases() to use release tag name instead of release name for release version
|
kubernetes_minikube
|
train
|
eaa606b10c63018fa7d798ac5f8359d321d8b78d
|
diff --git a/tests/__init__.py b/tests/__init__.py
index <HASH>..<HASH> 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1,28 +1,16 @@
# -*- coding: utf-8 -*-
# Copyright © 2015 ACSONE SA/NV
# License LGPLv3 (http://www.gnu.org/licenses/lgpl-3.0-standalone.html)
+from contextlib import contextmanager
import os
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
-class WorkingDirectoryKeeper(object):
- """A context manager to get back the working directory as it was before.
- If you want to stack working directory keepers, you need a new instance
- for each stage.
- """
-
- active = False
-
- def __enter__(self):
- if self.active:
- raise RuntimeError("Already in a working directory keeper !")
- self.wd = os.getcwd()
- self.active = True
-
- def __exit__(self, *exc_args):
- os.chdir(self.wd)
- self.active = False
-
-
-working_directory_keeper = WorkingDirectoryKeeper()
+@contextmanager
+def working_directory_keeper():
+ wd = os.getcwd()
+ try:
+ yield
+ finally:
+ os.chdir(wd)
diff --git a/tests/test_prepare.py b/tests/test_prepare.py
index <HASH>..<HASH> 100644
--- a/tests/test_prepare.py
+++ b/tests/test_prepare.py
@@ -30,7 +30,7 @@ class TestPrepare(unittest.TestCase):
def test_addon1(self):
self.maxDiff = None
addon_dir = os.path.join(DATA_DIR, 'setup_reusable_addons', 'addon1')
- with working_directory_keeper:
+ with working_directory_keeper():
os.chdir(addon_dir)
keywords = prepare_odoo_addon()
self.assertEquals(keywords, {
@@ -59,7 +59,7 @@ class TestPrepare(unittest.TestCase):
def test_addon2(self):
addon_dir = os.path.join(DATA_DIR, 'setup_reusable_addons', 'addon2')
- with working_directory_keeper:
+ with working_directory_keeper():
os.chdir(addon_dir)
keywords = prepare_odoo_addon()
self.assertEquals(keywords, {
@@ -83,7 +83,7 @@ class TestPrepare(unittest.TestCase):
def test_addon7(self):
self.maxDiff = None
addon_dir = os.path.join(DATA_DIR, 'setup_reusable_addons', 'addon7')
- with working_directory_keeper:
+ with working_directory_keeper():
os.chdir(addon_dir)
keywords = prepare_odoo_addon()
self.assertEquals(keywords, {
@@ -105,7 +105,7 @@ class TestPrepare(unittest.TestCase):
def test_addon8(self):
self.maxDiff = None
addon_dir = os.path.join(DATA_DIR, 'setup_reusable_addons', 'addon8')
- with working_directory_keeper:
+ with working_directory_keeper():
os.chdir(addon_dir)
keywords = prepare_odoo_addon()
self.assertEquals(keywords, {
@@ -125,7 +125,7 @@ class TestPrepare(unittest.TestCase):
def test_addons_dir(self):
addons_dir = os.path.join(DATA_DIR, 'setup_custom_project')
- with working_directory_keeper:
+ with working_directory_keeper():
os.chdir(addons_dir)
keywords = prepare_odoo_addons()
self.assertEquals(keywords, {
|
Simplify working_directory_keeper
|
acsone_setuptools-odoo
|
train
|
af46df7eaea3e5687e483d0aeceb250d14f10aa3
|
diff --git a/lib/request.js b/lib/request.js
index <HASH>..<HASH> 100644
--- a/lib/request.js
+++ b/lib/request.js
@@ -360,12 +360,6 @@ req.__defineGetter__('stale', function(){
return connect.utils.modified(this, this.res);
});
-// Callback for isXMLHttpRequest / xhr
-
-function isxhr() {
- return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';
-}
-
/**
* Check if the request was an _XMLHttpRequest_.
*
@@ -373,5 +367,7 @@ function isxhr() {
* @api public
*/
-req.__defineGetter__('isXMLHttpRequest', isxhr);
-req.__defineGetter__('xhr', isxhr);
+req.__defineGetter__('xhr', function(){
+ return this.header('X-Requested-With', '')
+ .toLowerCase() == 'xmlhttprequest';
+});
|
Removed req.isXMLHttpRequest
let me know if you actually use this :)
|
expressjs_express
|
train
|
93e104d96924019986b24350f5090409725f8792
|
diff --git a/src/Illuminate/Database/Concerns/BuildsQueries.php b/src/Illuminate/Database/Concerns/BuildsQueries.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Database/Concerns/BuildsQueries.php
+++ b/src/Illuminate/Database/Concerns/BuildsQueries.php
@@ -332,7 +332,7 @@ trait BuildsQueries
* @param int $perPage
* @param \Illuminate\Pagination\Cursor $cursor
* @param array $options
- * @return \Illuminate\Pagination\Paginator
+ * @return \Illuminate\Pagination\CursorPaginator
*/
protected function cursorPaginator($items, $perPage, $cursor, $options)
{
diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Database/Query/Builder.php
+++ b/src/Illuminate/Database/Query/Builder.php
@@ -2407,7 +2407,7 @@ class Builder
* @param array $columns
* @param string $cursorName
* @param string|null $cursor
- * @return \Illuminate\Contracts\Pagination\Paginator
+ * @return \Illuminate\Contracts\Pagination\CursorPaginator
* @throws \Illuminate\Pagination\CursorPaginationException
*/
public function cursorPaginate($perPage = 15, $columns = ['*'], $cursorName = 'cursor', $cursor = null)
|
[8.x] fix return type PHPDoc of the cursorPaginate method (#<I>)
|
laravel_framework
|
train
|
3629b756798ab3e3f03eee863a5fdacbd84f6c7a
|
diff --git a/test/lib/Elastica/Query/MatchAllTest.php b/test/lib/Elastica/Query/MatchAllTest.php
index <HASH>..<HASH> 100644
--- a/test/lib/Elastica/Query/MatchAllTest.php
+++ b/test/lib/Elastica/Query/MatchAllTest.php
@@ -1,7 +1,7 @@
<?php
require_once dirname(__FILE__) . '/../../../bootstrap.php';
-class Elastica_Query_MatchAllTest extends PHPUnit_Framework_TestCase
+class Elastica_Query_MatchAllTest extends Elastica_Test
{
public function testToArray()
{
@@ -11,4 +11,21 @@ class Elastica_Query_MatchAllTest extends PHPUnit_Framework_TestCase
$this->assertEquals($expectedArray, $query->toArray());
}
+
+ public function testMatchAllIndicesTypes() {
+ $index1 = $this->_createIndex('test1');
+ $index2 = $this->_createIndex('test1');
+
+ $doc = new Elastica_Document(1, array('name' => 'ruflin'));
+ $index1->getType('test')->addDocument($doc);
+ $index2->getType('test')->addDocument($doc);
+
+ $index1->refresh();
+ $index2->refresh();
+
+ $search = new Elastica_Search($index1->getClient());
+ $resultSet = $search->search(new Elastica_Query_MatchAll());
+
+ $this->assertEquals(2, $resultSet->count());
+ }
}
|
test case for match all query with multiple indices
|
ruflin_Elastica
|
train
|
01612672ebab7b4d06d2e090bd44407afa78b72b
|
diff --git a/DataItemInspector.py b/DataItemInspector.py
index <HASH>..<HASH> 100644
--- a/DataItemInspector.py
+++ b/DataItemInspector.py
@@ -130,7 +130,7 @@ class ParamInspector(InspectorSection):
self.param_slider.maximum = 100
self.param_slider.bind_value(data_item_binding_source, "param")
self.param_field = self.ui.create_line_edit_widget()
- self.param_field.bind_text(data_item_binding_source, "param", converter=UserInterfaceUtility.FloatToStringConverter())
+ self.param_field.bind_text(data_item_binding_source, "param", converter=UserInterfaceUtility.FloatToPercentStringConverter())
self.param_row.add(param_label)
self.param_row.add_spacing(8)
self.param_row.add(self.param_slider)
@@ -551,7 +551,7 @@ class DataItemInspector(object):
self.widget.add_spacing(6)
self.__inspectors.append(InfoInspector(self.ui, self.__data_item_content_binding))
- self.__inspectors.append(ParamInspector(self.ui, self.__data_item_binding_source))
+ # self.__inspectors.append(ParamInspector(self.ui, self.__data_item_binding_source))
self.__inspectors.append(CalibrationsInspector(self.ui, self.__data_item_content_binding))
self.__inspectors.append(DisplayLimitsInspector(self.ui, self.__data_item_content_binding))
self.__inspectors.append(GraphicsInspector(self.ui, self.__data_item_content_binding))
diff --git a/UserInterfaceUtility.py b/UserInterfaceUtility.py
index <HASH>..<HASH> 100644
--- a/UserInterfaceUtility.py
+++ b/UserInterfaceUtility.py
@@ -43,14 +43,24 @@ class FloatFormatter(object):
class FloatToStringConverter(object):
"""
- Converter object to convert from float value to string and back.
- """
+ Convert from float value to string and back.
+ """
def convert(self, value):
return "%g" % float(value)
def convert_back(self, str):
return float(str)
+class FloatToPercentStringConverter(object):
+ """
+ Convert from float value to string and back.
+ """
+ def convert(self, value):
+ return str(int(value * 100)) + "%"
+ def convert_back(self, str):
+ return float(str.strip('%'))/100.0
+
+
class PropertyTwoWayBinding(Storage.Observable):
"""
|
Add float to percent converter and test.
svn r<I>
|
nion-software_nionswift
|
train
|
17e947f0865c9697d4a84c2e2de01ed77e27549d
|
diff --git a/tests/AdapterTest.php b/tests/AdapterTest.php
index <HASH>..<HASH> 100644
--- a/tests/AdapterTest.php
+++ b/tests/AdapterTest.php
@@ -140,6 +140,10 @@ class AdapterTest extends TestCase
public function testRead(AdapterInterface $adapter, $config, $options)
{
$this->assertArrayHasKey('contents', $adapter->read("foo/{$options['machineId']}/bar.md"));
+ $this->assertSame(
+ $adapter->read("foo/{$options['machineId']}/bar.md"),
+ file_get_contents($adapter->getUrl("foo/{$options['machineId']}/bar.md"))
+ );
}
/**
@@ -158,6 +162,7 @@ class AdapterTest extends TestCase
*/
public function testReadStream(AdapterInterface $adapter, $config, $options)
{
+ $this->assertArrayHasKey('stream', $adapter->readStream("foo/{$options['machineId']}/bar.md"));
$this->assertSame(
stream_get_contents(fopen($adapter->getUrl("foo/{$options['machineId']}/bar.md"), 'rb', false)),
stream_get_contents($adapter->readStream("foo/{$options['machineId']}/bar.md")['stream'])
|
Update AdapterTest.php
|
freyo_flysystem-qcloud-cos-v5
|
train
|
4430a6fbb8bd24617d15522e73ca316a820a6638
|
diff --git a/client/lib/transaction/store.js b/client/lib/transaction/store.js
index <HASH>..<HASH> 100644
--- a/client/lib/transaction/store.js
+++ b/client/lib/transaction/store.js
@@ -84,7 +84,7 @@ TransactionStore.dispatchToken = Dispatcher.register( function( payload ) {
setPayment( action.payment );
break;
- case UpgradesActionTypes.SET_TRANSACTION_NEW_CREDIT_CARD_DETAILS:
+ case UpgradesActionTypes.TRANSACTION_NEW_CREDIT_CARD_DETAILS_SET:
setNewCreditCardDetails( {
rawDetails: action.rawDetails,
maskedDetails: action.maskedDetails
diff --git a/client/lib/upgrades/actions/checkout.js b/client/lib/upgrades/actions/checkout.js
index <HASH>..<HASH> 100644
--- a/client/lib/upgrades/actions/checkout.js
+++ b/client/lib/upgrades/actions/checkout.js
@@ -23,7 +23,7 @@ function setNewCreditCardDetails( options ) {
const { rawDetails, maskedDetails } = options;
Dispatcher.handleViewAction( {
- type: ActionTypes.SET_TRANSACTION_NEW_CREDIT_CARD_DETAILS,
+ type: ActionTypes.TRANSACTION_NEW_CREDIT_CARD_DETAILS_SET,
rawDetails,
maskedDetails
} );
diff --git a/client/lib/upgrades/constants.js b/client/lib/upgrades/constants.js
index <HASH>..<HASH> 100644
--- a/client/lib/upgrades/constants.js
+++ b/client/lib/upgrades/constants.js
@@ -45,7 +45,6 @@ module.exports.action = keyMirror( {
PURCHASES_USER_FETCH: null,
PURCHASES_USER_FETCH_COMPLETED: null,
PURCHASES_USER_FETCH_FAILED: null,
- SET_TRANSACTION_NEW_CREDIT_CARD_DETAILS: null,
SET_TRANSACTION_PAYMENT: null,
SITE_REDIRECT_FETCH: null,
SITE_REDIRECT_FETCH_COMPLETED: null,
@@ -61,6 +60,7 @@ module.exports.action = keyMirror( {
STORED_CARDS_FETCH_COMPLETED: null,
STORED_CARDS_FETCH_FAILED: null,
TRANSACTION_DOMAIN_DETAILS_SET: null,
+ TRANSACTION_NEW_CREDIT_CARD_DETAILS_SET: null,
TRANSACTION_RESET: null,
TRANSACTION_STEP_SET: null,
WAPI_DOMAIN_INFO_FETCH: null,
|
Checkout: Rename constant for set new credit card details in transaction action to be more consistent
|
Automattic_wp-calypso
|
train
|
ca1ad6fcedf674868e45f2c9a3748d62bc1da2d7
|
diff --git a/src/frontend/org/voltdb/utils/SQLCommand.java b/src/frontend/org/voltdb/utils/SQLCommand.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/utils/SQLCommand.java
+++ b/src/frontend/org/voltdb/utils/SQLCommand.java
@@ -382,7 +382,7 @@ public class SQLCommand
private static final Pattern SemicolonToken = Pattern.compile("^.*\\s*;+\\s*$", Pattern.CASE_INSENSITIVE);
private static final Pattern RecallToken = Pattern.compile("^\\s*recall\\s*([^;]+)\\s*;*\\s*$", Pattern.CASE_INSENSITIVE);
private static final Pattern FileToken = Pattern.compile("^\\s*file\\s*['\"]*([^;'\"]+)['\"]*\\s*;*\\s*", Pattern.CASE_INSENSITIVE);
- private static List<String> Lines = new ArrayList<String>();
+ private static List<String> RecallableSessionLines = new ArrayList<String>();
/**
* The list of recognized basic tab-complete-able SQL command prefixes.
@@ -440,22 +440,19 @@ public class SQLCommand
StringBuilder query = new StringBuilder();
boolean isRecall = false;
- while (true) {
- String prompt = isRecall ? "" : ((Lines.size() + 1) + "> ");
+ boolean executeImmediate = false;
+ while ( ! executeImmediate) {
+ String prompt = isRecall ? "" : ((RecallableSessionLines.size() + 1) + "> ");
isRecall = false;
String line = lineInputReader.readLine(prompt);
- if (line == null) {
- //* enable to debug */ System.err.println("Read null interactive line.");
- parsedQueries = parseQuery(query.toString());
- return parsedQueries;
- }
+ assert(line != null);
// Was there a line-ending semicolon typed at the prompt?
// This mostly matters for "non-directive" statements, but, for
// now, for backward compatibility, it needs to be noted for FILE
// commands prior to their processing.
- boolean executeImmediate = SemicolonToken.matcher(line).matches();
+ executeImmediate = SemicolonToken.matcher(line).matches();
// When we are tracking the progress of a multi-line statement,
// avoid coincidentally recognizing mid-statement SQL content as sqlcmd
@@ -472,23 +469,25 @@ public class SQLCommand
if (recallMatcher.matches()) {
int recall = -1;
try { recall = Integer.parseInt(recallMatcher.group(1))-1; } catch(Exception x){}
- if (recall > -1 && recall < Lines.size()) {
- line = Lines.get(recall);
+ if (recall > -1 && recall < RecallableSessionLines.size()) {
+ line = RecallableSessionLines.get(recall);
lineInputReader.putString(line);
lineInputReader.flush();
isRecall = true;
} else {
- System.out.printf("%s> Invalid RECALL reference: '" + recallMatcher.group(1) + "'.\n", Lines.size());
+ System.out.printf("%s> Invalid RECALL reference: '" + recallMatcher.group(1) + "'.\n", RecallableSessionLines.size());
}
+ executeImmediate = false; // let user edit the recalled line.
continue;
}
// Queue up the line to the recall stack
//TODO: In the future, we may not want to have simple directives count as recallable
// lines, so this call would move down a ways.
- Lines.add(line);
+ RecallableSessionLines.add(line);
if (executesAsSimpleDirective(line)) {
+ executeImmediate = false; // return to prompt.
continue;
}
@@ -496,6 +495,7 @@ public class SQLCommand
//TODO: to be deprecated in favor of just typing a semicolon on its own line to finalize
// a multi-line statement.
if (GoToken.matcher(line).matches()) {
+ executeImmediate = true;
line = ";";
}
@@ -510,11 +510,11 @@ public class SQLCommand
if (m_returningToPromptAfterError) {
// readScriptFile stopped because of an error. Wipe the slate clean.
query = new StringBuilder();
- line = null;
// Until we execute statements as they are read, there will always be a
// chance that errors in queued statements are still waiting to be detected,
// so, this reset is not 100% effective (as discovered in ENG-7335).
m_returningToPromptAfterError = false;
+ executeImmediate = false; // return to prompt.
continue;
}
// else treat the line(s) from the file(s) as regular database commands
@@ -529,23 +529,18 @@ public class SQLCommand
// very pretty for very long statements, behaved best for line editing (cursor synch)
// purposes.
// The multiLineStatementBuffer MAY become useful here.
- Lines.add(line);
+ RecallableSessionLines.add(line);
}
+ //TODO: Here's where we might use multiLineStatementBuffer to note a sql statement
+ // in progress -- if the line(s) so far contained anything more than whitespace.
+
// Collect lines ...
query.append(line);
query.append("\n");
-
- // ... until there was a line-ending semicolon typed at the prompt.
- if (executeImmediate) {
- parsedQueries = parseQuery(query.toString());
- return parsedQueries;
- }
- else {
- //TODO: Here's where we might use multiLineStatementBuffer to note a sql statement
- // in progress -- if the line(s) so far contained anything more than whitespace.
- }
}
+ parsedQueries = parseQuery(query.toString());
+ return parsedQueries;
}
/// A stripped down variant of the processing in "interactWithTheUser" suitable for
|
Fix a sqlcmd regression in the soon-to-die 'go' support, act on related review feedback.
|
VoltDB_voltdb
|
train
|
620ba56b3a814a5bf4463a14eee0c0f9dad6442d
|
diff --git a/lib/vault.rb b/lib/vault.rb
index <HASH>..<HASH> 100644
--- a/lib/vault.rb
+++ b/lib/vault.rb
@@ -38,19 +38,19 @@ module Vault
def update_index
source_index.add_spec(spec)
- # do this in a rake task!
+ # TODO: throw this in a rake task and cron it
# upload(source_path, source_index)
indexify("specs.#{Gem.marshal_version}.gz", source_index.gems)
indexify("latest_specs.#{Gem.marshal_version}.gz", source_index.latest_specs)
end
def indexify(key, specs)
- upload key, specs.map do |*raw_spec|
+ upload(key, specs.map { |*raw_spec|
spec = raw_spec.flatten.last
platform = spec.original_platform
platform = Gem::Platform::RUBY if platform.nil? or platform.empty?
[spec.name, spec.version, platform]
- end
+ })
end
def upload(key, data)
|
Ruby, you frighten me
|
rubygems_rubygems.org
|
train
|
85e6d32cbb3656f012f187dcba069ba841423e7c
|
diff --git a/src/lib/is-utf-8.js b/src/lib/is-utf-8.js
index <HASH>..<HASH> 100644
--- a/src/lib/is-utf-8.js
+++ b/src/lib/is-utf-8.js
@@ -3,5 +3,5 @@
module.exports = function (win) {
win = win || global;
- return win.document.characterSet.toLowerCase() === 'utf-8';
+ return Boolean(win.document.characterSet && win.document.characterSet.toLowerCase() === 'utf-8');
};
|
Only check utf8 on browsers that have characterSet property
|
braintree_braintree-web-drop-in
|
train
|
56f734a3615ad522a1dbaafc7442f19e4651640b
|
diff --git a/actionpack/lib/action_dispatch/journey/path/pattern.rb b/actionpack/lib/action_dispatch/journey/path/pattern.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_dispatch/journey/path/pattern.rb
+++ b/actionpack/lib/action_dispatch/journey/path/pattern.rb
@@ -59,31 +59,6 @@ module ActionDispatch
}.map(&:name).uniq
end
- class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
- attr_reader :offsets
-
- def initialize(matchers)
- @matchers = matchers
- @capture_count = [0]
- end
-
- def visit(node)
- super
- @capture_count
- end
-
- def visit_SYMBOL(node)
- node = node.to_sym
-
- if @matchers.key?(node)
- re = /#{@matchers[node]}|/
- @capture_count.push((re.match('').length - 1) + (@capture_count.last || 0))
- else
- @capture_count << (@capture_count.last || 0)
- end
- end
- end
-
class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc:
def initialize(separator, matchers)
@separator = separator
@@ -193,8 +168,20 @@ module ActionDispatch
def offsets
return @offsets if @offsets
- viz = RegexpOffsets.new(@requirements)
- @offsets = viz.accept(spec)
+ @offsets = [0]
+
+ spec.find_all(&:symbol?).each do |node|
+ node = node.to_sym
+
+ if @requirements.key?(node)
+ re = /#{@requirements[node]}|/
+ @offsets.push((re.match('').length - 1) + @offsets.last)
+ else
+ @offsets << @offsets.last
+ end
+ end
+
+ @offsets
end
end
end
|
pull RegexpOffsets in to a method
we don't really need this visitor
|
rails_rails
|
train
|
f10454b6802be76fc270458f699b269cdb1fc6fb
|
diff --git a/packages/ipfs-unixfs-importer/test/importer.spec.js b/packages/ipfs-unixfs-importer/test/importer.spec.js
index <HASH>..<HASH> 100644
--- a/packages/ipfs-unixfs-importer/test/importer.spec.js
+++ b/packages/ipfs-unixfs-importer/test/importer.spec.js
@@ -20,6 +20,7 @@ const blockApi = require('./helpers/block')
const uint8ArrayConcat = require('uint8arrays/concat')
const uint8ArrayFromString = require('uint8arrays/from-string')
const uint8ArrayToString = require('uint8arrays/to-string')
+const last = require('it-last')
function stringifyMh (files) {
return files.map((file) => {
@@ -1059,4 +1060,26 @@ describe('configuration', () => {
expect(validated).to.be.true()
expect(chunked).to.be.true()
})
+
+ it('imports the same data with different CID versions and gets the same multihash', async () => {
+ const ipld = await inMemory(IPLD)
+ const block = blockApi(ipld)
+ const buf = uint8ArrayFromString('content')
+
+ const { cid: cidV0 } = await last(importer([{
+ content: buf
+ }], block, {
+ cidVersion: 0,
+ rawLeaves: false
+ }))
+
+ const { cid: cidV1 } = await last(importer([{
+ content: buf
+ }], block, {
+ cidVersion: 1,
+ rawLeaves: false
+ }))
+
+ expect(cidV0.multihash).to.deep.equal(cidV1.multihash)
+ })
})
|
test: adds a test for getting the same multihash from different CID versions (#<I>)
Just a small example test
|
ipfs_js-ipfs-unixfs
|
train
|
aef11128c063306ac08ff84bc69a9e77f8294798
|
diff --git a/doctr/travis.py b/doctr/travis.py
index <HASH>..<HASH> 100644
--- a/doctr/travis.py
+++ b/doctr/travis.py
@@ -477,8 +477,8 @@ def commit_docs(*, added, removed):
DOCTR_COMMAND = ' '.join(map(shlex.quote, sys.argv))
- if added:
- run(['git', 'add', *added])
+ for f in added:
+ run(['git', 'add', f])
if removed:
run(['git', 'rm', *removed])
|
Test adding the "slow" way
See if my test in .travis.yml really does test the right thing.
|
drdoctr_doctr
|
train
|
1bf2ce1a3261b5486d3d9643826b05cb8d8ee35b
|
diff --git a/cmd/influxd/launcher/query_test.go b/cmd/influxd/launcher/query_test.go
index <HASH>..<HASH> 100644
--- a/cmd/influxd/launcher/query_test.go
+++ b/cmd/influxd/launcher/query_test.go
@@ -748,7 +748,7 @@ from(bucket: "%s")
}
}
-func TestLauncher_Query_PushDownWindowAggregate(t *testing.T) {
+func TestLauncher_Query_PushDownWindowAggregateAndBareAggregate(t *testing.T) {
l := launcher.RunTestLauncherOrFail(t, ctx,
"--feature-flags", "pushDownWindowAggregateCount=true")
l.SetupOrFail(t)
@@ -811,6 +811,22 @@ from(bucket: v.bucket)
,,0,5,f,m0,k0,1970-01-01T00:00:15Z
`,
},
+ {
+ name: "bare count",
+ q: `
+from(bucket: v.bucket)
+ |> range(start: 1970-01-01T00:00:00Z, stop: 1970-01-01T00:00:15Z)
+ |> count()
+ |> drop(columns: ["_start", "_stop"])
+`,
+ res: `
+#group,false,false,false,true,true,true
+#datatype,string,long,long,string,string,string
+#default,_result,,,,,
+,result,table,_value,_field,_measurement,k
+,,0,15,f,m0,k0
+`,
+ },
} {
t.Run(tt.name, func(t *testing.T) {
wantCount := getReadRequestCount() + 1
diff --git a/query/stdlib/influxdata/influxdb/rules.go b/query/stdlib/influxdata/influxdb/rules.go
index <HASH>..<HASH> 100644
--- a/query/stdlib/influxdata/influxdb/rules.go
+++ b/query/stdlib/influxdata/influxdb/rules.go
@@ -25,10 +25,8 @@ func init() {
PushDownReadTagKeysRule{},
PushDownReadTagValuesRule{},
SortedPivotRule{},
- // For the following two rules to take effect the appropriate capabilities must be
- // added AND feature flags must be enabled.
PushDownWindowAggregateRule{},
- // PushDownBareAggregateRule{},
+ PushDownBareAggregateRule{},
PushDownGroupAggregateRule{},
)
}
@@ -781,7 +779,7 @@ func (PushDownWindowAggregateRule) Rewrite(ctx context.Context, pn plan.Node) (p
type PushDownBareAggregateRule struct{}
func (p PushDownBareAggregateRule) Name() string {
- return "PushDownWindowAggregateRule"
+ return "PushDownBareAggregateRule"
}
func (p PushDownBareAggregateRule) Pattern() plan.Pattern {
|
feat(query): register bare aggregate
|
influxdata_influxdb
|
train
|
61bad0192df26895c27ddc882cf797e4c8fec977
|
diff --git a/code/media/lib_koowa/js/tabs.js b/code/media/lib_koowa/js/tabs.js
index <HASH>..<HASH> 100644
--- a/code/media/lib_koowa/js/tabs.js
+++ b/code/media/lib_koowa/js/tabs.js
@@ -20,6 +20,8 @@ if(!Koowa) var Koowa = {};
*/
Koowa.Tabs = new Class({
+ Implements: [Options, Events],
+
getOptions: function()
{
return {
@@ -85,6 +87,4 @@ Koowa.Tabs = new Class({
this.hideAllBut(i);
this.fireEvent('onActive', [this.titles[i], this.descriptions[i]])
}
-});
-
-Koowa.Tabs.implement(new Events, new Options);
\ No newline at end of file
+});
\ No newline at end of file
|
Fixed Mootools <I> and Joomla <I> compatibility issues.
|
timble_kodekit
|
train
|
82547816ac041a219841bb3e42d89110510099ac
|
diff --git a/src/com/google/javascript/jscomp/parsing/IRFactory.java b/src/com/google/javascript/jscomp/parsing/IRFactory.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/parsing/IRFactory.java
+++ b/src/com/google/javascript/jscomp/parsing/IRFactory.java
@@ -701,6 +701,7 @@ class IRFactory {
case EXPRESSION_STATEMENT:
case LABELLED_STATEMENT:
case EXPORT_DECLARATION:
+ case TEMPLATE_SUBSTITUTION:
return false;
case CALL_EXPRESSION:
case CONDITIONAL_EXPRESSION:
diff --git a/test/com/google/javascript/jscomp/TypeCheckNoTranspileTest.java b/test/com/google/javascript/jscomp/TypeCheckNoTranspileTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/TypeCheckNoTranspileTest.java
+++ b/test/com/google/javascript/jscomp/TypeCheckNoTranspileTest.java
@@ -1679,6 +1679,13 @@ public final class TypeCheckNoTranspileTest extends TypeCheckTestCase {
"required: string"));
}
+ public void testTaggedTemplateLiteral_argumentWithCast() {
+ testTypes(
+ lines(
+ "function tag(strings, /** string */ s) {}", // preserve newline
+ "tag`${ /** @type {?} */ (123) }`;"));
+ }
+
public void testTaggedTemplateLiteral_optionalArguments() {
testTypes(
lines(
diff --git a/test/com/google/javascript/jscomp/parsing/ParserTest.java b/test/com/google/javascript/jscomp/parsing/ParserTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/parsing/ParserTest.java
+++ b/test/com/google/javascript/jscomp/parsing/ParserTest.java
@@ -2679,6 +2679,24 @@ public final class ParserTest extends BaseJSTypeTestCase {
parseError("`hello\\07`", "Invalid escape sequence");
}
+ public void testTemplateLiteralSubstitutionWithCast() {
+ mode = LanguageMode.ECMASCRIPT6;
+
+ Node root = parse("`${ /** @type {?} */ (3)}`");
+ Node exprResult = root.getFirstChild();
+ Node templateLiteral = exprResult.getFirstChild();
+ assertNode(templateLiteral).hasType(Token.TEMPLATELIT);
+
+ Node substitution = templateLiteral.getSecondChild();
+ assertNode(substitution).hasType(Token.TEMPLATELIT_SUB);
+
+ Node cast = substitution.getFirstChild();
+ assertNode(cast).hasType(Token.CAST);
+
+ Node number = cast.getFirstChild();
+ assertNode(number).hasType(Token.NUMBER);
+ }
+
public void testExponentialLiterals() {
parse("0e0");
parse("0E0");
|
Correctly handle JSDoc in template literal substitution expressions.
This fixes a bug where IRFactory was trying to put JSDoc on the container TEMPLATELIT_SUB node, instead of on the expression inside it.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
bbace7e98cb82323d46ed6aaea47128bb44a643b
|
diff --git a/src/org/jgroups/protocols/TP.java b/src/org/jgroups/protocols/TP.java
index <HASH>..<HASH> 100644
--- a/src/org/jgroups/protocols/TP.java
+++ b/src/org/jgroups/protocols/TP.java
@@ -49,7 +49,7 @@ import java.util.concurrent.locks.ReentrantLock;
* The {@link #receive(Address, Address, byte[], int, int)} method must
* be called by subclasses when a unicast or multicast message has been received.
* @author Bela Ban
- * @version $Id: TP.java,v 1.189 2008/05/13 07:43:58 belaban Exp $
+ * @version $Id: TP.java,v 1.190 2008/05/13 13:29:00 belaban Exp $
*/
@MBean(description="Transport protocol")
public abstract class TP extends Protocol {
@@ -173,6 +173,9 @@ public abstract class TP extends Protocol {
*/
protected ThreadNamingPattern thread_naming_pattern=new ThreadNamingPattern("cl");
+ /** */
+ int connect_count=0;
+
/** ================================== OOB thread pool ============================== */
/** The thread pool which handles OOB messages */
@@ -779,11 +782,11 @@ public abstract class TP extends Protocol {
protected void handleConnect() throws Exception {
- ;
+ connect_count++;
}
protected void handleDisconnect() {
- ;
+ connect_count=Math.max(0, connect_count -1);
}
public String getSingletonName() {
|
removed exception when bundling timeout or size is set without corresponding enable_bundling
|
belaban_JGroups
|
train
|
a5223cc2afbd5688ad07a50697e9efb6cef5a200
|
diff --git a/minimatch.js b/minimatch.js
index <HASH>..<HASH> 100644
--- a/minimatch.js
+++ b/minimatch.js
@@ -853,7 +853,12 @@ function match (f, partial) {
var set = this.set
this.debug(this.pattern, "set", set)
- var splitFile = path.basename(f.join("/")).split("/")
+ // Find the basename of the split file name
+ var splitFile;
+ for (var i = f.length - 1; i >= 0; i--) {
+ splitFile = [f[i]]
+ if (f[i]) break
+ }
for (var i = 0, l = set.length; i < l; i ++) {
var pattern = set[i], file = f
@@ -975,7 +980,7 @@ Minimatch.prototype.matchOne = function (file, pattern, partial) {
}
// no match was found.
// However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
+ // If there's more *pattern* left, then
if (partial) {
// ran out of file
this.debug("\n>>> no match, partial?", file, fr, pattern, pr)
|
Look up basename using already split segments
Previously path.basename was used in conjunction with joining
and splitting the segments array which was much slower than just
looking up the basename from the already split segments array.
|
isaacs_minimatch
|
train
|
9c05da7d6bceb11e3f1cf61bd72888d743e98df0
|
diff --git a/vb_suite/test_perf.py b/vb_suite/test_perf.py
index <HASH>..<HASH> 100755
--- a/vb_suite/test_perf.py
+++ b/vb_suite/test_perf.py
@@ -356,7 +356,7 @@ def print_report(df,h_head=None,h_msg="",h_baseline=None,b_msg=""):
if not args.quiet:
prprint(s)
- if args.stats:
+ if args.stats and args.quiet:
prprint(stats_footer)
prprint("Results were also written to the logfile at '%s'" %
|
BLD: test_perf don't print stats twice
|
pandas-dev_pandas
|
train
|
4351e62eb182b6c555ed32ebfc1ce159acc9ed2f
|
diff --git a/Controller/ArticleController.php b/Controller/ArticleController.php
index <HASH>..<HASH> 100644
--- a/Controller/ArticleController.php
+++ b/Controller/ArticleController.php
@@ -243,8 +243,10 @@ class ArticleController extends AbstractRestController implements ClassResourceI
$query = new BoolQuery();
foreach ($types as $type) {
- $query->add(new TermQuery('type', $type));
+ $query->add(new TermQuery('type', $type), BoolQuery::SHOULD);
}
+
+ $search->addQuery($query);
} elseif ($types[0]) {
$search->addQuery(new TermQuery('type', $types[0]));
}
diff --git a/Tests/Functional/Controller/ArticleControllerTest.php b/Tests/Functional/Controller/ArticleControllerTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Functional/Controller/ArticleControllerTest.php
+++ b/Tests/Functional/Controller/ArticleControllerTest.php
@@ -43,7 +43,7 @@ class ArticleControllerTest extends SuluTestCase
{
use ArticleViewDocumentIdTrait;
- private static $typeMap = ['default' => 'blog', 'simple' => 'video'];
+ private static $typeMap = ['default' => 'blog', 'simple' => 'video', 'default_fallback' => 'other'];
/**
* @var Client
@@ -936,6 +936,22 @@ class ArticleControllerTest extends SuluTestCase
$this->assertContains([$article2['id'], $article2['title']], $items);
}
+ public function testCGetMultipleTypes()
+ {
+ $article1 = $this->testPost('Sulu', 'default');
+ $article2 = $this->testPost('Sulu is awesome', 'simple');
+ $article3 = $this->testPost('Sulu is great', 'default_fallback');
+ $this->flush();
+
+ $this->client->request('GET', '/api/articles?locale=de&types=blog,video&fields=title');
+
+ $this->assertHttpStatusCode(200, $this->client->getResponse());
+
+ $response = json_decode($this->client->getResponse()->getContent(), true);
+
+ $this->assertEquals(2, $response['total']);
+ }
+
public function testCGetFilterByContactId()
{
// create contact1
|
Fix filter by multiple types (#<I>)
|
sulu_SuluArticleBundle
|
train
|
1219dab87385888f63bd4088fe31e34727c59395
|
diff --git a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestNoAddressingTestCase.java b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestNoAddressingTestCase.java
index <HASH>..<HASH> 100644
--- a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestNoAddressingTestCase.java
+++ b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestNoAddressingTestCase.java
@@ -41,7 +41,6 @@ import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -68,8 +67,6 @@ public class TestNoAddressingTestCase {
addAsResource(WSHandler.class.getPackage(), "ws-handler.xml", "org/jboss/as/test/integration/ws/wsa/ws-handler.xml");
log.info(war.toString(true));
- war.as(ZipExporter.class).exportTo(new File("/tmp/jaxws-wsa.war"), true);
-
return war;
}
diff --git a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestOptionalAddressingTestCase.java b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestOptionalAddressingTestCase.java
index <HASH>..<HASH> 100644
--- a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestOptionalAddressingTestCase.java
+++ b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestOptionalAddressingTestCase.java
@@ -35,7 +35,6 @@ import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -63,8 +62,6 @@ public class TestOptionalAddressingTestCase {
addAsResource(WSHandler.class.getPackage(), "ws-handler.xml", "org/jboss/as/test/integration/ws/wsa/ws-handler.xml");
log.info(war.toString(true));
- war.as(ZipExporter.class).exportTo(new File("/tmp/jaxws-wsa.war"), true);
-
return war;
}
diff --git a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestRequiredAddressingTestCase.java b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestRequiredAddressingTestCase.java
index <HASH>..<HASH> 100644
--- a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestRequiredAddressingTestCase.java
+++ b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ws/wsa/TestRequiredAddressingTestCase.java
@@ -36,7 +36,6 @@ import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -64,8 +63,6 @@ public class TestRequiredAddressingTestCase {
addAsResource(WSHandler.class.getPackage(), "ws-handler.xml", "org/jboss/as/test/integration/ws/wsa/ws-handler.xml");
log.info(war.toString(true));
- war.as(ZipExporter.class).exportTo(new File("/tmp/jaxws-wsa.war"), true);
-
return war;
}
|
Unnecessary archive export removed
|
wildfly_wildfly
|
train
|
8a0bea567b7c0d7be3356bbc34b868fd3d611327
|
diff --git a/lib/ipfilter.js b/lib/ipfilter.js
index <HASH>..<HASH> 100644
--- a/lib/ipfilter.js
+++ b/lib/ipfilter.js
@@ -32,6 +32,8 @@ Netmask = require('netmask').Netmask;
* - `errorCode` the HTTP status code to use when denying access. Defaults to 401.
* - `errorMessage` the error message to use when denying access. Defaults to 'Unauthorized'.
* - `allowPrivateIPs` whether to grant access to any IP using the private IP address space unless explicitly denied. Defaults to false.
+ * - `allowCloudFlare` set false to disable cloud flare header
+ * - `allowForwardedIps` set false to disable forwared ips
* - 'cidr' whether ips are ips with a submnet mask. Defaults to 'false'.
* - 'ranges' whether ranges are supplied as ips
* - 'excluding' routes that should be excluded from ip filtering
@@ -51,6 +53,8 @@ module.exports = function ipfilter(ips, opts) {
errorCode: 401,
errorMessage: 'Unauthorized',
allowPrivateIPs: false,
+ allowCloudFlare: true,
+ allowForwardedIps: true,
cidr: false,
ranges: false,
excluding: []
@@ -63,17 +67,19 @@ module.exports = function ipfilter(ips, opts) {
//Allow getting cloudflare connecting client IP
var cloudFlareConnectingIp=req.headers['cf-connecting-ip'];
- if (forwardedIpsStr) {
+ if (settings.allowForwardedIps && forwardedIpsStr) {
var forwardedIps = forwardedIpsStr.split(',');
ipAddress = forwardedIps[0];
}
+ if(settings.allowCloudFlare && cloudFlareConnectingIp!=undefined){
+ ipAddress=cloudFlareConnectingIp;
+ }
+
if (!ipAddress) {
ipAddress = req.connection.remoteAddress;
}
- if(cloudFlareConnectingIp!=undefined){
- ipAddress=cloudFlareConnectingIp;
- }
+
if(!ipAddress){
return '';
diff --git a/test.js b/test.js
index <HASH>..<HASH> 100644
--- a/test.js
+++ b/test.js
@@ -606,6 +606,77 @@ describe('enforcing cloudflare based client IP address blacklist restrictions',
});
});
+
+describe('ignore cloudflare based client IP address when disabled', function () {
+ beforeEach(function () {
+ this.ipfilter = ipfilter(['127.0.0.1'], {log: false, allowCloudFlare: false});
+ this.req = {
+ session: {},
+ headers: [],
+ connection: {
+ remoteAddress: '127.0.0.1'
+ }
+ }
+ });
+
+ it('should deny blacklisted not regarding cloudflare header', function (done) {
+ this.req.headers['cf-connecting.ip'] = '127.0.0.2';
+ var res = {
+ end: function () {
+ assert.equal(401, res.statusCode);
+ done();
+ }
+ };
+
+ this.ipfilter(this.req, res, function () {
+ });
+ });
+
+ it('should allow valid remoteAddress not regarding cloudflare header', function (done) {
+ this.req.headers['cf-connecting.ip'] = '127.0.0.1';
+ this.req.connection.remoteAddress = '127.0.0.2';
+
+ this.ipfilter(this.req, {}, function () {
+ done();
+ });
+ });
+});
+
+describe('ignore forwarded client IP address when disabled', function () {
+ beforeEach(function () {
+ this.ipfilter = ipfilter(['127.0.0.1'], {log: false, allowForwardedIps: false});
+ this.req = {
+ session: {},
+ headers: [],
+ connection: {
+ remoteAddress: '127.0.0.1'
+ }
+ }
+ });
+
+ it('should deny blacklisted not regarding forwarded header', function (done) {
+ this.req.headers['cf-connecting.ip'] = '127.0.0.2';
+ var res = {
+ end: function () {
+ assert.equal(401, res.statusCode);
+ done();
+ }
+ };
+
+ this.ipfilter(this.req, res, function () {
+ });
+ });
+
+ it('should allow valid remoteAddress not regarding forwarded header', function (done) {
+ this.req.headers['cf-connecting.ip'] = '127.0.0.1';
+ this.req.connection.remoteAddress = '127.0.0.2';
+
+ this.ipfilter(this.req, {}, function () {
+ done();
+ });
+ });
+});
+
describe('enforcing cloudflare based client IP address whitelist restrictions', function(){
beforeEach(function(){
this.ipfilter = ipfilter([ '127.0.0.1' ], { log: false, mode: 'allow' });
|
fixed the issue that there is no option to deny proxy/cloudflare forwards
see <URL>
|
ryanbillingsley_express-ipfilter
|
train
|
c476c8213e8cc03dbaca2e439acd56cd4374dede
|
diff --git a/github/checks.go b/github/checks.go
index <HASH>..<HASH> 100644
--- a/github/checks.go
+++ b/github/checks.go
@@ -51,7 +51,6 @@ type CheckRunOutput struct {
// CheckRunAnnotation represents an annotation object for a CheckRun output.
type CheckRunAnnotation struct {
Path *string `json:"path,omitempty"`
- BlobHRef *string `json:"blob_href,omitempty"`
StartLine *int `json:"start_line,omitempty"`
EndLine *int `json:"end_line,omitempty"`
StartColumn *int `json:"start_column,omitempty"`
diff --git a/github/checks_test.go b/github/checks_test.go
index <HASH>..<HASH> 100644
--- a/github/checks_test.go
+++ b/github/checks_test.go
@@ -148,7 +148,6 @@ func TestChecksService_ListCheckRunAnnotations(t *testing.T) {
})
fmt.Fprint(w, `[{
"path": "README.md",
- "blob_href": "https://github.com/octocat/Hello-World/blob/837db83be4137ca555d9a5598d0a1ea2987ecfee/README.md",
"start_line": 2,
"end_line": 2,
"start_column": 1,
@@ -167,7 +166,6 @@ func TestChecksService_ListCheckRunAnnotations(t *testing.T) {
want := []*CheckRunAnnotation{{
Path: String("README.md"),
- BlobHRef: String("https://github.com/octocat/Hello-World/blob/837db83be4137ca555d9a5598d0a1ea2987ecfee/README.md"),
StartLine: Int(2),
EndLine: Int(2),
StartColumn: Int(1),
@@ -506,7 +504,6 @@ func Test_CheckRunMarshal(t *testing.T) {
Annotations: []*CheckRunAnnotation{
{
AnnotationLevel: String("a"),
- BlobHRef: String("b"),
EndLine: Int(1),
Message: String("m"),
Path: String("p"),
@@ -598,7 +595,6 @@ func Test_CheckRunMarshal(t *testing.T) {
"annotations": [
{
"path": "p",
- "blob_href": "b",
"start_line": 1,
"end_line": 1,
"annotation_level": "a",
diff --git a/github/github-accessors.go b/github/github-accessors.go
index <HASH>..<HASH> 100644
--- a/github/github-accessors.go
+++ b/github/github-accessors.go
@@ -636,14 +636,6 @@ func (c *CheckRunAnnotation) GetAnnotationLevel() string {
return *c.AnnotationLevel
}
-// GetBlobHRef returns the BlobHRef field if it's non-nil, zero value otherwise.
-func (c *CheckRunAnnotation) GetBlobHRef() string {
- if c == nil || c.BlobHRef == nil {
- return ""
- }
- return *c.BlobHRef
-}
-
// GetEndColumn returns the EndColumn field if it's non-nil, zero value otherwise.
func (c *CheckRunAnnotation) GetEndColumn() int {
if c == nil || c.EndColumn == nil {
|
Remove blob_href from check annotations (#<I>)
|
google_go-github
|
train
|
cf9f42463cf8caea6cd44648ed90c3553feb4dce
|
diff --git a/library/CM/Site/Abstract.php b/library/CM/Site/Abstract.php
index <HASH>..<HASH> 100644
--- a/library/CM/Site/Abstract.php
+++ b/library/CM/Site/Abstract.php
@@ -263,6 +263,21 @@ abstract class CM_Site_Abstract extends CM_Model_Abstract {
}
/**
+ * @return boolean
+ */
+ public function isRobotIndexingDisallowed() {
+ return $this->_get('robotIndexingDisallowed');
+ }
+
+ /**
+ * @param boolean|null $value
+ */
+ public function setRobotIndexingDisallowed($value = null) {
+ $value = (null !== $value) ? (boolean) $value : true;
+ $this->_set('robotIndexingDisallowed', $value);
+ }
+
+ /**
* @param CM_Comparable $other
* @return bool
* @throws CM_Exception_Invalid
@@ -280,9 +295,10 @@ abstract class CM_Site_Abstract extends CM_Model_Abstract {
protected function _getSchema() {
return new CM_Model_Schema_Definition([
- 'name' => ['type' => 'string'],
- 'emailAddress' => ['type' => 'string'],
- 'default' => ['type' => 'bool', 'optional' => true],
+ 'name' => ['type' => 'string'],
+ 'emailAddress' => ['type' => 'string'],
+ 'robotIndexingDisallowed' => ['type' => 'boolean'],
+ 'default' => ['type' => 'bool', 'optional' => true],
]);
}
diff --git a/tests/helpers/CMTest/library/CMTest/TestCase.php b/tests/helpers/CMTest/library/CMTest/TestCase.php
index <HASH>..<HASH> 100644
--- a/tests/helpers/CMTest/library/CMTest/TestCase.php
+++ b/tests/helpers/CMTest/library/CMTest/TestCase.php
@@ -94,8 +94,9 @@ abstract class CMTest_TestCase extends PHPUnit_Framework_TestCase implements CM_
public function getMockSite($className = null, array $configuration = null, array $settings = null) {
$siteClass = $this->getMockSiteClass($className, $configuration);
$defaultSettings = [
- 'name' => 'Example site',
- 'emailAddress' => 'hello@example.com',
+ 'name' => 'Example site',
+ 'emailAddress' => 'hello@example.com',
+ 'robotIndexingDisallowed' => false,
];
$settings = array_merge($defaultSettings, (array) $settings);
diff --git a/tests/library/CM/Site/AbstractTest.php b/tests/library/CM/Site/AbstractTest.php
index <HASH>..<HASH> 100644
--- a/tests/library/CM/Site/AbstractTest.php
+++ b/tests/library/CM/Site/AbstractTest.php
@@ -10,8 +10,9 @@ class CM_Site_AbstractTest extends CMTest_TestCase {
'url' => 'http://www.foo.com',
'urlCdn' => 'http://www.cdn.com',
], [
- 'name' => 'Foo',
- 'emailAddress' => 'foo@foo.com',
+ 'name' => 'Foo',
+ 'emailAddress' => 'foo@foo.com',
+ 'robotIndexingDisallowed' => false,
]);
}
@@ -108,6 +109,14 @@ class CM_Site_AbstractTest extends CMTest_TestCase {
$site->setName('Bar');
$this->assertSame('bar@bar.com', $site->getEmailAddress());
$this->assertSame('Bar', $site->getName());
+
+ $this->assertSame(false, $site->isRobotIndexingDisallowed());
+ $site->setRobotIndexingDisallowed();
+ $this->assertSame(true, $site->isRobotIndexingDisallowed());
+ $site->setRobotIndexingDisallowed(false);
+ $this->assertSame(false, $site->isRobotIndexingDisallowed());
+ $site->setRobotIndexingDisallowed(true);
+ $this->assertSame(true, $site->isRobotIndexingDisallowed());
}
public function testDefault() {
|
added "robotIndexingDisallowed"-property to CM_Site
|
cargomedia_cm
|
train
|
1947938f7e0207c746cefc448528997dbe10cfc4
|
diff --git a/processor/command/complete.rb b/processor/command/complete.rb
index <HASH>..<HASH> 100644
--- a/processor/command/complete.rb
+++ b/processor/command/complete.rb
@@ -30,6 +30,7 @@ if __FILE__ == $0
require_relative '../mock'
dbgr, cmd = MockDebugger::setup
%w(d b bt).each do |prefix|
+ cmd.proc.instance_variable_set('@cmd_argstr', prefix)
cmd.run [cmd.name, prefix]
puts '=' * 40
end
|
Fix up standalone code for "complete" command.
|
rocky_rbx-trepanning
|
train
|
5e6491c3fedf2b23e6e1593f473ca4d30d61179c
|
diff --git a/discord/ext/commands/core.py b/discord/ext/commands/core.py
index <HASH>..<HASH> 100644
--- a/discord/ext/commands/core.py
+++ b/discord/ext/commands/core.py
@@ -204,10 +204,16 @@ class Command:
if converter.__module__.startswith('discord.') and not converter.__module__.endswith('converter'):
converter = getattr(converters, converter.__name__ + 'Converter')
- if inspect.isclass(converter) and issubclass(converter, converters.Converter):
- instance = converter()
- ret = yield from instance.convert(ctx, argument)
- return ret
+ if inspect.isclass(converter):
+ if issubclass(converter, converters.Converter):
+ instance = converter()
+ ret = yield from instance.convert(ctx, argument)
+ return ret
+ else:
+ method = getattr(converter, 'convert', None)
+ if method is not None and inspect.ismethod(method):
+ ret = yield from method(ctx, argument)
+ return ret
elif isinstance(converter, converters.Converter):
ret = yield from converter.convert(ctx, argument)
return ret
|
[commands] Allow inline advanced converters via classmethods.
That way you don't need to have, e.g. Foo and FooConverter and can
do it inline via Foo instead.
|
Rapptz_discord.py
|
train
|
1e8130488611c36422e6230e3c60b9ef3f3a762b
|
diff --git a/load_balancers.go b/load_balancers.go
index <HASH>..<HASH> 100644
--- a/load_balancers.go
+++ b/load_balancers.go
@@ -6,26 +6,44 @@ import (
type LoadBalancer struct {
Resource
- Name string
- Status string
- CreatedAt *time.Time `json:"created_at"`
- DeletedAt *time.Time `json:"deleted_at"`
- Locked bool
- Account Account
- Nodes []Server
- CloudIPs []CloudIP `json:"cloud_ips"`
- Policy string
- BufferSize int `json:"buffer_size"`
- Listeners []LoadBalancerListener
- // Certificate FIXME
- // Healthcheck FIXME
+ Name string
+ Status string
+ CreatedAt *time.Time `json:"created_at"`
+ DeletedAt *time.Time `json:"deleted_at"`
+ Locked bool
+ Account Account
+ Nodes []Server
+ CloudIPs []CloudIP `json:"cloud_ips"`
+ Policy string
+ BufferSize int `json:"buffer_size"`
+ Listeners []LoadBalancerListener
+ Healthcheck LoadBalancerHealthCheck
+ Certificate *LoadBalancerCertificate
+}
+
+type LoadBalancerCertificate struct {
+ ExpiresAt time.Time `json:"expires_at"`
+ ValidFrom time.Time `json:"valid_from"`
+ SslV3 bool `json:"sslv3"`
+ Issuer string `json:"issuer"`
+ Subject string `json:"subject"`
+}
+
+type LoadBalancerHealthCheck struct {
+ Type string `json:"type"`
+ Port int `json:"port"`
+ Request string `json:"request,omitempty"`
+ Interval int `json:"interval,omitempty"`
+ Timeout int `json:"timeout,omitempty"`
+ ThresholdUp int `json:"threshold_up,omitempty"`
+ ThresholdDown int `json:"threshold_down,omitempty"`
}
type LoadBalancerListener struct {
Protocol string `json:"protocol"`
In int `json:"in"`
Out int `json:"out"`
- Timeout int `json:"timeout"`
+ Timeout int `json:"timeout,omitempty"`
}
func (c *Client) LoadBalancers() ([]LoadBalancer, error) {
diff --git a/load_balancers_test.go b/load_balancers_test.go
index <HASH>..<HASH> 100644
--- a/load_balancers_test.go
+++ b/load_balancers_test.go
@@ -62,4 +62,11 @@ func TestLoadBalancer(t *testing.T) {
assert.Equal(t, 80, lnr.Out, "listener out port incorrect")
assert.Equal(t, 50000, lnr.Timeout, "listener timeout incorrect")
assert.Equal(t, "http", lnr.Protocol, "listener protocol incorrect")
+
+ assert.Equal(t, "http", lb.Healthcheck.Type, "healthcheck type incorrect")
+ assert.Equal(t, "/", lb.Healthcheck.Request, "healthcheck request incorrect")
+ assert.Equal(t, 80, lb.Healthcheck.Port, "healthchech port incorrect")
+
+ require.NotNil(t, lb.Certificate, "certificate is nil")
+ assert.Equal(t, "/CN=www.example.com", lb.Certificate.Subject, "certificate subject is incorrect")
}
diff --git a/testdata/load_balancer.json b/testdata/load_balancer.json
index <HASH>..<HASH> 100644
--- a/testdata/load_balancer.json
+++ b/testdata/load_balancer.json
@@ -21,7 +21,12 @@
"timeout": 5000,
"threshold_up": 3,
"threshold_down": 3},
- "certificate": null,
+ "certificate":
+ {"issuer": "/O=Root CA/OU=http://www.cacert.org/CN=CA Cert Signing Authority/emailAddress=support@cacert.org",
+ "subject": "/CN=www.example.com",
+ "sslv3": false,
+ "valid_from": "2012-08-01T21:41:26Z",
+ "expires_at": "2013-01-28T21:41:26Z"},
"account":
{"id": "acc-43ks4",
"resource_type": "account",
|
LoadBalancer Healthcheck and Certificate structs
|
brightbox_gobrightbox
|
train
|
e6154b214f22bf7f027c25f80040a177312501d0
|
diff --git a/agent/core/src/main/java/org/jolokia/discovery/MulticastUtil.java b/agent/core/src/main/java/org/jolokia/discovery/MulticastUtil.java
index <HASH>..<HASH> 100644
--- a/agent/core/src/main/java/org/jolokia/discovery/MulticastUtil.java
+++ b/agent/core/src/main/java/org/jolokia/discovery/MulticastUtil.java
@@ -54,8 +54,6 @@ public class MulticastUtil {
if (address instanceof Inet6Address) {
throw new IllegalArgumentException("Wrong address " + address + " found");
}
- System.out.println("Address: " + address);
- System.out.println("NI: " + NetworkInterface.getByInetAddress(address));
socket.setNetworkInterface(NetworkInterface.getByInetAddress(address));
socket.setTimeToLive(255);
// V6: ffx8::/16
|
Removed system.out.println use for debugging.
|
rhuss_jolokia
|
train
|
a013539f1850a44765acc8f5155ea89c69f4583e
|
diff --git a/lib/Thulium/Db/ModelQueryBuilder.php b/lib/Thulium/Db/ModelQueryBuilder.php
index <HASH>..<HASH> 100644
--- a/lib/Thulium/Db/ModelQueryBuilder.php
+++ b/lib/Thulium/Db/ModelQueryBuilder.php
@@ -133,8 +133,10 @@ class ModelQueryBuilder
return 0;
}
- $sql = 'DELETE FROM ' . $this->_model->getTableName() . ' WHERE ' . $this->_where;
- $this->_db->query($sql, $this->_whereValues);
+ $queryBuilder = new QueryBuilder($this->_db, array(), true);
+ $queryBuilder->from($this->_model->getTableName())
+ ->where($this->_where, $this->_whereValues)
+ ->delete();
return $this->rowAffected();
}
diff --git a/lib/Thulium/Db/QueryBuilder.php b/lib/Thulium/Db/QueryBuilder.php
index <HASH>..<HASH> 100644
--- a/lib/Thulium/Db/QueryBuilder.php
+++ b/lib/Thulium/Db/QueryBuilder.php
@@ -14,13 +14,14 @@ use Thulium\Utilities\Objects;
class QueryBuilder
{
private $_db = null;
- private $_query = 'SELECT ';
+ private $_query;
private $_queryValues = array();
public $_fetchStyle = PDO::FETCH_ASSOC;
+ private $_delete;
public $queryPrepared = null;
- public function __construct(Db $dbHandle, array $columns = array())
+ public function __construct(Db $dbHandle, array $columns = array(), $delete = false)
{
if ($dbHandle instanceof Db) {
$this->_db = $dbHandle;
@@ -28,6 +29,9 @@ class QueryBuilder
throw new DbSelectException('Wrong database handler');
}
+ $this->_delete = $delete;
+ $this->_query = $delete ? 'DELETE ' : 'SELECT ';
+
$this->columns($columns);
}
@@ -42,11 +46,13 @@ class QueryBuilder
private function columns(array $columns = array())
{
- if (!empty($columns)) {
- $this->_fetchStyle = PDO::FETCH_NUM;
- $this->_query .= Joiner::on(', ')->map($this->addAliases())->join($columns);
- } else {
- $this->_query .= 'main.*';
+ if (!$this->_delete) {
+ if (!empty($columns)) {
+ $this->_fetchStyle = PDO::FETCH_NUM;
+ $this->_query .= Joiner::on(', ')->map($this->addAliases())->join($columns);
+ } else {
+ $this->_query .= 'main.*';
+ }
}
return $this;
}
@@ -159,6 +165,11 @@ class QueryBuilder
return $this->_fetch('fetchAll');
}
+ public function delete()
+ {
+ $this->_db->query($this->_query, $this->_queryValues);
+ }
+
private function addAliases()
{
return function ($alias, $column) {
diff --git a/test/lib/Thulium/Db/ModelQueryBuilderTest.php b/test/lib/Thulium/Db/ModelQueryBuilderTest.php
index <HASH>..<HASH> 100644
--- a/test/lib/Thulium/Db/ModelQueryBuilderTest.php
+++ b/test/lib/Thulium/Db/ModelQueryBuilderTest.php
@@ -349,4 +349,20 @@ class ModelQueryBuilderTest extends DbTransactionalTestCase
$this->assertEquals(0, $affectedRows);
//no interaction with db
}
+
+ /**
+ * @test
+ */
+ public function shouldDeleteRecord()
+ {
+ //given
+ $product = Product::create(array('name' => 'a', 'description' => 'bob'));
+
+ //when
+ $product->delete();
+
+ //then
+ $allProducts = Product::all();
+ $this->assertCount(0, $allProducts);
+ }
}
\ No newline at end of file
|
Implemented delete in query builder.
|
letsdrink_ouzo
|
train
|
6744dfaee88e466a2ba553dbb873d4a6bd912150
|
diff --git a/cumulusci/core/tests/test_config_expensive.py b/cumulusci/core/tests/test_config_expensive.py
index <HASH>..<HASH> 100644
--- a/cumulusci/core/tests/test_config_expensive.py
+++ b/cumulusci/core/tests/test_config_expensive.py
@@ -24,13 +24,11 @@ __location__ = os.path.dirname(os.path.realpath(__file__))
@mock.patch("os.path.expanduser")
class TestBaseGlobalConfig(unittest.TestCase):
- @classmethod
- def setup_class(cls):
- cls.tempdir_home = tempfile.mkdtemp()
+ def setup_method(self, method):
+ self.tempdir_home = tempfile.mkdtemp()
- @classmethod
- def teardown_class(cls):
- shutil.rmtree(cls.tempdir_home)
+ def teardown_method(self, method):
+ shutil.rmtree(self.tempdir_home)
def _create_global_config_local(self, content):
global_local_dir = os.path.join(self.tempdir_home, ".cumulusci")
@@ -125,14 +123,14 @@ class TestBaseProjectConfig(unittest.TestCase):
with open(filename, "w") as f:
f.write(content)
- def setUp(self):
+ def setup_method(self, method):
self.tempdir_home = tempfile.mkdtemp()
self.tempdir_project = tempfile.mkdtemp()
self.project_name = "TestRepo"
self.current_commit = "abcdefg1234567890"
self.current_branch = "master"
- def tearDown(self):
+ def teardown_method(self, method):
shutil.rmtree(self.tempdir_home)
shutil.rmtree(self.tempdir_project)
|
Switch to per-method tmp because tests conflict
|
SFDO-Tooling_CumulusCI
|
train
|
7a504f94b141c0cdddeea0cc80bb9c91ece79d93
|
diff --git a/liquibase-core/src/main/java/liquibase/change/core/InsertDataChange.java b/liquibase-core/src/main/java/liquibase/change/core/InsertDataChange.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/change/core/InsertDataChange.java
+++ b/liquibase-core/src/main/java/liquibase/change/core/InsertDataChange.java
@@ -95,6 +95,12 @@ public class InsertDataChange extends AbstractChange implements ChangeWithColumn
if (column.getValueClobFile() != null) {
needsPreparedStatement = true;
}
+ if (LoadDataChange.LOAD_DATA_TYPE.BLOB.name().equalsIgnoreCase(column.getType())) {
+ needsPreparedStatement = true;
+ }
+ if (LoadDataChange.LOAD_DATA_TYPE.CLOB.name().equalsIgnoreCase(column.getType())) {
+ needsPreparedStatement = true;
+ }
if (!needsPreparedStatement && (database instanceof InformixDatabase)) {
if (column.getValue() != null) {
|
CLOB/BLOB types on insertData need to use the a perpared statement
|
liquibase_liquibase
|
train
|
097df4dda3baf483f7ca27a5d6a6eb5cf8a3ffbb
|
diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java
+++ b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java
@@ -18,15 +18,14 @@ public class DnsCacheFile implements Recorder {
public DnsCacheFile(String directory) throws IOException {
this.directory = directory;
f = new File(directory);
- if (!f.isDirectory() || !f.exists()) {
+ if (!f.isDirectory()) {
+ throw new IOException("does not mkdir");
+ }
+ if (!f.exists()) {
boolean r = f.mkdirs();
if (!r) {
throw new IOException("mkdir failed");
}
- return;
- }
- if (!f.isDirectory()) {
- throw new IOException("does not mkdir");
}
}
diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java
+++ b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java
@@ -20,12 +20,16 @@ public class DnsCacheInfo implements java.io.Serializable {
public String localIp;
public ConcurrentHashMap<String, List<IDnsNetworkAddress>> info;
- public static DnsCacheInfo createDnsCacheInfoByJsonData(byte[] jsonData) {
+ public static DnsCacheInfo createDnsCacheInfoByData(byte[] jsonData) {
if (jsonData == null){
return null;
}
- DnsCacheInfo dnsCacheInfo = (DnsCacheInfo)StringUtils.toObject(jsonData);
- return dnsCacheInfo;
+ Object dnsCacheInfo = StringUtils.toObject(jsonData);
+ if (dnsCacheInfo instanceof DnsCacheInfo){
+ return (DnsCacheInfo)dnsCacheInfo;
+ } else {
+ return null;
+ }
}
public DnsCacheInfo() {
diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java b/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java
+++ b/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java
@@ -8,22 +8,15 @@ import com.qiniu.android.common.ZonesInfo;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.http.metrics.UploadRegionRequestMetrics;
import com.qiniu.android.storage.GlobalConfiguration;
-import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UpToken;
import com.qiniu.android.utils.AndroidNetwork;
-import com.qiniu.android.utils.StringUtils;
import com.qiniu.android.utils.Utils;
import com.qiniu.android.utils.Wait;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@@ -226,7 +219,7 @@ public class DnsPrefetcher {
private boolean recoverDnsCache(byte[] data){
- DnsCacheInfo dnsCacheInfo = DnsCacheInfo.createDnsCacheInfoByJsonData(data);
+ DnsCacheInfo dnsCacheInfo = DnsCacheInfo.createDnsCacheInfoByData(data);
if (dnsCacheInfo == null || dnsCacheInfo.info == null || dnsCacheInfo.info.size() == 0){
return false;
}
|
modify dns cache file create logic and optimize dns cache info create by data
|
qiniu_android-sdk
|
train
|
1912aea14032082df690e7d493cbc53adb319cd9
|
diff --git a/src/com/algolia/search/AlgoliaClient.java b/src/com/algolia/search/AlgoliaClient.java
index <HASH>..<HASH> 100644
--- a/src/com/algolia/search/AlgoliaClient.java
+++ b/src/com/algolia/search/AlgoliaClient.java
@@ -6,6 +6,7 @@ import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
+import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
@@ -83,7 +84,7 @@ public class AlgoliaClient {
* List all existing indexes
* return an JSON Object in the form:
* { "items": [ {"name": "contacts", "createdAt": "2013-01-18T15:33:13.556Z"},
- * {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]��}
+ * {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]}
*/
public JSONObject listIndexes() throws AlgoliaException {
return _getRequest("/1/indexes/");
@@ -96,7 +97,11 @@ public class AlgoliaClient {
* return an object containing a "deletedAt" attribute
*/
public JSONObject deleteIndex(String indexName) throws AlgoliaException {
- return _deleteRequest("/1/indexes/" + indexName);
+ try {
+ return _deleteRequest("/1/indexes/" + URLEncoder.encode(indexName, "UTF-8"));
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
}
/**
|
Added url encoding of Index name on delete call
|
algolia_algoliasearch-client-android
|
train
|
5a61461b8f440371f8ab665dcc5889b0eb2de562
|
diff --git a/juicer/admin/JuicerAdmin.py b/juicer/admin/JuicerAdmin.py
index <HASH>..<HASH> 100644
--- a/juicer/admin/JuicerAdmin.py
+++ b/juicer/admin/JuicerAdmin.py
@@ -150,6 +150,7 @@ class JuicerAdmin(object):
Delete repo in specified environments
"""
+ orphan_query = '/content/orphans/rpm/'
juicer.utils.Log.log_debug("Delete Repo: %s", self.args.name)
for env in self.args.envs:
@@ -163,6 +164,18 @@ class JuicerAdmin(object):
if _r.status_code == Constants.PULP_DELETE_ACCEPTED:
juicer.utils.Log.log_info("deleted repo `%s` in %s",
(name, env))
+
+ # if delete was successful, delete orphaned rpms
+ _r = self.connectors[env].get(orphan_query)
+ if _r.status_code is Constants.PULP_GET_OK:
+ if len(juicer.utils.load_json_str(_r.content)) > 0:
+ __r = self.connectors[env].delete(orphan_query)
+ if __r.status_code is Constants.PULP_DELETE_OK:
+ juicer.utils.Log.log_debug("deleted orphaned rpms in %s." % env)
+ else:
+ juicer.utils.Log.log_error("unable to delete orphaned rpms in %s. a %s error was returned", (env, __r.status_code))
+ else:
+ juicer.utils.Log.log_error("unable to get a list of orphaned rpms. encountered a %s error." % _r.status_code)
else:
_r.raise_for_status()
return True
|
remove all orphaned rpms when deleting a repo for #<I>
|
juicer_juicer
|
train
|
132dd74a97529d1e27c103a3f28642e7d8e05cb8
|
diff --git a/src/Model/controller.php b/src/Model/controller.php
index <HASH>..<HASH> 100644
--- a/src/Model/controller.php
+++ b/src/Model/controller.php
@@ -312,29 +312,6 @@ $this->get('/admin/system/model/:schema/create', function ($request, $response)
$data['schema']['singular']
);
- //add custom page helpers
- $this->package('global')
- ->handlebars()
- ->registerHelper('json_encode', function (...$args) {
- $options = array_pop($args);
- $value = array_shift($args);
-
- foreach ($args as $arg) {
- if (!isset($value[$arg])) {
- $value = null;
- break;
- }
-
- $value = $value[$arg];
- }
-
- if (!$value) {
- return '';
- }
-
- return json_encode($value, JSON_PRETTY_PRINT);
- });
-
//render the body
$body = $this
->package('cradlephp/cradle-system')
@@ -513,28 +490,6 @@ $this->get('/admin/system/model/:schema/update/:id', function ($request, $respon
$data['schema']['singular']
);
- //add custom page helpers
- $this->package('global')
- ->handlebars()
- ->registerHelper('json_encode', function (...$args) {
- $options = array_pop($args);
- $value = array_shift($args);
- foreach ($args as $arg) {
- if (!isset($value[$arg])) {
- $value = null;
- break;
- }
-
- $value = $value[$arg];
- }
-
- if (!$value) {
- return '';
- }
-
- return json_encode($value, JSON_PRETTY_PRINT);
- });
-
//render the body
$body = $this
->package('cradlephp/cradle-system')
@@ -718,28 +673,6 @@ $this->get('/admin/system/model/:schema/detail/:id', function ($request, $respon
$compiled
);
- //add custom page helpers
- $this->package('global')
- ->handlebars()
- ->registerHelper('json_encode', function (...$args) {
- $options = array_pop($args);
- $value = array_shift($args);
- foreach ($args as $arg) {
- if (!isset($value[$arg])) {
- $value = null;
- break;
- }
-
- $value = $value[$arg];
- }
-
- if (!$value) {
- return '';
- }
-
- return json_encode($value, JSON_PRETTY_PRINT);
- });
-
//render the body
$body = $this
->package('cradlephp/cradle-system')
diff --git a/src/Model/template/form/_fields.html b/src/Model/template/form/_fields.html
index <HASH>..<HASH> 100644
--- a/src/Model/template/form/_fields.html
+++ b/src/Model/template/form/_fields.html
@@ -932,7 +932,7 @@
{{#each field.attributes}}
{{@key}}="{{this}}"
{{/each}}
- >{{json_encode ../item @key}}</textarea>
+ >{{{json_encode ../item @key}}}</textarea>
{{/when}}
{{#when field.type '===' 'multifield'}}
{{#each field.schema.detail}}
diff --git a/src/helpers.php b/src/helpers.php
index <HASH>..<HASH> 100644
--- a/src/helpers.php
+++ b/src/helpers.php
@@ -117,6 +117,33 @@ return function($request, $response) {
return $options['inverse']();
});
+ $handlebars->registerHelper('json_encode', function (...$args) {
+ $options = array_pop($args);
+ $value = array_shift($args);
+ foreach ($args as $arg) {
+ if (!isset($value[$arg])) {
+ $value = null;
+ break;
+ }
+
+ $value = $value[$arg];
+ }
+
+ if (!$value) {
+ return '';
+ }
+
+ if (!is_array($value) && !is_object($value)) {
+ return $value;
+ }
+
+ return json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+ });
+
+ $handlebars->registerHelper('json_pretty', function ($value, $options) {
+ return nl2br(str_replace(' ', ' ', json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)));
+ });
+
/**
* Add Template Builder
*/
|
critical fix with JSON fields and format when form results in an error
|
CradlePHP_cradle-system
|
train
|
9dc6c30cd254ced78bb4819dc9f6ae512d9c6979
|
diff --git a/servers/src/main/java/tachyon/master/next/MasterBase.java b/servers/src/main/java/tachyon/master/next/MasterBase.java
index <HASH>..<HASH> 100644
--- a/servers/src/main/java/tachyon/master/next/MasterBase.java
+++ b/servers/src/main/java/tachyon/master/next/MasterBase.java
@@ -23,6 +23,7 @@ import org.slf4j.LoggerFactory;
import tachyon.Constants;
import tachyon.master.next.journal.Journal;
import tachyon.master.next.journal.JournalEntry;
+import tachyon.master.next.journal.JournalSerializable;
import tachyon.master.next.journal.JournalTailerThread;
import tachyon.master.next.journal.JournalWriter;
@@ -97,6 +98,19 @@ public abstract class MasterBase implements Master {
}
}
+ protected void writeJournalEntry(JournalSerializable entry) {
+ if (mJournalWriter == null) {
+ // TODO: Add this check back
+ // throw new RuntimeException("Cannot write entry: journal writer is null.");
+ return;
+ }
+ try {
+ entry.writeToJournal(mJournalWriter.getEntryOutputStream());
+ } catch (IOException ioe) {
+ throw new RuntimeException(ioe);
+ }
+ }
+
protected void flushJournal() {
if (mJournalWriter == null) {
// TODO: Add this check back
diff --git a/servers/src/main/java/tachyon/master/next/filesystem/FileSystemMaster.java b/servers/src/main/java/tachyon/master/next/filesystem/FileSystemMaster.java
index <HASH>..<HASH> 100644
--- a/servers/src/main/java/tachyon/master/next/filesystem/FileSystemMaster.java
+++ b/servers/src/main/java/tachyon/master/next/filesystem/FileSystemMaster.java
@@ -34,7 +34,6 @@ import tachyon.master.block.BlockId;
import tachyon.master.next.MasterBase;
import tachyon.master.next.block.BlockMaster;
import tachyon.master.next.filesystem.journal.AddCheckpointEntry;
-import tachyon.master.next.filesystem.journal.InodeDirectoryEntry;
import tachyon.master.next.filesystem.journal.InodeEntry;
import tachyon.master.next.filesystem.meta.Dependency;
import tachyon.master.next.filesystem.meta.DependencyMap;
@@ -283,13 +282,20 @@ public class FileSystemMaster extends MasterBase {
throws InvalidPathException, FileAlreadyExistException, BlockInfoException {
// TODO: metrics
synchronized (mInodeTree) {
+ TachyonURI firstNonexistentPathPrefix = mInodeTree.firstNonexistentPathPrefix(path);
InodeFile inode = (InodeFile) mInodeTree.createPath(path, blockSizeBytes, recursive, false);
if (mWhitelist.inList(path.toString())) {
inode.setCache(true);
}
- return inode.getId();
- // TODO: write to journal
+ if (firstNonexistentPathPrefix != null) {
+ Inode firstCreatedInode = mInodeTree.getInodeByPath(firstNonexistentPathPrefix);
+ writeJournalEntry(firstCreatedInode);
+ } else {
+ writeJournalEntry(inode);
+ }
+
+ return inode.getId();
}
}
diff --git a/servers/src/main/java/tachyon/master/next/filesystem/meta/InodeTree.java b/servers/src/main/java/tachyon/master/next/filesystem/meta/InodeTree.java
index <HASH>..<HASH> 100644
--- a/servers/src/main/java/tachyon/master/next/filesystem/meta/InodeTree.java
+++ b/servers/src/main/java/tachyon/master/next/filesystem/meta/InodeTree.java
@@ -63,10 +63,10 @@ public final class InodeTree implements JournalSerializable {
/**
* Inode id management. Inode ids are essentially block ids.
- *
+ *
* inode files: Each file id will be composed of a unique block container id, with the maximum
* sequence number.
- *
+ *
* inode directories: Each directory id will be a unique block id, in order to avoid any collision
* with file ids.
*/
@@ -231,6 +231,27 @@ public final class InodeTree implements JournalSerializable {
}
/**
+ * Returns the first(shortest) path prefix that is nonexistent in the inode tree.
+ *
+ * @param path The path to check whether its prefixes are in the inode tree
+ * @return The first nonexistent path prefix, or null if the path is in the tree
+ * @throws InvalidPathException when the path is invalid
+ */
+ public TachyonURI firstNonexistentPathPrefix(TachyonURI path) throws InvalidPathException {
+ String[] pathComponents = PathUtils.getPathComponents(path.getPath());
+ TraversalResult traversalResult = traverseToInode(pathComponents);
+ if (traversalResult.isFound()) {
+ return null;
+ }
+ int nonexistentPathIndex = traversalResult.getNonexistentPathIndex();
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i <= nonexistentPathIndex; i ++) {
+ sb.append(pathComponents[i]);
+ }
+ return new TachyonURI(sb.toString());
+ }
+
+ /**
* Returns a list of all descendants of a particular {@link InodeDirectory}. Any directory inode
* precedes its descendants in the list.
*
@@ -301,7 +322,7 @@ public final class InodeTree implements JournalSerializable {
/**
* Adds the inode represented by the entry parameter into the inode tree. If the inode entry
* represents the root inode, the tree is "reset", and all state is cleared.
- *
+ *
* @param entry The journal entry representing an inode.
*/
public void addInodeFromJournal(InodeEntry entry) {
|
Write journal in FileSystemMaster#createFile
|
Alluxio_alluxio
|
train
|
b67f45a72eba9270eb1d77b81455add26e2e73f0
|
diff --git a/go/dhcp/main.go b/go/dhcp/main.go
index <HASH>..<HASH> 100644
--- a/go/dhcp/main.go
+++ b/go/dhcp/main.go
@@ -482,7 +482,7 @@ func (h *Interface) ServeDHCP(p dhcp.Packet, msgType dhcp.MessageType) (answer A
reqIP = net.IP(p.CIAddr())
}
- clientHostname := string(options[12])
+ clientHostname := string(options[dhcp.OptionHostName])
log.LoggerWContext(ctx).Info(prettyType + " for " + reqIP.String() + " from " + clientMac + " (" + clientHostname + ")")
answer.IP = reqIP
|
use constant for pfdhcp option
|
inverse-inc_packetfence
|
train
|
7e63f7bc21e6857f8e741ea0f0de41068c61a1bc
|
diff --git a/newsletter-bundle/src/Resources/contao/dca/tl_newsletter_recipients.php b/newsletter-bundle/src/Resources/contao/dca/tl_newsletter_recipients.php
index <HASH>..<HASH> 100644
--- a/newsletter-bundle/src/Resources/contao/dca/tl_newsletter_recipients.php
+++ b/newsletter-bundle/src/Resources/contao/dca/tl_newsletter_recipients.php
@@ -365,6 +365,12 @@ class tl_newsletter_recipients extends Backend
if (strlen(Input::get('tid')))
{
$this->toggleVisibility(Input::get('tid'), (Input::get('state') == 1));
+
+ if (Environment::get('isAjaxRequest'))
+ {
+ exit;
+ }
+
$this->redirect($this->getReferer());
}
|
[Newsletter] Correctly handle "toggle visibility" requests via Ajax
|
contao_contao
|
train
|
c5ac79815c0d1532f94be91ce3b560141c3fe482
|
diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Database/Query/Builder.php
+++ b/src/Illuminate/Database/Query/Builder.php
@@ -1613,7 +1613,7 @@ class Builder
{
$this->lock = $value;
- if ($this->lock) {
+ if (isset($this->lock)) {
$this->useWritePdo();
}
|
[<I>] Execute queries with lock only in write database (#<I>)
* Fix namespace. (#<I>)
* Execute queries with lock only in write database.
|
laravel_framework
|
train
|
dd050b3320e90bb38660b6e8b75469b6cf3812b4
|
diff --git a/course/lib.php b/course/lib.php
index <HASH>..<HASH> 100644
--- a/course/lib.php
+++ b/course/lib.php
@@ -1121,15 +1121,13 @@ function print_course_admin_links($course, $width=180) {
$admindata[]="<a href=\"teacher.php?id=$course->id\">$course->teachers...</a>";
$adminicon[]="<img src=\"$CFG->pixpath/i/users.gif\" height=16 width=16 alt=\"\">";
}
- }
- if (!$course->students) {
- $course->students = get_string("defaultcoursestudents");
- }
- $admindata[]="<a href=\"student.php?id=$course->id\">$course->students...</a>";
- $adminicon[]="<img src=\"$CFG->pixpath/i/users.gif\" height=16 width=16 alt=\"\">";
+ if (!$course->students) {
+ $course->students = get_string("defaultcoursestudents");
+ }
+ $admindata[]="<a href=\"student.php?id=$course->id\">$course->students...</a>";
+ $adminicon[]="<img src=\"$CFG->pixpath/i/users.gif\" height=16 width=16 alt=\"\">";
- if ($isteacheredit) {
$admindata[]="<a href=\"$CFG->wwwroot/backup/backup.php?id=$course->id\">".get_string("backup")."...</a>";
$adminicon[]="<img src=\"$CFG->pixpath/i/backup.gif\" height=16 width=16 alt=\"\">";
|
Non-editing teachers should not be able to assign students
|
moodle_moodle
|
train
|
d5859de46c5af39d9f229242d194d12ebcb16469
|
diff --git a/modules/admin/tests/admin/ngrest/plugins/SelectModelTest.php b/modules/admin/tests/admin/ngrest/plugins/SelectModelTest.php
index <HASH>..<HASH> 100644
--- a/modules/admin/tests/admin/ngrest/plugins/SelectModelTest.php
+++ b/modules/admin/tests/admin/ngrest/plugins/SelectModelTest.php
@@ -6,6 +6,7 @@ use admintests\AdminTestCase;
use admintests\data\fixtures\UserFixture;
use luya\admin\models\User;
use luya\admin\ngrest\plugins\SelectModel;
+use yii\base\Event;
class SelectModelTest extends AdminTestCase
{
@@ -96,4 +97,34 @@ class SelectModelTest extends AdminTestCase
unset($plugin);
}
+
+ /**
+ * Test relating with i18n casted select fields:
+ *
+ * https://github.com/luyadev/luya/issues/1125#issuecomment-269737028
+ */
+ public function testAfterFindEventWithI18n()
+ {
+ $event = new Event();
+ $model = new UserFixture();
+ $model->load();
+
+ $user = $model->getModel('user1');
+ $event->sender = $user;
+
+ $plugin = new SelectModel([
+ 'name' => 'id',
+ 'alias' => 'test',
+ 'i18n' => true,
+ 'modelClass' => User::class,
+ 'valueField' => 'id',
+ 'labelField' => 'email',
+ ]);
+
+ $plugin->onFind($event);
+
+ $this->assertSame("", $user->id);
+
+ unset($plugin);
+ }
}
\ No newline at end of file
|
added very basic empty string test when i<I>n cast on i<I>n field #<I>
|
luyadev_luya
|
train
|
2428b9021aa04afcf83f49325a366010275c89fa
|
diff --git a/Encoder/JWTEncoderInterface.php b/Encoder/JWTEncoderInterface.php
index <HASH>..<HASH> 100644
--- a/Encoder/JWTEncoderInterface.php
+++ b/Encoder/JWTEncoderInterface.php
@@ -13,6 +13,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException;
interface JWTEncoderInterface
{
/**
+ * @param array $header
* @param array $data
*
* @return string the encoded token string
@@ -20,15 +21,16 @@ interface JWTEncoderInterface
* @throws JWTEncodeFailureException If an error occurred while trying to create
* the token (invalid crypto key, invalid payload...)
*/
- public function encode(array $data);
+ public function encode(array $header, array $data);
/**
* @param string $token
+ * @param array $header
*
* @return array
*
* @throws JWTDecodeFailureException If an error occurred while trying to load the token
* (invalid signature, invalid crypto key, expired token...)
*/
- public function decode($token);
+ public function decode($token, array &$header = array());
}
|
Header used for JWT encoding and decoding ops
|
lexik_LexikJWTAuthenticationBundle
|
train
|
40093176d53932985f74c844ba77956c212eaa4a
|
diff --git a/h2o-algos/src/main/java/hex/tree/SharedTree.java b/h2o-algos/src/main/java/hex/tree/SharedTree.java
index <HASH>..<HASH> 100755
--- a/h2o-algos/src/main/java/hex/tree/SharedTree.java
+++ b/h2o-algos/src/main/java/hex/tree/SharedTree.java
@@ -189,15 +189,6 @@ public abstract class SharedTree<
_isUplift = _parms._treatment_column != null;
}
- @Override
- public String[] specialColNames() {
- String[] colNames = super.specialColNames();
- if(_parms._treatment_column != null) {
- return ArrayUtils.append(colNames, _parms._treatment_column);
- }
- return colNames;
- }
-
protected void validateRowSampleRate() {
if (!(0.0 < _parms._sample_rate && _parms._sample_rate <= 1.0))
error("_sample_rate", "sample_rate should be in interval ]0,1] but it is " + _parms._sample_rate + ".");
diff --git a/h2o-core/src/main/java/hex/ModelBuilder.java b/h2o-core/src/main/java/hex/ModelBuilder.java
index <HASH>..<HASH> 100644
--- a/h2o-core/src/main/java/hex/ModelBuilder.java
+++ b/h2o-core/src/main/java/hex/ModelBuilder.java
@@ -1048,16 +1048,6 @@ abstract public class ModelBuilder<M extends Model<M,P,O>, P extends Model.Param
public boolean hasFoldCol() { return _parms._fold_column != null;} // don't look at transient Vec
public boolean hasTreatmentCol() { return _parms._treatment_column != null;}
public int numSpecialCols() { return (hasOffsetCol() ? 1 : 0) + (hasWeightCol() ? 1 : 0) + (hasFoldCol() ? 1 : 0) + (hasTreatmentCol() ? 1 : 0); }
- public String[] specialColNames() {
- String[] n = new String[numSpecialCols()];
- int i=0;
- if (hasOffsetCol()) n[i++]=_parms._offset_column;
- if (hasWeightCol()) n[i++]=_parms._weights_column;
- if (hasFoldCol()) n[i++]=_parms._fold_column;
- if (hasTreatmentCol()) n[i++]=_parms._treatment_column;
- return n;
- }
- // no hasResponse, call isSupervised instead (response is mandatory if isSupervised is true)
public boolean havePojo() { return false; }
public boolean haveMojo() { return false; }
|
SharedTree doesn't need to address treatment column, MB already handles it
|
h2oai_h2o-3
|
train
|
bc50885172640416efbd957221eeb254267d00d3
|
diff --git a/src/main/resources/META-INF/resources/primefaces/sheet/sheet.js b/src/main/resources/META-INF/resources/primefaces/sheet/sheet.js
index <HASH>..<HASH> 100644
--- a/src/main/resources/META-INF/resources/primefaces/sheet/sheet.js
+++ b/src/main/resources/META-INF/resources/primefaces/sheet/sheet.js
@@ -245,6 +245,26 @@ PrimeFaces.widget.Sheet.prototype.bindDynamicEvents = function() {
_self.cells.filter('.ui-state-highlight').removeClass('ui-state-highlight');
_self.selectCell(cell);
}
+
+ cell = cell.parent();
+ var bTable = _self.body.children('table:first'),
+ yScrolled = _self.body.height() < bTable.height(),
+ xScrolled = _self.body.width() < bTable.width();
+
+ // up/down nav with scrolling
+ var diff = cell.offset().top + cell.outerHeight(true) - _self.body.offset().top;
+ if( diff > _self.body.height() )
+ _self.body.scrollTop(_self.body.scrollTop() + (diff - _self.body.height()) + (xScrolled ? 16 : 0));
+ else if( (diff -= cell.outerHeight(true)*2 - cell.height()) < 0 )
+ _self.body.scrollTop( _self.body.scrollTop() + diff);
+
+
+ // left/right nav with scrolling
+ diff = cell.offset().left + cell.outerWidth(true) - _self.body.offset().left;
+ if( diff > _self.body.width() )
+ _self.body.scrollLeft(_self.body.scrollLeft() + (diff - _self.body.width()) + (yScrolled ? 16 : 0));
+ else if( (diff -= cell.outerWidth(true)*2 - cell.width()) < 0 )
+ _self.body.scrollLeft( _self.body.scrollLeft() + diff);
})
.dblclick(function(e) {
var cell = $(this),
@@ -364,24 +384,28 @@ PrimeFaces.widget.Sheet.prototype.bindStaticEvents = function() {
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
case keyCode.DOWN:
- _self.cursor = _self.cursor.parents('tr:first').next().children().eq(_self.cursor.parent().index()).children('div.ui-sh-c');
+ var next = _self.cursor.parents('tr:first').next().children().eq(_self.cursor.parent().index()).children('div.ui-sh-c');
+ if(next && next.length){
+ _self.cursor = next;
+ if(shift)
+ _self.selectCells(origin, _self.cursor);
+ else
+ _self.cursor.click();
+ }
- if(shift)
- _self.selectCells(origin, _self.cursor);
- else
- _self.cursor.click();
-
e.preventDefault();
break;
case keyCode.UP:
- _self.cursor = _self.cursor.parents('tr:first').prev().children().eq(_self.cursor.parent().index()).children('div.ui-sh-c');
+ var prev = _self.cursor.parents('tr:first').prev().children().eq(_self.cursor.parent().index()).children('div.ui-sh-c');
+ if(prev && prev.length){
+ _self.cursor = prev;
+ if(shift)
+ _self.selectCells(origin, _self.cursor);
+ else
+ _self.cursor.click();
+ }
- if(shift)
- _self.selectCells(origin, _self.cursor);
- else
- _self.cursor.click();
-
e.preventDefault();
break;
|
Improved sheet with arrow navigation.
|
primefaces_primefaces
|
train
|
7353ec466f18d80ad4003d957810acedcb5ea718
|
diff --git a/ReadMe.md b/ReadMe.md
index <HASH>..<HASH> 100644
--- a/ReadMe.md
+++ b/ReadMe.md
@@ -13,7 +13,7 @@
var say = require('say'),
colors = require('colors'),
- sys = require('sys');
+ util = require('util');
// no callback, fire and forget
say.speak('Alex', 'whats up, dog?');
@@ -23,7 +23,7 @@
// output some text to the console as the callback
say.speak('Good News', 'whats up, dog?', function () {
- sys.puts('text to speech complete'.green);
+ util.puts('text to speech complete'.green);
});
diff --git a/examples/demo.js b/examples/demo.js
index <HASH>..<HASH> 100644
--- a/examples/demo.js
+++ b/examples/demo.js
@@ -1,6 +1,6 @@
var say = require('../lib/say'),
colors = require('colors'),
-sys = require('sys');
+util = require('util');
// no callback, fire and forget
say.speak('Alex', 'whats up, dog?');
@@ -10,5 +10,5 @@ say.speak('Cellos', 'whats up, dog?');
// output some text to the console as the callback
say.speak('Good News', 'whats up, dog?', function () {
- sys.puts('text to speech complete'.green);
+ util.puts('text to speech complete'.green);
});
diff --git a/lib/say.js b/lib/say.js
index <HASH>..<HASH> 100644
--- a/lib/say.js
+++ b/lib/say.js
@@ -89,7 +89,7 @@ exports.speak = function(voice, text, callback){
sys.puts('whats, up dog?'); // did you hear that?
exports.puts = function(){
- var s2 = require('sys');
+ var s2 = require('util');
// don't try this at home
sys.puts = function(text){
s2.puts(text);
|
[fix] Changed require('util') to require('util') for compatibility with node <I>
|
Marak_say.js
|
train
|
e54d2e93ccc95be7805633badb06471d0056d03c
|
diff --git a/lib/metanorma/collection_renderer.rb b/lib/metanorma/collection_renderer.rb
index <HASH>..<HASH> 100644
--- a/lib/metanorma/collection_renderer.rb
+++ b/lib/metanorma/collection_renderer.rb
@@ -338,7 +338,7 @@ module Metanorma
f.close
# warn "metanorma compile -x html #{f.path}"
c = Compile.new
- options = {format: :asciidoc, extension_keys: @format}.merge @compile_options
+ options = { format: :asciidoc, extension_keys: @format }.merge @compile_options
c.compile f.path, options
@files[identifier][:outputs] = {}
@format.each do |e|
diff --git a/spec/compile_spec.rb b/spec/compile_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/compile_spec.rb
+++ b/spec/compile_spec.rb
@@ -31,7 +31,7 @@ RSpec.describe Metanorma::Compile do
allow(compile).to receive(:fontist_install) {}
expect(compile).to receive(:fontist_install).once
- compile.compile("spec/assets/test.adoc", type: "iso", :"agree-to-terms" => true, :"no_install_fonts" => false)
+ compile.compile("spec/assets/test.adoc", type: "iso", :"agree-to-terms" => true, :"no-install-fonts" => false)
end
it "skip font install with no_install_fonts" do
|
Fix formatting in brackets and misstype in no-install-fonts
|
metanorma_metanorma
|
train
|
48062e2e3f4ad32952db2bb15075a0ef8ca3fc64
|
diff --git a/lib/Doctrine/ODM/PHPCR/DocumentManager.php b/lib/Doctrine/ODM/PHPCR/DocumentManager.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ODM/PHPCR/DocumentManager.php
+++ b/lib/Doctrine/ODM/PHPCR/DocumentManager.php
@@ -414,6 +414,8 @@ class DocumentManager implements ObjectManager
*/
public function getDocumentsByQuery(\PHPCR\Query\QueryInterface $query, $className = null)
{
+ $this->errorIfClosed();
+
$documents = array();
// get all nodes from the node iterator
@@ -475,6 +477,7 @@ class DocumentManager implements ObjectManager
*/
public function getLocalesFor($document)
{
+ $this->errorIfClosed();
return $this->unitOfWork->getLocalesFor($document);
}
@@ -502,10 +505,10 @@ class DocumentManager implements ObjectManager
*/
public function merge($document)
{
+ $this->errorIfClosed();
throw new \BadMethodCallException(__METHOD__.' not yet implemented');
// TODO: implemenent
- $this->errorIfClosed();
return $this->getUnitOfWork()->merge($document);
}
|
check if the DM is closed in all relevant places
|
doctrine_phpcr-odm
|
train
|
2e2c4c0a1c8aba18b856feec4ac0fae9ac1ddbbd
|
diff --git a/bcbio/variation/population.py b/bcbio/variation/population.py
index <HASH>..<HASH> 100644
--- a/bcbio/variation/population.py
+++ b/bcbio/variation/population.py
@@ -41,7 +41,10 @@ def _do_db_build(samples):
"""Confirm we should build a gemini database: need gemini + human samples.
"""
config = samples[0]["config"]
- gemini = config_utils.get_program("gemini", config)
+ try:
+ gemini = config_utils.get_program("gemini", config)
+ except config_utils.CmdNotFound:
+ return False
try:
p = subprocess.Popen([gemini, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.wait()
|
Correctly catch CmdNotFound errors when retrieving gemini information from configuration.
|
bcbio_bcbio-nextgen
|
train
|
b5273babb50b6b9699655f2701aac7bf841ffe1b
|
diff --git a/src/ol/View.js b/src/ol/View.js
index <HASH>..<HASH> 100644
--- a/src/ol/View.js
+++ b/src/ol/View.js
@@ -971,6 +971,9 @@ class View extends BaseObject {
*/
getResolutionForZoom(zoom) {
if (this.resolutions_) {
+ if (this.resolutions_.length <= 1) {
+ return 0;
+ }
const baseLevel = clamp(Math.floor(zoom), 0, this.resolutions_.length - 2);
const zoomFactor = this.resolutions_[baseLevel] / this.resolutions_[baseLevel + 1];
return this.resolutions_[baseLevel] / Math.pow(zoomFactor, clamp(zoom - baseLevel, 0, 1));
|
View / handle resolutions array with length=1
|
openlayers_openlayers
|
train
|
542828825bc99bd5a59f58eaf74cfd2eaa1440de
|
diff --git a/arthur/test/test_ui.py b/arthur/test/test_ui.py
index <HASH>..<HASH> 100644
--- a/arthur/test/test_ui.py
+++ b/arthur/test/test_ui.py
@@ -243,7 +243,7 @@ class LauncherTests(unittest.SynchronousTestCase):
class UnhandledInputTests(unittest.SynchronousTestCase):
def test_quit(self):
- """The unhandled input handler raises urwid.ExitMainLoop on C-q.
+ """The unhandled input handler raises urwid.ExitMainLoop on C-w.
"""
- self.assertRaises(urwid.ExitMainLoop, ui._unhandledInput, "ctrl q")
+ self.assertRaises(urwid.ExitMainLoop, ui._unhandledInput, "ctrl w")
diff --git a/arthur/ui.py b/arthur/ui.py
index <HASH>..<HASH> 100644
--- a/arthur/ui.py
+++ b/arthur/ui.py
@@ -63,7 +63,7 @@ def _unhandledInput(event):
"""Handles input events that weren't handled anywhere else.
"""
- if event == "ctrl q":
+ if event == "ctrl w":
raise urwid.ExitMainLoop()
|
Use C-w instead of C-q
|
crypto101_arthur
|
train
|
953e6ad73144b738d57892c7fe3f9ec7882310da
|
diff --git a/library/Benri/Db/Table.php b/library/Benri/Db/Table.php
index <HASH>..<HASH> 100644
--- a/library/Benri/Db/Table.php
+++ b/library/Benri/Db/Table.php
@@ -43,17 +43,17 @@ class Benri_Db_Table extends Zend_Db_Table
/**
* Fetches all rows.
*
- * @param int $currentPage An SQL LIMIT offset
+ * @param int $pageNumber An SQL LIMIT offset
* @param int $pageSize An SQL LIMIT count
* @param string|array $order An SQL ORDER clause
* @return Benri_Db_Table_Row The row results
*/
- public static function all($currentPage = 1, $pageSize = 10, $order = null)
+ public static function all($pageNumber = 1, $pageSize = 10, $order = null)
{
$table = new static();
$select = $table->select()
->order($order)
- ->limitPage($currentPage, $pageSize);
+ ->limitPage($pageNumber, $pageSize);
return $table->fetchAll($select);
}
|
Removed _setupDatabaseAdapter(). Not a very common use case (closes #4).
|
douggr_benri
|
train
|
eef006542fc364afbfe313b3bb6eba208cd83bdd
|
diff --git a/src/frontend/org/voltdb/parser/SQLParser.java b/src/frontend/org/voltdb/parser/SQLParser.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/parser/SQLParser.java
+++ b/src/frontend/org/voltdb/parser/SQLParser.java
@@ -17,7 +17,10 @@
package org.voltdb.parser;
+import java.io.BufferedReader;
import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@@ -1327,8 +1330,28 @@ public class SQLParser extends SQLPatternFactory
* like CREATE, ALTER, DROP, PARTITION, or EXPORT
*/
public static boolean batchBeginsWithDDLKeyword(String batch) {
- // This method is really supposed to look at a single statement, but it seems
- // also to work for a batch of statements.
- return queryIsDDL(batch);
+
+ BufferedReader reader = new BufferedReader(new StringReader(batch));
+ String line;
+ try {
+ while ((line = reader.readLine()) != null) {
+
+ line = SingleLineComments.matcher(line).replaceAll("");
+ line = line.trim();
+ if (line.equals(""))
+ continue;
+
+ // we have a non-blank line that contains more than just a comment.
+ return queryIsDDL(line);
+ }
+ }
+ catch (IOException e) {
+ // This should never happen for a StringReader
+ assert(false);
+ }
+
+
+ // degenerate batch: no lines are non-blank or non-comment
+ return false;
}
}
diff --git a/tests/frontend/org/voltdb/parser/TestSQLParser.java b/tests/frontend/org/voltdb/parser/TestSQLParser.java
index <HASH>..<HASH> 100644
--- a/tests/frontend/org/voltdb/parser/TestSQLParser.java
+++ b/tests/frontend/org/voltdb/parser/TestSQLParser.java
@@ -67,13 +67,22 @@ public class TestSQLParser extends TestCase {
+ "create table t (i integer); -- let's not forget the index...\n"
+ "create index idx on t (i);"));
+ // This currently does not work.
+ // assertTrue(SQLParser.batchBeginsWithDDLKeyword(
+ // "/* here's some DDL: */\n"
+ // + "create table t (i integer); -- let's not forget the index...\n"
+ // + "create index idx on t (i);"));
+
assertTrue(SQLParser.batchBeginsWithDDLKeyword(
- "/* here's some DDL: */\n"
+ "// here's some DDL; check it out!\n"
+ "create table t (i integer); -- let's not forget the index...\n"
+ "create index idx on t (i);"));
+ // leading whitespace
assertTrue(SQLParser.batchBeginsWithDDLKeyword(
- "// here's some DDL; check it out!\n"
+ " \n"
+ + "// here's some DDL; check it out!\n"
+ + " \n"
+ "create table t (i integer); -- let's not forget the index...\n"
+ "create index idx on t (i);"));
@@ -82,17 +91,23 @@ public class TestSQLParser extends TestCase {
public void testBatchBeginsWithDDLKeywordNegative() {
assertFalse(SQLParser.batchBeginsWithDDLKeyword(
- "insert into t values (47);"));
+ "insert into t values (47);\n"
+ + "partition table t on z;"));
assertFalse(SQLParser.batchBeginsWithDDLKeyword(
"delete from t where i = 9;"));
assertFalse(SQLParser.batchBeginsWithDDLKeyword(
- "upsert into t values (32);"));
+ "upsert into t values (32);\n"
+ + "alter table t add column j bigint;"));
assertFalse(SQLParser.batchBeginsWithDDLKeyword(
"update t set i = 70 where i > 69;"));
+ assertFalse(SQLParser.batchBeginsWithDDLKeyword(
+ "update t set i = 70 where i > 69;\n"
+ + "create table mytable (i integer);"));
+
// Now some comments
assertFalse(SQLParser.batchBeginsWithDDLKeyword(
@@ -103,10 +118,25 @@ public class TestSQLParser extends TestCase {
"// create table was done earlier...\n"
+ "update t set i = 70 where i > 69;"));
+ // This passes only because the C-style comment
+ // doesn't look like DDL--it isn't stripped out.
assertFalse(SQLParser.batchBeginsWithDDLKeyword(
"/* create table was done earlier... */\n"
+ "update t set i = 70 where i > 69;"));
+ assertFalse(SQLParser.batchBeginsWithDDLKeyword(
+ " \n"
+ + "select * from foo;"
+ + "create table catdog (dogcat bigint);"));
+
+ assertFalse(SQLParser.batchBeginsWithDDLKeyword(
+ " \n"
+ + " -- hello world!!"
+ + " \t\n"
+ + "select * from foo;"
+ + "create table catdog (dogcat bigint);"));
+
+
// Near misses that might appear in a ddl.sql file
// but that cannot be batched
|
Fix issue with finding DDL in the middle of a batch.
I didn't realize PAT_ANY_DDL_FIRST_TOKEN matches any line where a DDL
token is the first token (not just the first line).
|
VoltDB_voltdb
|
train
|
1215d2a7c1ef44b68a00a5e84b5d5bbb82193391
|
diff --git a/splunklib/client.py b/splunklib/client.py
index <HASH>..<HASH> 100644
--- a/splunklib/client.py
+++ b/splunklib/client.py
@@ -76,7 +76,8 @@ __all__ = [
"NotSupportedError",
"OperationError",
"IncomparableException",
- "Service"
+ "Service",
+ "namespace"
]
PATH_APPS = "apps/local/"
@@ -2423,7 +2424,12 @@ class Job(Entity):
:return: The ``InputStream`` IO handle to this job's events.
"""
- return self.get("events", **kwargs).body
+ if 'segmentation' not in kwargs:
+ segmentation = 'none'
+ else:
+ segmentation = kwargs.pop('segmentation')
+ return self.get("events", segmentation=segmentation,
+ **kwargs).body
def finalize(self):
"""Stops the job and provides intermediate results for retrieval.
@@ -2508,7 +2514,12 @@ class Job(Entity):
:return: The ``InputStream`` IO handle to this job's results.
"""
- return self.get("results", **query_params).body
+ if 'segmentation' not in query_params:
+ segmentation = 'none'
+ else:
+ segmentation = query_params.pop('segmentation')
+ return self.get("results", segmentation=segmentation,
+ **query_params).body
def preview(self, **query_params):
"""Returns a streaming handle to this job's preview search results.
@@ -2550,7 +2561,12 @@ class Job(Entity):
:return: The ``InputStream`` IO handle to this job's preview results.
"""
- return self.get("results_preview", **query_params).body
+ if 'segmentation' not in query_params:
+ segmentation = 'none'
+ else:
+ segmentation = query_params.pop('segmentation')
+ return self.get("results_preview", segmentation=segmentation,
+ **query_params).body
def searchlog(self, **kwargs):
"""Returns a streaming handle to this job's search log.
@@ -2717,7 +2733,14 @@ class Jobs(Collection):
"""
if "exec_mode" in params:
raise TypeError("Cannot specify an exec_mode to export.")
- return self.post(path_segment="export", search=query, **params).body
+ if 'segmentation' not in params:
+ segmentation = 'none'
+ else:
+ segmentation = params.pop('segmentation')
+ return self.post(path_segment="export",
+ search=query,
+ segmentation=segmentation,
+ **params).body
def itemmeta(self):
"""There is no metadata available for class:``Jobs``.
@@ -2777,7 +2800,14 @@ class Jobs(Collection):
"""
if "exec_mode" in params:
raise TypeError("Cannot specify an exec_mode to oneshot.")
- return self.post(search=query, exec_mode="oneshot", **params).body
+ if 'segmentation' not in params:
+ segmentation = 'none'
+ else:
+ segmentation = params.pop('segmentation')
+ return self.post(search=query,
+ exec_mode="oneshot",
+ segmentation=segmentation,
+ **params).body
class Loggers(Collection):
|
Added segmentation=none to all results methods. Added namespace to export list in client.py.
|
splunk_splunk-sdk-python
|
train
|
38f0bdb9284bcaeb2a0ae0dcc6533b52cdba4afb
|
diff --git a/salt/state.py b/salt/state.py
index <HASH>..<HASH> 100644
--- a/salt/state.py
+++ b/salt/state.py
@@ -191,6 +191,7 @@ class State(object):
chunk['__sls__'] = body['__sls__']
if body.has_key('__env__'):
chunk['__env__'] = body['__env__']
+ chunk['__id__'] = name
funcs = set()
names = set()
for arg in run:
@@ -273,12 +274,10 @@ class State(object):
status = 'unmet'
for req in low['require']:
for chunk in chunks:
- if chunk['name'] == req[req.keys()[0]]:
+ if chunk['__id__'] == req[req.keys()[0]]:
if chunk['state'] == req.keys()[0]:
reqs.append(chunk)
fun_stats = []
- if not reqs:
- return 'fail'
for req in reqs:
tag = req['state'] + '.' + req['name'] + '.' + req['fun']
if not running.has_key(tag):
|
Add __id__ to the data compiler and require section - makes requires
based on <type>: __id__ which fixes the issues with one name with many
branches
|
saltstack_salt
|
train
|
d243e6009a49f044d43f6cd630f43e4ab507bde1
|
diff --git a/Minimal-J/src/main/java/org/minimalj/frontend/vaadin/VaadinBorderLayout.java b/Minimal-J/src/main/java/org/minimalj/frontend/vaadin/VaadinBorderLayout.java
index <HASH>..<HASH> 100644
--- a/Minimal-J/src/main/java/org/minimalj/frontend/vaadin/VaadinBorderLayout.java
+++ b/Minimal-J/src/main/java/org/minimalj/frontend/vaadin/VaadinBorderLayout.java
@@ -251,27 +251,4 @@ public class VaadinBorderLayout extends VerticalLayout {
return minimumEastWidth;
}
- /**
- * Return component from specific position
- *
- * @param position
- * @return
- */
- public Component getComponent(Constraint position) {
- if (position == Constraint.NORTH) {
- return north;
- } else if (position == Constraint.WEST) {
- return west;
- } else if (position == Constraint.CENTER) {
- return center;
- } else if (position == Constraint.EAST) {
- return east;
- } else if (position == Constraint.SOUTH) {
- return south;
- } else {
- throw new IllegalArgumentException(
- "Invalid BorderLayout constraint.");
- }
- }
-
}
\ No newline at end of file
|
VaadinBorderLayout: removed unused method
|
BrunoEberhard_minimal-j
|
train
|
15d876d299025a8eddd84e27b4d48fe025b0dd16
|
diff --git a/promptly/form.py b/promptly/form.py
index <HASH>..<HASH> 100644
--- a/promptly/form.py
+++ b/promptly/form.py
@@ -1,13 +1,12 @@
# -*- coding: utf-8 -*-
-import sys
from .inputs import String
from .inputs import Integer
from .inputs import Select
from .inputs import Boolean
from .inputs import MultiSelect
from .inputs import Branch
+from .inputs import Notification
from .utils import numeric_options
-from .utils import prepare_stylesheet
class AddAction(object):
@@ -18,6 +17,10 @@ class AddAction(object):
def __call__(self, key, obj):
self.form._fields.append((key, obj))
+ def notification(self, label):
+ obj = Notification(label)
+ self.form._add(id(obj), obj)
+
def string(self, key, label, **kwargs):
obj = String(label, **kwargs)
self.form._add(key, obj)
@@ -67,7 +70,8 @@ class Form(object):
def __iter__(self):
for k, v in iter(self._fields):
- if not isinstance(v, Branch):
+ if not isinstance(v, Branch) and \
+ not isinstance(v, Notification):
yield k, v.value
def __getattr__(self, key):
diff --git a/promptly/renderers/console.py b/promptly/renderers/console.py
index <HASH>..<HASH> 100644
--- a/promptly/renderers/console.py
+++ b/promptly/renderers/console.py
@@ -19,11 +19,19 @@ class ConsolePrompt(Prompt):
return str(self.input.default)
return None
+ @property
+ def seperator(self):
+ return unichr(0x00b7)
+
+ @property
+ def footer_style(self):
+ return Style.styles_for_key('notification.footer', self.stylesheet)
+
def append_notifications(self, prompt, notifications):
- styles_footer = Style.styles_for_key('notification.footer', self.stylesheet)
+ styles_footer = self.footer_style
notices = []
- dot = unichr(0x00b7)
+ dot = self.seperator
for each in notifications:
x = self.runner.notification('', each, prefix=False)
diff --git a/promptly/runners/console.py b/promptly/runners/console.py
index <HASH>..<HASH> 100644
--- a/promptly/runners/console.py
+++ b/promptly/runners/console.py
@@ -82,6 +82,17 @@ class ConsoleRunner(object):
prompt = (yield)
while 1:
+ if isinstance(prompt, console.NotificationPrompt):
+ footer_style = prompt.footer_style
+ seperator = prompt.seperator
+ wrap = footer_style(seperator.ljust(3, seperator))
+
+ notification = '\n%s\n%s\n%s\n' % \
+ (wrap, prompt.prompt, wrap)
+
+ sys.stdout.write(notification)
+ break
+
result = self.render(
prompt.prompt,
default=prompt.default)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -28,7 +28,7 @@ requires = get_requires()
setup(
name='promptly',
- version='0.5.2',
+ version='0.5.3',
description='Console Prompting',
long_description=readme,
author='Aubrey Taylor <aubricus@gmail.com>, Adam Venturella <aventurella@gmail.com>',
|
Added support for notifications to be added to forms. Notifications will just print and continue to the next prompt when the form runs.
|
aventurella_promptly
|
train
|
5e58fcb6203f33119950b0155b8dd40d6595a69b
|
diff --git a/python/ray/tests/test_multi_tenancy.py b/python/ray/tests/test_multi_tenancy.py
index <HASH>..<HASH> 100644
--- a/python/ray/tests/test_multi_tenancy.py
+++ b/python/ray/tests/test_multi_tenancy.py
@@ -268,7 +268,11 @@ def test_not_killing_workers_that_own_objects(shutdown_only):
# New workers shouldn't be registered because we reused the
# previous workers that own objects.
- assert num_workers == len(get_workers())
+ cur_num_workers = len(get_workers())
+ # TODO(ekl) ideally these would be exactly equal, however the test is
+ # occasionally flaky with that check.
+ assert abs(num_workers - cur_num_workers) < 2, \
+ (num_workers, cur_num_workers)
assert len(ref2) == expected_num_workers
assert len(ref) == expected_num_workers
|
Relax check on test_multi_tenancy.py::test_not_killing_workers_that_own_objects (#<I>)
|
ray-project_ray
|
train
|
1fd60f06d692143474218bd5e30fb44390508389
|
diff --git a/src/main/java/net/emaze/dysfunctional/Consumers.java b/src/main/java/net/emaze/dysfunctional/Consumers.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/emaze/dysfunctional/Consumers.java
+++ b/src/main/java/net/emaze/dysfunctional/Consumers.java
@@ -93,7 +93,7 @@ public abstract class Consumers {
* @return a collection filled with iterator values
*/
public static <E, R extends Collection<E>> R all(Iterable<E> iterable, Provider<R> provider) {
- dbc.precondition(iterable != null, "cannot call first with a null iterable");
+ dbc.precondition(iterable != null, "cannot call all with a null iterable");
return Consumers.all(iterable.iterator(), provider);
}
@@ -186,7 +186,7 @@ public abstract class Consumers {
* @return just the first element or nothing
*/
public static <E> Maybe<E> maybeFirst(Iterable<E> iterable) {
- dbc.precondition(iterable != null, "cannot call search with a null iterable");
+ dbc.precondition(iterable != null, "cannot call maybeFirst with a null iterable");
return new MaybeFirstElement<E>().perform(iterable.iterator());
}
@@ -233,7 +233,7 @@ public abstract class Consumers {
* @return the found element
*/
public static <E> E first(Iterable<E> iterable) {
- dbc.precondition(iterable != null, "cannot call find with a null iterable");
+ dbc.precondition(iterable != null, "cannot call first with a null iterable");
return new FirstElement<E>().perform(iterable.iterator());
}
@@ -272,7 +272,7 @@ public abstract class Consumers {
* @return just the element or nothing
*/
public static <E> Maybe<E> maybeOne(Iterable<E> iterable) {
- dbc.precondition(iterable != null, "cannot call searchOne with a null iterable");
+ dbc.precondition(iterable != null, "cannot call maybeOne with a null iterable");
return new MaybeOneElement<E>().perform(iterable.iterator());
}
@@ -312,7 +312,7 @@ public abstract class Consumers {
* @return the found element
*/
public static <E> E one(Iterable<E> iterable) {
- dbc.precondition(iterable != null, "cannot call findOne with a null iterable");
+ dbc.precondition(iterable != null, "cannot call one with a null iterable");
return new OneElement<E>().perform(iterable.iterator());
}
@@ -348,7 +348,7 @@ public abstract class Consumers {
* @return the last element or nothing
*/
public static <E> Maybe<E> maybeLast(Iterable<E> iterable) {
- dbc.precondition(iterable != null, "cannot call searchLast with a null iterable");
+ dbc.precondition(iterable != null, "cannot call maybeLast with a null iterable");
return new MaybeLastElement<E>().perform(iterable.iterator());
}
|
fix: wrong labels on preconditions
|
cybazeitalia_emaze-dysfunctional
|
train
|
bf284b1818d4b13899b9e14a864c90f0fd8b235d
|
diff --git a/src/mobilebone.js b/src/mobilebone.js
index <HASH>..<HASH> 100644
--- a/src/mobilebone.js
+++ b/src/mobilebone.js
@@ -357,7 +357,8 @@
options = options || {};
// get current page(will be out) according to 'page_or_child'
var current_page = document.querySelector(".in." + this.classPage);
-
+ // get page-title from element_or_options or options
+ var page_title;
if (element_or_options) {
if (element_or_options.nodeType == 1) {
// legal elements
@@ -369,6 +370,7 @@
response = options.response;
} else {
response = element_or_options.response || options.response;
+ page_title = element_or_options.title || options.title;
}
}
@@ -381,11 +383,19 @@
} else {
create.appendChild(dom_or_html);
}
+ var create_title = create.getElementsByTagName("title")[0];
// get the page element
if (!(create_page = create.querySelector("." + this.classPage))) {
create.className = "page out";
+ if (typeof page_title == "string") create.setAttribute("data-title", page_title);
create_page = create;
- }
+ } else {
+ if (create_title) {
+ create_page.setAttribute("data-title", create_title.innerText);
+ } else if (typeof page_title == "string") {
+ create_page.setAttribute("data-title", page_title);
+ }
+ }
// insert create page as a last-child
document.body.appendChild(create_page);
|
Update mobilebone.js
Ajax page's title can get from <title> element or ajax options;
|
zhangxinxu_mobilebone
|
train
|
79f81f8ac38256fa84951905431391eed9414ec1
|
diff --git a/salt/utils/http.py b/salt/utils/http.py
index <HASH>..<HASH> 100644
--- a/salt/utils/http.py
+++ b/salt/utils/http.py
@@ -461,7 +461,7 @@ def get_ca_bundle(opts=None):
if os.path.exists(path):
return path
- if salt.utils.is_windows():
+ if salt.utils.is_windows() and HAS_CERTIFI:
return certifi.where()
return None
|
Added HAS_CERTIFI check
|
saltstack_salt
|
train
|
8297fe6e57906e750a918e480ae34c048fe5a68f
|
diff --git a/internal/backend_adlv1.go b/internal/backend_adlv1.go
index <HASH>..<HASH> 100644
--- a/internal/backend_adlv1.go
+++ b/internal/backend_adlv1.go
@@ -25,6 +25,7 @@ import (
"net/http"
"net/url"
"os"
+ "sort"
"strconv"
"strings"
"syscall"
@@ -671,43 +672,30 @@ func (b *ADLv1) DeleteBlob(param *DeleteBlobInput) (*DeleteBlobOutput, error) {
return &DeleteBlobOutput{}, nil
}
-func (b *ADLv1) DeleteBlobs(param *DeleteBlobsInput) (*DeleteBlobsOutput, error) {
- progress := true
- toDelete := param.Items
-
- for progress {
- progress = false
- var dirs []string
-
- for _, i := range toDelete {
- _, err := b.DeleteBlob(&DeleteBlobInput{i})
- if err != nil {
- if err != fuse.ENOENT {
- // if we delete a directory that's not
- // empty, ADLv1 returns 403. That can
- // happen if we want to delete both
- // "dir1" and "dir1/file" but delete
- // them in the wrong order for example
- if err == syscall.EACCES {
- dirs = append(dirs, i)
- } else {
- return nil, err
- }
- } else {
- progress = true
- }
- } else {
- progress = true
- }
+func (b *ADLv1) DeleteBlobs(param *DeleteBlobsInput) (ret *DeleteBlobsOutput, err error) {
+ // if we delete a directory that's not empty, ADLv1 returns
+ // 403. That can happen if we want to delete both "dir1" and
+ // "dir1/file" but delete them in the wrong order for example
+ // sort the blobs so the deepest tree are deleted first to
+ // avoid this problem unfortunately because of this dependency
+ // it's difficult to delete in parallel
+ sort.Slice(param.Items, func(i, j int) bool {
+ depth1 := len(strings.Split(strings.TrimRight(param.Items[i], "/"), "/"))
+ depth2 := len(strings.Split(strings.TrimRight(param.Items[j], "/"), "/"))
+ if depth1 != depth2 {
+ return depth2 < depth1
+ } else {
+ return strings.Compare(param.Items[i], param.Items[j]) < 0
}
+ })
- if len(dirs) == 0 {
- break
+ for _, i := range param.Items {
+ _, err := b.DeleteBlob(&DeleteBlobInput{i})
+ if err != nil {
+ return nil, err
}
- toDelete = dirs
}
-
return &DeleteBlobsOutput{}, nil
}
diff --git a/internal/goofys_test.go b/internal/goofys_test.go
index <HASH>..<HASH> 100644
--- a/internal/goofys_test.go
+++ b/internal/goofys_test.go
@@ -241,7 +241,7 @@ func (s *GoofysTest) setupBlobs(t *C, env map[string]io.ReadSeeker) {
// double check
for path := range env {
wg.Add(1)
- func(path string) {
+ go func(path string) {
defer wg.Done()
params := &HeadBlobInput{Key: path}
res, err := s.cloud.HeadBlob(params)
|
sort the blobs first before deleting them in adlv1
shaves ~1s in each test cleanup
|
kahing_goofys
|
train
|
49e0f03696ce52528e31cdbe8ff64b48f7c04bca
|
diff --git a/locksmith/auth/urls.py b/locksmith/auth/urls.py
index <HASH>..<HASH> 100644
--- a/locksmith/auth/urls.py
+++ b/locksmith/auth/urls.py
@@ -5,5 +5,5 @@ urlpatterns = patterns('locksmith.auth.views',
url(r'^update_key/$', 'update_key', name='update_key'),
url(r'^update_key_by_email/$', 'update_key', {'get_by':'email'},
name='update_key_by_email'),
- url(r'replicate_key/(?P<key_uuid>[a-zA-Z0-9]{32})/$', 'accept_key', name='replicate_key'),
+ url(r'replicate_key/(?P<key_uuid>[a-zA-Z0-9]+)/$', 'accept_key', name='replicate_key'),
)
diff --git a/locksmith/auth/views.py b/locksmith/auth/views.py
index <HASH>..<HASH> 100644
--- a/locksmith/auth/views.py
+++ b/locksmith/auth/views.py
@@ -47,11 +47,6 @@ def accept_key(request, key_uuid):
if not verify_signature(request.POST):
return HttpResponseBadRequest('bad signature')
- try:
- uuid = UUID(key_uuid)
- except ValueError:
- return HttpResponseBadRequest('bad uuid')
-
if u'status' not in request.POST:
return HttpResponseBadRequest('no status specified')
diff --git a/locksmith/mongoauth/urls.py b/locksmith/mongoauth/urls.py
index <HASH>..<HASH> 100644
--- a/locksmith/mongoauth/urls.py
+++ b/locksmith/mongoauth/urls.py
@@ -5,6 +5,6 @@ urlpatterns = patterns('locksmith.mongoauth.views',
url(r'^update_key/$', 'update_key', name='update_key'),
url(r'^update_key_by_email/$', 'update_key', {'get_by':'email'},
name='update_key_by_email'),
- url(r'replicate_key/(?P<key_uuid>[a-zA-Z0-9]{32})/$', 'accept_key', name='replicate_key'),
+ url(r'replicate_key/(?P<key_uuid>[a-zA-Z0-9]+)/$', 'accept_key', name='replicate_key'),
)
diff --git a/locksmith/mongoauth/views.py b/locksmith/mongoauth/views.py
index <HASH>..<HASH> 100644
--- a/locksmith/mongoauth/views.py
+++ b/locksmith/mongoauth/views.py
@@ -45,11 +45,6 @@ def accept_key(request, key_uuid):
if not verify_signature(request.POST):
return HttpResponseBadRequest('bad signature')
- try:
- uuid = UUID(key_uuid)
- except ValueError:
- return HttpResponseBadRequest('bad uuid')
-
if u'status' not in request.POST:
return HttpResponseBadRequest('no status specified')
|
Removed requirement that the key actually be a UUID.
|
sunlightlabs_django-locksmith
|
train
|
4bd6f1e24501cbb52db2bfc42c3b3ee68b819f38
|
diff --git a/findimports.py b/findimports.py
index <HASH>..<HASH> 100755
--- a/findimports.py
+++ b/findimports.py
@@ -60,7 +60,6 @@ import sets
import getopt
import compiler
import linecache
-from sets import Set
from compiler import ast
from compiler.visitor import ASTVisitor
@@ -247,8 +246,8 @@ class ModuleGraph(object):
module.imported_names = find_imports(filename)
module.unused_names = None
dir = os.path.dirname(filename)
- module.imports = Set([self.findModuleOfName(name, filename, dir)
- for name in module.imported_names])
+ module.imports = sets.Set([self.findModuleOfName(name, filename, dir)
+ for name in module.imported_names])
def filenameToModname(self, filename):
"""Convert a filename to a module name."""
@@ -458,21 +457,20 @@ class ModuleGraph(object):
"""Produce a dependency graph in dot format."""
print "digraph ModuleDependencies {"
print " node[shape=box];"
- allNames = Set()
+ allNames = sets.Set()
nameDict = {}
for n, module in enumerate(self.listModules()):
module._dot_name = "mod%d" % n
nameDict[module.modname] = module._dot_name
print " %s[label=\"%s\"];" % (module._dot_name,
quote(module.label))
- for name in module.imports:
- if name not in self.modules:
- allNames.add(name)
+ allNames |= module.imports
print " node[style=dotted];"
if self.external_dependencies:
- names = list(allNames)
- names.sort()
- for n, name in enumerate(names):
+ myNames = sets.Set(self.modules)
+ extNames = list(allNames - myNames)
+ extNames.sort()
+ for n, name in enumerate(extNames):
nameDict[name] = id = "extmod%d" % n
print " %s[label=\"%s\"];" % (id, name)
for module in self.modules.values():
|
Refactoring.
Originally committed <I>-<I>-<I> <I>:<I>:<I> <I> to a different SVN repository
(python-tools) as revision <I>.
|
mgedmin_findimports
|
train
|
0ce2e1166f52c86e432bb774475e1caf4b8cb9fd
|
diff --git a/client/html/templates/catalog/count/tree-body-standard.php b/client/html/templates/catalog/count/tree-body-standard.php
index <HASH>..<HASH> 100644
--- a/client/html/templates/catalog/count/tree-body-standard.php
+++ b/client/html/templates/catalog/count/tree-body-standard.php
@@ -14,13 +14,11 @@ var catalogCounts = <?= $this->get( 'treeCountList', map() )->toJson( JSON_FORCE
$(".catalog-filter-count .cat-item").each(function(index, item) {
var id = $(item).data("id");
- $("a.cat-item", item).append(function() {
- if( catalogCounts[id] ) {
- return '<span class="cat-count">' + catalogCounts[id] + '</span>';
- } else if($(item).hasClass("nochild")) {
- $(item).addClass("disabled");
- }
- });
+ if(catalogCounts[id]) {
+ $("a.cat-item", item).append('<span class="cat-count">' + catalogCounts[id] + '</span>');
+ } else if($(item).hasClass("nochild")) {
+ $(item).addClass("disabled");
+ }
});
// -->
<?php $this->block()->stop() ?>
|
Simplified catalog/count tree JS
|
aimeos_ai-client-html
|
train
|
e64ea7f74bbc53fbd4bfcaab772156124bd5a12b
|
diff --git a/flatpages_i18n/forms.py b/flatpages_i18n/forms.py
index <HASH>..<HASH> 100644
--- a/flatpages_i18n/forms.py
+++ b/flatpages_i18n/forms.py
@@ -20,9 +20,12 @@ class FlatpageForm(forms.ModelForm):
raise forms.ValidationError(_(u"URL '%(url)s' is missing a leading slash.") % {'url': url})
# check trailing slash
+ try:
+ middlewares = settings.MIDDLEWARE_CLASSES
+ except AttributeError:
+ middlewares = settings.MIDDLEWARE
if settings.APPEND_SLASH and \
- self.REQUIRED_MIDDLEWARE in settings.MIDDLEWARE_CLASSES and \
- not url.endswith('/'):
+ self.REQUIRED_MIDDLEWARE in middlewares and not url.endswith('/'):
raise forms.ValidationError(_(u"URL '%(url)s' is missing a trailing slash.") % {'url': url})
# check URL uniqueness
|
Fix compatibility issues with APPEND_SLASH and settings.MIDDLEWARE_CLASSES/MIDDLEWARE
|
PragmaticMates_django-flatpages-i18n
|
train
|
3af6450e93ffde6c847bcbe16463368b55c50928
|
diff --git a/src/Post.php b/src/Post.php
index <HASH>..<HASH> 100644
--- a/src/Post.php
+++ b/src/Post.php
@@ -1890,7 +1890,7 @@ class Post extends Base
*/
public static function decodeLinkObject($encoded)
{
- return json_decode(urldecode($encoded));
+ return json_decode(stripslashes(urldecode($encoded)));
}
@@ -1901,7 +1901,7 @@ class Post extends Base
*/
public function getDecodedLinkObjectFromField($field)
{
- return json_decode(urldecode($this->get($field)));
+ return json_decode(stripslashes(urldecode($this->get($field))));
}
|
remove slashes for encoded links
|
tacowordpress_tacowordpress
|
train
|
ddc7cfcf8339a591daa7c2db66c9dcf44c4a6bf0
|
diff --git a/jodd-core/src/main/java/jodd/exception/ExceptionUtil.java b/jodd-core/src/main/java/jodd/exception/ExceptionUtil.java
index <HASH>..<HASH> 100644
--- a/jodd-core/src/main/java/jodd/exception/ExceptionUtil.java
+++ b/jodd-core/src/main/java/jodd/exception/ExceptionUtil.java
@@ -193,11 +193,19 @@ public class ExceptionUtil {
if (cause == null) {
return throwable;
}
- throwable = cause;
- while ((throwable = throwable.getCause()) != null) {
- cause = throwable;
+
+ Throwable t = throwable;
+
+ // defend against (malicious?) circularity
+ for (int i = 0; i < 1000; i++) {
+ cause = t.getCause();
+ if (cause == null) {
+ return t;
+ }
+ t = cause;
}
- return cause;
+
+ return throwable;
}
/**
|
Added protection against circular exception dependencies.
|
oblac_jodd
|
train
|
de963fccd3b7bbabc894f979b12071eca36e8c8d
|
diff --git a/Eloquent/Builder.php b/Eloquent/Builder.php
index <HASH>..<HASH> 100755
--- a/Eloquent/Builder.php
+++ b/Eloquent/Builder.php
@@ -1223,6 +1223,17 @@ class Builder
}
/**
+ * Qualify the given column name by the model's table.
+ *
+ * @param string $column
+ * @return string
+ */
+ public function qualifyColumn($column)
+ {
+ return $this->model->qualifyColumn($column);
+ }
+
+ /**
* Get the given macro by name.
*
* @param string $name
diff --git a/Eloquent/Model.php b/Eloquent/Model.php
index <HASH>..<HASH> 100644
--- a/Eloquent/Model.php
+++ b/Eloquent/Model.php
@@ -250,6 +250,21 @@ abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializab
}
/**
+ * Qualify the given column name by the model's table.
+ *
+ * @param string $column
+ * @return string
+ */
+ public function qualifyColumn($column)
+ {
+ if (Str::contains($column, '.')) {
+ return $column;
+ }
+
+ return $this->getTable().'.'.$column;
+ }
+
+ /**
* Remove the table name from a given key.
*
* @param string $key
@@ -1206,7 +1221,7 @@ abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializab
*/
public function getQualifiedKeyName()
{
- return $this->getTable().'.'.$this->getKeyName();
+ return $this->qualifyColumn($this->getKeyName());
}
/**
diff --git a/Eloquent/Relations/BelongsTo.php b/Eloquent/Relations/BelongsTo.php
index <HASH>..<HASH> 100755
--- a/Eloquent/Relations/BelongsTo.php
+++ b/Eloquent/Relations/BelongsTo.php
@@ -253,7 +253,7 @@ class BelongsTo extends Relation
}
return $query->select($columns)->whereColumn(
- $this->getQualifiedForeignKey(), '=', $query->getModel()->getTable().'.'.$this->ownerKey
+ $this->getQualifiedForeignKey(), '=', $query->qualifyColumn($this->ownerKey)
);
}
@@ -327,7 +327,7 @@ class BelongsTo extends Relation
*/
public function getQualifiedForeignKey()
{
- return $this->child->getTable().'.'.$this->foreignKey;
+ return $this->child->qualifyColumn($this->foreignKey);
}
/**
@@ -347,7 +347,7 @@ class BelongsTo extends Relation
*/
public function getQualifiedOwnerKeyName()
{
- return $this->related->getTable().'.'.$this->ownerKey;
+ return $this->related->qualifyColumn($this->ownerKey);
}
/**
diff --git a/Eloquent/Relations/BelongsToMany.php b/Eloquent/Relations/BelongsToMany.php
index <HASH>..<HASH> 100755
--- a/Eloquent/Relations/BelongsToMany.php
+++ b/Eloquent/Relations/BelongsToMany.php
@@ -959,7 +959,7 @@ class BelongsToMany extends Relation
*/
public function getQualifiedParentKeyName()
{
- return $this->parent->getTable().'.'.$this->parentKey;
+ return $this->parent->qualifyColumn($this->parentKey);
}
/**
diff --git a/Eloquent/Relations/HasManyThrough.php b/Eloquent/Relations/HasManyThrough.php
index <HASH>..<HASH> 100644
--- a/Eloquent/Relations/HasManyThrough.php
+++ b/Eloquent/Relations/HasManyThrough.php
@@ -125,7 +125,7 @@ class HasManyThrough extends Relation
*/
public function getQualifiedParentKeyName()
{
- return $this->parent->getTable().'.'.$this->secondLocalKey;
+ return $this->parent->qualifyColumn($this->secondLocalKey);
}
/**
@@ -495,7 +495,7 @@ class HasManyThrough extends Relation
*/
public function getQualifiedFirstKeyName()
{
- return $this->throughParent->getTable().'.'.$this->firstKey;
+ return $this->throughParent->qualifyColumn($this->firstKey);
}
/**
@@ -505,7 +505,7 @@ class HasManyThrough extends Relation
*/
public function getQualifiedForeignKeyName()
{
- return $this->related->getTable().'.'.$this->secondKey;
+ return $this->related->qualifyColumn($this->secondKey);
}
/**
@@ -515,6 +515,6 @@ class HasManyThrough extends Relation
*/
public function getQualifiedLocalKeyName()
{
- return $this->farParent->getTable().'.'.$this->localKey;
+ return $this->farParent->qualifyColumn($this->localKey);
}
}
diff --git a/Eloquent/Relations/HasOneOrMany.php b/Eloquent/Relations/HasOneOrMany.php
index <HASH>..<HASH> 100755
--- a/Eloquent/Relations/HasOneOrMany.php
+++ b/Eloquent/Relations/HasOneOrMany.php
@@ -396,7 +396,7 @@ abstract class HasOneOrMany extends Relation
*/
public function getQualifiedParentKeyName()
{
- return $this->parent->getTable().'.'.$this->localKey;
+ return $this->parent->qualifyColumn($this->localKey);
}
/**
diff --git a/Eloquent/SoftDeletes.php b/Eloquent/SoftDeletes.php
index <HASH>..<HASH> 100644
--- a/Eloquent/SoftDeletes.php
+++ b/Eloquent/SoftDeletes.php
@@ -164,6 +164,6 @@ trait SoftDeletes
*/
public function getQualifiedDeletedAtColumn()
{
- return $this->getTable().'.'.$this->getDeletedAtColumn();
+ return $this->qualifyColumn($this->getDeletedAtColumn());
}
}
|
[<I>] Add a "qualifyColumn" method to the Eloquent Model (#<I>)
* Add a "qualify" method to the Eloquent Model
* Change name to "qualifyColumn"
|
illuminate_database
|
train
|
0c9cd7871ae5d3848bb6c3516be5878ad093ddeb
|
diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -23,7 +23,7 @@
},
"scripts": {
"phpstan": [
- "phpstan analyze src --level 4"
+ "phpstan analyze src --level 5"
],
"check-cs": [
"php-cs-fixer fix src --diff --dry-run -v --rules=@Symfony,-blank_line_after_opening_tag --allow-risky yes",
diff --git a/src/ObjectCalisthenics/Helper/ClassAnalyzer.php b/src/ObjectCalisthenics/Helper/ClassAnalyzer.php
index <HASH>..<HASH> 100644
--- a/src/ObjectCalisthenics/Helper/ClassAnalyzer.php
+++ b/src/ObjectCalisthenics/Helper/ClassAnalyzer.php
@@ -12,16 +12,16 @@ final class ClassAnalyzer
*/
private static $propertyList;
- public static function getClassProperties(PHP_CodeSniffer_File $phpcsFile, int $stackPtr): array
+ public static function getClassProperties(PHP_CodeSniffer_File $file, int $stackPtr): array
{
- $tokens = $phpcsFile->getTokens();
+ $tokens = $file->getTokens();
$token = $tokens[$stackPtr];
$pointer = $token['scope_opener'];
self::$propertyList = [];
- while (($pointer = $phpcsFile->findNext(T_VARIABLE, ($pointer + 1), $token['scope_closer'])) !== false) {
- self::extractPropertyIfFound($phpcsFile, $pointer);
+ while (($pointer = $file->findNext(T_VARIABLE, ($pointer + 1), $token['scope_closer'])) !== false) {
+ self::extractPropertyIfFound($file, (int) $pointer);
}
return self::$propertyList;
diff --git a/src/ObjectCalisthenics/Sniffs/Classes/PropertyVisibilitySniff.php b/src/ObjectCalisthenics/Sniffs/Classes/PropertyVisibilitySniff.php
index <HASH>..<HASH> 100644
--- a/src/ObjectCalisthenics/Sniffs/Classes/PropertyVisibilitySniff.php
+++ b/src/ObjectCalisthenics/Sniffs/Classes/PropertyVisibilitySniff.php
@@ -51,7 +51,7 @@ final class PropertyVisibilitySniff extends PHP_CodeSniffer_Standards_AbstractVa
/**
* @param PHP_CodeSniffer_File $phpcsFile
- * @param int $stackPtr
+ * @param int $stackPtr
*/
protected function processVariable(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
@@ -60,7 +60,7 @@ final class PropertyVisibilitySniff extends PHP_CodeSniffer_Standards_AbstractVa
/**
* @param PHP_CodeSniffer_File $phpcsFile
- * @param int $stackPtr
+ * @param int $stackPtr
*/
protected function processVariableInString(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
@@ -74,6 +74,10 @@ final class PropertyVisibilitySniff extends PHP_CodeSniffer_Standards_AbstractVa
}
}
+
+ /**
+ * @param int|bool $modifier
+ */
private function handlePublicProperty(int $modifier)
{
if ($this->tokens[$modifier]['code'] === T_PUBLIC) {
@@ -81,7 +85,11 @@ final class PropertyVisibilitySniff extends PHP_CodeSniffer_Standards_AbstractVa
}
}
- private function handleVisibilityDeclaration(int $modifier)
+
+ /**
+ * @param int|bool $modifier
+ */
+ private function handleVisibilityDeclaration($modifier)
{
if (($modifier === false) || ($this->tokens[$modifier]['line'] !== $this->tokens[$this->stackPtr]['line'])) {
$this->phpcsFile->addError(
|
phpstan: bump to lvl 5
|
object-calisthenics_phpcs-calisthenics-rules
|
train
|
ca81b5a903bf83b41faf70dbb4c8cef40d2a4d1e
|
diff --git a/lib/honeybadger/logging.rb b/lib/honeybadger/logging.rb
index <HASH>..<HASH> 100644
--- a/lib/honeybadger/logging.rb
+++ b/lib/honeybadger/logging.rb
@@ -133,11 +133,15 @@ module Honeybadger
private
def supplement(msg, level)
- msg << sprintf(INFO_SUPPLEMENT, level, Process.pid)
+ return msg unless msg.kind_of?(String)
+
+ r = msg.dup
+ r << sprintf(INFO_SUPPLEMENT, level, Process.pid)
if level == :debug && l = caller_location
- msg << sprintf(DEBUG_SUPPLEMENT, l.dump)
+ r << sprintf(DEBUG_SUPPLEMENT, l.dump)
end
- msg
+
+ r
end
def caller_location
|
Don't modify string in place.
|
honeybadger-io_honeybadger-ruby
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.