hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
e33632f79b883fd8ac65d5d5605fa872117edb6d
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -14,6 +14,10 @@ async function getGitUserInfo(options = {}) {
function getUserFromConfig(options) {
return new Promise((resolve, reject) => {
+ if (typeof options.path !== 'string') {
+ return resolve(null)
+ }
+
parse(options, (err, config) => {
if (err) {
reject(err)
diff --git a/test/user-info.test.js b/test/user-info.test.js
index <HASH>..<HASH> 100644
--- a/test/user-info.test.js
+++ b/test/user-info.test.js
@@ -26,3 +26,13 @@ test('does not crash if no `path` is given', async function (t) {
await getGitUserInfo()
t.end()
})
+
+test('does not crash if `path` is given', async function (t) {
+ await getGitUserInfo()
+ t.end()
+})
+
+test('should return null on invalid path', async function (t) {
+ t.equals(await getGitUserInfo({path: 123}), null, 'should be null')
+ t.end()
+})
|
fix: return null on undefined path
|
rexxars_git-user-info
|
train
|
ff7357a603db123cbafd5d301c89e9c3fe3ad92c
|
diff --git a/lib/certmeister/redis/store.rb b/lib/certmeister/redis/store.rb
index <HASH>..<HASH> 100644
--- a/lib/certmeister/redis/store.rb
+++ b/lib/certmeister/redis/store.rb
@@ -4,17 +4,35 @@ module Certmeister
class Store
- def initialize(redis)
+ def initialize(redis, environment = "development")
@redis = redis
+ @environment = environment
@healthy = true
end
+ def store(cn, pem)
+ @redis.set(pem_key(cn), pem)
+ end
+
+ def fetch(cn)
+ @redis.get(pem_key(cn))
+ end
+
+ def remove(cn)
+ num_removed = @redis.del(pem_key(cn))
+ num_removed == 1
+ end
+
def health_check
@healthy
end
private
+ def pem_key(cn)
+ "certmeister:#{@environment}:certificate:#{cn}"
+ end
+
def break!
@healthy = false
end
diff --git a/spec/certmeister/redis/store_spec.rb b/spec/certmeister/redis/store_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/certmeister/redis/store_spec.rb
+++ b/spec/certmeister/redis/store_spec.rb
@@ -1,6 +1,7 @@
require 'spec_helper'
require 'certmeister/test/memory_store_interface'
+require 'redis'
require 'certmeister/redis/store'
describe Certmeister::Redis::Store do
@@ -9,9 +10,30 @@ describe Certmeister::Redis::Store do
include Certmeister::Test::MemoryStoreInterface
end
- subject { Certmeister::Redis::Store.new(double("Redis")) }
-
+ let(:redis) { Redis.new }
+ subject { Certmeister::Redis::Store.new(redis, "test") }
+
it_behaves_like_a_certmeister_store
+ private
+
+ def redis_cleanup
+ ["axl.starjuice.net", "axl.hetzner.africa"].each do |cn|
+ redis.del(subject.send(:pem_key, "axl.hetzner.africa"))
+ end
+ leftovers = redis.keys("*")
+ if !leftovers.empty?
+ fail "redis keys not cleaned up: #{leftovers.inspect}"
+ end
+ end
+
+ before(:each) do
+ redis_cleanup
+ end
+
+ after(:each) do
+ redis_cleanup
+ end
+
end
|
Implement redis store
It does not implement a real health check yet.
|
sheldonh_certmeister
|
train
|
71328ff0b057288ed1a97fd637497fba7f500103
|
diff --git a/lib/autoit/version.rb b/lib/autoit/version.rb
index <HASH>..<HASH> 100644
--- a/lib/autoit/version.rb
+++ b/lib/autoit/version.rb
@@ -1,3 +1,3 @@
module Autoit
- VERSION = '1.3.2'.freeze
+ VERSION = '1.3.3'.freeze
end
|
Bump autoit to <I>
|
rpossan_autoit
|
train
|
f623779212ec20dd4e1548f3a2ea11c72205e4ec
|
diff --git a/jctools-core/src/main/java/org/jctools/queues/BaseMpscLinkedArrayQueue.java b/jctools-core/src/main/java/org/jctools/queues/BaseMpscLinkedArrayQueue.java
index <HASH>..<HASH> 100644
--- a/jctools-core/src/main/java/org/jctools/queues/BaseMpscLinkedArrayQueue.java
+++ b/jctools-core/src/main/java/org/jctools/queues/BaseMpscLinkedArrayQueue.java
@@ -540,11 +540,6 @@ public abstract class BaseMpscLinkedArrayQueue<E> extends BaseMpscLinkedArrayQue
* @return current buffer capacity for elements (excluding next pointer and jump entry) * 2
*/
protected abstract long getCurrentBufferCapacity(long mask);
-// {
-// // consider replacing if with subclass
-// return (!isFixedChunkSize && mask + 2 == maxQueueCapacity) ? maxQueueCapacity
-// : mask;
-// }
@Override
public int fill(Supplier<E> s) {
@@ -566,11 +561,11 @@ public abstract class BaseMpscLinkedArrayQueue<E> extends BaseMpscLinkedArrayQue
ExitCondition exit) {
while (exit.keepRunning()) {
- while (fill(s, MpmcArrayQueue.RECOMENDED_OFFER_BATCH) != 0) {
+ while (fill(s, MpmcArrayQueue.RECOMENDED_OFFER_BATCH) != 0 && exit.keepRunning()) {
continue;
}
int idleCounter = 0;
- while (fill(s, MpmcArrayQueue.RECOMENDED_OFFER_BATCH) == 0 && exit.keepRunning()) {
+ while (exit.keepRunning() && fill(s, MpmcArrayQueue.RECOMENDED_OFFER_BATCH) == 0) {
idleCounter = w.idle(idleCounter);
}
|
Fix prepetual fill issue for unbounded queues
|
JCTools_JCTools
|
train
|
9eb0c83d7be31f9ac5cd85275fc02058db8d14e5
|
diff --git a/ykman/driver_otp.py b/ykman/driver_otp.py
index <HASH>..<HASH> 100644
--- a/ykman/driver_otp.py
+++ b/ykman/driver_otp.py
@@ -407,5 +407,7 @@ def open_devices():
for i in range(255):
dev = ykpers.yk_open_key(i)
if not dev:
+ logger.debug('Failed to open key at position %s', i)
break
+ logger.debug('Success in opening key at position %s', i)
yield OTPDriver(dev)
|
Log error/success when opening device over OTP
|
Yubico_yubikey-manager
|
train
|
7c49a5b983479c6ce54d00167c7d05527df5144d
|
diff --git a/stream.js b/stream.js
index <HASH>..<HASH> 100644
--- a/stream.js
+++ b/stream.js
@@ -28,6 +28,13 @@ function LineStream () {
self.writable = true
self.buffer = ''
+ self.downstream = null
+
+ self.on('pipe', function(upstream) {
+ upstream.on('end', function(data, encoding) {
+ self.emit('end', data, encoding)
+ })
+ })
}
|
Support "end" events through the pipe
|
iriscouch_couchjs
|
train
|
c99462ebdd828a9a3aad2a9803d8a664013cd427
|
diff --git a/components/List/ListItem.js b/components/List/ListItem.js
index <HASH>..<HASH> 100644
--- a/components/List/ListItem.js
+++ b/components/List/ListItem.js
@@ -7,7 +7,6 @@ const ListItemContainer = styled.li`
color: ${({ active, theme }) => active ? theme.colors.primary : theme.colors.black};
padding: ${({ theme }) => `${theme.padding.medium} ${theme.padding.large}`};
border-bottom: 1px solid ${({ theme }) => theme.colors.borderLight};
- border-right: 1px solid ${({ theme, active }) => active ? theme.colors.gutter : theme.colors.borderLight};
position: relative;
overflow-x: visible;
`;
diff --git a/components/List/ShowMore.js b/components/List/ShowMore.js
index <HASH>..<HASH> 100644
--- a/components/List/ShowMore.js
+++ b/components/List/ShowMore.js
@@ -4,7 +4,6 @@ const ShowMore = styled.div`
background: ${({ theme }) => theme.colors.primaryLight};
color: ${({ theme }) => theme.colors.primaryText};
padding: ${({ theme }) => `${theme.padding.medium} ${theme.padding.large}`};
- border-right: 1px solid ${({ theme }) => theme.colors.borderLight};
cursor: pointer;
`;
diff --git a/components/SidebarLayout.js b/components/SidebarLayout.js
index <HASH>..<HASH> 100644
--- a/components/SidebarLayout.js
+++ b/components/SidebarLayout.js
@@ -9,6 +9,7 @@ const SidebarLayout = styled.div.withConfig({ displayName: 'SidebarLayout' })`
& > *:first-child {
flex: 3;
+ border-right: 1px solid ${({ theme }) => theme.colors.borderLight};
}
& > *:last-child {
|
Remove List border, give border to SidebarLayout instead
|
Bandwidth_shared-components
|
train
|
eb68a078291299716dee3f78dfaae3af360d09eb
|
diff --git a/code/checkout/components/CustomerDetailsCheckoutComponent.php b/code/checkout/components/CustomerDetailsCheckoutComponent.php
index <HASH>..<HASH> 100644
--- a/code/checkout/components/CustomerDetailsCheckoutComponent.php
+++ b/code/checkout/components/CustomerDetailsCheckoutComponent.php
@@ -6,35 +6,39 @@ class CustomerDetailsCheckoutComponent extends CheckoutComponent{
'FirstName','Surname','Email'
);
- public function getFormFields(Order $order){
+ public function getFormFields(Order $order) {
$fields = new FieldList(
- $firstname = TextField::create('FirstName', _t('CheckoutField.FIRSTNAME','First Name')),
- $surname = TextField::create('Surname', _t('CheckoutField.SURNAME','Surname')),
- $email = EmailField::create('Email', _t('CheckoutField.EMAIL','Email'))
+ $firstname = TextField::create('FirstName', _t('CheckoutField.FIRSTNAME', 'First Name')),
+ $surname = TextField::create('Surname', _t('CheckoutField.SURNAME', 'Surname')),
+ $email = EmailField::create('Email', _t('CheckoutField.EMAIL', 'Email'))
);
- //populate fields with member details, if logged in
- if($member = Member::currentUser()){
- $firstname->setValue($member->FirstName);
- $surname->setValue($member->Surname);
- $email->setValue($member->Email);
- }
return $fields;
}
- public function validateData(Order $order, array $data){
+ public function validateData(Order $order, array $data) {
//all fields are required
}
- public function getData(Order $order){
- return array(
- 'FirstName' => $order->FirstName,
- 'Surname' => $order->Surname,
- 'Email' => $order->Email
- );
+ public function getData(Order $order) {
+ if($order->FirstName || $order->Surname || $order->Email){
+ return array(
+ 'FirstName' => $order->FirstName,
+ 'Surname' => $order->Surname,
+ 'Email' => $order->Email
+ );
+ }
+ if($member = Member::currentUser()){
+ return array(
+ 'FirstName' => $member->FirstName,
+ 'Surname' => $member->Surname,
+ 'Email' => $member->Email
+ );
+ }
+ return array();
}
- public function setData(Order $order, array $data){
+ public function setData(Order $order, array $data) {
$order->update($data);
$order->write();
}
diff --git a/code/checkout/steps/CheckoutStep_ContactDetails.php b/code/checkout/steps/CheckoutStep_ContactDetails.php
index <HASH>..<HASH> 100644
--- a/code/checkout/steps/CheckoutStep_ContactDetails.php
+++ b/code/checkout/steps/CheckoutStep_ContactDetails.php
@@ -7,31 +7,27 @@ class CheckoutStep_ContactDetails extends CheckoutStep{
'ContactDetailsForm'
);
- public function contactdetails(){
+ public function contactdetails() {
return array(
'OrderForm' => $this->ContactDetailsForm()
);
}
- public function ContactDetailsForm(){
- $form = new CheckoutForm($this->owner, 'ContactDetailsForm', $this->checkoutconfig());
+ public function ContactDetailsForm() {
+ $cart = ShoppingCart::curr();
+ if(!$cart){
+ return false;
+ }
+ $config = new CheckoutComponentConfig(ShoppingCart::curr());
+ $config->addComponent(new CustomerDetailsCheckoutComponent());
+ $form = new CheckoutForm($this->owner, 'ContactDetailsForm', $config);
+ $form->setRedirectLink($this->NextStepLink());
$form->setActions(new FieldList(
- new FormAction("setcontactdetails","Continue")
+ new FormAction("checkoutSubmit", "Continue")
));
- $this->owner->extend('updateContactDetailsForm',$form);
+ $this->owner->extend('updateContactDetailsForm', $form);
return $form;
}
- public function setcontactdetails($data,$form){
- $this->checkoutconfig()->setData($form->getData());
- $this->owner->redirect($this->NextStepLink());
- }
-
- public function checkoutconfig(){
- $config = new CheckoutComponentConfig(ShoppingCart::curr());
- $config->addComponent(new CustomerDetailsCheckoutComponent());
- return $config;
- }
-
}
|
Don't generate the contact details step form if there is no order available.
Also, fill out customer details from current member object, if not already present in order.
|
silvershop_silvershop-core
|
train
|
bace19ea71a3341da90b8f9ce39b74a4ae796910
|
diff --git a/src/java/com/threerings/miso/client/MisoScenePanel.java b/src/java/com/threerings/miso/client/MisoScenePanel.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/miso/client/MisoScenePanel.java
+++ b/src/java/com/threerings/miso/client/MisoScenePanel.java
@@ -1,5 +1,5 @@
//
-// $Id: MisoScenePanel.java,v 1.39 2003/05/28 18:15:26 ray Exp $
+// $Id: MisoScenePanel.java,v 1.40 2003/05/29 01:04:58 ray Exp $
package com.threerings.miso.client;
@@ -33,7 +33,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
-import java.util.Random;
import com.samskivert.swing.Controller;
import com.samskivert.swing.RadialMenu;
@@ -1335,7 +1334,7 @@ public class MisoScenePanel extends VirtualMediaPanel
protected Tile computeFringeTile (int tx, int ty)
{
return _ctx.getTileManager().getAutoFringer().getFringeTile(
- _model, tx, ty, _masks, _rando);
+ _model, tx, ty, _masks);
}
/**
@@ -1512,9 +1511,6 @@ public class MisoScenePanel extends VirtualMediaPanel
/** For computing fringe tiles. */
protected HashMap _masks = new HashMap();
- /** For computing fringe tiles. */
- protected Random _rando = new Random();
-
/** The dirty sprites and objects that need to be re-painted. */
protected DirtyItemList _dirtyItems = new DirtyItemList();
diff --git a/src/java/com/threerings/miso/tile/AutoFringer.java b/src/java/com/threerings/miso/tile/AutoFringer.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/miso/tile/AutoFringer.java
+++ b/src/java/com/threerings/miso/tile/AutoFringer.java
@@ -1,5 +1,5 @@
//
-// $Id: AutoFringer.java,v 1.22 2003/05/02 23:33:30 mdb Exp $
+// $Id: AutoFringer.java,v 1.23 2003/05/29 01:04:58 ray Exp $
package com.threerings.miso.tile;
@@ -57,7 +57,7 @@ public class AutoFringer
* location.
*/
public Tile getFringeTile (MisoSceneModel scene, int col, int row,
- HashMap masks, Random rando)
+ HashMap masks)
{
// get the tileset id of the base tile we are considering
int underset = scene.getBaseTileId(col, row) >> 16;
@@ -110,14 +110,23 @@ public class AutoFringer
}
}
- return composeFringeTile(frecs, masks, rando);
+ return composeFringeTile(frecs, masks, generateHashValue(col, row));
+ }
+
+ /**
+ * Create a hash value for picking which fringe to use for a particular
+ * tile.
+ */
+ protected int generateHashValue (int col, int row)
+ {
+ return col ^ row;
}
/**
* Compose a FringeTile out of the various fringe images needed.
*/
protected Tile composeFringeTile (
- FringerRec[] fringers, HashMap masks, Random rando)
+ FringerRec[] fringers, HashMap masks, int hashValue)
{
// sort the array so that higher priority fringers get drawn first
QuickSort.sort(fringers);
@@ -128,7 +137,7 @@ public class AutoFringer
for (int jj = 0; jj < indexes.length; jj++) {
try {
ftimg = getTileImage(ftimg, fringers[ii].baseset,
- indexes[jj], masks, rando);
+ indexes[jj], masks, hashValue);
} catch (NoSuchTileException nste) {
Log.warning("Autofringer couldn't find a needed tile " +
"[error=" + nste + "].");
@@ -147,11 +156,11 @@ public class AutoFringer
*/
protected BufferedImage getTileImage (
BufferedImage ftimg, int baseset, int index,
- HashMap masks, Random rando)
+ HashMap masks, int hashValue)
throws NoSuchTileException, NoSuchTileSetException
{
FringeConfiguration.FringeTileSetRecord tsr =
- _fringeconf.getRandomFringe(baseset, rando);
+ _fringeconf.getFringe(baseset, hashValue);
int fringeset = tsr.fringe_tsid;
TileSet fset = _tmgr.getTileSet(fringeset);
diff --git a/src/java/com/threerings/miso/tile/FringeConfiguration.java b/src/java/com/threerings/miso/tile/FringeConfiguration.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/miso/tile/FringeConfiguration.java
+++ b/src/java/com/threerings/miso/tile/FringeConfiguration.java
@@ -1,5 +1,5 @@
//
-// $Id: FringeConfiguration.java,v 1.13 2002/08/19 22:58:15 mdb Exp $
+// $Id: FringeConfiguration.java,v 1.14 2003/05/29 01:04:58 ray Exp $
package com.threerings.miso.tile;
@@ -119,12 +119,13 @@ public class FringeConfiguration implements Serializable
* Get a random FringeTileSetRecord from amongst the ones
* listed for the specified base tileset.
*/
- public FringeTileSetRecord getRandomFringe (int baseset, Random rando)
+ public FringeTileSetRecord getFringe (int baseset, int hashValue)
{
FringeRecord f = (FringeRecord) _frecs.get(baseset);
int size = f.tilesets.size();
- return (FringeTileSetRecord) f.tilesets.get(rando.nextInt(size));
+ int pick = Math.abs(hashValue) % size;
+ return (FringeTileSetRecord) f.tilesets.get(pick);
}
/** The mapping from base tileset id to fringerecord. */
|
The AutoFringer picks which fringe tile to use next by querying a
Random, instead it relies on a duplicatable hashing method.
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@<I> <I>f4-<I>e9-<I>-aa3c-eee0fc<I>fb1
|
threerings_narya
|
train
|
e21c25891843b6f5f0879f796d59dba0fb2be128
|
diff --git a/test/interface_test.rb b/test/interface_test.rb
index <HASH>..<HASH> 100644
--- a/test/interface_test.rb
+++ b/test/interface_test.rb
@@ -20,6 +20,10 @@ module Byebug
@interface = SpecificInterface.new
end
+ def teardown
+ @interface.history.clear
+ end
+
def test_reads_simple_commands
@interface.fake_input_queue = ['a_command']
|
Ensure test clears up Readline::HISTORY
|
deivid-rodriguez_byebug
|
train
|
6dce2885e932453c9abd0320faccd8f2e58be906
|
diff --git a/tests/tests_pgi/test_pgi_misc.py b/tests/tests_pgi/test_pgi_misc.py
index <HASH>..<HASH> 100644
--- a/tests/tests_pgi/test_pgi_misc.py
+++ b/tests/tests_pgi/test_pgi_misc.py
@@ -254,7 +254,7 @@ if 2:
"raises -> (bool, contents: str, etag_out: str)")
def test_virtual_method(self):
- from gi.repository import Atk
+ from gi.repository import Gtk
- string = Atk.Object.do_get_object_locale.__doc__
- self.assertEqual(string, "do_get_object_locale() -> str")
+ string = Gtk.Widget.do_map_event.__doc__
+ self.assertEqual(string, "do_map_event(event: Gdk.EventAny) -> bool")
|
tests: use a differend vfunc, the atk one is too new for the ubuntu CI
|
pygobject_pgi
|
train
|
76983b1ec6c54f4cceeaaf0d841b0a783318f9f0
|
diff --git a/Eloquent/Model.php b/Eloquent/Model.php
index <HASH>..<HASH> 100755
--- a/Eloquent/Model.php
+++ b/Eloquent/Model.php
@@ -1529,6 +1529,7 @@ abstract class Model implements ArrayAccess, ArrayableInterface, JsonableInterfa
foreach ($this->touches as $relation)
{
$this->$relation()->touch();
+ $this->$relation->touchOwners();
}
}
|
Ensure to propagate touchOwner on relationships.
|
illuminate_database
|
train
|
ea3f86c66743b964cc2a6386fedecee905877d35
|
diff --git a/clam/clamservice.py b/clam/clamservice.py
index <HASH>..<HASH> 100755
--- a/clam/clamservice.py
+++ b/clam/clamservice.py
@@ -2493,7 +2493,7 @@ def set_defaults():
settings.BASICAUTH = False #default is HTTP Digest
if not 'LISTPROJECTS' in settingkeys:
settings.LISTPROJECTS = True
- if not 'ALLOWSHARE' in settingkeys:
+ if not 'ALLOWSHARE' in settingkeys: #TODO: all there are not implemented yet
settings.ALLOWSHARE = True
if not 'ALLOWANONSHARE' in settingkeys:
settings.ALLOWANONSHARE = True
diff --git a/clam/static/clam.js b/clam/static/clam.js
index <HASH>..<HASH> 100644
--- a/clam/static/clam.js
+++ b/clam/static/clam.js
@@ -92,7 +92,12 @@ function initclam() {
if (inputtemplate != null) {
if (inputtemplate.filename) {
$('#editorfilename').val(inputtemplate.filename);
+ $('.editorfilenamerow').hide();
+ } else {
+ $('.editorfilenamerow').show();
}
+ } else {
+ $('.editorfilenamerow').show();
}
});
diff --git a/clam/static/interface.xsl b/clam/static/interface.xsl
index <HASH>..<HASH> 100644
--- a/clam/static/interface.xsl
+++ b/clam/static/interface.xsl
@@ -370,7 +370,7 @@
<tr><th><label for="editorparameters">Parameters:</label></th><td>
<div id="editorparameters" class="parameters"><em>Select a type first</em></div>
</td></tr>
- <tr><th><label for="editorfilename">Desired filename:</label></th><td><input id="editorfilename" /></td></tr>
+ <tr class="editorfilenamerow"><th><label for="editorfilename">Desired filename:</label></th><td><input id="editorfilename" /></td></tr>
<tr><th></th><td><input id="editorsubmit" class="uploadbutton" type="submit" value="Add to input files" /></td></tr>
</table>
</div>
|
hide filename field in editor interface when filename is fixed anyway (issue #<I>)
|
proycon_clam
|
train
|
a61ae2fa3aec6fba981271aeac35809e1e7a90a4
|
diff --git a/harvestingkit/inspire_cds_package/mappings.py b/harvestingkit/inspire_cds_package/mappings.py
index <HASH>..<HASH> 100644
--- a/harvestingkit/inspire_cds_package/mappings.py
+++ b/harvestingkit/inspire_cds_package/mappings.py
@@ -366,6 +366,10 @@ mappings = {
{
"cds": "Nuclear Physics - Theory",
"inspire": "Theory-Nucl"
+ },
+ {
+ "cds": "Quantum Technology",
+ "inspire": "Quantum Physics"
}
],
"categories_inspire": [
@@ -460,6 +464,10 @@ mappings = {
{
"cds": "Nuclear Physics - Theory",
"inspire": "Theory-Nucl"
+ },
+ {
+ "cds": "Quantum Physics",
+ "inspire": "Quantum Technology"
}
],
}
|
inspire_cds_package: add Quantum subject
|
inspirehep_harvesting-kit
|
train
|
6bf0c5d2341a589a9d31f3b8be8d459348b90244
|
diff --git a/src/main/java/org/fit/layout/impl/DefaultArea.java b/src/main/java/org/fit/layout/impl/DefaultArea.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/fit/layout/impl/DefaultArea.java
+++ b/src/main/java/org/fit/layout/impl/DefaultArea.java
@@ -15,6 +15,7 @@ import java.util.Vector;
import org.fit.layout.model.Area;
import org.fit.layout.model.AreaTopology;
+import org.fit.layout.model.AreaTree;
import org.fit.layout.model.Box;
import org.fit.layout.model.Rectangular;
import org.fit.layout.model.Tag;
@@ -29,6 +30,9 @@ public class DefaultArea extends DefaultContentRect implements Area
/** Area name to be displayed to the users */
private String name;
+ /** The area tree this node belongs to */
+ private AreaTree areaTree;
+
/** The topology assigned to the area */
private AreaTopology topology;
@@ -127,6 +131,16 @@ public class DefaultArea extends DefaultContentRect implements Area
return name;
}
+ public AreaTree getAreaTree()
+ {
+ return areaTree;
+ }
+
+ public void setAreaTree(AreaTree areaTree)
+ {
+ this.areaTree = areaTree;
+ }
+
public Rectangular getContentBounds()
{
return contentBounds;
@@ -215,6 +229,7 @@ public class DefaultArea extends DefaultContentRect implements Area
@Override
public void appendChild(Area child)
{
+ ((DefaultArea) child).setAreaTree(areaTree);
add((DefaultArea) child);
getBounds().expandToEnclose(child.getBounds());
}
@@ -225,6 +240,7 @@ public class DefaultArea extends DefaultContentRect implements Area
for (Area child : list)
{
add((DefaultArea) child);
+ ((DefaultArea) child).setAreaTree(areaTree);
getBounds().expandToEnclose(child.getBounds());
}
}
@@ -232,12 +248,14 @@ public class DefaultArea extends DefaultContentRect implements Area
@Override
public void insertChild(Area child, int index)
{
+ ((DefaultArea) child).setAreaTree(areaTree);
insert((DefaultArea) child, index);
}
@Override
public void removeChild(Area child)
{
+ ((DefaultArea) child).setAreaTree(null);
remove((DefaultArea) child);
}
diff --git a/src/main/java/org/fit/layout/model/Area.java b/src/main/java/org/fit/layout/model/Area.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/fit/layout/model/Area.java
+++ b/src/main/java/org/fit/layout/model/Area.java
@@ -18,6 +18,12 @@ public interface Area extends ContentRect, AreaTreeNode<Area>, Taggable
{
/**
+ * Obtains the tree the node belongs to.
+ * @return the tree or {@code null} when the node does not form part of any tree.
+ */
+ public AreaTree getAreaTree();
+
+ /**
* Returns the list of boxes that belong directly to this area.
* @return the list of boxes (possibly empty)
*/
diff --git a/src/main/java/org/fit/layout/model/AreaTree.java b/src/main/java/org/fit/layout/model/AreaTree.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/fit/layout/model/AreaTree.java
+++ b/src/main/java/org/fit/layout/model/AreaTree.java
@@ -20,4 +20,9 @@ public interface AreaTree extends SearchableAreaContainer
*/
public Area getRoot();
+ /**
+ * Updates the topology structures (e.g. grids) for all the areas in the tree.
+ */
+ public void updateTopologies();
+
}
|
getAreaTree api for the individual areas
|
FitLayout_api
|
train
|
23c1b7d47412f640553184a4031ee225f253d7c6
|
diff --git a/src/OmniApp/Cli/Output.php b/src/OmniApp/Cli/Output.php
index <HASH>..<HASH> 100644
--- a/src/OmniApp/Cli/Output.php
+++ b/src/OmniApp/Cli/Output.php
@@ -125,4 +125,12 @@ class Output extends \OmniApp\BaseEmitter
return isset($this->env[$key]) ? $this->env[$key] : null;
}
+
+ /**
+ * @return string
+ */
+ public function __toString()
+ {
+ return $this->env['body'];
+ }
}
\ No newline at end of file
diff --git a/src/OmniApp/Http/Output.php b/src/OmniApp/Http/Output.php
index <HASH>..<HASH> 100644
--- a/src/OmniApp/Http/Output.php
+++ b/src/OmniApp/Http/Output.php
@@ -515,4 +515,12 @@ class Output extends \OmniApp\BaseEmitter
return isset($this->env[$key]) ? $this->env[$key] : null;
}
+
+ /**
+ * @return string
+ */
+ public function __toString()
+ {
+ return $this->env['body'];
+ }
}
\ No newline at end of file
|
Add Output->__toString method
|
hfcorriez_pagon
|
train
|
68ee6b05e5282db4cb4f7be8d3a4ab3955346903
|
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
index <HASH>..<HASH> 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
@@ -490,6 +490,17 @@ public abstract class OMVRBTree<K, V> extends AbstractMap<K, V> implements ONavi
final int oldPageIndex = pageIndex;
final OMVRBTreeEntry<K, V> prevNd = previous(lastNode);
+
+ if(prevNd == null) {
+ pageIndex = oldPageIndex;
+ pageItemFound = false;
+
+ if(iGetContainer)
+ return lastNode;
+
+ return null;
+ }
+
pageItemComparator = ((OCompositeKey)prevNd.getKey()).compareTo(compositeKey);
if(pageItemComparator == 0) {
|
NPE issue reported in ML by Rob was fixed.
|
orientechnologies_orientdb
|
train
|
b59e13015fac9aea671e743e450649439cd0dec8
|
diff --git a/Classes/Controller/SearchController.php b/Classes/Controller/SearchController.php
index <HASH>..<HASH> 100644
--- a/Classes/Controller/SearchController.php
+++ b/Classes/Controller/SearchController.php
@@ -274,11 +274,11 @@ class Tx_SolrFrontend_Controller_SearchController extends Tx_Extbase_MVC_Control
public function autoCompleteAction() {
$searchTerm = filter_var($_GET['term'], FILTER_SANITIZE_STRING);
- $query = $this->solr->createSelect();
+ $query = $this->solr->createSuggester();
$query->setQuery($searchTerm);
- $results = $this->solr->select($query)->getResponse()->getBody();
+ $results = $this->solr->suggester($query)->getResponse()->getBody();
$this->view->assign('results', $results);
}
diff --git a/Resources/Public/JavaScript/solr_frontend.js b/Resources/Public/JavaScript/solr_frontend.js
index <HASH>..<HASH> 100644
--- a/Resources/Public/JavaScript/solr_frontend.js
+++ b/Resources/Public/JavaScript/solr_frontend.js
@@ -7,13 +7,7 @@ jQuery(document).ready(function() {
var autocompleteUrl = updateQueryStringParameter(autocompleteUrl, "term", request.term);
jQuery.getJSON(autocompleteUrl, function (data) {
- var suggestions = [];
- jQuery.each(
- data.response.docs,
- function(k, v) {
- suggestions.push(v.uebersetzung);
- }
- );
+ var suggestions = data.spellcheck.suggestions[1].suggestion;
add(suggestions);
}
);
|
Updated suggestion for suggest component in solr
|
subugoe_typo3-find
|
train
|
e08329cae4a1198e124c7615e92f44a7319a2cb8
|
diff --git a/org/junit/tests/AssertionTest.java b/org/junit/tests/AssertionTest.java
index <HASH>..<HASH> 100644
--- a/org/junit/tests/AssertionTest.java
+++ b/org/junit/tests/AssertionTest.java
@@ -224,6 +224,7 @@ public class AssertionTest {
@Test public void sameWithMessage() {
try {
assertSame("not same", "hello", "good-bye");
+ fail();
} catch (AssertionError exception) {
assertEquals("not same expected same:<hello> was not:<good-bye>",
exception.getMessage());
@@ -233,22 +234,27 @@ public class AssertionTest {
@Test public void sameNullMessage() {
try {
assertSame("hello", "good-bye");
+ fail();
} catch (AssertionError exception) {
assertEquals("expected same:<hello> was not:<good-bye>", exception.getMessage());
}
}
@Test public void notSameWithMessage() {
+ Object o= new Object();
try {
- assertNotSame("not same", "hello", "good-bye");
+ assertNotSame("message", o, o);
+ fail();
} catch (AssertionError exception) {
- assertEquals("not same expected not same", exception.getMessage());
+ assertEquals("message expected not same", exception.getMessage());
}
}
@Test public void notSameNullMessage() {
+ Object o= new Object();
try {
- assertNotSame("hello", "good-bye");
+ assertNotSame(o, o);
+ fail();
} catch (AssertionError exception) {
assertEquals("expected not same", exception.getMessage());
}
@@ -265,6 +271,7 @@ public class AssertionTest {
@Test public void nullMessageDisappearsWithStringAssertEquals() {
try {
assertEquals(null, "a", "b");
+ fail();
} catch (ComparisonFailure e) {
assertEquals("expected:<[a]> but was:<[b]>", e.getMessage());
}
@@ -273,6 +280,7 @@ public class AssertionTest {
@Test public void nullMessageDisappearsWithAssertEquals() {
try {
assertEquals(null, 1, 2);
+ fail();
} catch (AssertionError e) {
assertEquals("expected:<1> but was:<2>", e.getMessage());
}
|
Fixed tests for assertSame and assertNotSame.
|
junit-team_junit4
|
train
|
6cac0edb7ac1ca9e6c7c3aa61539b1d2dc0769cb
|
diff --git a/wunderline-add.js b/wunderline-add.js
index <HASH>..<HASH> 100755
--- a/wunderline-add.js
+++ b/wunderline-add.js
@@ -118,7 +118,7 @@ function main() {
// set the dueDate as date for reminder, if no valid datetime given
reminderDatetime = moment(dueDate);
} else {
- console.error("Invalid reminder datetime!");
+ console.error("Invalid reminder datetime (format: YYYY-MM-DD HH:mm)!");
process.exit(1);
}
}
|
Add expected format to error for invalid reminder
related to #<I>
|
wayneashleyberry_wunderline
|
train
|
82e8d11c12f160fbf07a8faef5931c2f7a364a6a
|
diff --git a/src/selector.js b/src/selector.js
index <HASH>..<HASH> 100644
--- a/src/selector.js
+++ b/src/selector.js
@@ -809,8 +809,8 @@ var contains = document.compareDocumentPosition ? function(a, b){
};
var isXML = function(elem){
- return elem && elem.nodeType === 9 && elem.nodeName !== "HTML" ||
- isXML( elem.ownerDocument );
+ return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
+ !!elem.ownerDocument && isXML( elem.ownerDocument );
};
var posProcess = function(selector, context){
|
Re-worked the logic for handling isXML detection.
|
jquery_jquery
|
train
|
52cee243cc4e84f940a29a99d6df360230579840
|
diff --git a/examples/server/settings.py b/examples/server/settings.py
index <HASH>..<HASH> 100644
--- a/examples/server/settings.py
+++ b/examples/server/settings.py
@@ -15,6 +15,16 @@ ROOT_URLCONF = 'server.urls'
SECRET_KEY = 'secret'
+INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.admin',
+ 'django.contrib.staticfiles',
+ 'djangular',
+ 'server',
+)
+
USE_L10N = True
# Absolute path to the directory that holds media.
@@ -28,12 +38,23 @@ MEDIA_URL = ''
# Absolute path to the directory that holds static files.
# Example: "/home/media/media.lawrence.com/static/"
-STATIC_ROOT = '/examples/static/'
+STATIC_ROOT = '/var/tmp/static_root/'
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
+TEMPLATE_CONTEXT_PROCESSORS = (
+ 'django.contrib.auth.context_processors.auth',
+ 'django.core.context_processors.debug',
+ 'django.core.context_processors.i18n',
+ 'django.core.context_processors.media',
+ 'django.core.context_processors.static',
+ 'django.core.context_processors.tz',
+ 'django.core.context_processors.request',
+ 'django.contrib.messages.context_processors.messages',
+)
+
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
@@ -46,9 +67,47 @@ TEMPLATE_DIRS = (
# Don't forget to use absolute paths, not relative paths.
)
-INSTALLED_APPS = (
- 'django.contrib.contenttypes',
- 'django.contrib.staticfiles',
- 'djangular',
- 'server',
-)
+TIME_ZONE = 'Europe/Berlin'
+
+LOGGING = {
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ 'formatters': {
+ 'simple': {
+ 'format': '[%(asctime)s %(module)s] %(levelname)s: %(message)s'
+ },
+ },
+ 'handlers': {
+ 'console': {
+ 'level': 'DEBUG',
+ 'class': 'logging.StreamHandler',
+ 'formatter': 'simple',
+ },
+ },
+ 'loggers': {
+ 'django': {
+ 'handlers': ['console'],
+ 'level': 'DEBUG',
+ 'propagate': True,
+ },
+ },
+}
+
+# if package django-websocket-redis is installed, some more tests can be be added
+try:
+ import ws4redis
+
+ INSTALLED_APPS += ('ws4redis',)
+
+ # This setting is required to override the Django's main loop, when running in
+ # development mode, such as ./manage runserver
+ WSGI_APPLICATION = 'ws4redis.django_runserver.application'
+
+ # URL that distinguishes websocket connections from normal requests
+ WEBSOCKET_URL = '/ws/'
+
+ # Set the number of seconds each message shall persited
+ WS4REDIS_EXPIRE = 3600
+
+except ImportError:
+ pass
|
redis4ws optionally loaded
|
jrief_django-angular
|
train
|
e9709aec0a5f76164c09beb6fa0a77b3c004d4b8
|
diff --git a/app/models/agents/peak_detector_agent.rb b/app/models/agents/peak_detector_agent.rb
index <HASH>..<HASH> 100644
--- a/app/models/agents/peak_detector_agent.rb
+++ b/app/models/agents/peak_detector_agent.rb
@@ -138,7 +138,7 @@ module Agents
def remember(group, event)
memory['data'] ||= {}
memory['data'][group] ||= []
- memory['data'][group] << [ Utils.value_at(event.payload, interpolated['value_path']), event.created_at.to_i ]
+ memory['data'][group] << [ Utils.value_at(event.payload, interpolated['value_path']).to_f, event.created_at.to_i ]
cleanup group
end
diff --git a/spec/models/agents/peak_detector_agent_spec.rb b/spec/models/agents/peak_detector_agent_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/agents/peak_detector_agent_spec.rb
+++ b/spec/models/agents/peak_detector_agent_spec.rb
@@ -78,6 +78,13 @@ describe Agents::PeakDetectorAgent do
:pattern => { 'filter' => "something" })
expect(@agent.memory['peaks']['something'].length).to eq(1)
end
+
+ it 'raised an exception if the extracted data can not be casted to a float' do
+ event = Event.new(payload: {count: ["not working"]})
+ expect {
+ @agent.receive([event])
+ }.to raise_error(NoMethodError, /undefined method `to_f'/)
+ end
end
describe "validation" do
|
Prevent PeakDetectorAgent from storing invalid data in it's memory
The Agent expects the data in its memory groups to be castable to a
float. By attempting the type cast when receiving events we prevent the
memory from being corrupted with invalid data which lead exceptions
while trying to access it.
#<I>
|
huginn_huginn
|
train
|
b764d49945ac1f9e5d6546170bdd5eca85a20c4b
|
diff --git a/lib/reek/block_context.rb b/lib/reek/block_context.rb
index <HASH>..<HASH> 100644
--- a/lib/reek/block_context.rb
+++ b/lib/reek/block_context.rb
@@ -21,7 +21,19 @@ module Reek
end
end
- class BlockContext < CodeContext
+ class VariableContainer < CodeContext
+
+ def initialize(outer, exp)
+ super
+ @local_variables = Set.new
+ end
+
+ def record_local_variable(sym)
+ @local_variables << Name.new(sym)
+ end
+ end
+
+ class BlockContext < VariableContainer
def initialize(outer, exp)
super
@@ -29,7 +41,6 @@ module Reek
@parameters = exp[0] if exp
@parameters ||= []
@parameters.extend(ParameterSet)
- @local_variables = Set.new
end
def inside_a_block?
@@ -43,10 +54,6 @@ module Reek
def nested_block?
@outer.inside_a_block?
end
-
- def record_local_variable(sym)
- @local_variables << Name.new(sym)
- end
def outer_name
"#{@outer.outer_name}#{@name}/"
diff --git a/lib/reek/method_context.rb b/lib/reek/method_context.rb
index <HASH>..<HASH> 100644
--- a/lib/reek/method_context.rb
+++ b/lib/reek/method_context.rb
@@ -1,5 +1,5 @@
require 'reek/name'
-require 'reek/code_context'
+require 'reek/block_context'
require 'reek/object_refs'
class Array
@@ -51,7 +51,7 @@ module Reek
end
end
- class MethodContext < CodeContext
+ class MethodContext < VariableContainer
attr_reader :parameters
attr_reader :calls
attr_reader :refs
@@ -62,7 +62,6 @@ module Reek
@parameters = exp[exp[0] == :defn ? 2 : 3] # SMELL: SimulatedPolymorphism
@parameters ||= []
@parameters.extend(MethodParameters)
- @local_variables = []
@name = Name.new(exp[1])
@num_statements = 0
@calls = Hash.new(0)
@@ -114,10 +113,6 @@ module Reek
@depends_on_self = true
end
- def record_local_variable(sym)
- @local_variables << Name.new(sym)
- end
-
def outer_name
"#{@outer.outer_name}#{@name}/"
end
@@ -132,7 +127,7 @@ module Reek
end
def variable_names
- @parameters.names + @local_variables
+ @parameters.names + @local_variables.to_a
end
end
end
|
Removed duplication between blocks and methods
|
troessner_reek
|
train
|
8c76bbb53d3ce4b3b8eb384f75309a9e793c7ece
|
diff --git a/salt/modules/dnsutil.py b/salt/modules/dnsutil.py
index <HASH>..<HASH> 100644
--- a/salt/modules/dnsutil.py
+++ b/salt/modules/dnsutil.py
@@ -2,8 +2,9 @@
'''
Compendium of generic DNS utilities.
-.. note:
- Some functions in the `dnsutil` execution module depend on `dig`.
+.. note::
+
+ Some functions in the ``dnsutil`` execution module depend on ``dig``.
'''
from __future__ import absolute_import
@@ -245,7 +246,7 @@ def check_ip(ip_addr):
def A(host, nameserver=None):
'''
- Return the A record(s) for `host`.
+ Return the A record(s) for ``host``.
Always returns a list.
@@ -270,7 +271,7 @@ def A(host, nameserver=None):
def AAAA(host, nameserver=None):
'''
- Return the AAAA record(s) for `host`.
+ Return the AAAA record(s) for ``host``.
Always returns a list.
|
Some minor doc fixes for dnsutil module so they'll render correctly
|
saltstack_salt
|
train
|
5bc0c40a060a72dee33b08e9ce4e34c845af704d
|
diff --git a/lib/slurper.rb b/lib/slurper.rb
index <HASH>..<HASH> 100644
--- a/lib/slurper.rb
+++ b/lib/slurper.rb
@@ -1,6 +1,6 @@
require 'yaml'
require 'story'
-YAML::ENGINE.yamler='syck'
+YAML::ENGINE.yamler='syck' if RUBY_VERSION > '1.9'
class Slurper
|
Set yaml engine only if ruby is greater than <I>
|
hashrocket_slurper
|
train
|
6e8094376ac237bfb4acc77612fc14af1db64848
|
diff --git a/lib/namey/generator.rb b/lib/namey/generator.rb
index <HASH>..<HASH> 100644
--- a/lib/namey/generator.rb
+++ b/lib/namey/generator.rb
@@ -11,8 +11,12 @@ module Namey
# initialize the name generator
# * +dbname+ - Sequel style db URI ex: 'sqlite://foo.db'
def initialize(dbname = nil)
- dbname = Namey.db_path if dbname.nil?
- @db = Sequel.connect(dbname)
+ if dbname.is_a? Sequel::Database
+ @db = dbname
+ else
+ dbname = Namey.db_path if dbname.nil?
+ @db = Sequel.connect(dbname)
+ end
end
#
diff --git a/lib/namey/version.rb b/lib/namey/version.rb
index <HASH>..<HASH> 100644
--- a/lib/namey/version.rb
+++ b/lib/namey/version.rb
@@ -1,4 +1,4 @@
module Namey
NAME = "namey"
- VERSION = "0.0.7"
+ VERSION = "0.0.8"
end
diff --git a/spec/generator_spec.rb b/spec/generator_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/generator_spec.rb
+++ b/spec/generator_spec.rb
@@ -6,6 +6,13 @@ describe "Namey::Generator" do
@gen = Namey::Generator.new(@uri)
end
+ describe "incoming sequel object" do
+ it "should work" do
+ @tmp = Sequel.connect(@uri)
+ @gen2 = Namey::Generator.new(@tmp)
+ end
+ end
+
describe "name" do
it "should pass params to generate" do
@gen.should_receive(:generate).with(:frequency => :common, :with_surname => true)
|
accept an existing Sequel DB as an option
|
muffinista_namey
|
train
|
06d088161a77389884e0895614f63c50e6ee25da
|
diff --git a/src/feat/database/driver.py b/src/feat/database/driver.py
index <HASH>..<HASH> 100644
--- a/src/feat/database/driver.py
+++ b/src/feat/database/driver.py
@@ -22,7 +22,7 @@
from urllib import urlencode, quote
from zope.interface import implements
-from twisted.internet import error as tw_error, base
+from twisted.internet import error as tw_error
from twisted.python import failure
from twisted.protocols import basic
from twisted.web.http import _DataLoss as DataLoss
@@ -65,7 +65,20 @@ class ChangeReceiver(basic.LineReceiver):
def connectionMade(self):
d = self._deferred
self._deferred = None
- d.callback(self)
+ if self.status == 200:
+ d.callback(self)
+ elif self.status == 404:
+ self.stopping = True
+ f = failure.Failure(NotFoundError(self._notifier.name))
+ f.cleanFailure()
+ d.errback(f)
+ else:
+ self.stopping = True
+ msg = ("Calling change notifier: %s gave %s status code" %
+ (self._notifier.name, int(self.status)))
+ f = failure.Failure(DatabaseError(msg))
+ f.cleanFailure()
+ d.errback(f)
def lineReceived(self, line):
if not line:
@@ -89,9 +102,6 @@ class ChangeReceiver(basic.LineReceiver):
def connectionLost(self, reason=None):
if self.stopping:
return
- if self.status == 404:
- reason = failure.Failure(NotFoundError())
- reason.cleanFailure()
if not reason or reason.check(DataLoss):
reason = failure.Failure(
tw_error.ConnectionLost("Couchdb closed connection"))
@@ -178,6 +188,8 @@ class Notifier(object):
def connectionLost(self, reason):
self._changes = None
+ if reason.check(NotFoundError):
+ return reason
self._db.connectionLost(reason)
diff --git a/src/feat/test/integration/test_idatabase_client.py b/src/feat/test/integration/test_idatabase_client.py
index <HASH>..<HASH> 100644
--- a/src/feat/test/integration/test_idatabase_client.py
+++ b/src/feat/test/integration/test_idatabase_client.py
@@ -675,9 +675,9 @@ class TestCase(object):
@defer.inlineCallbacks
def testUsingQueryView(self):
- views = (QueryView, )
- design_doc = view.DesignDocument.generate_from_views(views)[0]
- yield self.connection.save_document(design_doc)
+ views = (QueryView, view.DocumentDeletions)
+ for design_doc in view.DesignDocument.generate_from_views(views):
+ yield self.connection.save_document(design_doc)
for x in range(20):
if x % 2 == 0:
@@ -796,6 +796,15 @@ class PaisleySpecific(object):
self.database.add_reconnected_cb(mock.on_connect)
return mock
+ def testFilteredChanges404(self):
+
+ def listener(doc_id, rev, deleted, own_change):
+ pass
+
+ d = self.connection.changes_listener(view.DocumentDeletions, listener)
+ self.assertFailure(d, NotFoundError)
+ return d
+
@defer.inlineCallbacks
def testGettingDocsWhileDisconnected(self):
doc = DummyDocument(field=u'sth')
diff --git a/src/feat/web/httpclient.py b/src/feat/web/httpclient.py
index <HASH>..<HASH> 100644
--- a/src/feat/web/httpclient.py
+++ b/src/feat/web/httpclient.py
@@ -49,6 +49,7 @@ class Response(object):
self.headers = {}
self.length = None
self.body = None
+ self.protocol = None
class Delegate(object):
@@ -64,32 +65,22 @@ class Delegate(object):
setattr(instance.__dict__[self.attr], self.name, value)
-class BaseDecoder(object, Protocol):
+class ResponseDecoder(object, Protocol):
+ protocol = Delegate('_response', 'protocol')
status = Delegate('_response', 'status')
headers = Delegate('_response', 'headers')
length = Delegate('_response', 'length')
body = Delegate('_response', 'body')
def __init__(self):
- self._response = None
-
- ### private interface of the decoder ###
-
- def get_result(self):
- return self
-
-
-class ResponseDecoder(BaseDecoder):
-
- def __init__(self):
self._deferred = defer.Deferred()
- BaseDecoder.__init__(self)
+ self._response = Response()
### IProtocol ###
def connectionMade(self):
- self._response = Response()
+ pass
def dataReceived(self, data):
if self._response.body is None:
@@ -206,9 +197,9 @@ class Protocol(http.BaseProtocol):
return
protocol, status = parts
self._response = self._requests.pop(0)
- self._response.makeConnection(self.transport)
self._response.protocol = protocol
self._response.status = status
+ self._response.makeConnection(self.transport)
# HTTP 1.0 doesn't require Content-Length or Transfer-Encoding
# response headers. It can simply start printing body after the
|
Respond with correct failure when couchdb client tries to use
filtered changes listener with an unexisting filter.
Also change the order of calls against the response decoder in http client.
Now connectionMade() is called when the response status is already set,
so that it could use this value to respond.
|
f3at_feat
|
train
|
6a79239944fa495130aded67c048592eb40c97b6
|
diff --git a/pkg/kubectl/cmd/attach.go b/pkg/kubectl/cmd/attach.go
index <HASH>..<HASH> 100644
--- a/pkg/kubectl/cmd/attach.go
+++ b/pkg/kubectl/cmd/attach.go
@@ -115,7 +115,8 @@ func (*DefaultRemoteAttach) Attach(method string, url *url.URL, config *restclie
type AttachOptions struct {
StreamOptions
- CommandName string
+ CommandName string
+ SuggestedCmdUsage string
Pod *api.Pod
@@ -168,6 +169,15 @@ func (p *AttachOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn [
p.PodName = attachablePod.Name
p.Namespace = namespace
+ fullCmdName := ""
+ cmdParent := cmd.Parent()
+ if cmdParent != nil {
+ fullCmdName = cmdParent.CommandPath()
+ }
+ if len(fullCmdName) > 0 && cmdutil.IsSiblingCommandExists(cmd, "describe") {
+ p.SuggestedCmdUsage = fmt.Sprintf("Use '%s describe pod/%s -n %s' to see all of the containers in this pod.", fullCmdName, p.PodName, p.Namespace)
+ }
+
config, err := f.ClientConfig()
if err != nil {
return err
@@ -311,6 +321,11 @@ func (p *AttachOptions) containerToAttachTo(pod *api.Pod) (*api.Container, error
return nil, fmt.Errorf("container not found (%s)", p.ContainerName)
}
+ if len(p.SuggestedCmdUsage) > 0 {
+ fmt.Fprintf(p.Err, "Defaulting container name to %s.\n", pod.Spec.Containers[0].Name)
+ fmt.Fprintf(p.Err, "%s\n", p.SuggestedCmdUsage)
+ }
+
glog.V(4).Infof("defaulting container name to %s", pod.Spec.Containers[0].Name)
return &pod.Spec.Containers[0], nil
}
|
suggest using describe cmd to list pod containers
|
kubernetes_kubernetes
|
train
|
3b52a879ad4e9adf01d344f8117e550d8d5f6e4f
|
diff --git a/src/frontend/org/voltdb/iv2/BaseInitiator.java b/src/frontend/org/voltdb/iv2/BaseInitiator.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/iv2/BaseInitiator.java
+++ b/src/frontend/org/voltdb/iv2/BaseInitiator.java
@@ -172,14 +172,6 @@ public abstract class BaseInitiator implements Initiator
} catch (Exception e) {
tmLog.info("Exception during shutdown.", e);
}
-
- try {
- if (m_siteThread != null) {
- m_siteThread.interrupt();
- }
- } catch (Exception e) {
- tmLog.info("Exception during shutdown.");
- }
}
@Override
|
Don't interrupt IV2 sites on shutdown. Let the poinson pill take care of the
running procedures.
|
VoltDB_voltdb
|
train
|
5fe17e0433ee4be97ab17f3aa88a76b0e114e714
|
diff --git a/test/lib/queue_worker.spec.js b/test/lib/queue_worker.spec.js
index <HASH>..<HASH> 100644
--- a/test/lib/queue_worker.spec.js
+++ b/test/lib/queue_worker.spec.js
@@ -1752,7 +1752,7 @@ describe('QueueWorker', function() {
} catch (errorB) {
done(errorB)
}
- }, 0);
+ }, 100);
});
});
});
|
Reducing possibility of a race-condition in new shutdown() test
|
FirebaseExtended_firebase-queue
|
train
|
94d0c17b808904d8c9d18133dfcbc46bcd433f2f
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -161,6 +161,26 @@ There are props that are common for all components and special props for each co
</thead>
<tbody>
<tr>
+ <td>audio-src</td>
+ <td><code>String</code></td>
+ <td><code>null</code></td>
+ <td>
+ Audio element src attribute. When provided creates audio element
+ wrapped in "div".
+ </td>
+ </tr>
+ <tr>
+ <td>ref-link</td>
+ <td><code>String</code></td>
+ <td><code>null</code></td>
+ <td>
+ Reference to parent audio element via Vue "ref" attribute. When set,
+ then local audio element is not created and the plugin will connect
+ audio analyser to parent audio element. Multiple plugin instances
+ can connect to the same audio element (see example above).
+ </td>
+ </tr>
+ <tr>
<td>audio-controls</td>
<td><code>Boolean</code></td>
<td><code>true</code></td>
diff --git a/src/components/AvBase.js b/src/components/AvBase.js
index <HASH>..<HASH> 100644
--- a/src/components/AvBase.js
+++ b/src/components/AvBase.js
@@ -188,7 +188,7 @@ export default {
this.mainLoop()
},
beforeDestroy () {
- this.audioCtx.close()
+ this.audioCtx.close()
},
methods
}
diff --git a/test/unit/specs/AvBars.canvas.spec.js b/test/unit/specs/AvBars.canvas.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/specs/AvBars.canvas.spec.js
+++ b/test/unit/specs/AvBars.canvas.spec.js
@@ -9,8 +9,8 @@ describe('AvBars canvas build', () => {
const d = document
const f = document.createElement
document.createElement = (param) => param === 'canvas'
- ? mockCanvas()
- : f.call(d, param)
+ ? mockCanvas()
+ : f.call(d, param)
})
it('should not draw caps by default', () => {
diff --git a/test/unit/specs/AvBars.component.spec.js b/test/unit/specs/AvBars.component.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/specs/AvBars.component.spec.js
+++ b/test/unit/specs/AvBars.component.spec.js
@@ -20,7 +20,7 @@ describe('AvBars component insert', () => {
<audio ref="bar" audio-src="/assets/foo.mp3"/>
<av-bars ref-link="bar"></av-bars>
</div>`
- }
+ }
const Comp = mount(App, { localVue })
expect(Comp.vm.$avAudioRefs).not.toBeUndefined()
expect(Comp.vm.$avAudioRefs.bar).not.toBeUndefined()
diff --git a/test/unit/specs/AvCircle.component.spec.js b/test/unit/specs/AvCircle.component.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/specs/AvCircle.component.spec.js
+++ b/test/unit/specs/AvCircle.component.spec.js
@@ -21,7 +21,7 @@ describe('AvCircle component insert', () => {
<audio ref="circ" audio-src="/assets/foo.mp3"/>
<av-circle ref-link="circ"></av-circle>
</div>`
- }
+ }
const Comp = mount(App, { localVue })
expect(Comp.vm.$avAudioRefs).not.toBeUndefined()
expect(Comp.vm.$avAudioRefs.circ).not.toBeUndefined()
diff --git a/test/unit/specs/AvLine.component.spec.js b/test/unit/specs/AvLine.component.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/specs/AvLine.component.spec.js
+++ b/test/unit/specs/AvLine.component.spec.js
@@ -20,7 +20,7 @@ describe('AvLine component insert', () => {
<audio ref="foo" audio-src="/assets/foo.mp3"/>
<av-line ref-link="foo"></av-line>
</div>`
- }
+ }
const Comp = mount(App, { localVue })
expect(Comp.vm.$avAudioRefs).not.toBeUndefined()
expect(Comp.vm.$avAudioRefs.foo).not.toBeUndefined()
|
Fix some lint problems and add info to readme file.
|
staskobzar_vue-audio-visual
|
train
|
bc4bf66d17e38016733b310a3ca2ee7c2c762ae6
|
diff --git a/dvc/remote/local.py b/dvc/remote/local.py
index <HASH>..<HASH> 100644
--- a/dvc/remote/local.py
+++ b/dvc/remote/local.py
@@ -626,8 +626,12 @@ class LocalCache(LocalRemote, CacheMixin):
func = pbar.wrap_fn(func)
with ThreadPoolExecutor(max_workers=jobs) as executor:
if download:
- fails = sum(executor.map(func, *dir_plans))
- fails += sum(executor.map(func, *file_plans))
+ from_infos, to_infos, names, _ = (
+ d + f for d, f in zip(dir_plans, file_plans)
+ )
+ fails = sum(
+ executor.map(func, from_infos, to_infos, names)
+ )
else:
# for uploads, push files first, and any .dir files last
|
(bugfix) get/import: fix broken progress bar (#<I>)
PR #<I> (6d<I>e) extended `LocalRemote::_get_plans` to return one
`checksums` too. As all of the args from `_get_plans` was passed
down to `download()`, it recognized extra arg of checksum as
`no_progress_bar` due to which it became True and stopped showing
progress bar at all.
Fix #<I>
|
iterative_dvc
|
train
|
83b05948907f290669a198d57dc1f5a311dc3310
|
diff --git a/app/controllers/humpyard/pages_controller.rb b/app/controllers/humpyard/pages_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/humpyard/pages_controller.rb
+++ b/app/controllers/humpyard/pages_controller.rb
@@ -251,6 +251,8 @@ module Humpyard
raise ::ActionController::RoutingError, "No route matches \"#{request.path}\"" if @page.nil?
response.headers['X-Humpyard-Page'] = "#{@page.id}"
+ response.headers['X-Humpyard-Modified'] = "#{@page.last_modified}"
+ response.headers['X-Humpyard-ServerTime'] = "#{Time.now.utc}"
@page_partial ||= "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show"
@local_vars ||= {:page => @page}
@@ -258,7 +260,7 @@ module Humpyard
self.class.layout(@page.template_name)
if Rails::Application.config.action_controller.perform_caching
- fresh_when :etag => "#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}", :last_modified => @page.last_modified(:include_pages => true).utc, :public => @humpyard_user.nil?
+ fresh_when :etag => "#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}", :last_modified => @page.last_modified(:include_pages => true), :public => @humpyard_user.nil?
end
end
|
Better fresh_when config and some debug headers
|
humpyard_humpyard
|
train
|
58a9c52e530343ba1391c18cb5bf93a59512bbb2
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,7 @@
+v0.7 [30-04-2013]
+* implemented Array and Hash properties types
+* fixed a bug with Date property implementation
+
v0.6.2 [23-05-2012]
* adds an ability to specify/create indices on *has_one* and *belongs_to* associations
* fixed error with updating indices in *belongs_to* association with :as option
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -82,8 +82,11 @@ Supported property types:
* **RedisOrm::Boolean**
there is no Boolean class in Ruby so it's a special class to store TrueClass or FalseClass objects
-* **Time**
+* **Time** or **DateTime**
+* **Array** or **Hash**
+ RedisOrm automatically will handle serializing/deserializing into string using Marshal class
+
Following options are available in property declaration:
* **:default**
diff --git a/lib/redis_orm/redis_orm.rb b/lib/redis_orm/redis_orm.rb
index <HASH>..<HASH> 100644
--- a/lib/redis_orm/redis_orm.rb
+++ b/lib/redis_orm/redis_orm.rb
@@ -542,6 +542,15 @@ module RedisOrm
def save
return false if !valid?
+ # an exception should be raised before all saving procedures if wrong value type is specified (especcially true for Arrays and Hashes)
+ @@properties[model_name].each do |prop|
+ prop_value = self.send(prop[:name].to_sym)
+
+ if prop_value && prop[:class] != prop_value.class.to_s && ['Array', 'Hash'].include?(prop[:class].to_s)
+ raise TypeMismatchError
+ end
+ end
+
# store here initial persisted flag so we could invoke :after_create callbacks in the end of the function
was_persisted = persisted?
@@ -651,7 +660,7 @@ module RedisOrm
@@properties[model_name].each do |prop|
prop_value = self.send(prop[:name].to_sym)
-
+
if prop_value.nil? && !prop[:options][:default].nil?
prop_value = prop[:options][:default]
diff --git a/test/basic_functionality_test.rb b/test/basic_functionality_test.rb
index <HASH>..<HASH> 100644
--- a/test/basic_functionality_test.rb
+++ b/test/basic_functionality_test.rb
@@ -171,6 +171,26 @@ describe "check basic functionality" do
saved_article.comments.should == ["Hello", "there are comments"]
end
+ it "should store default hash in the property if it's not provided" do
+ a = ArticleWithComments.new :title => "Article #1"
+ expect {
+ a.save
+ }.to change(ArticleWithComments, :count).by(1)
+
+ saved_article = ArticleWithComments.last
+ saved_article.rates.should == {1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0}
+ end
+
+ it "should store hash in the property correctly" do
+ a = ArticleWithComments.new :title => "Article #1", :rates => {4 => 134}
+ expect {
+ a.save
+ }.to change(ArticleWithComments, :count).by(1)
+
+ saved_article = ArticleWithComments.last
+ saved_article.rates.should == {4 => 134}
+ end
+
it "should properly transform :default values to right classes (if :default values are wrong) so when comparing them to other/stored instances they'll be the same" do
# SortableUser class has 3 properties with wrong classes of :default value
u = SortableUser.new :name => "Alan"
diff --git a/test/classes/article_with_comments.rb b/test/classes/article_with_comments.rb
index <HASH>..<HASH> 100644
--- a/test/classes/article_with_comments.rb
+++ b/test/classes/article_with_comments.rb
@@ -2,5 +2,7 @@ class ArticleWithComments < RedisOrm::Base
property :title, String
property :comments, Array
+ property :rates, Hash, :default => {1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0}
+
has_many :categories
end
diff --git a/test/exceptions_test.rb b/test/exceptions_test.rb
index <HASH>..<HASH> 100644
--- a/test/exceptions_test.rb
+++ b/test/exceptions_test.rb
@@ -32,4 +32,16 @@ describe "exceptions test" do
jigsaw = Jigsaw.create :title => "jigsaw"
lambda { User.create!(:name => "John", :age => 44, :profile => jigsaw) }.should raise_error(RedisOrm::TypeMismatchError)
end
+
+ it "should throw an exception if wrong format of the default value is specified for Array/Hash property" do
+ a = ArticleWithComments.new :title => "Article #1", :rates => [1,2,3,4,5]
+ lambda {
+ a.save
+ }.should raise_error(RedisOrm::TypeMismatchError)
+
+ a = ArticleWithComments.new :title => "Article #1", :comments => 12
+ lambda {
+ a.save
+ }.should raise_error(RedisOrm::TypeMismatchError)
+ end
end
|
added tests for new Hash and Array type properties (now also throwing an exception if passed wrong property value)
|
german_redis_orm
|
train
|
973d661007b251405d7f8b5dcaf32885807a89d6
|
diff --git a/lib/ransack/nodes/sort.rb b/lib/ransack/nodes/sort.rb
index <HASH>..<HASH> 100644
--- a/lib/ransack/nodes/sort.rb
+++ b/lib/ransack/nodes/sort.rb
@@ -3,7 +3,7 @@ module Ransack
class Sort < Node
include Bindable
- attr_reader :name, :dir
+ attr_reader :name, :dir, :ransacker_args
i18n_word :asc, :desc
class << self
@@ -16,7 +16,7 @@ module Ransack
def build(params)
params.with_indifferent_access.each do |key, value|
- if key.match(/^(name|dir)$/)
+ if key.match(/^(name|dir|ransacker_args)$/)
self.send("#{key}=", value)
end
end
@@ -45,6 +45,10 @@ module Ransack
end
end
+ def ransacker_args=(ransack_args)
+ @ransacker_args = ransack_args
+ end
+
end
end
end
diff --git a/spec/ransack/adapters/active_record/base_spec.rb b/spec/ransack/adapters/active_record/base_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/ransack/adapters/active_record/base_spec.rb
+++ b/spec/ransack/adapters/active_record/base_spec.rb
@@ -333,6 +333,34 @@ module Ransack
/LIKE \'\%Rails has been released\%\'/
)
end
+
+ it 'should allow search and sort passing ransacker arguments to a ransacker' do
+ s = Person.ransack(
+ c: [{
+ a: {
+ '0' => {
+ name: 'dynamic_hstore',
+ ransacker_args: ['hstore_column', 'example_field']
+ }
+ },
+ p: 'cont',
+ v: ['Some Value']
+ }],
+ s: {
+ '0' => {
+ 'name' => 'dynamic_hstore',
+ 'dir' => 'asc',
+ 'ransacker_args' => ['hstore_column', 'example_field']
+ }
+ }
+ )
+ expect(s.result.to_sql).to match(
+ /(\"people\".\"hstore_column\" -> 'example_field' LIKE '%Some Value%')/
+ )
+ expect(s.result.to_sql).to match(
+ /ORDER BY \"people\".\"hstore_column\" -> 'example_field' ASC/
+ )
+ end
end
describe '#ransackable_attributes' do
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
@@ -80,6 +80,11 @@ class Person < ActiveRecord::Base
Arel.sql(sql.squish)
end
+ ransacker :dynamic_hstore, args: [:parent, :ransacker_args] do |parent, args|
+ column, field = args
+ Arel::Nodes::InfixOperation.new("->", Person.arel_table[column], Arel::Nodes.build_quoted(field))
+ end
+
def self.ransackable_attributes(auth_object = nil)
if auth_object == :admin
column_names + _ransackers.keys - ['only_sort']
|
Added support of ransacker_args to Ransack::Nodes::Sort and related test.
|
activerecord-hackery_ransack
|
train
|
a13bdfc159192dfd320c01d45d498e10732cc6de
|
diff --git a/lib/vagrant_snap.rb b/lib/vagrant_snap.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant_snap.rb
+++ b/lib/vagrant_snap.rb
@@ -16,6 +16,7 @@ module Snap
end
def parse_tree(vmname)
+ init
vm = VirtualBox::VM.find( vmname )
@@current = vm.current_snapshot
return unless @@current
@@ -81,25 +82,6 @@ module Snap
end
result
end
-
- ## [TODO] darty hack, should be written more simply
- # def _parse(snapshot, guide = "")
- # snapnames << snapshot.name
- # time = time_elapse(Time.now - snapshot.time_stamp)
- # snapinfo = "#{snapshot.name} [ #{time} ]"
- # snapinfo = snapinfo.yellow if snapshot.uuid == @@current.uuid
- # result = "#{guide} #{snapinfo}"
- # result << " #{snapshot.description}" unless snapshot.description.empty?
- # result << "\n"
-
- # last_child_idx = snapshot.children.size - 1
- # snapshot.children.each_with_index do |e, idx|
- # tmp = guide.chop.chop.sub("`", " ") + " "
- # tmp << "#{last_child_idx == idx ? '`' : '|'}" << "--"
- # result << _parse(e, "#{tmp}")
- # end
- # result
- # end
end
end #}}}
end
@@ -169,10 +151,23 @@ module Snap
with_target(target) do |vmname, vagvmname|
puts "[#{vagvmname}]"
VBox::SnapShot.parse_tree( vmname )
- new_name = options.name if options.name
+ if options.name
+ if VBox::SnapShot.include? options.name
+ warn "#{options.name} is already exist".red
+ next
+ else
+ new_name = options.name
+ end
+ end
unless new_name
lastname = VBox::SnapShot.lastname
- new_name = lastname.nil? ? "001" : lastname.succ
+ new_name = if lastname.nil?
+ "001"
+ else
+ n = lastname.succ
+ n = n.succ while VBox::SnapShot.include? n
+ n
+ end
end
desc = options.desc ? " --description '#{options.desc}'" : ""
system "VBoxManage snapshot #{vmname} take #{new_name} #{desc} --pause"
|
check snapshot name uniqueness before taking new snapshot
|
t9md_vagrant-snap
|
train
|
4eb779e596dd498f2bdf4763ce06f0d1b62c1a08
|
diff --git a/provider/marathon.go b/provider/marathon.go
index <HASH>..<HASH> 100644
--- a/provider/marathon.go
+++ b/provider/marathon.go
@@ -235,24 +235,11 @@ func (provider *Marathon) taskFilter(task marathon.Task, applications *marathon.
}
}
if portValueLabel != "" {
- port, err := strconv.Atoi((*application.Labels)["traefik.port"])
+ _, err := strconv.Atoi((*application.Labels)["traefik.port"])
if err != nil {
log.Debugf("Filtering marathon task %s with unexpected value for traefik.port label", task.AppID)
return false
}
-
- var foundPort bool
- for _, exposedPort := range ports {
- if port == exposedPort {
- foundPort = true
- break
- }
- }
-
- if !foundPort {
- log.Debugf("Filtering marathon task %s without a matching port for traefik.port label", task.AppID)
- return false
- }
}
//filter healthchecks
diff --git a/provider/marathon_test.go b/provider/marathon_test.go
index <HASH>..<HASH> 100644
--- a/provider/marathon_test.go
+++ b/provider/marathon_test.go
@@ -519,39 +519,19 @@ func TestMarathonTaskFilter(t *testing.T) {
{
task: marathon.Task{
AppID: "specify-port-number",
- Ports: []int{80, 443},
- },
- applications: &marathon.Applications{
- Apps: []marathon.Application{
- {
- ID: "specify-port-number",
- Ports: []int{80, 443},
- Labels: &map[string]string{
- "traefik.port": "80",
- },
- },
- },
- },
- expected: true,
- exposedByDefault: true,
- },
- {
- task: marathon.Task{
- AppID: "specify-unknown-port-number",
- Ports: []int{80, 443},
+ Ports: []int{80},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
- ID: "specify-unknown-port-number",
- Ports: []int{80, 443},
+ ID: "specify-port-number",
Labels: &map[string]string{
"traefik.port": "8080",
},
},
},
},
- expected: false,
+ expected: true,
exposedByDefault: true,
},
{
|
Allow traefik.port to not be in the list of marathon ports
|
containous_traefik
|
train
|
484741ccf0ff6eca78ac2a84400d5b5399a6516a
|
diff --git a/buffer_test.go b/buffer_test.go
index <HASH>..<HASH> 100644
--- a/buffer_test.go
+++ b/buffer_test.go
@@ -9,6 +9,16 @@ import (
"testing"
)
+func TestSpill(t *testing.T) {
+ buf := NewMulti(New(5), NewDiscard())
+ buf.Write([]byte("Hello World"))
+ data := make([]byte, 12)
+ n, _ := buf.Read(data)
+ if !bytes.Equal(data[:n], []byte("Hello")) {
+ t.Error("ReadAt Failed. " + string(data[:n]))
+ }
+}
+
func TestReadAt(t *testing.T) {
buf := NewMulti(NewFile(2), NewFile(2), NewFile(2), NewFile(2), NewFile(2), NewFile(2))
buf.Write([]byte("Hello World"))
|
Added Discard Buffer, which is always empty, and accepts all writes
|
djherbis_buffer
|
train
|
164f64fb9f92440256787ba30af39b4cdc5b4617
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@
#### Fixes
* Your contribution here.
+* [#1893](https://github.com/ruby-grape/grape/pull/1893): Allows `Grape::API` to behave like a Rack::app in some instances where it was misbehaving - [@myxoh](https://github.com/myxoh).
### 1.2.4 (2019/06/13)
diff --git a/lib/grape/api.rb b/lib/grape/api.rb
index <HASH>..<HASH> 100644
--- a/lib/grape/api.rb
+++ b/lib/grape/api.rb
@@ -48,7 +48,12 @@ module Grape
# (http://www.rubydoc.info/github/rack/rack/master/file/SPEC) for more.
# NOTE: This will only be called on an API directly mounted on RACK
def call(*args, &block)
- base_instance.call(*args, &block)
+ instance_for_rack = if never_mounted?
+ base_instance
+ else
+ mounted_instances.first
+ end
+ instance_for_rack.call(*args, &block)
end
# Allows an API to itself be inheritable:
@@ -147,6 +152,14 @@ module Grape
end
end
end
+
+ def never_mounted?
+ mounted_instances.empty?
+ end
+
+ def mounted_instances
+ instances - [base_instance]
+ end
end
end
end
diff --git a/spec/grape/integration/rack_spec.rb b/spec/grape/integration/rack_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/grape/integration/rack_spec.rb
+++ b/spec/grape/integration/rack_spec.rb
@@ -31,4 +31,26 @@ describe Rack do
input.unlink
end
end
+
+ context 'when the app is mounted' do
+ def app
+ @main_app ||= Class.new(Grape::API) do
+ get 'ping'
+ end
+ end
+
+ let!(:base) do
+ app_to_mount = app
+ Class.new(Grape::API) do
+ namespace 'namespace' do
+ mount app_to_mount
+ end
+ end
+ end
+
+ it 'finds the app on the namespace' do
+ get '/namespace/ping'
+ expect(last_response.status).to eq 200
+ end
+ end
end
|
Makes sure Grape::API behaves as a Rack::App (#<I>)
Makes sure Grape::API behaves as a Rack::App by calling: 'call' on the first mounted instance rather than the base instance (which is never mounted) which will have the environment information as to where it was mounted.
|
ruby-grape_grape
|
train
|
a4856efbfe6d9f0a1ca4968de926a9e68d354ec7
|
diff --git a/src/TwigBridge/TwigBridge.php b/src/TwigBridge/TwigBridge.php
index <HASH>..<HASH> 100644
--- a/src/TwigBridge/TwigBridge.php
+++ b/src/TwigBridge/TwigBridge.php
@@ -24,7 +24,7 @@ class TwigBridge
/**
* @var string TwigBridge version
*/
- const VERSION = '0.1.12';
+ const VERSION = '0.2.4';
/**
* @var Illuminate\Foundation\Application
|
Bumped version for release <I>
|
rcrowe_TwigBridge
|
train
|
3b4a82fdd9e32fb765764c3f22a2181839dccd5b
|
diff --git a/src/Util/Href.php b/src/Util/Href.php
index <HASH>..<HASH> 100644
--- a/src/Util/Href.php
+++ b/src/Util/Href.php
@@ -20,10 +20,6 @@ class Href
*/
public function __construct( $url, $validate = false )
{
- if ($validate && !$this->isValid( $url )) {
- throw new InvalidUrl( sprintf( '"%s" is not a valid url', $url ) );
- }
-
$this->url = $url;
if ($validate) {
$this->validate();
diff --git a/tests/HrefTest.php b/tests/HrefTest.php
index <HASH>..<HASH> 100644
--- a/tests/HrefTest.php
+++ b/tests/HrefTest.php
@@ -81,20 +81,6 @@ class HrefTest extends PHPUnit_Framework_TestCase
$this->assertEquals( 'http://test.com/api/', $this->href->output() );
}
- /**
- * @param string $template The url template
- * @param string $result The desired result
- * @param array $keyValue The replacement key value
- *
- * @dataProvider urlTemplates
- */
- public function testUrlReplacement($template, $result, $key, $value)
- {
- $href = new Href($template);
- $href->replace($key, $value);
- $this->assertEquals($result, $href->getUrl());
- }
-
public function validUrls()
{
return array(
@@ -146,24 +132,6 @@ class HrefTest extends PHPUnit_Framework_TestCase
);
}
- public function urlTemplates()
- {
- return array(
- array(
- 'http://test.com/api/{resource}/',
- 'http://test.com/api/foo/',
- 'resource',
- 'foo'
- ),
- array(
- 'http://test.com/api/foo/{teSt_TEST}/',
- 'http://test.com/api/foo/bar/',
- 'teSt_TEST',
- 'bar'
- )
- );
- }
-
public function invalidExtensions()
{
return array(
|
Updated Href class and tests
|
cuevae_collection-json-php
|
train
|
7e6928466118168ab232fd1e89b778d6704f36b8
|
diff --git a/framework/core/src/Core/Handlers/Events/DiscussionMetadataUpdater.php b/framework/core/src/Core/Handlers/Events/DiscussionMetadataUpdater.php
index <HASH>..<HASH> 100755
--- a/framework/core/src/Core/Handlers/Events/DiscussionMetadataUpdater.php
+++ b/framework/core/src/Core/Handlers/Events/DiscussionMetadataUpdater.php
@@ -54,12 +54,14 @@ class DiscussionMetadataUpdater
{
$discussion = $post->discussion;
- $discussion->refreshCommentsCount();
+ if ($discussion->exists) {
+ $discussion->refreshCommentsCount();
- if ($discussion->last_post_id == $post->id) {
- $discussion->refreshLastPost();
- }
+ if ($discussion->last_post_id == $post->id) {
+ $discussion->refreshLastPost();
+ }
- $discussion->save();
+ $discussion->save();
+ }
}
}
diff --git a/framework/core/src/Core/Handlers/Events/UserActivitySyncer.php b/framework/core/src/Core/Handlers/Events/UserActivitySyncer.php
index <HASH>..<HASH> 100755
--- a/framework/core/src/Core/Handlers/Events/UserActivitySyncer.php
+++ b/framework/core/src/Core/Handlers/Events/UserActivitySyncer.php
@@ -71,6 +71,6 @@ class UserActivitySyncer
protected function postedActivity(Post $post)
{
- return $post->number === 1 ? new StartedDiscussionActivity($post) : new PostedActivity($post);
+ return $post->number == 1 ? new StartedDiscussionActivity($post) : new PostedActivity($post);
}
}
diff --git a/framework/core/src/Core/Models/Discussion.php b/framework/core/src/Core/Models/Discussion.php
index <HASH>..<HASH> 100755
--- a/framework/core/src/Core/Models/Discussion.php
+++ b/framework/core/src/Core/Models/Discussion.php
@@ -6,6 +6,7 @@ use Flarum\Core\Support\VisibleScope;
use Flarum\Core\Events\DiscussionWasDeleted;
use Flarum\Core\Events\DiscussionWasStarted;
use Flarum\Core\Events\DiscussionWasRenamed;
+use Flarum\Core\Events\PostWasDeleted;
use Flarum\Core\Models\User;
class Discussion extends Model
@@ -79,7 +80,16 @@ class Discussion extends Model
static::deleted(function ($discussion) {
$discussion->raise(new DiscussionWasDeleted($discussion));
- $discussion->posts()->allTypes()->delete();
+ $posts = $discussion->posts()->allTypes();
+
+ foreach ($posts->get() as $post) {
+ $post->setRelation('discussion', $discussion);
+
+ $discussion->raise(new PostWasDeleted($post));
+ }
+
+ $posts->delete();
+
$discussion->readers()->detach();
});
}
|
Make sure user activity is synced when whole discussions are deleted
We need to fire the PostWasDeleted event for every post when a
discussion is deleted. This means deleting big discussions will be an
intensive process, but that’s OK because it’s very rare.
|
flarum_core
|
train
|
cab9932a8c2787a378e52fc52921492c6bef7d71
|
diff --git a/rq_scheduler/scheduler.py b/rq_scheduler/scheduler.py
index <HASH>..<HASH> 100644
--- a/rq_scheduler/scheduler.py
+++ b/rq_scheduler/scheduler.py
@@ -131,8 +131,11 @@ class Scheduler(object):
"""
timeout = kwargs.pop('timeout', None)
job_id = kwargs.pop('job_id', None)
+ job_ttl = kwargs.pop('job_ttl', None)
+ job_result_ttl = kwargs.pop('job_result_ttl', None)
- job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout, id=job_id)
+ job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout,
+ id=job_id, result_ttl=job_result_ttl, ttl=job_ttl)
self.connection._zadd(self.scheduled_jobs_key,
to_unix(scheduled_time),
job.id)
@@ -146,8 +149,11 @@ class Scheduler(object):
"""
timeout = kwargs.pop('timeout', None)
job_id = kwargs.pop('job_id', None)
+ job_ttl = kwargs.pop('job_ttl', None)
+ job_result_ttl = kwargs.pop('job_result_ttl', None)
- job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout, id=job_id)
+ job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout,
+ id=job_id, result_ttl=job_result_ttl, ttl=job_ttl)
self.connection._zadd(self.scheduled_jobs_key,
to_unix(datetime.utcnow() + time_delta),
job.id)
diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py
index <HASH>..<HASH> 100644
--- a/tests/test_scheduler.py
+++ b/tests/test_scheduler.py
@@ -148,6 +148,22 @@ class TestScheduler(RQTestCase):
job = self.scheduler.enqueue_at(datetime.utcnow(), say_hello, job_id=job_id)
self.assertEqual(job.id, job_id)
+ def test_enqueue_at_sets_job_ttl(self):
+ """
+ Ensure that a job scheduled via enqueue_at can be created with a custom job ttl.
+ """
+ job_ttl = 123456789
+ job = self.scheduler.enqueue_at(datetime.utcnow(), say_hello, job_ttl=job_ttl)
+ self.assertEqual(job.ttl, job_ttl)
+
+ def test_enqueue_at_sets_job_result_ttl(self):
+ """
+ Ensure that a job scheduled via enqueue_at can be created with a custom result ttl.
+ """
+ job_result_ttl = 1234567890
+ job = self.scheduler.enqueue_at(datetime.utcnow(), say_hello, job_result_ttl=job_result_ttl)
+ self.assertEqual(job.result_ttl, job_result_ttl)
+
def test_enqueue_in(self):
"""
Ensure that jobs have the right scheduled time.
@@ -183,6 +199,22 @@ class TestScheduler(RQTestCase):
job = self.scheduler.enqueue_in(timedelta(minutes=1), say_hello, job_id=job_id)
self.assertEqual(job.id, job_id)
+ def test_enqueue_in_sets_job_ttl(self):
+ """
+ Ensure that a job scheduled via enqueue_in can be created with a custom job ttl.
+ """
+ job_ttl = 123456789
+ job = self.scheduler.enqueue_in(timedelta(minutes=1), say_hello, job_ttl=job_ttl)
+ self.assertEqual(job.ttl, job_ttl)
+
+ def test_enqueue_in_sets_job_result_ttl(self):
+ """
+ Ensure that a job scheduled via enqueue_in can be created with a custom result ttl.
+ """
+ job_result_ttl = 1234567890
+ job = self.scheduler.enqueue_in(timedelta(minutes=1), say_hello, job_result_ttl=job_result_ttl)
+ self.assertEqual(job.result_ttl, job_result_ttl)
+
def test_count(self):
now = datetime.utcnow()
self.scheduler.enqueue_at(now, say_hello)
|
[Feat] Updated enqueue_in/at to accept job_ttl and job_result_ttl arguments
|
rq_rq-scheduler
|
train
|
61c43de3dcb4acaa6f13b9d3a9dff20ad62345f3
|
diff --git a/pyqode/core/widgets/filesystem_treeview.py b/pyqode/core/widgets/filesystem_treeview.py
index <HASH>..<HASH> 100644
--- a/pyqode/core/widgets/filesystem_treeview.py
+++ b/pyqode/core/widgets/filesystem_treeview.py
@@ -287,7 +287,15 @@ class FileSystemHelper:
_logger().info('%s <%s> to <%s>' % (
'copying' if copy else 'cutting', src, destination))
perform_copy = True
- final_dest = os.path.join(destination, os.path.split(src)[1])
+ ext = os.path.splitext(src)[1]
+ original = os.path.splitext(os.path.split(src)[1])[0]
+ filename, status = QtWidgets.QInputDialog.getText(
+ self.tree_view, 'Copy', 'New name:',
+ QtWidgets.QLineEdit.Normal, original)
+ if filename == '' or not status:
+ return
+ filename = filename + ext
+ final_dest = os.path.join(destination, filename)
if os.path.exists(final_dest):
rep = QtWidgets.QMessageBox.question(
self.tree_view, 'File exists',
@@ -300,7 +308,7 @@ class FileSystemHelper:
if not perform_copy:
continue
try:
- shutil.copy(src, destination)
+ shutil.copy(src, final_dest)
except (IOError, OSError) as e:
QtWidgets.QMessageBox.warning(
self.tree_view, 'Failed to copy file', str(e))
|
FSTreeView: improve action paste
Now it will always prompt you for a new name (this is needed if you copy a file in the same directory).
|
pyQode_pyqode.core
|
train
|
691ad461b09f249f2cbd4614c68576ebb303ea2f
|
diff --git a/Auth/OpenID.php b/Auth/OpenID.php
index <HASH>..<HASH> 100644
--- a/Auth/OpenID.php
+++ b/Auth/OpenID.php
@@ -97,7 +97,7 @@ define('Auth_OpenID_punct',
"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
if (Auth_OpenID_getMathLib() === null) {
- define('Auth_OpenID_NO_MATH_SUPPORT', true);
+ Auth_OpenID_setNoMathSupport();
}
/**
@@ -574,4 +574,4 @@ class Auth_OpenID {
}
}
}
-?>
\ No newline at end of file
+?>
diff --git a/Auth/OpenID/Association.php b/Auth/OpenID/Association.php
index <HASH>..<HASH> 100644
--- a/Auth/OpenID/Association.php
+++ b/Auth/OpenID/Association.php
@@ -423,7 +423,7 @@ function Auth_OpenID_getDefaultAssociationOrder()
{
$order = array();
- if (!defined('Auth_OpenID_NO_MATH_SUPPORT')) {
+ if (!Auth_OpenID_noMathSupport()) {
$order[] = array('HMAC-SHA1', 'DH-SHA1');
if (Auth_OpenID_HMACSHA256_SUPPORTED) {
diff --git a/Auth/OpenID/BigMath.php b/Auth/OpenID/BigMath.php
index <HASH>..<HASH> 100644
--- a/Auth/OpenID/BigMath.php
+++ b/Auth/OpenID/BigMath.php
@@ -427,7 +427,7 @@ function &Auth_OpenID_getMathLib()
return $lib;
}
- if (defined('Auth_OpenID_NO_MATH_SUPPORT')) {
+ if (Auth_OpenID_noMathSupport()) {
$null = null;
return $null;
}
@@ -443,7 +443,7 @@ function &Auth_OpenID_getMathLib()
}
$triedstr = implode(", ", $tried);
- define('Auth_OpenID_NO_MATH_SUPPORT', true);
+ Auth_OpenID_setNoMathSupport();
$result = null;
return $result;
@@ -456,4 +456,16 @@ function &Auth_OpenID_getMathLib()
return $lib;
}
+function Auth_OpenID_setNoMathSupport()
+{
+ if (!defined('Auth_OpenID_NO_MATH_SUPPORT')) {
+ define('Auth_OpenID_NO_MATH_SUPPORT', true);
+ }
+}
+
+function Auth_OpenID_noMathSupport()
+{
+ return defined('Auth_OpenID_NO_MATH_SUPPORT');
+}
+
?>
diff --git a/examples/detect.php b/examples/detect.php
index <HASH>..<HASH> 100644
--- a/examples/detect.php
+++ b/examples/detect.php
@@ -194,8 +194,9 @@ function detect_math($r, &$out)
$out .= $r->ol(array(
'Install the ' . $gmp_lnk . ' PHP extension',
'Install the ' . $bc_lnk . ' PHP extension',
- 'If your site is low-security, define ' .
- 'Auth_OpenID_NO_MATH_SUPPORT. The library will function, but ' .
+ 'If your site is low-security, call ' .
+ 'Auth_OpenID_setNoMathSupport(), defined in Auth/OpenID/BigMath.php. ',
+ 'The library will function, but ' .
'the security of your OpenID server will depend on the ' .
'security of the network links involved. If you are only ' .
'using consumer support, you should still be able to operate ' .
|
[project @ [FIX #<I>] Replace direct usage of NO_MATH_SUPPORT with function calls]
|
openid_php-openid
|
train
|
6812db497df96cd9c3d19821c43ac5e2413a32b3
|
diff --git a/spec/unit/controller_filters_spec.rb b/spec/unit/controller_filters_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/controller_filters_spec.rb
+++ b/spec/unit/controller_filters_spec.rb
@@ -4,29 +4,29 @@ describe ActiveAdmin, "filters" do
let(:application){ ActiveAdmin::Application.new }
describe "before filters" do
- it "should add a new before filter to ActiveAdmin::ResourceController" do
- ActiveAdmin::ResourceController.should_receive(:before_filter).and_return(true)
+ it "should add a new before filter to ActiveAdmin::BaseController" do
+ ActiveAdmin::BaseController.should_receive(:before_filter).and_return(true)
application.before_filter :my_filter, :only => :show
end
end
describe "skip before filters" do
- it "should add a new skip before filter to ActiveAdmin::ResourceController" do
- ActiveAdmin::ResourceController.should_receive(:skip_before_filter).and_return(true)
+ it "should add a new skip before filter to ActiveAdmin::BaseController" do
+ ActiveAdmin::BaseController.should_receive(:skip_before_filter).and_return(true)
application.skip_before_filter :my_filter, :only => :show
end
end
describe "after filters" do
- it "should add a new after filter to ActiveAdmin::ResourceController" do
- ActiveAdmin::ResourceController.should_receive(:after_filter).and_return(true)
+ it "should add a new after filter to ActiveAdmin::BaseController" do
+ ActiveAdmin::BaseController.should_receive(:after_filter).and_return(true)
application.after_filter :my_filter, :only => :show
end
end
describe "around filters" do
- it "should add a new around filter to ActiveAdmin::ResourceController" do
- ActiveAdmin::ResourceController.should_receive(:around_filter).and_return(true)
+ it "should add a new around filter to ActiveAdmin::BaseController" do
+ ActiveAdmin::BaseController.should_receive(:around_filter).and_return(true)
application.around_filter :my_filter, :only => :show
end
end
|
controller_filters_spec updated (test are passing now).
|
activeadmin_activeadmin
|
train
|
e795451474a784b11061cf7f5ff9768a71dec143
|
diff --git a/src/main/java/org/aeonbits/owner/Converters.java b/src/main/java/org/aeonbits/owner/Converters.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/aeonbits/owner/Converters.java
+++ b/src/main/java/org/aeonbits/owner/Converters.java
@@ -28,7 +28,7 @@ public enum Converters {
}
},
- STRING_CONSTRUCTOR {
+ CLASS_WITH_STRING_CONSTRUCTOR {
@Override
Object convert(Class<?> targetType, String text) {
try {
@@ -40,6 +40,18 @@ public enum Converters {
}
},
+ CLASS_WITH_OBJECT_CONSTRUCTOR {
+ @Override
+ Object convert(Class<?> targetType, String text) {
+ try {
+ Constructor<?> constructor = targetType.getConstructor(Object.class);
+ return constructor.newInstance(text);
+ } catch (ReflectiveOperationException ex) {
+ return null;
+ }
+ }
+ },
+
CLASS_CONVERTER {
@Override
Object convert(Class<?> targetType, String text) {
diff --git a/src/test/java/org/aeonbits/owner/SpecialTypesTest.java b/src/test/java/org/aeonbits/owner/SpecialTypesTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/aeonbits/owner/SpecialTypesTest.java
+++ b/src/test/java/org/aeonbits/owner/SpecialTypesTest.java
@@ -39,7 +39,7 @@ public class SpecialTypesTest {
}
@Test
- public void testCustomType() throws Throwable {
+ public void testClassWithStringConstructor() throws Throwable {
SpecialTypes config = ConfigFactory.create(SpecialTypes.class);
CustomType custom = config.customType();
assertNotNull(custom);
@@ -47,6 +47,14 @@ public class SpecialTypesTest {
}
@Test
+ public void testClassWithObjectConstructor() throws Throwable {
+ SpecialTypes config = ConfigFactory.create(SpecialTypes.class);
+ Reference reference = config.reference();
+ assertNotNull(reference);
+ assertEquals("foobar", reference.toString());
+ }
+
+ @Test
public void testCustomTypeWithParameter() throws Throwable {
SpecialTypes config = ConfigFactory.create(SpecialTypes.class);
CustomType custom = config.salutation("Luigi");
|
added class with object constructor converter; refactoring
|
lviggiano_owner
|
train
|
32f40ab9525256f1f7654d54f3307a4e9e1bc7c4
|
diff --git a/core/Date.php b/core/Date.php
index <HASH>..<HASH> 100644
--- a/core/Date.php
+++ b/core/Date.php
@@ -290,6 +290,18 @@ class Date
}
/**
+ * Returns `true` if the current year is a leap year, false otherwise.
+ *
+ * @return bool
+ */
+ public function isLeapYear()
+ {
+ $currentYear = date('Y', $this->getTimestamp());
+
+ return ($currentYear % 400) == 0 || (($currentYear % 4) == 0 && ($currentYear % 100) != 0);
+ }
+
+ /**
* Converts this date to the requested string format. See {@link http://php.net/date}
* for the list of format strings.
*
diff --git a/tests/PHPUnit/Core/DateTest.php b/tests/PHPUnit/Core/DateTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/Core/DateTest.php
+++ b/tests/PHPUnit/Core/DateTest.php
@@ -238,4 +238,31 @@ class DateTest extends PHPUnit_Framework_TestCase
$date = $date->subPeriod(5, 'year');
$this->assertEquals($dateExpected->getTimestamp(), $date->getTimestamp());
}
+
+ /**
+ * @group Core
+ */
+ public function testIsLeapYear()
+ {
+ $date = Date::factory('2011-03-01');
+ $this->assertFalse($date->isLeapYear());
+ $date = Date::factory('2011-01-01');
+ $this->assertFalse($date->isLeapYear());
+ $date = Date::factory('2011-01-31');
+ $this->assertFalse($date->isLeapYear());
+
+ $date = Date::factory('2012-01-01');
+ $this->assertTrue($date->isLeapYear());
+ $date = Date::factory('2012-12-31');
+ $this->assertTrue($date->isLeapYear());
+
+ $date = Date::factory('2013-01-01');
+ $this->assertFalse($date->isLeapYear());
+ $date = Date::factory('2013-12-31');
+ $this->assertFalse($date->isLeapYear());
+
+ $date = Date::factory('2052-01-01');
+ $this->assertTrue($date->isLeapYear());
+
+ }
}
|
refs #<I> added method to detect whether current year is a leap year
|
matomo-org_matomo
|
train
|
c041c89f598e55d766195536375696f68bd32f22
|
diff --git a/spec/fixture-helper.js b/spec/fixture-helper.js
index <HASH>..<HASH> 100644
--- a/spec/fixture-helper.js
+++ b/spec/fixture-helper.js
@@ -57,20 +57,20 @@ module.exports = function fixtureHelper (tmpDir) {
},
// Creates a cordova project with one platform installed
- projectWithPlatform () {
+ async projectWithPlatform () {
const projectFixture = path.join(__dirname, 'cordova/fixtures/basePkgJson');
const projectPath = path.join(fixturesBaseDir, 'project-with-platform');
- return fs.copy(projectFixture, projectPath)
- .then(_ => process.chdir(projectPath))
- .then(_ => {
- // Talk about a clunky interface :(
- const platforms = ['android'];
- const opts = { platforms, save: true };
- const hooksRunner = new HooksRunner(projectPath);
- return platformAdd(hooksRunner, projectPath, platforms, opts);
- })
- .then(_ => projectPath);
+ fs.copySync(projectFixture, projectPath);
+ process.chdir(projectPath);
+
+ // Talk about a clunky interface :(
+ const platforms = ['android'];
+ const opts = { platforms, save: true };
+ const hooksRunner = new HooksRunner(projectPath);
+ await platformAdd(hooksRunner, projectPath, platforms, opts);
+
+ return projectPath;
},
androidPlatform () {
@@ -89,10 +89,10 @@ module.exports = function fixtureHelper (tmpDir) {
fixturePromises[name] = Promise.resolve(fixtureConstructors[name]());
}
return {
- copyTo (targetPath) {
- return fixturePromises[name]
- .then(fixturePath => fs.copy(fixturePath, targetPath))
- .then(_ => targetPath);
+ async copyTo (targetPath) {
+ const fixturePath = await fixturePromises[name];
+ fs.copySync(fixturePath, targetPath);
+ return targetPath;
}
};
};
|
test: use fs.copySync for increased performance (#<I>)
|
apache_cordova-lib
|
train
|
8f6dfaf2808a48aed8c4fb99731d3bb176b7360b
|
diff --git a/Resources/public/js/calendar-settings.js b/Resources/public/js/calendar-settings.js
index <HASH>..<HASH> 100644
--- a/Resources/public/js/calendar-settings.js
+++ b/Resources/public/js/calendar-settings.js
@@ -1,35 +1,34 @@
$(function () {
- var date = new Date();
- var d = date.getDate();
- var m = date.getMonth();
- var y = date.getFullYear();
-
- $('#calendar-holder').fullCalendar({
- header: {
- left: 'prev, next',
- center: 'title',
- right: 'month,basicWeek,basicDay,'
- },
- lazyFetching:true,
- timeFormat: {
- // for agendaWeek and agendaDay
- agenda: 'h:mmt', // 5:00 - 6:30
+ var date = new Date();
+ var d = date.getDate();
+ var m = date.getMonth();
+ var y = date.getFullYear();
- // for all other views
- '': 'h:mmt' // 7p
- },
- eventSources: [
- {
- url: Routing.generate('fullcalendar_loader'),
- type: 'POST',
- // A way to add custom filters to your event listeners
- data: {
+ $('#calendar-holder').fullCalendar({
+ header: {
+ left: 'prev, next',
+ center: 'title',
+ right: 'month, basicWeek, basicDay,'
+ },
+ lazyFetching: true,
+ timeFormat: {
+ // for agendaWeek and agendaDay
+ agenda: 'h:mmt', // 5:00 - 6:30
- },
- error: function() {
- //alert('There was an error while fetching Google Calendar!');
- }
- }
- ]
- });
+ // for all other views
+ '': 'h:mmt' // 7p
+ },
+ eventSources: [
+ {
+ url: Routing.generate('fullcalendar_loader'),
+ type: 'POST',
+ // A way to add custom filters to your event listeners
+ data: {
+ },
+ error: function() {
+ //alert('There was an error while fetching Google Calendar!');
+ }
+ }
+ ]
+ });
});
|
Fix JavaScript file indentation inconsistency.
|
adesigns_calendar-bundle
|
train
|
9092ec083d2910069204ad97270d56bbd0a51054
|
diff --git a/text/text.go b/text/text.go
index <HASH>..<HASH> 100644
--- a/text/text.go
+++ b/text/text.go
@@ -21,7 +21,6 @@ import (
"image"
"image/color"
"math"
- "reflect"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
@@ -113,25 +112,6 @@ func drawGlyph(dst *ebiten.Image, face font.Face, r rune, x, y fixed.Int26_6, cl
}
var (
- fontFaces = map[font.Face]struct{}{}
-)
-
-func uniqFace(f font.Face) font.Face {
- if _, ok := fontFaces[f]; ok {
- return f
- }
- // If the (DeepEqual-ly) same font exists,
- // reuse this to avoid to consume a lot of cache (#498).
- for key := range fontFaces {
- if reflect.DeepEqual(key, f) {
- return key
- }
- }
- fontFaces[f] = struct{}{}
- return f
-}
-
-var (
// Use pointers to avoid copying on browsers.
glyphBoundsCache = map[font.Face]map[rune]*fixed.Rectangle26_6{}
)
@@ -223,6 +203,9 @@ var textM sync.Mutex
// Glyphs used for rendering are cached in least-recently-used way.
// It is OK to call this function with a same text and a same face at every frame in terms of performance.
//
+// Be careful that the passed font face is held by this package and is never released.
+// This is a known issue (#498).
+//
// This function is concurrent-safe.
func Draw(dst *ebiten.Image, text string, face font.Face, x, y int, clr color.Color) {
textM.Lock()
@@ -235,9 +218,8 @@ func Draw(dst *ebiten.Image, text string, face font.Face, x, y int, clr color.Co
if prevR >= 0 {
fx += face.Kern(prevR, r)
}
- fa := uniqFace(face)
- drawGlyph(dst, fa, r, fx, fixed.I(y), clr)
- fx += glyphAdvance(fa, r)
+ drawGlyph(dst, face, r, fx, fixed.I(y), clr)
+ fx += glyphAdvance(face, r)
prevR = r
}
|
text: Remove uniqFace for performance
Fixes #<I>. Add comments for #<I>.
|
hajimehoshi_ebiten
|
train
|
3d17f21de491b6976aa453f5b06badb70f8449cc
|
diff --git a/java/com/couchbase/lite/ApiTest.java b/java/com/couchbase/lite/ApiTest.java
index <HASH>..<HASH> 100644
--- a/java/com/couchbase/lite/ApiTest.java
+++ b/java/com/couchbase/lite/ApiTest.java
@@ -167,14 +167,14 @@ public class ApiTest extends LiteTestCase {
UnsavedRevision newRev =doc.createRevision();
Document newRevDocument = newRev.getDocument();
- assertEquals(newRevDocument, doc);
- assertEquals(newRev.getDatabase(), db);
+ assertEquals(doc, newRevDocument);
+ assertEquals(db, newRev.getDatabase());
assertNull(newRev.getParentRevisionId());
assertNull(newRev.getParentRevision());
Map<String,Object> expectProperties=new HashMap<String, Object>();
expectProperties.put("_id", doc.getId());
- assertEquals(newRev.getProperties(), expectProperties);
+ assertEquals(expectProperties, newRev.getProperties());
assertTrue(!newRev.isDeletion());
assertEquals(newRev.getSequence(), 0);
@@ -187,20 +187,20 @@ public class ApiTest extends LiteTestCase {
SavedRevision rev1 = newRev.save();
assertNotNull("Save 1 failed", rev1);
- assertEquals(rev1, doc.getCurrentRevision());
+ assertEquals(doc.getCurrentRevision(), rev1);
assertNotNull(rev1.getId().startsWith("1-"));
- assertEquals(rev1.getSequence(), 1);
+ assertEquals(1, rev1.getSequence());
assertNull(rev1.getParentRevisionId());
assertNull(rev1.getParentRevision());
newRev = rev1.createRevision();
newRevDocument = newRev.getDocument();
- assertEquals(newRevDocument, doc);
- assertEquals(newRev.getDatabase(), db);
- assertEquals(newRev.getParentRevisionId(), rev1.getId());
- assertEquals(newRev.getParentRevision(), rev1);
- assertEquals(newRev.getProperties(), rev1.getProperties());
- assertEquals(newRev.getUserProperties(), rev1.getUserProperties());
+ assertEquals(doc, newRevDocument);
+ assertEquals(db, newRev.getDatabase());
+ assertEquals(rev1.getId(), newRev.getParentRevisionId());
+ assertEquals(rev1, newRev.getParentRevision());
+ assertEquals(rev1.getProperties(), newRev.getProperties());
+ assertEquals(rev1.getUserProperties(), newRev.getUserProperties());
assertNotNull(!newRev.isDeletion());
// we can't add/modify one property as on ios. need to add separate method?
@@ -209,24 +209,24 @@ public class ApiTest extends LiteTestCase {
newRev.setUserProperties(properties);
SavedRevision rev2 = newRev.save();
assertNotNull( "Save 2 failed", rev2);
- assertEquals(rev2, doc.getCurrentRevision());
+ assertEquals(doc.getCurrentRevision(), rev2);
assertNotNull(rev2.getId().startsWith("2-"));
- assertEquals(rev2.getSequence(), 2);
- assertEquals(rev2.getParentRevisionId(), rev1.getId());
- assertEquals(rev2.getParentRevision(), rev1);
+ assertEquals(2, rev2.getSequence());
+ assertEquals(rev1.getId(), rev2.getParentRevisionId());
+ assertEquals(rev1, rev2.getParentRevision());
assertNotNull("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-"));
// Add a deletion/tombstone revision:
newRev = doc.createRevision();
- assertEquals(newRev.getParentRevisionId(), rev2.getId());
- assertEquals(newRev.getParentRevision(), rev2);
+ assertEquals(rev2.getId(), newRev.getParentRevisionId());
+ assertEquals(rev2, newRev.getParentRevision());
newRev.setIsDeletion(true);
SavedRevision rev3 = newRev.save();
assertNotNull("Save 3 failed", rev3);
- assertEquals(rev3, doc.getCurrentRevision());
+ assertEquals(doc.getCurrentRevision(), rev3);
assertNotNull("Unexpected revID " + rev3.getId(), rev3.getId().startsWith("3-"));
- assertEquals(rev3.getSequence(), 3);
+ assertEquals(3, rev3.getSequence());
assertTrue(rev3.isDeletion());
assertTrue(doc.isDeleted());
|
Expected vs actual was reversed in the assertion
|
couchbase_couchbase-lite-android
|
train
|
55082718a4699f1bc3eefed2b7494552fdea2243
|
diff --git a/tests/HttpClientTest.php b/tests/HttpClientTest.php
index <HASH>..<HASH> 100644
--- a/tests/HttpClientTest.php
+++ b/tests/HttpClientTest.php
@@ -81,4 +81,31 @@ class HttpClientTest extends \PHPUnit_Framework_TestCase {
$this->assertNotEmpty($httpClient->request, 'No request found');
$this->assertInstanceOf('\noFlash\CherryHttp\HttpRequest', $httpClient->request);
}
+
+ public function testAfterReadingWholeBufferCompositedFromTwoChunksRequestIsPresent()
+ {
+ $request = "GET / HTTP/1.1\r\n";
+
+ $stream = $this->getStreamMockWithContent($request);
+
+ $httpClient = new HttpClient($stream, null, $this->loggerMock);
+
+ while (!feof($stream)) {
+ $httpClient->onReadReady();
+ }
+
+ $this->assertNull($httpClient->request, 'Request created after 1st chunk');
+
+ $restOfRequest = "Connection: close\r\n".
+ "\r\n";
+ fwrite($stream, $restOfRequest);
+ fseek($stream, strlen($request), SEEK_SET);
+
+ while (!feof($stream)) {
+ $httpClient->onReadReady();
+ }
+
+ $this->assertNotEmpty($httpClient->request, 'No request found after 2nd chunk');
+ $this->assertInstanceOf('\noFlash\CherryHttp\HttpRequest', $httpClient->request);
+ }
}
|
Added test for request creation from valid HTTP request delivered in 2 chunks.
|
kiler129_CherryHttp
|
train
|
faa649efa0bbe971ab2eefd6d1902f4f6ee518ab
|
diff --git a/mutant/management/__init__.py b/mutant/management/__init__.py
index <HASH>..<HASH> 100644
--- a/mutant/management/__init__.py
+++ b/mutant/management/__init__.py
@@ -86,7 +86,6 @@ def model_definition_post_save(sender, instance, created, **kwargs):
old_db_table = old_model_class._meta.db_table
if db_table != old_db_table:
perform_ddl('alter_db_table', model_class, old_db_table, db_table)
- remove_from_app_cache(old_model_class)
ContentType.objects.clear_cache()
instance._model_class = model_class.model
|
Removed a redundant call to remove_from_app_cache.
ModelDefinition.save() already deals with unregistration of stale model_class.
|
charettes_django-mutant
|
train
|
748ba06e26bcdb855eddeba1546323ee8077e242
|
diff --git a/cache2k-core/src/main/java/org/cache2k/impl/xmlConfiguration/CacheConfigurationProviderImpl.java b/cache2k-core/src/main/java/org/cache2k/impl/xmlConfiguration/CacheConfigurationProviderImpl.java
index <HASH>..<HASH> 100644
--- a/cache2k-core/src/main/java/org/cache2k/impl/xmlConfiguration/CacheConfigurationProviderImpl.java
+++ b/cache2k-core/src/main/java/org/cache2k/impl/xmlConfiguration/CacheConfigurationProviderImpl.java
@@ -84,8 +84,8 @@ public class CacheConfigurationProviderImpl
@Override
public Cache2kConfiguration getDefaultConfiguration(final CacheManager mgr) {
- try {
Cache2kConfiguration cfg = getManagerContext(mgr).getDefaultManagerConfiguration();
+ try {
return Util.copyViaSerialization(cfg);
} catch (Exception ex) {
throw new ConfigurationException("Copying default cache configuration for manager '" + mgr.getName() + "'", ex);
diff --git a/cache2k-core/src/test/java/org/cache2k/impl/xmlConfiguration/IntegrationTest.java b/cache2k-core/src/test/java/org/cache2k/impl/xmlConfiguration/IntegrationTest.java
index <HASH>..<HASH> 100644
--- a/cache2k-core/src/test/java/org/cache2k/impl/xmlConfiguration/IntegrationTest.java
+++ b/cache2k-core/src/test/java/org/cache2k/impl/xmlConfiguration/IntegrationTest.java
@@ -131,6 +131,11 @@ public class IntegrationTest {
.build();
}
+ /**
+ * As soon as we use the manager for building the cache the configuration
+ * is read. This configuration file disables {@code skipCheckOnStartup}
+ * so it should fail immediately.
+ */
@Test
public void unknownPropertyYieldsExceptionOnStartup() {
try {
|
fix for latest commits: wrong catch blocks, masks more precise exception
|
cache2k_cache2k
|
train
|
42dec6be1f4e20ad3f9205b90fdb9e0f9286ac8a
|
diff --git a/tests/functional/Tcpdf/FpdiTest.php b/tests/functional/Tcpdf/FpdiTest.php
index <HASH>..<HASH> 100644
--- a/tests/functional/Tcpdf/FpdiTest.php
+++ b/tests/functional/Tcpdf/FpdiTest.php
@@ -152,9 +152,10 @@ class FpdiTest extends TestCase
public function testReleaseOfStreamHandleOnUnset()
{
- copy(__DIR__ . '/../../_files/pdfs/Noisy-Tube.pdf', 'test.pdf');
+ $tmpName = tempnam(sys_get_temp_dir(), 'fpdi-test');
+ copy(__DIR__ . '/../../_files/pdfs/Noisy-Tube.pdf', $tmpName);
$pdf = new Fpdi();
- $pdf->setSourceFile('test.pdf');
+ $pdf->setSourceFile($tmpName);
$tpl = $pdf->importPage(1);
$pdf->AddPage();
$pdf->useTemplate($tpl);
@@ -164,6 +165,6 @@ class FpdiTest extends TestCase
$this->assertSame($a, $b);
- $this->assertTrue(unlink('test.pdf'));
+ $this->assertTrue(unlink($tmpName));
}
}
\ No newline at end of file
diff --git a/tests/functional/Tfpdf/FpdiTest.php b/tests/functional/Tfpdf/FpdiTest.php
index <HASH>..<HASH> 100644
--- a/tests/functional/Tfpdf/FpdiTest.php
+++ b/tests/functional/Tfpdf/FpdiTest.php
@@ -122,25 +122,27 @@ class FpdiTest extends TestCase
public function testStreamHandleIsOpen()
{
- copy(__DIR__ . '/../../_files/pdfs/Noisy-Tube.pdf', 'test.pdf');
+ $tmpName = tempnam(sys_get_temp_dir(), 'fpdi-test');
+ copy(__DIR__ . '/../../_files/pdfs/Noisy-Tube.pdf', $tmpName);
$pdf = new Fpdi();
- $pdf->setSourceFile('test.pdf');
+ $pdf->setSourceFile($tmpName);
try {
- unlink('test.pdf');
+ unlink($tmpName);
$this->markTestSkipped('Stream was not locked on this OS.');
} catch (\PHPUnit_Framework_Error_Warning $e) {
$pdf->cleanUp();
}
- $this->assertTrue(unlink('test.pdf'));
+ $this->assertTrue(unlink($tmpName));
}
public function testReleaseOfStreamHandleOnUnset()
{
- copy(__DIR__ . '/../../_files/pdfs/Noisy-Tube.pdf', 'test.pdf');
+ $tmpName = tempnam(sys_get_temp_dir(), 'fpdi-test');
+ copy(__DIR__ . '/../../_files/pdfs/Noisy-Tube.pdf', $tmpName);
$pdf = new Fpdi();
- $pdf->setSourceFile('test.pdf');
+ $pdf->setSourceFile($tmpName);
$tpl = $pdf->importPage(1);
$pdf->AddPage();
$pdf->useTemplate($tpl);
@@ -150,6 +152,6 @@ class FpdiTest extends TestCase
$this->assertSame($a, $b);
- $this->assertTrue(unlink('test.pdf'));
+ $this->assertTrue(unlink($tmpName));
}
}
\ No newline at end of file
|
Optimized some tests in view to handling of temporary files.
|
Setasign_FPDI
|
train
|
b05c70d29737eb96cf44bfbcbc68d932d01c9924
|
diff --git a/pkg/namesgenerator/names-generator.go b/pkg/namesgenerator/names-generator.go
index <HASH>..<HASH> 100644
--- a/pkg/namesgenerator/names-generator.go
+++ b/pkg/namesgenerator/names-generator.go
@@ -151,6 +151,9 @@ var (
// Alexander Graham Bell - an eminent Scottish-born scientist, inventor, engineer and innovator who is credited with inventing the first practical telephone - https://en.wikipedia.org/wiki/Alexander_Graham_Bell
"bell",
+ // Karl Friedrich Benz - a German automobile engineer. Inventor of the first practical motorcar. https://en.wikipedia.org/wiki/Karl_Benz
+ "benz",
+
// Homi J Bhabha - was an Indian nuclear physicist, founding director, and professor of physics at the Tata Institute of Fundamental Research. Colloquially known as "father of Indian nuclear programme"- https://en.wikipedia.org/wiki/Homi_J._Bhabha
"bhabha",
@@ -291,6 +294,9 @@ var (
// Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg
"heisenberg",
+ // Grete Hermann was a German philosopher noted for her philosophical work on the foundations of quantum mechanics. https://en.wikipedia.org/wiki/Grete_Hermann
+ "hermann",
+
// Jaroslav Heyrovský was the inventor of the polarographic method, father of the electroanalytical method, and recipient of the Nobel Prize in 1959. His main field of work was polarography. https://en.wikipedia.org/wiki/Jaroslav_Heyrovsk%C3%BD
"heyrovsky",
@@ -318,6 +324,9 @@ var (
// Mary Lou Jepsen, was the founder and chief technology officer of One Laptop Per Child (OLPC), and the founder of Pixel Qi. https://en.wikipedia.org/wiki/Mary_Lou_Jepsen
"jepsen",
+ // Katherine Coleman Goble Johnson - American physicist and mathematician contributed to the NASA. https://en.wikipedia.org/wiki/Katherine_Johnson
+ "johnson",
+
// Irène Joliot-Curie - French scientist who was awarded the Nobel Prize for Chemistry in 1935. Daughter of Marie and Pierre Curie. https://en.wikipedia.org/wiki/Ir%C3%A8ne_Joliot-Curie
"joliot",
@@ -417,6 +426,9 @@ var (
// Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock
"murdock",
+ // John von Neumann - todays computer architectures are based on the von Neumann architecture. https://en.wikipedia.org/wiki/Von_Neumann_architecture
+ "neumann",
+
// Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton
"newton",
|
Added four names to namesgenerator
|
moby_moby
|
train
|
7df62d3a00d5345369ea5ccb2d410fa970f4bebe
|
diff --git a/systemd/journal.py b/systemd/journal.py
index <HASH>..<HASH> 100644
--- a/systemd/journal.py
+++ b/systemd/journal.py
@@ -113,7 +113,7 @@ class Journal(_Journal):
# Default conversion in unicode
try:
result = _convert_unicode(value)
- except:
+ except UnicodeDecodeError:
# Leave in default bytes
result = value
return result
|
systemd-python: Journal convert_unicode exception handling change
Rather than catch all, is now limited to UnicodeDecodeError
|
systemd_python-systemd
|
train
|
dfadb5c20e8e1ecf53a024ba08dd408d4fd23a28
|
diff --git a/lib/active_support/cache/dalli_store23.rb b/lib/active_support/cache/dalli_store23.rb
index <HASH>..<HASH> 100644
--- a/lib/active_support/cache/dalli_store23.rb
+++ b/lib/active_support/cache/dalli_store23.rb
@@ -22,8 +22,6 @@ module ActiveSupport
DELETED = "DELETED\r\n"
end
- ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/
-
def self.build_mem_cache(*addresses)
addresses = addresses.flatten
options = addresses.extract_options!
@@ -172,8 +170,7 @@ module ActiveSupport
end
def escape_key(key)
- key = key.to_s.gsub(ESCAPE_KEY_CHARS){|match| "%#{match.getbyte(0).to_s(16).upcase}"}
- key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250
+ # Rails 3.0 only
key
end
end
|
Remove escape_key(), does not work on Ruby <I>
|
petergoldstein_dalli
|
train
|
fcaf926885aaec071cd9142aae8393ec62bf5def
|
diff --git a/tests/test_configuration.py b/tests/test_configuration.py
index <HASH>..<HASH> 100644
--- a/tests/test_configuration.py
+++ b/tests/test_configuration.py
@@ -94,6 +94,26 @@ def test_tox_generative_environments_has_common_definition():
assert tox_environments == tox_ini
+def test_tox_multiline_settings_are_written_next_line():
+ """Multiline tox settings should be written starting next line."""
+ multiline_settings = [
+ "commands",
+ "commands_post",
+ "depends",
+ "deps",
+ "envlist",
+ "whitelist_externals",
+ ]
+
+ ini_parser = configparser.ConfigParser()
+ ini_parser.read("tox.ini")
+ for section in ini_parser.values():
+ for setting in multiline_settings:
+ value = section.get(setting)
+ if value is not None:
+ assert value.startswith("\n") or not value
+
+
def test_coverage_include_all_packages():
"""Coverage source should include all packages.
|
test: ensure multiline tox settings are written on the new line
|
dry-python_dependencies
|
train
|
46e313aab153c336c8204a86eaf3b15123e56a4e
|
diff --git a/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2MetadataGenerator.java b/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2MetadataGenerator.java
index <HASH>..<HASH> 100644
--- a/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2MetadataGenerator.java
+++ b/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2MetadataGenerator.java
@@ -1,4 +1,3 @@
-
package org.pac4j.saml.metadata;
import net.shibboleth.utilities.java.support.xml.SerializeSupport;
@@ -62,6 +61,12 @@ public class SAML2MetadataGenerator implements SAMLMetadataGenerator {
protected String requestInitiatorLocation = null;
+ protected String binding;
+
+ public SAML2MetadataGenerator(final String binding) {
+ this.binding = binding;
+ }
+
@Override
public final MetadataResolver buildMetadataResolver() throws Exception {
final EntityDescriptor md = buildEntityDescriptor();
@@ -194,9 +199,7 @@ public class SAML2MetadataGenerator implements SAMLMetadataGenerator {
spDescriptor.getNameIDFormats().addAll(buildNameIDFormat());
int index = 0;
- spDescriptor.getAssertionConsumerServices().add(
- getAssertionConsumerService(SAMLConstants.SAML2_POST_BINDING_URI, index++,
- this.defaultACSIndex == index));
+ spDescriptor.getAssertionConsumerServices().add(getAssertionConsumerService(binding, index++, this.defaultACSIndex == index));
if (credentialProvider != null) {
spDescriptor.getKeyDescriptors().add(getKeyDescriptor(UsageType.SIGNING,
diff --git a/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2ServiceProviderMetadataResolver.java b/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2ServiceProviderMetadataResolver.java
index <HASH>..<HASH> 100644
--- a/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2ServiceProviderMetadataResolver.java
+++ b/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2ServiceProviderMetadataResolver.java
@@ -16,7 +16,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.WritableResource;
-import javax.annotation.Nullable;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
@@ -45,28 +44,18 @@ public class SAML2ServiceProviderMetadataResolver implements SAML2MetadataResolv
private final boolean forceSpMetadataGeneration;
private boolean authnRequestSigned;
private boolean wantsAssertionsSigned;
+ private String binding;
- public SAML2ServiceProviderMetadataResolver(final SAML2ClientConfiguration configuration,
- final String callbackUrl,
+ public SAML2ServiceProviderMetadataResolver(final SAML2ClientConfiguration configuration, final String callbackUrl,
final CredentialProvider credentialProvider) {
- this(configuration.getServiceProviderMetadataResource(), callbackUrl,
- configuration.getServiceProviderEntityId(), configuration.isForceServiceProviderMetadataGeneration(), credentialProvider,
- configuration.isAuthnRequestSigned(), configuration.getWantsAssertionsSigned());
- }
-
- private SAML2ServiceProviderMetadataResolver(final WritableResource spMetadataResource,
- final String callbackUrl,
- @Nullable final String spEntityId,
- final boolean forceSpMetadataGeneration,
- final CredentialProvider credentialProvider,
- boolean authnRequestSigned, boolean wantsAssertionsSigned) {
- this.authnRequestSigned = authnRequestSigned;
- this.wantsAssertionsSigned = wantsAssertionsSigned;
- this.spMetadataResource = spMetadataResource;
- this.spEntityId = spEntityId;
+ this.authnRequestSigned = configuration.isAuthnRequestSigned();
+ this.wantsAssertionsSigned = configuration.getWantsAssertionsSigned();
+ this.spMetadataResource = configuration.getServiceProviderMetadataResource();
+ this.spEntityId = configuration.getServiceProviderEntityId();
this.credentialProvider = credentialProvider;
this.callbackUrl = callbackUrl;
- this.forceSpMetadataGeneration = forceSpMetadataGeneration;
+ this.forceSpMetadataGeneration = configuration.isForceServiceProviderMetadataGeneration();
+ this.binding = configuration.getDestinationBindingType();
// If the spEntityId is blank, use the callback url
try {
@@ -92,7 +81,7 @@ public class SAML2ServiceProviderMetadataResolver implements SAML2MetadataResolv
}
try {
- final SAML2MetadataGenerator metadataGenerator = new SAML2MetadataGenerator();
+ final SAML2MetadataGenerator metadataGenerator = new SAML2MetadataGenerator(binding);
metadataGenerator.setWantAssertionSigned(this.wantsAssertionsSigned);
metadataGenerator.setAuthnRequestSigned(this.authnRequestSigned);
|
Binding not properly generated in SAML metadata (#<I>)
* Binding not properly generated in SAML metadata
* remove useless private constrctor
|
pac4j_pac4j
|
train
|
b279f8bfb4250c2c151f6f7ea0563c8de0a91472
|
diff --git a/src/RenderExpressionTrait.php b/src/RenderExpressionTrait.php
index <HASH>..<HASH> 100644
--- a/src/RenderExpressionTrait.php
+++ b/src/RenderExpressionTrait.php
@@ -3,8 +3,8 @@
namespace Dhii\Expression\Renderer;
use ArrayAccess;
-use Dhii\Expression\ExpressionInterface;
use Dhii\Expression\Renderer\ExpressionContextInterface as ExprCtx;
+use Dhii\Expression\TermInterface;
use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;
use InvalidArgumentException;
@@ -64,16 +64,16 @@ trait RenderExpressionTrait
}
/**
- * Renders a given expression and its terms.
+ * Renders a given expression or term.
*
* @since [*next-version*]
*
- * @param ExpressionInterface $expression The expression instance to render.
+ * @param TermInterface $expression The expression or term instance to render.
* @param array|ArrayAccess|stdClass|ContainerInterface|null $context The context.
*
* @return string|Stringable The rendered expression.
*/
- abstract protected function _renderExpression(ExpressionInterface $expression, $context = null);
+ abstract protected function _renderExpression(TermInterface $expression, $context = null);
/**
* Retrieves an entry from a container or data set.
|
Loosened main render method param type
Given that this trait is intended to provide the render entry point, it must be able to support all possible renderable objects.
`TermInterface` is now used to allow terms that do not have chilren to be rendered using this functionality.
|
Dhii_expression-renderer-abstract
|
train
|
6e056c2445d3bdc09dbb6676db8d9a84017b1ff0
|
diff --git a/Python/phate/preprocessing.py b/Python/phate/preprocessing.py
index <HASH>..<HASH> 100644
--- a/Python/phate/preprocessing.py
+++ b/Python/phate/preprocessing.py
@@ -32,18 +32,37 @@ def library_size_normalize(data, verbose=False):
print("Normalizing library sizes for %s cells" % (data.shape[0]))
try:
- if isinstance(data, pd.core.sparse.frame.SparseDataFrame):
- data = data.to_coo()
- elif isinstance(data, pd.DataFrame):
- data = np.array(data)
+ if pandas.api.types.is_sparse(data):
+ data = sparse.csr_matrix(data.to_coo())
except NameError:
pass
median_transcript_count = np.median(np.array(data.sum(axis=1)))
- try:
+ if sparse.issparse(data) and data.nnz >= 2**31:
+ # check we can access elements by index
+ try:
+ data[0, 0]
+ except TypeError:
+ data = sparse.csr_matrix(data)
+ # normalize in chunks - sklearn doesn't does with more
+ # than 2**31 non-zero elements
+ #
+ # determine maximum chunk size
+ split = 2**30 // (data.nnz // data.shape[0])
+ size_ok = False
+ while not size_ok:
+ for i in range(0, data.shape[0], split):
+ if data[i:i + split, :].nnz >= 2**31:
+ split = split // 2
+ break
+ size_ok = True
+ # normalize
+ data_norm = []
+ for i in range(0, data.shape[0], split):
+ data_norm.append(normalize(data[i:i + split, :], 'l1', axis=1))
+ # combine chunks
+ data_norm = sparse.vstack(data_norm)
+ else:
data_norm = normalize(data, norm='l1', axis=1)
- except (ValueError, MemoryError):
- data_norm = sparse.vstack([normalize(
- data[i, :], 'l1', axis=1) for i in range(data.shape[0])])
# norm = 'l1' computes the L1 norm which computes the
# axis = 1 independently normalizes each sample
|
allow library size norm for large sparse matrices
|
KrishnaswamyLab_PHATE
|
train
|
db3a8585280feecfb8c51de20461a80dafb16be1
|
diff --git a/rets/interpreters/search.py b/rets/interpreters/search.py
index <HASH>..<HASH> 100644
--- a/rets/interpreters/search.py
+++ b/rets/interpreters/search.py
@@ -1,5 +1,8 @@
from rets.exceptions import InvalidSearch
import datetime
+import logging
+
+logger = logging.getLogger('rets')
class SearchInterpreter(object):
@@ -143,5 +146,5 @@ class SearchInterpreter(object):
search_string = ','.join(dmql_search_filters)
# Converts the filter dictionary to dmqp string
- print("Filter returned the following DMQL: {}".format(search_string))
+ logger.debug("Filter returned the following DMQL: {}".format(search_string))
return search_string
diff --git a/rets/parsers/search/one_x.py b/rets/parsers/search/one_x.py
index <HASH>..<HASH> 100644
--- a/rets/parsers/search/one_x.py
+++ b/rets/parsers/search/one_x.py
@@ -2,6 +2,10 @@ from rets.models import Record
from rets.models import Results
import xmltodict
from rets.parsers.base import Base
+import logging
+
+
+logger = logging.getLogger('rets')
class OneXSearchCursor(Base):
@@ -23,7 +27,7 @@ class OneXSearchCursor(Base):
return chr(int(self.base['DELIMITER'].get('@value', 9)))
else:
# assume tab delimited since it wasn't given
- print('Assuming TAB delimiter since none specified in response')
+ logger.debug('Assuming TAB delimiter since none specified in response')
return chr(9)
def get_column_names(self):
@@ -69,9 +73,9 @@ class OneXSearchCursor(Base):
if self.get_total_count() is not None:
rs.total_results_count = self.get_total_count()
- print("%s results found" % rs.total_results_count)
+ logger.debug("%s results found" % rs.total_results_count)
- print('%s results' % rs.results_count)
+ logger.debug('%s results' % rs.results_count)
if self.get_found_max_rows():
'''
@@ -80,6 +84,6 @@ class OneXSearchCursor(Base):
until this tag isn't found anymore.
'''
rs.max_rows_reached = True
- print("Maximum rows returned in response")
+ logger.debug("Maximum rows returned in response")
return rs
diff --git a/rets/parsers/search/recursive_one_x.py b/rets/parsers/search/recursive_one_x.py
index <HASH>..<HASH> 100644
--- a/rets/parsers/search/recursive_one_x.py
+++ b/rets/parsers/search/recursive_one_x.py
@@ -1,6 +1,10 @@
from rets.exceptions import AutomaticPaginationError
from .one_x import OneXSearchCursor
from rets.parsers.base import Base
+import logging
+
+
+logger = logging.getLogger('rets')
class RecursiveOneXCursor(Base):
diff --git a/rets/session.py b/rets/session.py
index <HASH>..<HASH> 100644
--- a/rets/session.py
+++ b/rets/session.py
@@ -27,7 +27,7 @@ if sys.version_info < (3, 0):
else:
from urllib.parse import urlparse
-logger = logging.getLogger(__name__)
+logger = logging.getLogger('rets')
AUTH_BASIC = 'basic'
AUTH_DIGEST = 'digest'
SUPPORTED_VERSIONS = ['1.5', '1.7', '1.7.2', '1.8']
@@ -70,6 +70,7 @@ class Session(object):
self.cache_metadata = cache_metadata
if version not in SUPPORTED_VERSIONS:
+ logger.error("Attempted to initialize a session with an invalid RETS version.")
raise MissingConfiguration("The version parameter of {} is not currently supported.".format(version))
self.version = version
@@ -115,6 +116,7 @@ class Session(object):
# relative URL given, so build this into an absolute URL
login_url = self.capabilities.get('Login')
if not login_url:
+ logger.error("There is no login URL stored, so additional capabilities cannot be added.")
raise ValueError("Cannot automatically determine absolute path for {} given.".format(uri))
parts = urlparse(login_url)
@@ -128,6 +130,7 @@ class Session(object):
:return: Bulletin instance
"""
if None in [self.login_url, self.username]:
+ logger.error("The RETS session cannot login without a login_url and a username at a minimum.")
raise MissingConfiguration("Cannot issue login without a valid configuration loaded")
response = self.request('Login')
@@ -383,7 +386,7 @@ class Session(object):
ua_digest = self.user_agent_digest_hash()
options['headers']['RETS-UA-Authorization'] = 'Digest {}'.format(ua_digest)
- print("Sending HTTP Request for {}".format(capability))
+ logger.debug("Sending HTTP Request for {}".format(capability))
if 'query' in options:
query_str = '?' + '&'.join('{}={}'.format(k, v) for k, v in options['query'].items())
@@ -393,13 +396,13 @@ class Session(object):
self.last_request_url = url
if self.use_post_method:
- print('Using POST method per use_post_method option')
+ logger.debug('Using POST method per use_post_method option')
query = options.get('query')
response = self.client.post(url, data=query, headers=options['headers'])
else:
response = self.client.get(url + query_str, headers=options['headers'])
- print("Response: HTTP {}".format(response.status_code))
+ logger.debug("Response: HTTP {}".format(response.status_code))
return response
def user_agent_digest_hash(self):
|
added a rets logger
|
refindlyllc_rets
|
train
|
ac5db5ec115455e54090542870847820357739a2
|
diff --git a/lib/puppet/type/file.rb b/lib/puppet/type/file.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/type/file.rb
+++ b/lib/puppet/type/file.rb
@@ -466,96 +466,6 @@ module Puppet
@stat = nil
end
-
- # Build a recursive map of a link source
- def linkrecurse(recurse)
- target = @parameters[:target].should
-
- method = :lstat
- if self[:links] == :follow
- method = :stat
- end
-
- targetstat = nil
- unless FileTest.exist?(target)
- return
- end
- # Now stat our target
- targetstat = File.send(method, target)
- unless targetstat.ftype == "directory"
- return
- end
-
- # Now that we know our corresponding target is a directory,
- # change our type
- self[:ensure] = :directory
-
- unless FileTest.readable? target
- self.notice "Cannot manage %s: permission denied" % self.name
- return
- end
-
- children = Dir.entries(target).reject { |d| d =~ /^\.+$/ }
-
- # Get rid of ignored children
- if @parameters.include?(:ignore)
- children = handleignore(children)
- end
-
- added = []
- children.each do |file|
- Dir.chdir(target) do
- longname = File.join(target, file)
-
- # Files know to create directories when recursion
- # is enabled and we're making links
- args = {
- :recurse => recurse,
- :ensure => longname
- }
-
- if child = self.newchild(file, true, args)
- added << child
- end
- end
- end
-
- added
- end
-
- # Build up a recursive map of what's around right now
- def localrecurse(recurse)
- unless FileTest.exist?(self[:path]) and self.stat.directory?
- #self.info "%s is not a directory; not recursing" %
- # self[:path]
- return
- end
-
- unless FileTest.readable? self[:path]
- self.notice "Cannot manage %s: permission denied" % self.name
- return
- end
-
- children = Dir.entries(self[:path])
-
- #Get rid of ignored children
- if @parameters.include?(:ignore)
- children = handleignore(children)
- end
-
- added = []
- children.each { |file|
- file = File.basename(file)
- next if file =~ /^\.\.?$/ # skip . and ..
- options = {:recurse => recurse}
-
- if child = self.newchild(file, true, options)
- added << child
- end
- }
-
- added
- end
# Create a new file or directory object as a child to the current
# object.
@@ -791,84 +701,6 @@ module Puppet
currentpropvalues()
end
- # This recurses against the remote source and makes sure the local
- # and remote structures match. It's run after 'localrecurse'. This
- # method only does anything when its corresponding remote entry is
- # a directory; in that case, this method creates file objects that
- # correspond to any contained remote files.
- def sourcerecurse(recurse)
- # we'll set this manually as necessary
- if @arghash.include?(:ensure)
- @arghash.delete(:ensure)
- end
-
- r = false
- if recurse
- unless recurse == 0
- r = 1
- end
- end
-
- ignore = self[:ignore]
-
- result = []
- found = []
-
- # Keep track of all the files we found in the source, so we can purge
- # appropriately.
- sourced = []
-
- @parameters[:source].should.each do |source|
- sourceobj, path = uri2obj(source)
-
- # okay, we've got our source object; now we need to
- # build up a local file structure to match the remote
- # one
-
- server = sourceobj.server
-
- desc = server.list(path, self[:links], r, ignore)
- if desc == ""
- next
- end
-
- # Now create a new child for every file returned in the list.
- result += desc.split("\n").collect { |line|
- file, type = line.split("\t")
- next if file == "/" # skip the listing object
- name = file.sub(/^\//, '')
-
- # This makes sure that the first source *always* wins
- # for conflicting files.
- next if found.include?(name)
-
- # For directories, keep all of the sources, so that
- # sourceselect still works as planned.
- if type == "directory"
- newsource = @parameters[:source].should.collect do |tmpsource|
- tmpsource + file
- end
- else
- newsource = source + file
- end
- args = {:source => newsource}
- if type == file
- args[:recurse] = nil
- end
-
- found << name
- sourced << File.join(self[:path], name)
-
- self.newchild(name, false, args)
- }.reject {|c| c.nil? }
-
- if self[:sourceselect] == :first
- return [result, sourced]
- end
- end
- return [result, sourced]
- end
-
# Set the checksum, from another property. There are multiple
# properties that modify the contents of a file, and they need the
# ability to make sure that the checksum value is in sync.
|
Removing the old, obsolete recursion methods.
|
puppetlabs_puppet
|
train
|
28f7397fd087a072e7cd5b160b9ce74c68ceccd5
|
diff --git a/lib/chai/interface/assert.js b/lib/chai/interface/assert.js
index <HASH>..<HASH> 100644
--- a/lib/chai/interface/assert.js
+++ b/lib/chai/interface/assert.js
@@ -1344,7 +1344,7 @@ module.exports = function (chai, util) {
}
/**
- * ### .changes(function, object, property)
+ * ### .changes(function, object, property, [message])
*
* Asserts that a function changes the value of a property
*
@@ -1366,7 +1366,7 @@ module.exports = function (chai, util) {
}
/**
- * ### .doesNotChange(function, object, property)
+ * ### .doesNotChange(function, object, property, [message])
*
* Asserts that a function does not changes the value of a property
*
@@ -1388,7 +1388,7 @@ module.exports = function (chai, util) {
}
/**
- * ### .increases(function, object, property)
+ * ### .increases(function, object, property, [message])
*
* Asserts that a function increases an object property
*
@@ -1410,7 +1410,7 @@ module.exports = function (chai, util) {
}
/**
- * ### .doesNotIncrease(function, object, property)
+ * ### .doesNotIncrease(function, object, property, [message])
*
* Asserts that a function does not increase object property
*
@@ -1432,7 +1432,7 @@ module.exports = function (chai, util) {
}
/**
- * ### .decreases(function, object, property)
+ * ### .decreases(function, object, property, [message])
*
* Asserts that a function decreases an object property
*
@@ -1454,7 +1454,7 @@ module.exports = function (chai, util) {
}
/**
- * ### .doesNotDecrease(function, object, property)
+ * ### .doesNotDecrease(function, object, property, [message])
*
* Asserts that a function does not decreases an object property
*
|
Update doc comments to include message argument
|
chaijs_chai
|
train
|
d5fb5e1d019e004b5997557ed6b2a8c61e8e69c4
|
diff --git a/smack-core/src/main/java/org/jivesoftware/smack/packet/StreamOpen.java b/smack-core/src/main/java/org/jivesoftware/smack/packet/StreamOpen.java
index <HASH>..<HASH> 100644
--- a/smack-core/src/main/java/org/jivesoftware/smack/packet/StreamOpen.java
+++ b/smack-core/src/main/java/org/jivesoftware/smack/packet/StreamOpen.java
@@ -25,18 +25,64 @@ import org.jivesoftware.smack.util.XmlStringBuilder;
public class StreamOpen extends FullStreamElement {
public static final String ELEMENT = "stream:stream";
- public static final String NAMESPACE = "jabber:client";
+
+ public static final String CLIENT_NAMESPACE = "jabber:client";
+ public static final String SERVER_NAMESPACE = "jabber:server";
+
+ /**
+ * RFC 6120 § 4.7.5
+ */
public static final String VERSION = "1.0";
- private final String service;
+ /**
+ * RFC 6120 § 4.7.1
+ */
+ private final String from;
+
+ /**
+ * RFC 6120 § 4.7.2
+ */
+ private final String to;
+
+ /**
+ * RFC 6120 § 4.7.3
+ */
+ private final String id;
+
+ /**
+ * RFC 6120 § 4.7.4
+ */
+ private final String lang;
- public StreamOpen(String service) {
- this.service = service;
+ /**
+ * RFC 6120 § 4.8.2
+ */
+ private final String contentNamespace;
+
+ public StreamOpen(String to) {
+ this(to, null, null, null, StreamContentNamespace.client);
+ }
+
+ public StreamOpen(String to, String from, String id, String lang, StreamContentNamespace ns) {
+ this.to = to;
+ this.from = from;
+ this.id = id;
+ this.lang = lang;
+ switch (ns) {
+ case client:
+ this.contentNamespace = CLIENT_NAMESPACE;
+ break;
+ case server:
+ this.contentNamespace = SERVER_NAMESPACE;
+ break;
+ default:
+ throw new IllegalStateException();
+ }
}
@Override
public String getNamespace() {
- return NAMESPACE;
+ return contentNamespace;
}
@Override
@@ -47,11 +93,18 @@ public class StreamOpen extends FullStreamElement {
@Override
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder(this);
- xml.attribute("to", service);
+ xml.attribute("to", to);
xml.attribute("xmlns:stream", "http://etherx.jabber.org/streams");
xml.attribute("version", VERSION);
+ xml.optAttribute("from", from);
+ xml.optAttribute("id", id);
+ xml.xmllangAttribute(lang);
xml.rightAngleBracket();
return xml;
}
+ public enum StreamContentNamespace {
+ client,
+ server;
+ }
}
|
Add all possible attributes to StreamOpen
|
igniterealtime_Smack
|
train
|
c42b8c3b192e8a36d99bd702108aed051c31913e
|
diff --git a/bin/mastarm b/bin/mastarm
index <HASH>..<HASH> 100755
--- a/bin/mastarm
+++ b/bin/mastarm
@@ -149,7 +149,7 @@ commander
.description('Run tests using Jest')
.option('-u, --update-snapshots', 'Force update of snapshots. USE WITH CAUTION.')
.option('--coverage', 'Run Jest with coverage reporting')
- .option('--no-cache', 'Run Jest without cache')
+ .option('--cache', 'Run Jest with cache')
.action(function (options) {
const jest = require('jest')
const config = loadConfig(process.cwd(), commander.config, commander.env)
diff --git a/lib/jestPreprocessor.js b/lib/jestPreprocessor.js
index <HASH>..<HASH> 100644
--- a/lib/jestPreprocessor.js
+++ b/lib/jestPreprocessor.js
@@ -1,10 +1,13 @@
const babel = require('babel-core')
+const babel2015 = require('babel-preset-es2015')
const jestPreset = require('babel-preset-jest')
+const reactPreset = require('babel-preset-react')
+const stage0Preset = require('babel-preset-stage-0')
module.exports = {
process: function (src) {
const transformCfg = {
- presets: ['es2015', 'react', 'stage-0', jestPreset],
+ presets: [babel2015, reactPreset, stage0Preset, jestPreset],
retainLines: true
}
return babel.transform(src, transformCfg).code
diff --git a/lib/test.js b/lib/test.js
index <HASH>..<HASH> 100644
--- a/lib/test.js
+++ b/lib/test.js
@@ -11,7 +11,7 @@ module.exports.generateTestConfig = (options) => {
if (options.updateSnapshots) {
jestArguments.push('-u')
}
- if (options.cache === false) {
+ if (!options.cache) {
jestArguments.push('--no-cache')
}
jestArguments.push('--config', JSON.stringify(jestConfig))
|
refactor(tests): Refactor caching and jest preprocessing
Directly import presets for preprocessing with Jest
Change cache option so that it doesn’t cache by default. This is an
unfortunate issue with not having a babelrc file. While doing tests on
the Scenario Editor I noticed that unless I turned off caching, tests
would pass when they shouldn’t.
|
conveyal_mastarm
|
train
|
256401331c9736477fcc2d564613385becebee8c
|
diff --git a/airtest/report/report.py b/airtest/report/report.py
index <HASH>..<HASH> 100644
--- a/airtest/report/report.py
+++ b/airtest/report/report.py
@@ -461,6 +461,9 @@ class LogToHtml(object):
self.static_root = self.static_root.replace("\\", "/")
self.static_root += "/"
+ if not output_file:
+ output_file = HTML_FILE
+
data = {}
data['steps'] = steps
data['name'] = self.script_root
|
fix the bug that output_file is none
(cherry picked from commit afa<I>a<I>a<I>b<I>b<I>ee<I>b<I>c<I>d<I>)
|
AirtestProject_Airtest
|
train
|
23c73bc70f83bbc17c8f1e51fe52b6bb32b489da
|
diff --git a/packages/debugger-ui/src/ui/index.js b/packages/debugger-ui/src/ui/index.js
index <HASH>..<HASH> 100644
--- a/packages/debugger-ui/src/ui/index.js
+++ b/packages/debugger-ui/src/ui/index.js
@@ -49,10 +49,10 @@ const Page = (window.Page = {
const statusNode = document.getElementById('status');
switch (status.type) {
case 'connected':
- statusNode.innerHTML = 'Debugger session active.';
+ statusNode.textContent = 'Debugger session active.';
break;
case 'error':
- statusNode.innerHTML =
+ statusNode.textContent =
status.error.reason ||
'Disconnected from proxy. Attempting reconnection. Is node server running?';
break;
|
fix: use textContent instead of innerHTML in debugger-ui (#<I>)
Apply the fixes suggested in
<URL>
|
react-native-community_cli
|
train
|
e600d27b1fdfa8589a1b93335bca24787d28a7fc
|
diff --git a/lib/attachable.rb b/lib/attachable.rb
index <HASH>..<HASH> 100644
--- a/lib/attachable.rb
+++ b/lib/attachable.rb
@@ -45,7 +45,14 @@ module Attachable
def file=(tempfile)
tempfile.rewind #This may not be super efficient, but it's the necessary fix for Rails 3.1
self["#{attachment_file_prefix}_data"] = tempfile.read
- self["#{attachment_file_prefix}_size"] = tempfile.size
+
+ size = nil
+ if tempfile.respond_to?(:size)
+ size = tempfile.size
+ elsif tempfile.respond_to?(:stat)
+ size = tempfile.stat.size
+ end
+ self["#{attachment_file_prefix}_size"] = size unless size.nil?
filename = nil
if tempfile.respond_to?(:original_filename)
|
Make the size attribute optional. This is getting tiring.
|
bamnet_attachable
|
train
|
e800a3854f234a034906a6d8ad60b9c33cf829f0
|
diff --git a/src/unity/python/turicreate/test/test_json.py b/src/unity/python/turicreate/test/test_json.py
index <HASH>..<HASH> 100644
--- a/src/unity/python/turicreate/test/test_json.py
+++ b/src/unity/python/turicreate/test/test_json.py
@@ -23,6 +23,7 @@ import math
import os
import pandas
import pytz
+import six
import string
import sys
import unittest
@@ -110,11 +111,11 @@ class JSONTest(unittest.TestCase):
def _assertEqual(self, x, y):
if type(x) in [long,int]:
self.assertTrue(type(y) in [long,int])
- elif type(x) in [str, unicode]:
- self.assertTrue(type(y) in [str,unicode])
+ elif isinstance(x, six.string_types):
+ self.assertTrue(isinstance(y, six.string_types))
else:
self.assertEqual(type(x), type(y))
- if isinstance(x, (str, unicode)):
+ if isinstance(x, six.string_types):
self.assertEqual(str(x), str(y))
elif isinstance(x, SArray):
_SFrameComparer._assert_sarray_equal(x, y)
|
Fix test_json.py failure in Python 3 (#<I>)
The test for `(str, unicode)` should be done instead using
`six.string_types` since there is no `unicode` type in
Python 3.
|
apple_turicreate
|
train
|
bc2f8f96bc49127daf02da981030c6477bc17ae3
|
diff --git a/spec/ll/compiler_spec.rb b/spec/ll/compiler_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/ll/compiler_spec.rb
+++ b/spec/ll/compiler_spec.rb
@@ -34,4 +34,35 @@ describe LL::Compiler do
end
end
end
+
+ describe '#on_terminals' do
+ before do
+ @node = s(:terminals, s(:ident, 'A'))
+ end
+
+ it 'defines a new terminal' do
+ @compiler.on_terminals(@node, @compiled)
+
+ @compiled.has_terminal?('A').should == true
+ end
+
+ describe 'with an existing terminal' do
+ before do
+ @compiler.on_terminals(@node, @compiled)
+ end
+
+ it 'does not overwrite the existing terminal' do
+ @compiled.should_not receive(:add_terminal)
+
+ @compiler.on_terminals(@node, @compiled)
+ end
+
+ it 'adds an error message' do
+ @compiler.on_terminals(@node, @compiled)
+
+ @compiled.errors[0].message.should ==
+ 'The terminal "A" has already been defined'
+ end
+ end
+ end
end
|
Specs for Compiler#on_terminals.
|
YorickPeterse_ruby-ll
|
train
|
2b8354933ac8047440e393bcb03a5711e2e1d4e3
|
diff --git a/lib/io_streams/paths/sftp.rb b/lib/io_streams/paths/sftp.rb
index <HASH>..<HASH> 100644
--- a/lib/io_streams/paths/sftp.rb
+++ b/lib/io_streams/paths/sftp.rb
@@ -26,12 +26,13 @@ module IOStreams
include SemanticLogger::Loggable if defined?(SemanticLogger)
class << self
- attr_accessor :sshpass_bin, :sftp_bin, :sshpass_wait_seconds
+ attr_accessor :sshpass_bin, :sftp_bin, :sshpass_wait_seconds, :before_password_wait_seconds
end
- @sftp_bin = "sftp"
- @sshpass_bin = "sshpass"
- @sshpass_wait_seconds = 5
+ @sftp_bin = "sftp"
+ @sshpass_bin = "sshpass"
+ @before_password_wait_seconds = 2
+ @sshpass_wait_seconds = 5
attr_reader :hostname, :username, :ssh_options, :url, :port
@@ -168,9 +169,14 @@ module IOStreams
with_sftp_args do |args|
Open3.popen2e(*args) do |writer, reader, waith_thr|
begin
+ # Give time for remote sftp server to get ready to accept the password.
+ sleep self.class.before_password_wait_seconds
+
writer.puts password
+
# Give time for password to be processed and stdin to be passed to sftp process.
sleep self.class.sshpass_wait_seconds
+
writer.puts "get #{remote_file_name} #{local_file_name}"
writer.puts "bye"
writer.close
@@ -271,9 +277,9 @@ module IOStreams
end
def build_ssh_options
- options = ssh_options.dup
- options[:logger] ||= logger if defined?(SemanticLogger)
- options[:port] ||= port
+ options = ssh_options.dup
+ options[:logger] ||= logger if defined?(SemanticLogger)
+ options[:port] ||= port
options[:max_pkt_size] ||= 65_536
options[:password] ||= @password
options
|
Give time for remote sftp server to get ready to accept the password.
|
rocketjob_iostreams
|
train
|
cf9a4e7f8f5d63e0f37b5ec0b2ca59c8464c09ba
|
diff --git a/tests/unit/modules/test_mysql.py b/tests/unit/modules/test_mysql.py
index <HASH>..<HASH> 100644
--- a/tests/unit/modules/test_mysql.py
+++ b/tests/unit/modules/test_mysql.py
@@ -450,7 +450,9 @@ class MySQLTestCase(TestCase, LoaderModuleMockMixin):
connect_mock = MagicMock()
with patch.object(mysql, '_connect', connect_mock):
with patch.dict(mysql.__salt__, {'config.option': MagicMock()}):
- side_effect = MySQLdb.OperationalError(9999, 'Something Went Wrong')
+ # Use the OperationalError from the salt mysql module because that
+ # exception can come from either MySQLdb or pymysql
+ side_effect = mysql.OperationalError(9999, 'Something Went Wrong')
with patch.object(mysql, '_execute', MagicMock(side_effect=side_effect)):
mysql.query('testdb', 'SELECT * FROM testdb')
self.assertIn('mysql.error', mysql.__context__)
|
Use the `OperationalError` from the salt mysql module intead.
The reason is that the exception can come from either MySQLdb or
pymysql(which patches sys.modules to behave like MySQLdb).
|
saltstack_salt
|
train
|
f488e06bc7923f00bfdcb833565702b33f30b0e7
|
diff --git a/src/quart/testing/connections.py b/src/quart/testing/connections.py
index <HASH>..<HASH> 100644
--- a/src/quart/testing/connections.py
+++ b/src/quart/testing/connections.py
@@ -19,7 +19,7 @@ class HTTPDisconnectError(Exception):
pass
-class WebsocketDisconnect(Exception):
+class WebsocketDisconnectError(Exception):
pass
@@ -120,7 +120,7 @@ class TestWebsocketConnection:
await self._task
while not self._receive_queue.empty():
data = await self._receive_queue.get()
- if isinstance(data, Exception) and not isinstance(data, WebsocketDisconnect):
+ if isinstance(data, Exception) and not isinstance(data, WebsocketDisconnectError):
raise data
async def receive(self) -> AnyStr:
@@ -172,4 +172,4 @@ class TestWebsocketConnection:
)
)
elif message["type"] == "websocket.close":
- await self._receive_queue.put(WebsocketDisconnect(message.get("code", 1000)))
+ await self._receive_queue.put(WebsocketDisconnectError(message.get("code", 1000)))
|
fix build by renaming WebsocketDisconnect to WebsocketDisconnectError
|
pgjones_quart
|
train
|
68b198d7dad0355f3a567afb9afcc606c16c9902
|
diff --git a/rtv/docs.py b/rtv/docs.py
index <HASH>..<HASH> 100644
--- a/rtv/docs.py
+++ b/rtv/docs.py
@@ -17,7 +17,7 @@ Press `?` to open the help screen.
"""
HELP = """
-Basic Commands
+[Basic Commands]
`j/k` or `UP/DOWN` : Move the cursor up/down
`m/n` or `PgUp/PgDn`: Jump to the previous/next page
`o` or `ENTER` : Open the selected item as a webpage
@@ -27,7 +27,7 @@ Basic Commands
`?` : Show the help screen
`q/Q` : Quit/Force quit
-Authenticated Commands
+[Authenticated Commands]
`a/z` : Upvote/downvote
`c` : Compose a new post or comment
`e` : Edit an existing post or comment
@@ -35,12 +35,12 @@ Authenticated Commands
`i` : Display new messages prompt
`s` : Open/close subscribed subreddits list
-Subreddit Mode
+[Subreddit Mode]
`l` or `RIGHT` : Enter the selected submission
`/` : Open a prompt to switch subreddits
`f` : Open a prompt to search the current subreddit
-Submission Mode
+[Submission Mode]
`h` or `LEFT` : Return to subreddit mode
`l` or `RIGHT` : Open the selected comment in a new window
`SPACE` : Fold the selected comment, or load additional comments
diff --git a/rtv/page.py b/rtv/page.py
index <HASH>..<HASH> 100644
--- a/rtv/page.py
+++ b/rtv/page.py
@@ -79,7 +79,7 @@ class Page(object):
@PageController.register(Command('HELP'))
def show_help(self):
- self.term.show_notification(docs.HELP.strip().splitlines())
+ self.term.show_notification(docs.HELP.strip('\n').splitlines())
@PageController.register(Command('SORT_HOT'))
def sort_content_hot(self):
|
Added brackets to help page.
|
michael-lazar_rtv
|
train
|
7ca3dd67691388a00e7b747aa2615e630cca96ba
|
diff --git a/lxd/instance_exec.go b/lxd/instance_exec.go
index <HASH>..<HASH> 100644
--- a/lxd/instance_exec.go
+++ b/lxd/instance_exec.go
@@ -412,7 +412,7 @@ func (s *execWs) Do(op *operations.Operation) error {
}
exitCode, err := cmd.Wait()
- logger.Debug("Instance process stopped")
+ logger.Debug("Instance process stopped", log.Ctx{"exitCode": exitCode})
return finisher(exitCode, err)
}
|
lxd/instance/exec: Log exit code of command
|
lxc_lxd
|
train
|
7ea90d3a477e41e0ae6958545c5f8e9c3fde459f
|
diff --git a/src/main/resources/META-INF/resources/primefaces-extensions/fuzzysearch/1-fuzzysearch-widget.js b/src/main/resources/META-INF/resources/primefaces-extensions/fuzzysearch/1-fuzzysearch-widget.js
index <HASH>..<HASH> 100644
--- a/src/main/resources/META-INF/resources/primefaces-extensions/fuzzysearch/1-fuzzysearch-widget.js
+++ b/src/main/resources/META-INF/resources/primefaces-extensions/fuzzysearch/1-fuzzysearch-widget.js
@@ -1,8 +1,15 @@
/**
* PrimeFaces FuzzySearch Widget
+ *
+ * @since 8.0.1
*/
PrimeFaces.widget.FuzzySearch = PrimeFaces.widget.BaseWidget.extend({
+ /**
+ * @override
+ * @inheritdoc
+ * @param {PrimeFaces.widget.BaseWidget.cfg} cfg
+ */
init: function (cfg) {
this._super(cfg);
|
Added since tag and jsdoc
|
primefaces-extensions_core
|
train
|
fc35e5751d08b88547d776e423f2800128d7d498
|
diff --git a/src/actions/__tests__/entity-action-builder-test.js b/src/actions/__tests__/entity-action-builder-test.js
index <HASH>..<HASH> 100644
--- a/src/actions/__tests__/entity-action-builder-test.js
+++ b/src/actions/__tests__/entity-action-builder-test.js
@@ -13,28 +13,28 @@ describe('The actionBuilder', () => {
expect(()=>{ actionBuilder({name: 'test'})}).to.not.throw(NAME_MESSAGE);
});
it('should throw an error when called without a string type parameter : load,save,delete', () => {
- const NAME_MESSAGE = 'ACTION_BUILDER: the type parameter should be a string and the value one of these: load,save,delete.';
- expect(()=>{ actionBuilder({name: 'test'})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: undefined})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 1})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: {}})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: ()=>{}})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: ''})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'nimp'})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load'})}).to.not.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'save'})}).to.not.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'delete'})}).to.not.throw(NAME_MESSAGE);
+ const TYPE_MESSAGE = 'ACTION_BUILDER: the type parameter should be a string and the value one of these: load,save,delete.';
+ expect(()=>{ actionBuilder({name: 'test'})}).to.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: undefined})}).to.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 1})}).to.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: {}})}).to.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: ()=>{}})}).to.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: ''})}).to.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'nimp'})}).to.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load'})}).to.not.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'save'})}).to.not.throw(TYPE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'delete'})}).to.not.throw(TYPE_MESSAGE);
});
it('should throw an error when called without a Promise service parameter', () => {
- const NAME_MESSAGE = 'ACTION_BUILDER: the service parameter should be a Promise.';
- expect(()=>{ actionBuilder({name: 'test', type: 'load'})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load', service: undefined})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load', service: 1})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load', service: 'nimp'})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load', service: ()=>{}})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load', service: {}})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load', service: null})}).to.throw(NAME_MESSAGE);
- expect(()=>{ actionBuilder({name: 'test', type: 'load', service: Promise.resolve({test: 'test'})})}).to.not.throw(NAME_MESSAGE);
+ const SERVICE_MESSAGE = 'ACTION_BUILDER: the service parameter should be a Promise.';
+ expect(()=>{ actionBuilder({name: 'test', type: 'load'})}).to.throw(SERVICE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load', service: undefined})}).to.throw(SERVICE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load', service: 1})}).to.throw(SERVICE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load', service: 'nimp'})}).to.throw(SERVICE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load', service: ()=>{}})}).to.throw(SERVICE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load', service: {}})}).to.throw(SERVICE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load', service: null})}).to.throw(SERVICE_MESSAGE);
+ expect(()=>{ actionBuilder({name: 'test', type: 'load', service: Promise.resolve({test: 'test'})})}).to.not.throw(SERVICE_MESSAGE);
});
})
});
|
[tests] action builder rename message.
|
get-focus_deprecated-focus-graph
|
train
|
8dffa0ae9fd7ffcfb73225d14762ad45c15b38d0
|
diff --git a/src/mongo/queue/MongoTripodQueue.class.php b/src/mongo/queue/MongoTripodQueue.class.php
index <HASH>..<HASH> 100644
--- a/src/mongo/queue/MongoTripodQueue.class.php
+++ b/src/mongo/queue/MongoTripodQueue.class.php
@@ -33,6 +33,10 @@ class MongoTripodQueue extends MongoTripodBase
{
$now = new MongoDate();
$data = $this->fetchNextQueuedItem();
+
+ // set the config to what is received
+ MongoTripodConfig::setConfig($data["tripodConfig"]);
+
if(!empty($data))
{
/* @var $createdOn MongoDate */
diff --git a/test/unit/mongo/MongoTripodQueueTest.php b/test/unit/mongo/MongoTripodQueueTest.php
index <HASH>..<HASH> 100644
--- a/test/unit/mongo/MongoTripodQueueTest.php
+++ b/test/unit/mongo/MongoTripodQueueTest.php
@@ -92,7 +92,7 @@ class MongoTripodQueueTest extends MongoTripodTestBase
$mockQueue = $this->getMock('MongoTripodQueue', array('getUniqId'), array());
$mockQueue->expects($this->any())->method('getUniqId')->will($this->returnValue($itemId));
- $mockQueue->addItem(new ChangeSet(),array(),$this->tripod->storeName,$this->tripod->podName,array(OP_VIEWS));
+ $mockQueue->addItem(new ChangeSet(),array(),"foo","CBD_wibble",array(OP_VIEWS));
$item = $mockQueue->getItem($itemId);
$this->assertContains('qid_', $item['_id']);
|
tripodConfig is read from job data, not the queue
|
talis_tripod-php
|
train
|
0e6c90d71f5686aba38d86fca4807de682c18e87
|
diff --git a/src/main/java/com/marklogic/client/datamovement/impl/QueryBatcherImpl.java b/src/main/java/com/marklogic/client/datamovement/impl/QueryBatcherImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/marklogic/client/datamovement/impl/QueryBatcherImpl.java
+++ b/src/main/java/com/marklogic/client/datamovement/impl/QueryBatcherImpl.java
@@ -572,7 +572,7 @@ public class QueryBatcherImpl extends BatcherImpl implements QueryBatcher {
logger.error("Exception thrown by an onQueryFailure listener", e);
}
}
- logger.warn("Error iterating to queue uris", t.toString());
+ logger.warn("Error iterating to queue uris: {}", t.toString());
}
}
} catch (Throwable t) {
|
fix an error message that wasn't showing what error occured
|
marklogic_java-client-api
|
train
|
b148a904d8de88718ace087e5eb89d44b75f272f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -10,8 +10,11 @@ setup(
license='BSD',
url='http://github.com/praekelt/django-recaptcha',
packages=find_packages(),
+ install_requires = [
+ 'django',
+ ],
tests_require=[
- 'django-setuptest>=0.1',
+ 'django-setuptest>=0.2.1',
],
test_suite="setuptest.setuptest.SetupTestSuite",
include_package_data=True,
|
Up setuptest version so tests pass with Django <I>
|
praekelt_django-recaptcha
|
train
|
d63d54e53edbb12ece0d916380bc6f340da1f70e
|
diff --git a/jf_agent/jf_jira/jira_download.py b/jf_agent/jf_jira/jira_download.py
index <HASH>..<HASH> 100644
--- a/jf_agent/jf_jira/jira_download.py
+++ b/jf_agent/jf_jira/jira_download.py
@@ -140,9 +140,27 @@ def download_projects_and_versions(
if exclude_projects:
filters.append(lambda proj: proj.key not in exclude_projects)
if include_categories:
- filters.append(lambda proj: proj.projectCategory.name in include_categories)
+
+ def _include_filter(proj):
+ # If we have a category-based allowlist and the project
+ # does not have a category, do not include it.
+ if not hasattr(proj, 'projectCategory'):
+ return False
+
+ return proj.projectCategory.name in include_categories
+
+ filters.append(_include_filter)
if exclude_categories:
- filters.append(lambda proj: proj.projectCategory.name not in exclude_categories)
+
+ def _exclude_filter(proj):
+ # If we have a category-based excludelist and the project
+ # does not have a category, include it.
+ if not hasattr(proj, 'projectCategory'):
+ return True
+
+ return proj.projectCategory.name not in exclude_categories
+
+ filters.append(_exclude_filter)
def project_is_accessible(project_id):
try:
|
[OJ-<I>] Handle case where `projectCategory` is not set
If we are using category-based include/exclude conditions, handle the
case where projects lack a defined category.
|
Jellyfish-AI_jf_agent
|
train
|
58df297e19c9b6c29cae1fa944302b655e960071
|
diff --git a/orb/schema/table.py b/orb/schema/table.py
index <HASH>..<HASH> 100644
--- a/orb/schema/table.py
+++ b/orb/schema/table.py
@@ -472,10 +472,6 @@ class Table(object):
elif type(value) in (str, unicode):
value = orb.Query.fromXmlString(value)
- # restore the value from teh database
- else:
- value = column.restoreValue(value, options)
-
dvalues[column] = value
self.__record_dbloaded.add(column)
@@ -1139,7 +1135,8 @@ class Table(object):
# return none output's and non-auto inflated values immediately
if value is None or not (col.isReference() and inflated):
- return value if not Table.recordcheck(value) else value.id()
+ options = self.contextOptions()
+ return col.restoreValue(value, options) if not Table.recordcheck(value) else value.id()
# ensure we have a proper reference model
refmodel = col.referenceModel()
|
Moved the restoreValue from loading from the database to extracting the value from recordValue
|
orb-framework_orb
|
train
|
715758854a460c56f0067da2a10e4f51baa84109
|
diff --git a/src/server/worker/api_server.go b/src/server/worker/api_server.go
index <HASH>..<HASH> 100644
--- a/src/server/worker/api_server.go
+++ b/src/server/worker/api_server.go
@@ -527,13 +527,13 @@ func (a *APIServer) linkData(inputs []*Input, dir string) error {
return os.Symlink(filepath.Join(dir, "out"), filepath.Join(client.PPSInputPrefix, "out"))
}
-func (a *APIServer) unlinkData(inputs []*Input, dir string) error {
+func (a *APIServer) unlinkData(inputs []*Input) error {
for _, input := range inputs {
- if err := os.RemoveAll(filepath.Join(dir, input.Name)); err != nil {
+ if err := os.RemoveAll(filepath.Join(client.PPSInputPrefix, input.Name)); err != nil {
return err
}
}
- return os.RemoveAll(filepath.Join(dir, "out"))
+ return os.RemoveAll(filepath.Join(client.PPSInputPrefix, "out"))
}
func (a *APIServer) reportUserCodeStats(logger *taggedLogger) {
@@ -1414,7 +1414,7 @@ func (a *APIServer) processDatums(pachClient *client.APIClient, logger *taggedLo
return fmt.Errorf("error linkData: %v", err)
}
defer func() {
- if err := a.unlinkData(data, dir); err != nil && retErr == nil {
+ if err := a.unlinkData(data); err != nil && retErr == nil {
retErr = fmt.Errorf("error unlinkData: %v", err)
}
}()
|
Delete the symlinks, not their sources.
|
pachyderm_pachyderm
|
train
|
094b7ac2f0b4d13b61157e07d7010b38ee997edb
|
diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorPageSink.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorPageSink.java
index <HASH>..<HASH> 100644
--- a/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorPageSink.java
+++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorPageSink.java
@@ -136,6 +136,15 @@ public class RaptorPageSink
return new Page(blocks);
}
+ private void flushPageBufferIfNecessary(int rowsToAdd)
+ {
+ if (shouldFlush(rowsToAdd)) {
+ flushPages(pageBuffer.getPages());
+ pageBuffer.reset();
+ storagePageSink.flush();
+ }
+ }
+
/**
* Flushes pages in the PageBuffer to StoragePageSink if ANY of the following is true:
* <ul>
@@ -144,21 +153,9 @@ public class RaptorPageSink
* <li>pageBuffer has more than Integer.MAX_VALUE rows (PagesSorter.sort can sort Integer.MAX_VALUE rows at a time)</li>
* </ul>
*/
- private void flushPageBufferIfNecessary(int rowsToAdd)
+ private boolean shouldFlush(int rowsToAdd)
{
- if (storagePageSink.isFull()) {
- // This StoragePageSink is full, flush it for the next batch of pages
- flushPages(pageBuffer.getPages());
- pageBuffer.reset();
- storagePageSink.flush();
- return;
- }
-
- int maxRemainingRows = Integer.MAX_VALUE - Ints.checkedCast(pageBuffer.getRowCount());
- if (pageBuffer.isFull() || (!sortFields.isEmpty() && (rowsToAdd > maxRemainingRows))) {
- flushPages(pageBuffer.getPages());
- pageBuffer.reset();
- }
+ return storagePageSink.isFull() || !pageBuffer.canAddRows(rowsToAdd);
}
private void flushPages(List<Page> pages)
diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/storage/OrcStorageManager.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/storage/OrcStorageManager.java
index <HASH>..<HASH> 100644
--- a/presto-raptor/src/main/java/com/facebook/presto/raptor/storage/OrcStorageManager.java
+++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/storage/OrcStorageManager.java
@@ -189,7 +189,7 @@ public class OrcStorageManager
@Override
public PageBuffer createPageBuffer()
{
- return new PageBuffer(maxBufferSize.toBytes());
+ return new PageBuffer(maxBufferSize.toBytes(), Integer.MAX_VALUE);
}
@Override
diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/util/PageBuffer.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/util/PageBuffer.java
index <HASH>..<HASH> 100644
--- a/presto-raptor/src/main/java/com/facebook/presto/raptor/util/PageBuffer.java
+++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/util/PageBuffer.java
@@ -26,13 +26,16 @@ public class PageBuffer
{
private final long maxMemoryBytes;
private final List<Page> pages = new ArrayList<>();
+ private final long maxRows;
private long usedMemoryBytes;
private long rowCount;
- public PageBuffer(long maxMemoryBytes)
+ public PageBuffer(long maxMemoryBytes, long maxRows)
{
checkArgument(maxMemoryBytes > 0, "maxMemoryBytes must be positive");
+ checkArgument(maxRows > 0, "maxRows must be positive");
+ this.maxRows = maxRows;
this.maxMemoryBytes = maxMemoryBytes;
}
@@ -51,9 +54,14 @@ public class PageBuffer
usedMemoryBytes = 0;
}
+ public boolean canAddRows(int rowsToAdd)
+ {
+ return !isFull() && rowCount + rowsToAdd < maxRows;
+ }
+
public boolean isFull()
{
- return usedMemoryBytes >= maxMemoryBytes;
+ return rowCount >= maxRows || usedMemoryBytes >= maxMemoryBytes;
}
public List<Page> getPages()
|
Create a new storage page sink if we hit the max row count
|
prestodb_presto
|
train
|
484736882c9ad58f178997443bc11f87a72086ec
|
diff --git a/src/components/PasswordSetterBox.js b/src/components/PasswordSetterBox.js
index <HASH>..<HASH> 100644
--- a/src/components/PasswordSetterBox.js
+++ b/src/components/PasswordSetterBox.js
@@ -199,6 +199,7 @@ class PasswordSetterBox extends Nimiq.Observable {
this.$el.classList.remove('repeat-short');
this.$el.classList.add('repeat-long');
await AnimationUtils.animate('shake', this.$el);
+ this._passwordInput.focus();
}
}
}
|
re-focus password setter on wrong password
|
nimiq_keyguard-next
|
train
|
244aab4178ff9dd09172da5802c2149155885f90
|
diff --git a/lib/onebox/engine/whitelisted_generic_onebox.rb b/lib/onebox/engine/whitelisted_generic_onebox.rb
index <HASH>..<HASH> 100644
--- a/lib/onebox/engine/whitelisted_generic_onebox.rb
+++ b/lib/onebox/engine/whitelisted_generic_onebox.rb
@@ -16,6 +16,7 @@ module Onebox
def self.default_whitelist
%w(23hq.com
500px.com
+ 8tracks.com
about.com
answers.com
ask.com
@@ -243,25 +244,25 @@ module Onebox
if video_url
- # opengraph support multiple elements (videos, images ,etc).
+ # opengraph support multiple elements (videos, images ,etc).
# We attempt to find a video element with the type of video/mp4
# and generate a native <video> element for it.
if (@raw.metadata && @raw.metadata[:"video:type"])
video_type = @raw.metadata[:"video:type"]
- if video_type.include? "video/mp4" #find if there is a video with type
- if video_type.size > 1 #if more then one video item based on provided video_type
- ind = video_type.find_index("video/mp4") #get the first video index with type video/mp4
- video_url = @raw.metadata[:video][ind] #update video_url
- end
-
- attr = append_attribute(:width, attr, video)
+ if video_type.include? "video/mp4" # find if there is a video with type
+ if video_type.size > 1 # if more then one video item based on provided video_type
+ ind = video_type.find_index("video/mp4") # get the first video index with type video/mp4
+ video_url = @raw.metadata[:video][ind] # update video_url
+ end
+
+ attr = append_attribute(:width, attr, video)
attr = append_attribute(:height, attr, video)
-
+
# html_v1 = %Q(<video #{attr} title="#{data[:title]}" controls="" ><source src="#{video_url}"></video>)
site_name_and_title = ( ("<span style='color:#fff;background:#9B9B9B;border-radius:3px;padding:3px;margin-right: 5px;'>" + CGI::escapeHTML(@raw.metadata[:site_name][0].to_s) + '</span> ') + CGI::escapeHTML((@raw.title || @raw.description).to_s) )
-
+
orig_url = @raw.url
html_v2 = %Q(
<div style='position:relative;padding-top:29px;'>
@@ -271,7 +272,7 @@ module Onebox
)
html = html_v2
- else
+ else
html = "<iframe src=\"#{video_url}\" frameborder=\"0\" title=\"#{data[:title]}\""
append_attribute(:width, html, video)
@@ -293,4 +294,4 @@ module Onebox
end
end
end
-end
\ No newline at end of file
+end
|
Add 8tracks, fix some whitespace issues
|
discourse_onebox
|
train
|
35c905d77a2327ef215cfd7d95cd86efa610b274
|
diff --git a/lib/ibm_watson/speech_to_text_v1.rb b/lib/ibm_watson/speech_to_text_v1.rb
index <HASH>..<HASH> 100644
--- a/lib/ibm_watson/speech_to_text_v1.rb
+++ b/lib/ibm_watson/speech_to_text_v1.rb
@@ -533,7 +533,7 @@ module IBMWatson
"redaction" => redaction
}
options.delete_if { |_, v| v.nil? }
- WebSocketClient.new(audio: audio, chunk_data: chunk_data, options: options, recognize_callback: recognize_callback, url: url, headers: headers)
+ WebSocketClient.new(audio: audio, chunk_data: chunk_data, options: options, recognize_callback: recognize_callback, url: url, headers: headers, disable_ssl: @disable_ssl)
end
# :nocov:
diff --git a/lib/ibm_watson/websocket/speech_to_text_websocket_listener.rb b/lib/ibm_watson/websocket/speech_to_text_websocket_listener.rb
index <HASH>..<HASH> 100644
--- a/lib/ibm_watson/websocket/speech_to_text_websocket_listener.rb
+++ b/lib/ibm_watson/websocket/speech_to_text_websocket_listener.rb
@@ -11,7 +11,7 @@ TEN_MILLISECONDS = 0.01
# Class for interacting with the WebSocket API
class WebSocketClient
- def initialize(audio: nil, chunk_data:, options:, recognize_callback:, url:, headers:)
+ def initialize(audio: nil, chunk_data:, options:, recognize_callback:, url:, headers:, disable_ssl: false)
@audio = audio
@options = options
@callback = recognize_callback
@@ -24,6 +24,7 @@ class WebSocketClient
@mic_running = false
@data_size = audio.nil? ? 0 : @audio.size
@queue = Queue.new
+ @disable_ssl = disable_ssl
end
def start
@@ -77,6 +78,12 @@ class WebSocketClient
EM&.reactor_thread&.join
EM.run do
+ if @disable_ssl
+ @url = @url.sub("wss:", "ws:")
+ @client = Faye::WebSocket::Client.new(@url, nil, tls: { verify_peer: false, fail_if_no_peer_cert: false }, headers: @headers)
+ else
+ @client = Faye::WebSocket::Client.new(@url, nil, headers: @headers)
+ end
@client = Faye::WebSocket::Client.new(@url, nil, headers: @headers)
@client.onclose = on_close
@client.onerror = on_error
diff --git a/test/integration/test_speech_to_text_v1.rb b/test/integration/test_speech_to_text_v1.rb
index <HASH>..<HASH> 100644
--- a/test/integration/test_speech_to_text_v1.rb
+++ b/test/integration/test_speech_to_text_v1.rb
@@ -162,7 +162,8 @@ if !ENV["SPEECH_TO_TEXT_APIKEY"].nil? && !ENV["SPEECH_TO_TEXT_URL"].nil?
def test_recognize_websocket_as_chunks
audio_file = File.open(Dir.getwd + "/resources/speech.wav")
- mycallback = MyRecognizeCallback.new
+ atomic_boolean = Concurrent::AtomicBoolean.new
+ mycallback = MyRecognizeCallback.new(atomic_boolean: atomic_boolean)
speech = @service.recognize_using_websocket(
chunk_data: true,
recognize_callback: mycallback,
@@ -186,7 +187,8 @@ if !ENV["SPEECH_TO_TEXT_APIKEY"].nil? && !ENV["SPEECH_TO_TEXT_URL"].nil?
def test_recognize_websocket
audio_file = File.open(Dir.getwd + "/resources/speech.wav")
- mycallback = MyRecognizeCallback.new
+ atomic_boolean = Concurrent::AtomicBoolean.new
+ mycallback = MyRecognizeCallback.new(atomic_boolean: atomic_boolean)
speech = @service.recognize_using_websocket(
audio: audio_file,
recognize_callback: mycallback,
|
feat(SpeechToText): add support to disable ssl in STT websockets
|
watson-developer-cloud_ruby-sdk
|
train
|
af494f207dedfabb8b43bcf3b77028043229d35d
|
diff --git a/test/scope.js b/test/scope.js
index <HASH>..<HASH> 100644
--- a/test/scope.js
+++ b/test/scope.js
@@ -53,7 +53,8 @@ describe("Scope", function suite() {
var app = servers.express;
app.post('/login', function(req, res, next) {
- var bearer = scope.login(res, {
+ var givemeScope = req.query.scope;
+ var scopes = {
"user-44": true,
bookWriter: {
write: true
@@ -61,7 +62,9 @@ describe("Scope", function suite() {
bookReader: {
read: true
}
- });
+ };
+ if (givemeScope) scopes = {[givemeScope]: true};
+ var bearer = scope.login(res, scopes);
res.send({
bearer: bearer // convenient but not technically needed
});
@@ -71,7 +74,7 @@ describe("Scope", function suite() {
scope.logout(res);
});
- app.get(testPath, scope.restrict('bookReader'), function(req, res, next) {
+ app.get(testPath, scope.restrict('bookReader', 'bookSecond'), function(req, res, next) {
count(req, 1);
res.send({
value: (req.path || '/').substring(1),
@@ -264,5 +267,33 @@ describe("Scope", function suite() {
});
});
+ it("should log in with different scopes and cache each variant with proxy", function() {
+ var headers = {};
+ var req = {
+ headers: headers,
+ port: port,
+ path: testPath
+ };
+ var firstDate;
+ return runner.post(host + '/login?scope=bookReader').then(function(res) {
+ res.headers.should.have.property('set-cookie');
+ var cookies = cookie.parse(res.headers['set-cookie'][0]);
+ headers.Cookie = cookie.serialize("bearer", cookies.bearer);
+ return runner.get(req);
+ }).then(function(res) {
+ res.statusCode.should.equal(200);
+ firstDate = res.body.date;
+ return runner.post(host + '/login?scope=bookSecond');
+ }).then(function(res) {
+ res.headers.should.have.property('set-cookie');
+ var cookies = cookie.parse(res.headers['set-cookie'][0]);
+ headers.Cookie = cookie.serialize("bearer", cookies.bearer);
+ return runner.get(req);
+ }).then(function(res) {
+ res.statusCode.should.equal(200);
+ res.body.date.should.not.equal(firstDate);
+ });
+ });
+
});
|
Test multiple scopes on same url
|
kapouer_upcache
|
train
|
807220ac1620b2f3022d52b9474323f882120a02
|
diff --git a/enabler/src/com/openxc/enabler/OpenXcEnablerActivity.java b/enabler/src/com/openxc/enabler/OpenXcEnablerActivity.java
index <HASH>..<HASH> 100644
--- a/enabler/src/com/openxc/enabler/OpenXcEnablerActivity.java
+++ b/enabler/src/com/openxc/enabler/OpenXcEnablerActivity.java
@@ -62,12 +62,21 @@ public class OpenXcEnablerActivity extends FragmentActivity {
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
+ if (savedInstanceState != null) {
+ mPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
+ }
startService(new Intent(this, VehicleManager.class));
startService(new Intent(this, PreferenceManagerService.class));
}
@Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putInt("tab", mPager.getCurrentItem());
+ }
+
+ @Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
|
Save and restore current tab in Enabler.
Fixed #<I>.
|
openxc_openxc-android
|
train
|
3265a8b18e8c4c0ff6e8698cc7ca011ebf3b1db9
|
diff --git a/fastlane_core/lib/fastlane_core/cert_checker.rb b/fastlane_core/lib/fastlane_core/cert_checker.rb
index <HASH>..<HASH> 100644
--- a/fastlane_core/lib/fastlane_core/cert_checker.rb
+++ b/fastlane_core/lib/fastlane_core/cert_checker.rb
@@ -58,8 +58,8 @@ module FastlaneCore
url = 'https://developer.apple.com/certificationauthority/AppleWWDRCA.cer'
filename = File.basename(url)
keychain = wwdr_keychain
- keychain.prepend("-k ") unless keychain.empty?
- Helper.backticks("curl -O #{url} && security import #{filename} #{keychain.shellescape}", print: $verbose)
+ keychain = "-k #{keychain.shellescape}" unless keychain.empty?
+ Helper.backticks("curl -O #{url} && security import #{filename} #{keychain}", print: $verbose)
UI.user_error!("Could not install WWDR certificate") unless $?.success?
end
end
|
[fastlane_core] Fixed import check of WWDR certificate (#<I>)
|
fastlane_fastlane
|
train
|
ad15b6a18c0faf17e0a6d8b78c806b6c6a2f4fe6
|
diff --git a/src/stream/csv/parser.js b/src/stream/csv/parser.js
index <HASH>..<HASH> 100644
--- a/src/stream/csv/parser.js
+++ b/src/stream/csv/parser.js
@@ -18,7 +18,7 @@
/*exported _GpfStreamCsvParser*/ // gpf.stream.csv.Parser
/*#endif*/
-_gpfErrorDeclare("csv", {
+_gpfErrorDeclare("csv/parser", {
invalidCSV:
"Invalid CSV syntax (bad quote sequence or missing end of file)"
});
|
Fixing errors domain (#<I>)
|
ArnaudBuchholz_gpf-js
|
train
|
1ce39f486000c9ddbb407410bf7a690420811c01
|
diff --git a/src/ContactServiceProvider.php b/src/ContactServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/ContactServiceProvider.php
+++ b/src/ContactServiceProvider.php
@@ -99,7 +99,7 @@ class ContactServiceProvider extends ServiceProvider
/**
* Get the services provided by the provider.
*
- * @return array
+ * @return string[]
*/
public function provides()
{
diff --git a/src/Controllers/ContactController.php b/src/Controllers/ContactController.php
index <HASH>..<HASH> 100644
--- a/src/Controllers/ContactController.php
+++ b/src/Controllers/ContactController.php
@@ -16,12 +16,12 @@
namespace GrahamCampbell\Contact\Controllers;
+use GrahamCampbell\Binput\Facades\Binput;
+use GrahamCampbell\Contact\Facades\Mailer;
+use GrahamCampbell\Throttle\Throttlers\ThrottlerInterface;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
-use GrahamCampbell\Facades\Binput\Binput;
-use GrahamCampbell\Contact\Facades\Mailer;
-use GrahamCampbell\Throttle\Throttlers\ThrottlerInterface;
/**
* This is the contact controller class.
|
Tweaked use statements and docblocks
|
BootstrapCMS_Contact
|
train
|
d584a2b8ac57eff3bf230c760e5bda205c6ea747
|
diff --git a/python/pyspark/ml/tests.py b/python/pyspark/ml/tests.py
index <HASH>..<HASH> 100644
--- a/python/pyspark/ml/tests.py
+++ b/python/pyspark/ml/tests.py
@@ -466,6 +466,31 @@ class InducedErrorEstimator(Estimator, HasInducedError):
class CrossValidatorTests(PySparkTestCase):
+ def test_copy(self):
+ sqlContext = SQLContext(self.sc)
+ dataset = sqlContext.createDataFrame([
+ (10, 10.0),
+ (50, 50.0),
+ (100, 100.0),
+ (500, 500.0)] * 10,
+ ["feature", "label"])
+
+ iee = InducedErrorEstimator()
+ evaluator = RegressionEvaluator(metricName="rmse")
+
+ grid = (ParamGridBuilder()
+ .addGrid(iee.inducedError, [100.0, 0.0, 10000.0])
+ .build())
+ cv = CrossValidator(estimator=iee, estimatorParamMaps=grid, evaluator=evaluator)
+ cvCopied = cv.copy()
+ self.assertEqual(cv.getEstimator().uid, cvCopied.getEstimator().uid)
+
+ cvModel = cv.fit(dataset)
+ cvModelCopied = cvModel.copy()
+ for index in range(len(cvModel.avgMetrics)):
+ self.assertTrue(abs(cvModel.avgMetrics[index] - cvModelCopied.avgMetrics[index])
+ < 0.0001)
+
def test_fit_minimize_metric(self):
sqlContext = SQLContext(self.sc)
dataset = sqlContext.createDataFrame([
@@ -539,6 +564,8 @@ class CrossValidatorTests(PySparkTestCase):
cvModel.save(cvModelPath)
loadedModel = CrossValidatorModel.load(cvModelPath)
self.assertEqual(loadedModel.bestModel.uid, cvModel.bestModel.uid)
+ for index in range(len(loadedModel.avgMetrics)):
+ self.assertTrue(abs(loadedModel.avgMetrics[index] - cvModel.avgMetrics[index]) < 0.0001)
class TrainValidationSplitTests(PySparkTestCase):
diff --git a/python/pyspark/ml/tuning.py b/python/pyspark/ml/tuning.py
index <HASH>..<HASH> 100644
--- a/python/pyspark/ml/tuning.py
+++ b/python/pyspark/ml/tuning.py
@@ -248,7 +248,7 @@ class CrossValidator(Estimator, ValidatorParams, MLReadable, MLWritable):
h = 1.0 / nFolds
randCol = self.uid + "_rand"
df = dataset.select("*", rand(seed).alias(randCol))
- metrics = np.zeros(numModels)
+ metrics = [0.0] * numModels
for i in range(nFolds):
validateLB = i * h
validateUB = (i + 1) * h
@@ -266,7 +266,7 @@ class CrossValidator(Estimator, ValidatorParams, MLReadable, MLWritable):
else:
bestIndex = np.argmin(metrics)
bestModel = est.fit(dataset, epm[bestIndex])
- return self._copyValues(CrossValidatorModel(bestModel))
+ return self._copyValues(CrossValidatorModel(bestModel, metrics))
@since("1.4.0")
def copy(self, extra=None):
@@ -346,10 +346,11 @@ class CrossValidatorModel(Model, ValidatorParams, MLReadable, MLWritable):
.. versionadded:: 1.4.0
"""
- def __init__(self, bestModel):
+ def __init__(self, bestModel, avgMetrics=[]):
super(CrossValidatorModel, self).__init__()
#: best model from cross validation
self.bestModel = bestModel
+ self.avgMetrics = avgMetrics
def _transform(self, dataset):
return self.bestModel.transform(dataset)
@@ -367,7 +368,9 @@ class CrossValidatorModel(Model, ValidatorParams, MLReadable, MLWritable):
"""
if extra is None:
extra = dict()
- return CrossValidatorModel(self.bestModel.copy(extra))
+ bestModel = self.bestModel.copy(extra)
+ avgMetrics = self.avgMetrics
+ return CrossValidatorModel(bestModel, avgMetrics)
@since("2.0.0")
def write(self):
@@ -394,9 +397,10 @@ class CrossValidatorModel(Model, ValidatorParams, MLReadable, MLWritable):
# Load information from java_stage to the instance.
bestModel = JavaParams._from_java(java_stage.bestModel())
+ avgMetrics = list(java_stage.avgMetrics())
estimator, epms, evaluator = super(CrossValidatorModel, cls)._from_java_impl(java_stage)
# Create a new instance of this stage.
- py_stage = cls(bestModel=bestModel)\
+ py_stage = cls(bestModel=bestModel, avgMetrics=avgMetrics)\
.setEstimator(estimator).setEstimatorParamMaps(epms).setEvaluator(evaluator)
py_stage._resetUid(java_stage.uid())
return py_stage
@@ -408,12 +412,10 @@ class CrossValidatorModel(Model, ValidatorParams, MLReadable, MLWritable):
:return: Java object equivalent to this instance.
"""
- sc = SparkContext._active_spark_context
-
_java_obj = JavaParams._new_java_obj("org.apache.spark.ml.tuning.CrossValidatorModel",
self.uid,
self.bestModel._to_java(),
- _py2java(sc, []))
+ self.avgMetrics)
estimator, epms, evaluator = super(CrossValidatorModel, self)._to_java_impl()
_java_obj.set("evaluator", evaluator)
|
[SPARK-<I>][PYSPARK] PySpark CrossValidatorModel should support avgMetrics
## What changes were proposed in this pull request?
support avgMetrics in CrossValidatorModel with Python
## How was this patch tested?
Doctest and `test_save_load` in `pyspark/ml/test.py`
[JIRA](<URL>)
|
apache_spark
|
train
|
da84dc194b6b2e33064ee286513fddf6014293d3
|
diff --git a/Tests/js/views/actions/assets/ez-buttonactionview-tests.js b/Tests/js/views/actions/assets/ez-buttonactionview-tests.js
index <HASH>..<HASH> 100644
--- a/Tests/js/views/actions/assets/ez-buttonactionview-tests.js
+++ b/Tests/js/views/actions/assets/ez-buttonactionview-tests.js
@@ -1,13 +1,12 @@
YUI.add('ez-buttonactionview-tests', function (Y) {
- var container = Y.one('.container'),
- viewTest;
+ var viewTest;
viewTest = new Y.Test.Case({
name: "eZ Button Action View test",
setUp: function () {
this.view = new Y.eZ.ButtonActionView({
- container: container,
+ container: '.container',
actionId: "test",
hint: "Test hint",
label: "Test label"
@@ -29,7 +28,7 @@ YUI.add('ez-buttonactionview-tests', function (Y) {
};
this.view.render();
Y.Assert.isTrue(templateCalled, "The template should have used to render the this.view");
- Y.Assert.areNotEqual("", container.getHTML(), "View container should contain the result of the this.view");
+ Y.Assert.areNotEqual("", this.view.get('container').getHTML(), "View container should contain the result of the this.view");
},
"Test available variable in template": function () {
|
Refactored the button action view test to not use any "global" variable
|
ezsystems_PlatformUIBundle
|
train
|
cb5f22b760d8370c076223e8f2e0c06de58c3b98
|
diff --git a/structr-modules/structr-flow-module/src/main/java/org/structr/flow/impl/FlowComparison.java b/structr-modules/structr-flow-module/src/main/java/org/structr/flow/impl/FlowComparison.java
index <HASH>..<HASH> 100644
--- a/structr-modules/structr-flow-module/src/main/java/org/structr/flow/impl/FlowComparison.java
+++ b/structr-modules/structr-flow-module/src/main/java/org/structr/flow/impl/FlowComparison.java
@@ -18,6 +18,7 @@
*/
package org.structr.flow.impl;
+import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -77,6 +78,10 @@ public class FlowComparison extends FlowCondition implements DataSource, Deploya
if (data != null && data.getClass().isEnum()) {
data = ((Enum)data).name();
+ } else if (data instanceof Number && value instanceof Number) {
+
+ data = ((Number)data).doubleValue();
+ value = ((Number)data).doubleValue();
}
Comparable c = (Comparable) data;
|
Fixes bug in FlowComparison when comparing different number types.
|
structr_structr
|
train
|
10445db011ca518cf7bac24054e02f4cdf3a95e2
|
diff --git a/lib/arjdbc/db2/as400.rb b/lib/arjdbc/db2/as400.rb
index <HASH>..<HASH> 100644
--- a/lib/arjdbc/db2/as400.rb
+++ b/lib/arjdbc/db2/as400.rb
@@ -67,6 +67,11 @@ module ArJdbc
result
end
private :execute_and_auto_confirm
+
+ # disable all schemas browsing when default schema is specified
+ def table_exists?(name)
+ @connection.table_exists?(name, db2_schema)
+ end
DRIVER_NAME = 'com.ibm.as400.access.AS400JDBCDriver'.freeze
|
add db2_schema to table_exists?
|
jruby_activerecord-jdbc-adapter
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.