hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
0e8ee149512630ce602637215c782bbb5c695af6
|
diff --git a/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/ConverterUtils.java b/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/ConverterUtils.java
index <HASH>..<HASH> 100644
--- a/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/ConverterUtils.java
+++ b/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/ConverterUtils.java
@@ -42,7 +42,7 @@ import com.dataart.spreadsheetanalytics.api.model.IDataModel;
import com.dataart.spreadsheetanalytics.model.CellValue;
import com.dataart.spreadsheetanalytics.model.DmCell;
-final class ConverterUtils {
+ public final class ConverterUtils {
public static final String FORMULA_PREFIX = "=";
private static final String POI_FUNCTION_PREFIX = "_xlfn.";
@@ -149,4 +149,5 @@ final class ConverterUtils {
String filteredFormula = formula.replace(POI_FUNCTION_PREFIX, "");
return filteredFormula.startsWith(function) && filteredFormula.replace(function, "").startsWith("(");
}
+
}
diff --git a/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataModelConverters.java b/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataModelConverters.java
index <HASH>..<HASH> 100644
--- a/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataModelConverters.java
+++ b/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataModelConverters.java
@@ -19,6 +19,8 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.Calendar;
+import java.util.Date;
import org.apache.poi.ss.formula.eval.NotImplementedException;
import org.apache.poi.ss.usermodel.Cell;
@@ -28,6 +30,8 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.dataart.spreadsheetanalytics.api.model.IDataModel;
+import com.dataart.spreadsheetanalytics.api.model.IDmCell;
+import com.dataart.spreadsheetanalytics.api.model.IDmRow;
import com.dataart.spreadsheetanalytics.model.A1Address;
import com.dataart.spreadsheetanalytics.model.DataModel;
import com.dataart.spreadsheetanalytics.model.DmCell;
@@ -108,8 +112,26 @@ final class DataModelConverters {
* Convertes plain {@link IDataModel} to new {@link XSSFWorkbook} with formatting provided.
*/
static Workbook toWorkbook(final IDataModel dataModel, final Workbook formatting) throws IOException {
- /*TODO*/
- throw new NotImplementedException("You cannot convert from IDataModel to Workbook yet.");
- }
+ Workbook result = new XSSFWorkbook();
+ Sheet sheet = result.createSheet(dataModel.name());
+ for (int rowId = 0 ; rowId < dataModel.length(); rowId++) {
+ IDmRow dmRow = dataModel.getRow(rowId);
+ Row row = sheet.createRow(rowId);
+ for (int cellId = 0 ; cellId < dataModel.length(); cellId++) {
+ IDmCell dmCell = dmRow.getCell(cellId);
+ Cell cell = row.createCell(cellId);
+ populateCellWithCellValue(cell, dmCell.content().get());
+ }
+ }
+ return result;
+ }
+
+ static void populateCellWithCellValue(Cell cell, Object value) {
+ if (value instanceof Boolean) { cell.setCellValue((Boolean) value); }
+ else if (value instanceof Double) { cell.setCellValue((Double) value); }
+ else if (value instanceof String) { cell.setCellValue((String) value); }
+ else if (value instanceof Calendar) { cell.setCellValue((Calendar) value); }
+ else if (value instanceof Date) { cell.setCellValue((Date) value); }
+ }
}
|
#<I> implementing to WBook
|
DataArt_CalculationEngine
|
train
|
7bb2895415782b1cf54535121f23493fc1093794
|
diff --git a/internal/clock/now_js.go b/internal/clock/now_js.go
index <HASH>..<HASH> 100644
--- a/internal/clock/now_js.go
+++ b/internal/clock/now_js.go
@@ -21,10 +21,15 @@ import (
"time"
)
+var (
+ jsPerformance = js.Global().Get("performance")
+ jsNow = jsPerformance.Get("now").Call("bind", jsPerformance)
+)
+
func now() int64 {
// time.Now() is not reliable until GopherJS supports performance.now().
//
// performance.now is monotonic:
// https://www.w3.org/TR/hr-time-2/#sec-monotonic-clock
- return int64(js.Global().Get("performance").Call("now").Float() * float64(time.Millisecond))
+ return int64(jsNow.Invoke().Float() * float64(time.Millisecond))
}
|
clock: Avoid calling (js.Value).Get() for performance
|
hajimehoshi_ebiten
|
train
|
d50bfa4caf456648da2b1fdd35dcb1b41ad5bf24
|
diff --git a/graylog2-server/src/main/java/org/graylog2/grok/GrokPattern.java b/graylog2-server/src/main/java/org/graylog2/grok/GrokPattern.java
index <HASH>..<HASH> 100644
--- a/graylog2-server/src/main/java/org/graylog2/grok/GrokPattern.java
+++ b/graylog2-server/src/main/java/org/graylog2/grok/GrokPattern.java
@@ -36,8 +36,8 @@ public class GrokPattern {
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id)
- .add("name='", name)
- .add("pattern='", pattern)
+ .add("name", name)
+ .add("pattern", pattern)
.add("contentPack", contentPack)
.toString();
}
|
Remove superfluous characters in GrokPattern#toString
|
Graylog2_graylog2-server
|
train
|
26f7005313579474340f389d64d9982fb1e2d26d
|
diff --git a/src/RunOpenCode/ExchangeRate/Utils/CurrencyCodeUtil.php b/src/RunOpenCode/ExchangeRate/Utils/CurrencyCodeUtil.php
index <HASH>..<HASH> 100644
--- a/src/RunOpenCode/ExchangeRate/Utils/CurrencyCodeUtil.php
+++ b/src/RunOpenCode/ExchangeRate/Utils/CurrencyCodeUtil.php
@@ -160,7 +160,8 @@ final class CurrencyCodeUtil
'LUF' => 'Luxembourg Franc',
'PTE' => 'Portugal Escudo',
'ESP' => 'Spain Peseta',
- 'XDR' => 'IMF Special Drawing Rights'
+ 'XDR' => 'IMF Special Drawing Rights',
+ 'SKK' => 'Slovak Koruna'
);
/**
|
Slovak Koruna - SKK currency added to list
|
RunOpenCode_exchange-rate
|
train
|
3e751003901ecf9cbb6fe5998abfcff793c881cf
|
diff --git a/cdm/src/main/java/ucar/nc2/iosp/misc/Uspln.java b/cdm/src/main/java/ucar/nc2/iosp/misc/Uspln.java
index <HASH>..<HASH> 100644
--- a/cdm/src/main/java/ucar/nc2/iosp/misc/Uspln.java
+++ b/cdm/src/main/java/ucar/nc2/iosp/misc/Uspln.java
@@ -145,7 +145,7 @@ public class Uspln extends AbstractLightningIOSP {
*/
/** Magic string for determining if this is my type of file. */
- private static final String MAGIC = "LIGHTNING-..PLN1";
+ private static final String MAGIC = "LIGHTNING-.*[P|G]LN1";
/** Magic string for determining if this is my type of file. */
private static final String MAGIC_OLD = "..PLN-LIGHTNING";
|
Changing the "MAGIC" regex to better handle USPLN GLN text data files, hopefully.
|
Unidata_thredds
|
train
|
62b5b7b36fc4fc9abe2c4f179106fdf63ca15d15
|
diff --git a/scout/server/blueprints/variants/controllers.py b/scout/server/blueprints/variants/controllers.py
index <HASH>..<HASH> 100644
--- a/scout/server/blueprints/variants/controllers.py
+++ b/scout/server/blueprints/variants/controllers.py
@@ -31,8 +31,13 @@ def variants(store, institute_obj, case_obj, variants_query, page=1, per_page=50
skip_count = per_page * max(page - 1, 0)
more_variants = True if variant_count > (skip_count + per_page) else False
+ genome_build = case_obj.get('genome_build', '37')
+ if genome_build not in ['37','38']:
+ genome_build = '37'
+
+
return {
- 'variants': (parse_variant(store, institute_obj, case_obj, variant_obj, update=True) for
+ 'variants': (parse_variant(store, institute_obj, case_obj, variant_obj, update=True, genome_build=genome_build) for
variant_obj in variants_query.skip(skip_count).limit(per_page)),
'more_variants': more_variants,
}
@@ -43,8 +48,12 @@ def sv_variants(store, institute_obj, case_obj, variants_query, page=1, per_page
skip_count = (per_page * max(page - 1, 0))
more_variants = True if variants_query.count() > (skip_count + per_page) else False
+ genome_build = case_obj.get('genome_build', '37')
+ if genome_build not in ['37','38']:
+ genome_build = '37'
+
return {
- 'variants': (parse_variant(store, institute_obj, case_obj, variant) for variant in
+ 'variants': (parse_variant(store, institute_obj, case_obj, variant, genome_build=genome_build) for variant in
variants_query.skip(skip_count).limit(per_page)),
'more_variants': more_variants,
}
@@ -216,7 +225,7 @@ def parse_variant(store, institute_obj, case_obj, variant_obj, update=False, gen
continue
# Else we collect the gene object and check the id
if gene_obj.get('hgnc_symbol') is None:
- hgnc_gene = store.hgnc_gene(gene_obj['hgnc_id'], build=build)
+ hgnc_gene = store.hgnc_gene(gene_obj['hgnc_id'], build=genome_build)
if not hgnc_gene:
continue
has_changed = True
@@ -275,7 +284,7 @@ def variant_export_lines(store, case_obj, variants_query):
variant_line.append(variant['chromosome'])
variant_line.append(position)
variant_line.append(change)
- variant_line.append('_'.join([str(position), change]))
+ variant_line.append(str(position)+change)
# gather gene info:
gene_list = variant.get('genes') #this is a list of gene objects
|
Fixes bug where build should be genome_build
|
Clinical-Genomics_scout
|
train
|
50f0f68ecb87fb2052fd7e5e084c6681ed80ca56
|
diff --git a/common/src/main/java/tachyon/resource/ResourcePool.java b/common/src/main/java/tachyon/resource/ResourcePool.java
index <HASH>..<HASH> 100644
--- a/common/src/main/java/tachyon/resource/ResourcePool.java
+++ b/common/src/main/java/tachyon/resource/ResourcePool.java
@@ -20,6 +20,8 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
+import javax.annotation.concurrent.ThreadSafe;
+
/**
* Class representing a pool of resources to be temporarily used and returned. Inheriting classes
* must implement the close method as well as initialize the resources in the constructor. The
@@ -28,6 +30,7 @@ import java.util.concurrent.locks.ReentrantLock;
*
* @param <T> the type of resource this pool manages
*/
+@ThreadSafe
public abstract class ResourcePool<T> {
private final ReentrantLock mTakeLock;
private final Condition mNotEmpty;
|
Adding thread safety annotations for tachyon.resource in common module.
|
Alluxio_alluxio
|
train
|
0ea9b995f6a83ee8218d827a7cb5573138b9b4e2
|
diff --git a/spec/command_spec.rb b/spec/command_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/command_spec.rb
+++ b/spec/command_spec.rb
@@ -164,7 +164,7 @@ describe "Command" do
assert !outcome.success?
assert_nil outcome.result
- assert :is_a_bob, outcome.errors.symbolic[:bob]
+ assert_equal :is_a_bob, outcome.errors.symbolic[:bob]
end
end
@@ -186,7 +186,7 @@ describe "Command" do
assert !outcome.success?
assert_nil outcome.result
- assert :is_a_bob, outcome.errors[:people].symbolic[:bob]
+ assert_equal :is_a_bob, outcome.errors[:people].symbolic[:bob]
end
end
@@ -212,8 +212,8 @@ describe "Command" do
assert !outcome.success?
assert_nil outcome.result
- assert :is_short, outcome.errors.symbolic[:bob]
- assert :is_fat, outcome.errors.symbolic[:sally]
+ assert_equal :is_short, outcome.errors.symbolic[:bob]
+ assert_equal :is_fat, outcome.errors.symbolic[:sally]
end
end
|
Use assert_equal to check symbolic errors
The `assert` method checks whether its first argument is truthy. These
assertions could never fail, since symbols are always truthy.
We actually want to check if the first argument and the second argument
are equal, which is what `assert_equal` does.
|
cypriss_mutations
|
train
|
d9abe395c31d718c1d80a059685c98ae36060ea5
|
diff --git a/test/test_helper.rb b/test/test_helper.rb
index <HASH>..<HASH> 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -8,6 +8,7 @@ else
require File.join(File.dirname(__FILE__), %w{ .. lib ffi-geos })
end
+puts "Ruby version #{RUBY_VERSION} - #{RbConfig::CONFIG['RUBY_INSTALL_NAME']}"
puts "GEOS version #{Geos::GEOS_VERSION}"
if defined?(Geos::FFIGeos)
puts "Using #{Geos::FFIGeos.geos_library_paths.join(', ')}"
|
Output a bit of debugging information when running tests.
|
dark-panda_ffi-geos
|
train
|
5decab9d3f2fefb50e6feb3cb6e2237fd6af950c
|
diff --git a/Command/SlugMapRebuildCommand.php b/Command/SlugMapRebuildCommand.php
index <HASH>..<HASH> 100644
--- a/Command/SlugMapRebuildCommand.php
+++ b/Command/SlugMapRebuildCommand.php
@@ -102,6 +102,7 @@ class SlugMapRebuildCommand extends Command
$tableName = $this->em->getClassMetadata(SlugMapItem::class)->getTableName();
$connection = $this->em->getConnection();
+ $connection->exec('SET foreign_key_checks = 0');
$connection->exec($connection->getDriver()->getDatabasePlatform()->getTruncateTableSQL($tableName));
}
}
|
Disable foreign key checks before slug map rebuilding.
|
DarvinStudio_DarvinContentBundle
|
train
|
7b3ceb5a2980444647ee5ea4a6ee3179c44deb69
|
diff --git a/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php b/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php
+++ b/lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php
@@ -40,6 +40,13 @@ class FixtureTaskTest extends CakeTestCase {
public $fixtures = array('core.article', 'core.comment', 'core.datatype', 'core.binary_test', 'core.user');
/**
+ * Whether backup global state for each test method or not
+ *
+ * @var bool false
+ */
+ public $backupGlobals = false;
+
+/**
* setUp method
*
* @return void
@@ -53,8 +60,8 @@ class FixtureTaskTest extends CakeTestCase {
array('in', 'err', 'createFile', '_stop', 'clear'),
array($out, $out, $in)
);
- $this->Task->Model = $this->getMock('Shell',
- array('in', 'out', 'error', 'createFile', 'getName', 'getTable', 'listAll'),
+ $this->Task->Model = $this->getMock('ModelTask',
+ array('in', 'out', 'err', 'createFile', 'getName', 'getTable', 'listAll'),
array($out, $out, $in)
);
$this->Task->Template = new TemplateTask($out, $out, $in);
@@ -191,6 +198,7 @@ class FixtureTaskTest extends CakeTestCase {
/**
* test that execute passes runs bake depending with named model.
*
+ *
* @return void
*/
public function testExecuteWithNamedModel() {
@@ -201,36 +209,7 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticleFixture/'));
-
- $this->Task->execute();
- }
-
-/**
- * data provider for model name variations.
- *
- * @return array
- */
- public static function modelNameProvider() {
- return array(
- array('article'), array('articles'), array('Articles'), array('Article')
- );
- }
-
-/**
- * test that execute passes runs bake depending with named model.
- *
- * @dataProvider modelNameProvider
- * @return void
- */
- public function testExecuteWithNamedModelVariations($modelName) {
- $this->Task->connection = 'test';
- $this->Task->path = '/my/path/';
-
- $this->Task->args = array($modelName);
- $filename = '/my/path/ArticleFixture.php';
- $this->Task->expects($this->once())->method('createFile')
- ->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticleFixture/'));
-
+
$this->Task->execute();
}
@@ -245,7 +224,7 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->args = array('all');
$this->Task->Model->expects($this->any())
->method('listAll')
- ->will($this->returnValue(array('articles', 'comments')));
+ ->will($this->returnValue(array('Article', 'comments')));
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->at(0))
diff --git a/lib/Cake/Test/Case/Model/CakeSchemaTest.php b/lib/Cake/Test/Case/Model/CakeSchemaTest.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/Test/Case/Model/CakeSchemaTest.php
+++ b/lib/Cake/Test/Case/Model/CakeSchemaTest.php
@@ -575,10 +575,7 @@ class CakeSchemaTest extends CakeTestCase {
*/
public function testSchemaReadWithAppModel() {
$connections = ConnectionManager::enumConnectionObjects();
- if (!empty($connections['default'])) {
- $backup = $connections['default'];
- ConnectionManager::drop('default');
- }
+ ConnectionManager::drop('default');
ConnectionManager::create('default', $connections['test']);
try {
$read = $this->Schema->read(array(
@@ -586,18 +583,11 @@ class CakeSchemaTest extends CakeTestCase {
'name' => 'TestApp',
'models' => array('AppModel')
));
- if (!empty($backup)) {
- ConnectionManager::drop('default');
- ConnectionManager::create('default', $backup);
- }
} catch(MissingTableException $mte) {
- if (!empty($backup)) {
- ConnectionManager::drop('default');
- ConnectionManager::create('default', $backup);
- }
+ ConnectionManager::drop('default');
$this->fail($mte->getMessage());
}
-
+ ConnectionManager::drop('default');
}
/**
|
Fixing a few failing test cases and attempting to work around php segmentation fault when running the complete test suite
|
cakephp_cakephp
|
train
|
14da3798553ae3299d75ef2396cc6b7c07ee7b4a
|
diff --git a/feedfinder2.py b/feedfinder2.py
index <HASH>..<HASH> 100644
--- a/feedfinder2.py
+++ b/feedfinder2.py
@@ -132,7 +132,8 @@ def url_feed_prob(url):
return -1
kw = ["atom", "rss", "rdf", ".xml", "feed"]
for p, t in zip(range(len(kw), 0, -1), kw):
- return p
+ if t in url:
+ return p
return 0
|
fix a bug where the url was not used when deciding the probability of the url being a feed
|
dfm_feedfinder2
|
train
|
e95d6f9a9df83b38f9b34723da5958dd3c9dff01
|
diff --git a/src/Api/Handler/Request/Shipment/PlpHandler.php b/src/Api/Handler/Request/Shipment/PlpHandler.php
index <HASH>..<HASH> 100644
--- a/src/Api/Handler/Request/Shipment/PlpHandler.php
+++ b/src/Api/Handler/Request/Shipment/PlpHandler.php
@@ -21,13 +21,23 @@ use SkyHub\Api\EntityInterface\Shipment\Plp;
use SkyHub\Api\Handler\Request\HandlerAbstract;
use SkyHub\Api\DataTransformer\Shipment\Plp\Group as GroupTransformer;
+/**
+ * Class PlpHandler
+ *
+ * @package SkyHub\Api\Handler\Request\Shipment
+ */
class PlpHandler extends HandlerAbstract
{
+ /**
+ * @var int
+ */
+ const OFFSET_LIMIT = 25;
- /** @var string */
+ /**
+ * @var string
+ */
protected $baseUrlPath = '/shipments/b2w';
-
/**
* Retrieves a list of all PLP's in SkyHub.
*
@@ -37,24 +47,29 @@ class PlpHandler extends HandlerAbstract
{
/** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */
$responseHandler = $this->service()->get($this->baseUrlPath());
+
return $responseHandler;
}
-
/**
* Retrieves a list of all orders ready to be grouped in a PLP.
*
+ * @param int $offset
+ *
* @return \SkyHub\Api\Handler\Response\HandlerInterface
*/
- public function ordersReadyToGroup()
+ public function ordersReadyToGroup(int $offset = 1)
{
+ $query = [
+ 'offset' => min(max($offset, 1), self::OFFSET_LIMIT)
+ ];
+
/** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */
- $responseHandler = $this->service()->get($this->baseUrlPath('/to_group'));
+ $responseHandler = $this->service()->get($this->baseUrlPath('/to_group', $query));
return $responseHandler;
}
-
/**
* Group multiple orders in a PLP.
*
@@ -70,10 +85,10 @@ class PlpHandler extends HandlerAbstract
/** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */
$responseHandler = $this->service()->post($this->baseUrlPath(), $body);
+
return $responseHandler;
}
-
/**
* Get PLP file
*
@@ -84,7 +99,7 @@ class PlpHandler extends HandlerAbstract
public function viewFile($id)
{
$query = [
- 'plp_id' => $id
+ 'plp_id' => $id
];
/** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */
@@ -93,7 +108,6 @@ class PlpHandler extends HandlerAbstract
return $responseHandler;
}
-
/**
* Ungroup a PLP.
*
@@ -104,15 +118,15 @@ class PlpHandler extends HandlerAbstract
public function ungroup($id)
{
$params = [
- 'plp_id' => $id,
+ 'plp_id' => $id,
];
/** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */
$responseHandler = $this->service()->delete($this->baseUrlPath(), $params);
+
return $responseHandler;
}
-
/**
* @return Plp
*/
|
Changes:
- Allowing to pass offset parameter to method ordersReadyToGroup.
|
bittools_skyhub-php
|
train
|
3aa2166ee5e82ec696a56177cd46f068a01aac47
|
diff --git a/src/Permissions/DoctrinePermissionDriver.php b/src/Permissions/DoctrinePermissionDriver.php
index <HASH>..<HASH> 100644
--- a/src/Permissions/DoctrinePermissionDriver.php
+++ b/src/Permissions/DoctrinePermissionDriver.php
@@ -6,6 +6,7 @@ use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Illuminate\Contracts\Config\Repository;
+use LaravelDoctrine\ACL\Contracts\Permission;
use Illuminate\Support\Collection;
class DoctrinePermissionDriver implements PermissionDriver
|
Type-hint the Permissions Contract so that custom Permissions classes can be used.
|
laravel-doctrine_acl
|
train
|
eaf5fb9265623ef9cb999fa60c581874a186e1af
|
diff --git a/Tests/EventListener/UserLoadTest.php b/Tests/EventListener/UserLoadTest.php
index <HASH>..<HASH> 100644
--- a/Tests/EventListener/UserLoadTest.php
+++ b/Tests/EventListener/UserLoadTest.php
@@ -14,7 +14,8 @@ declare(strict_types=1);
namespace Hackzilla\Bundle\TicketBundle\Tests\EventListener;
use Hackzilla\Bundle\TicketBundle\EventListener\UserLoad;
-use Hackzilla\Bundle\TicketBundle\Manager\UserManager;
+use Hackzilla\Bundle\TicketBundle\Manager\UserManagerInterface;
+use Hackzilla\Bundle\TicketBundle\Tests\Fixtures\Entity\User;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class UserLoadTest extends WebTestCase
@@ -33,9 +34,18 @@ class UserLoadTest extends WebTestCase
$this->object = null;
}
- public function getUserManagerMock()
+ public function getUserManagerMock(): UserManagerInterface
{
- return $this->createMock(UserManager::class);
+ $userManager = $this->getMockBuilder(UserManagerInterface::class)
+ ->getMock();
+
+ $user = new User();
+
+ $userManager
+ ->method('getUserById')
+ ->willReturn($user);
+
+ return $userManager;
}
public function testObjectCreated(): void
diff --git a/Tests/Fixtures/Entity/User.php b/Tests/Fixtures/Entity/User.php
index <HASH>..<HASH> 100644
--- a/Tests/Fixtures/Entity/User.php
+++ b/Tests/Fixtures/Entity/User.php
@@ -47,6 +47,11 @@ class User implements UserInterface
*/
private $email;
+ public function __toString(): string
+ {
+ return 'Test User';
+ }
+
public function getId()
{
return $this->id;
|
rewrite test to handle userManager being final
|
hackzilla_TicketBundle
|
train
|
7df8579258a13fec3b3cc68e9085f934e3616559
|
diff --git a/test/FilterTest.py b/test/FilterTest.py
index <HASH>..<HASH> 100644
--- a/test/FilterTest.py
+++ b/test/FilterTest.py
@@ -307,7 +307,7 @@ class OrdinalTagFilterTest(TopydoTest):
self.todo1 = "Foo due:{}".format(self.today)
self.todo2 = "Bar due:{}".format(self.tomorrow)
- self.todo3 = "Baz due:nonsense"
+ self.todo3 = "Baz due:Nonsense"
self.todo4 = "Fnord due:2014-10-32"
self.todos = [
@@ -358,6 +358,22 @@ class OrdinalTagFilterTest(TopydoTest):
self.assertEqual(len(result), 1)
self.assertEqual(result[0].source(), self.todo2)
+ def test_filter6(self):
+ otf = Filter.OrdinalTagFilter('due:non')
+
+ result = otf.filter(self.todos)
+
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[0].source(), self.todo3)
+
+ def test_filter7(self):
+ otf = Filter.OrdinalTagFilter('due:Non')
+
+ result = otf.filter(self.todos)
+
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[0].source(), self.todo3)
+
if __name__ == '__main__':
unittest.main()
diff --git a/topydo/lib/Filter.py b/topydo/lib/Filter.py
index <HASH>..<HASH> 100644
--- a/topydo/lib/Filter.py
+++ b/topydo/lib/Filter.py
@@ -156,13 +156,28 @@ ORDINAL_TAG_MATCH = r"(?P<key>[^:]*):(?P<operator><=?|=|>=?|!)?(?P<value>\S+)"
class OrdinalTagFilter(Filter):
def __init__(self, p_expression):
super(OrdinalTagFilter, self).__init__()
- match = re.match(ORDINAL_TAG_MATCH, p_expression)
+
+ self.expression = p_expression
+
+ match = re.match(ORDINAL_TAG_MATCH, self.expression)
if match:
self.key = match.group('key')
self.operator = match.group('operator') or '='
self.value = match.group('value')
def match(self, p_todo):
+ """
+ Performs a match on a key:value tag in the todo.
+
+ First it tries to convert the value and the user-entered expression to
+ a date and makes a comparison if it succeeds, based on the given
+ operator (default ==).
+ Upon failure, it falls back to converting value and user-entered
+ expression to an integer and makes a numerical comparison based on the
+ given operator (default ==)
+ As a last resort, it falls back to using a Grep filter to see if the
+ user given expression is contained in the todo text.
+ """
if not self.key or not p_todo.has_tag(self.key):
return False
@@ -174,11 +189,15 @@ class OrdinalTagFilter(Filter):
operand2 = date_string_to_date(self.value)
except ValueError:
+ operand1 = p_todo.tag_value(self.key)
+ operand2 = self.value
+
try:
- operand1 = int(p_todo.tag_value(self.key))
- operand2 = int(self.value)
+ operand1 = int(operand1)
+ operand2 = int(operand2)
except ValueError:
- return False
+ grep = GrepFilter(self.expression)
+ return grep.match(p_todo)
if self.operator == '<':
return operand1 < operand2
|
Make 'topydo ls foo:somestring' work.
If there was a todo with 'foo:somestring', it wouldn't be returned with
the command above, because somestring couldn't be converted to a date or
an integer, and therefore the OrdinalTagFilter just returns False.
As a final fallback, use a GrepFilter match to do the string comparison
such that the todo item(s) with this key:value combination will be
returned.
|
bram85_topydo
|
train
|
26ed12dd9abc1efb42841bcfdbdce1c65896ed81
|
diff --git a/lib/govuk_elements_form_builder/form_builder.rb b/lib/govuk_elements_form_builder/form_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/govuk_elements_form_builder/form_builder.rb
+++ b/lib/govuk_elements_form_builder/form_builder.rb
@@ -20,8 +20,14 @@ module GovukElementsFormBuilder
%i[
email_field
password_field
+ number_field
+ phone_field
+ range_field
+ search_field
+ telephone_field
text_area
text_field
+ url_field
].each do |method_name|
define_method(method_name) do |attribute, *args|
content_tag :div, class: form_group_classes(attribute), id: form_group_id(attribute) do
diff --git a/spec/lib/govuk_elements_form_builder/form_builder_spec.rb b/spec/lib/govuk_elements_form_builder/form_builder_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/govuk_elements_form_builder/form_builder_spec.rb
+++ b/spec/lib/govuk_elements_form_builder/form_builder_spec.rb
@@ -200,10 +200,34 @@ RSpec.describe GovukElementsFormBuilder::FormBuilder do
include_examples 'input field', :email_field, :email
end
+ describe "#number_field" do
+ include_examples 'input field', :number_field, :number
+ end
+
describe '#password_field' do
include_examples 'input field', :password_field, :password
end
+ describe '#phone_field' do
+ include_examples 'input field', :phone_field, :tel
+ end
+
+ describe '#range_field' do
+ include_examples 'input field', :range_field, :range
+ end
+
+ describe '#search_field' do
+ include_examples 'input field', :search_field, :search
+ end
+
+ describe '#telephone_field' do
+ include_examples 'input field', :telephone_field, :tel
+ end
+
+ describe '#url_field' do
+ include_examples 'input field', :url_field, :url
+ end
+
describe '#radio_button_fieldset' do
it 'outputs radio buttons wrapped in labels' do
output = builder.radio_button_fieldset :location, choices: [:ni, :isle_of_man_channel_islands, :british_abroad]
|
Add methods for additional types of Rails input field helpers
Add helper methods to form builder for `#number_field`, `#phone_field`,
`#range_field`, `#search_field`, `#telephone_field`, and `#url_field`.
|
ministryofjustice_govuk_elements_form_builder
|
train
|
4bef6c3d46309c2c5c379cbacdfca6268f0b448b
|
diff --git a/core/etcd.go b/core/etcd.go
index <HASH>..<HASH> 100644
--- a/core/etcd.go
+++ b/core/etcd.go
@@ -3,7 +3,6 @@ package core
import (
"github.com/davecgh/go-spew/spew"
"github.com/coreos/go-etcd/etcd"
- "encoding/gob"
"pilosa/db"
"log"
"strings"
@@ -12,22 +11,47 @@ import (
"errors"
)
-func (service *Service) SetupEtcd() {
- gob.Register(db.Location{})
- service.Etcd = etcd.NewClient(nil)
+type MetaWatcher struct {
+ service *Service
+ namespace string
}
-func flatten(node *etcd.Node) []*etcd.Node {
- nodes := make([]*etcd.Node, 0)
- nodes = append(nodes, node)
- for _, node := range node.Nodes {
- nodes = append(nodes, flatten(&node)...)
+func (self *MetaWatcher) Run() {
+ log.Println(self.namespace + "/db")
+ resp, err := self.service.Etcd.Get(self.namespace + "/db", false, true)
+ if err != nil {
+ log.Fatal(err)
}
- return nodes
+ for _, node := range flatten(resp.Node) {
+ err := self.handlenode(node)
+ if err != nil {
+ spew.Dump(node)
+ log.Println(err)
+ }
+ }
+ receiver := make(chan *etcd.Response)
+ stop := make(chan bool)
+ go func() {
+ // TODO: error check and restart watcher
+ _, _ = self.service.Etcd.Watch(self.namespace + "/db", 0, true, receiver, stop)
+ }()
+ go func() {
+ for resp = range receiver {
+ switch resp.Action {
+ case "set":
+ self.handlenode(resp.Node)
+ }
+ // TODO: handle deletes
+ }
+ }()
+}
+
+func NewMetaWatcher(service *Service, namespace string) *MetaWatcher {
+ return &MetaWatcher{service, namespace}
}
-func handlenode(node *etcd.Node, namespace string, cluster *db.Cluster) error {
- key := node.Key[len(namespace)+1:]
+func (self *MetaWatcher) handlenode(node *etcd.Node) error {
+ key := node.Key[len(self.namespace)+1:]
bits := strings.Split(key, "/")
var database *db.Database
var frame *db.Frame
@@ -42,7 +66,7 @@ func handlenode(node *etcd.Node, namespace string, cluster *db.Cluster) error {
return nil
}
if len(bits) > 1 {
- database = cluster.GetOrCreateDatabase(bits[1])
+ database = self.service.Cluster.GetOrCreateDatabase(bits[1])
}
if len(bits) > 2 {
if bits[2] != "frame" {
@@ -91,32 +115,11 @@ func handlenode(node *etcd.Node, namespace string, cluster *db.Cluster) error {
return err
}
-func (service *Service) MetaWatcher() {
- namespace := "/pilosa/0"
- log.Println(namespace + "/db")
- cluster := db.NewCluster()
- resp, err := service.Etcd.Get(namespace + "/db", false, true)
- if err != nil {
- log.Fatal(err)
- }
- for _, node := range flatten(resp.Node) {
- err := handlenode(node, namespace, cluster)
- if err != nil {
- spew.Dump(node)
- log.Println(err)
- }
+func flatten(node *etcd.Node) []*etcd.Node {
+ nodes := make([]*etcd.Node, 0)
+ nodes = append(nodes, node)
+ for _, node := range node.Nodes {
+ nodes = append(nodes, flatten(&node)...)
}
- receiver := make(chan *etcd.Response)
- stop := make(chan bool)
- go func() {
- _, _ = service.Etcd.Watch(namespace + "/db", 0, true, receiver, stop)
- }()
- go func() {
- for resp = range receiver {
- switch resp.Action {
- case "set":
- handlenode(resp.Node, namespace, cluster)
- }
- }
- }()
+ return nodes
}
diff --git a/core/service.go b/core/service.go
index <HASH>..<HASH> 100644
--- a/core/service.go
+++ b/core/service.go
@@ -50,8 +50,9 @@ type Service struct {
Listener net.Listener
ConnectionRegisterChannel chan *PersistentConnection
Stats *Stats
- //Cluster query.Cluster
+ Cluster *db.Cluster
Cruncher *Cruncher
+ MetaWatcher *MetaWatcher
}
func NewService(tcp, http *db.Location) *Service {
@@ -62,6 +63,9 @@ func NewService(tcp, http *db.Location) *Service {
service.Inbox = make(chan *db.Message)
service.Stats = new(Stats)
service.Cruncher = new(Cruncher)
+ service.Etcd = etcd.NewClient(nil)
+ service.Cluster = db.NewCluster()
+ service.MetaWatcher = &MetaWatcher{service, "/pilosa/0"}
return service
}
@@ -300,7 +304,6 @@ func (service *Service) NewListener() chan *db.Message {
func (service *Service) Run() {
log.Println("Running service...")
- service.SetupEtcd()
//go r.SyncEtcd()
//go service.WatchEtcd()
//go service.HandleConnections()
@@ -308,7 +311,7 @@ func (service *Service) Run() {
//go service.Serve()
//go service.HandleInbox()
//go service.ServeHTTP()
- go service.MetaWatcher()
+ go service.MetaWatcher.Run()
go service.Cruncher.Run(config.GetInt("port_tcp"))
sigterm, sighup := service.GetSignals()
|
move things around, use new MetaWatcher struct
|
pilosa_pilosa
|
train
|
c72246bdbb2c810f58a80e83b4a7f2da4fffd535
|
diff --git a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java
index <HASH>..<HASH> 100644
--- a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java
+++ b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java
@@ -380,7 +380,7 @@ public class Cursor implements Resource, Shape, Updatable, Renderable
if (viewer != null)
{
offX = (int) viewer.getX();
- offY = (int) viewer.getY() - viewer.getViewY();
+ offY = (int) viewer.getY();
}
screenX = UtilMath.clamp(screenX, minX, maxX);
diff --git a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Camera.java b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Camera.java
index <HASH>..<HASH> 100644
--- a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Camera.java
+++ b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Camera.java
@@ -416,7 +416,7 @@ public class Camera extends FeaturableModel implements Viewer
@Override
public double getViewpointY(double y)
{
- return getY() + height - y - getViewY();
+ return getY() + height - y;
}
@Override
diff --git a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/viewer/MapTileViewerModel.java b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/viewer/MapTileViewerModel.java
index <HASH>..<HASH> 100644
--- a/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/viewer/MapTileViewerModel.java
+++ b/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/viewer/MapTileViewerModel.java
@@ -143,7 +143,7 @@ public class MapTileViewerModel extends FeatureModel implements MapTileViewer
{
final int inTileHeight = (int) Math.ceil(viewer.getHeight() / (double) map.getTileHeight());
final int sy = (int) Math.floor((viewer.getY() - viewer.getViewY()) / map.getTileHeight());
- final double viewY = viewer.getY() - viewer.getViewY() + viewer.getScreenHeight() - viewer.getViewY();
+ final double viewY = viewer.getY() + viewer.getScreenHeight();
for (int v = 0; v <= inTileHeight; v++)
{
|
#<I>: Camera vertical offset fixed.
MapTileViewer model fixed.
Cursor vertical location fixed.
|
b3dgs_lionengine
|
train
|
90e54f21b639e68ac546acae14b17e8e4ddd8081
|
diff --git a/percy/client.py b/percy/client.py
index <HASH>..<HASH> 100644
--- a/percy/client.py
+++ b/percy/client.py
@@ -3,7 +3,6 @@
from percy.connection import Connection
from percy.environment import Environment
from percy.config import Config
-from percy.user_agent import UserAgent
from percy import utils
__all__ = ['Client']
@@ -14,8 +13,7 @@ class Client(object):
def __init__(self, connection=None, config=None, environment=None):
self._environment = environment if environment else Environment()
self._config = config if config else Config()
- self._user_agent = str(UserAgent(self))
- self._connection = connection if connection else Connection(self.config, self._user_agent)
+ self._connection = connection if connection else Connection(self)
@property
def connection(self):
diff --git a/percy/connection.py b/percy/connection.py
index <HASH>..<HASH> 100644
--- a/percy/connection.py
+++ b/percy/connection.py
@@ -1,9 +1,10 @@
import requests
+from percy.user_agent import UserAgent
class Connection(object):
- def __init__(self, config, user_agent):
- self.config = config
- self.user_agent = user_agent
+ def __init__(self, client):
+ self.config = client.config
+ self.user_agent = str(UserAgent(client))
def _token_header(self):
return "Token token={0}".format(self.config.access_token)
diff --git a/tests/test_connection.py b/tests/test_connection.py
index <HASH>..<HASH> 100644
--- a/tests/test_connection.py
+++ b/tests/test_connection.py
@@ -7,10 +7,10 @@ from percy import connection
class TestPercyConnection(unittest.TestCase):
def setUp(self):
- self.percy_connection = connection.Connection(
- percy.Config(access_token='foo'),
- "Percy/v1 percy-client/0.4.5 (django/1.9.4; python/2.7.13)"
- )
+ config = percy.Config(access_token='foo')
+ client = percy.Client(config=config)
+
+ self.percy_connection = connection.Connection(client)
@requests_mock.Mocker()
def test_get(self, mock):
|
turn the user agent into a string later down the chain
|
percy_python-percy-client
|
train
|
84387d179dd6ccfb4447802c531697ce37c055d0
|
diff --git a/management/src/main/java/io/micronaut/management/endpoint/loggers/impl/RxLoggersDataCollector.java b/management/src/main/java/io/micronaut/management/endpoint/loggers/impl/RxLoggersDataCollector.java
index <HASH>..<HASH> 100644
--- a/management/src/main/java/io/micronaut/management/endpoint/loggers/impl/RxLoggersDataCollector.java
+++ b/management/src/main/java/io/micronaut/management/endpoint/loggers/impl/RxLoggersDataCollector.java
@@ -27,8 +27,7 @@ public class RxLoggersDataCollector implements LoggersDataCollector<Map<String,
@Override
public Publisher<Map<String, Object>> getOne(LoggingSystem loggingSystem, String name) {
- return Single.just(loggingSystem.getLogger(name).getData())
- .toFlowable();
+ return getLogger(loggingSystem.getLogger(name)).toFlowable();
}
/**
@@ -46,6 +45,14 @@ public class RxLoggersDataCollector implements LoggersDataCollector<Map<String,
}
/**
+ * @param configuration The logger configuration
+ * @return A {@link Single} that wraps the configuration data
+ */
+ protected Single<Map<String, Object>> getLogger(LoggerConfiguration configuration) {
+ return Single.just(configuration.getData());
+ }
+
+ /**
* @return A list with all {@link LogLevel} values as strings
*/
protected Single<List<String>> getLogLevels() {
|
Break apart getOne into pattern similar to getData
|
micronaut-projects_micronaut-core
|
train
|
1520d4e1b14203a84c33e2a6247fe0383acc2805
|
diff --git a/src/main/java/hex/nn/NN.java b/src/main/java/hex/nn/NN.java
index <HASH>..<HASH> 100644
--- a/src/main/java/hex/nn/NN.java
+++ b/src/main/java/hex/nn/NN.java
@@ -466,7 +466,7 @@ public class NN extends Job.ValidatedJob {
*/
private Frame reBalance(final Frame fr, long seed) {
Frame f = force_load_balance || shuffle_training_data ? MRUtils.shuffleAndBalance(fr, seed, shuffle_training_data) : fr;
- if (f != fr) tocleanup(f);
+// if (f != fr) tocleanup(f); //triggers assert since vector groups won't match
return f;
}
|
Avoid vector group mismatch assertion by not cleaning up memory after forced load balancing. Needs a better fix.
|
h2oai_h2o-2
|
train
|
bb20e10dfd34a78673647319ae3fa04b81ec5953
|
diff --git a/openxc/src/com/openxc/sources/BytestreamDataSource.java b/openxc/src/com/openxc/sources/BytestreamDataSource.java
index <HASH>..<HASH> 100644
--- a/openxc/src/com/openxc/sources/BytestreamDataSource.java
+++ b/openxc/src/com/openxc/sources/BytestreamDataSource.java
@@ -68,15 +68,11 @@ public abstract class BytestreamDataSource extends ContextualVehicleDataSource i
received = read(bytes);
} catch(IOException e) {
Log.e(getTag(), "Unable to read response");
+ mConnectionLock.unlock();
disconnect();
continue;
}
- if(received == -1) {
- Log.w(getTag(), "Lost connection to stream");
- break;
- }
-
if(received > 0) {
buffer.receive(bytes, received);
for(String record : buffer.readLines()) {
|
Make sure vehicle interface lock is given up on error conditions.
|
openxc_openxc-android
|
train
|
a180d06cb85905444a295a7843512844ef382beb
|
diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index <HASH>..<HASH> 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -3981,8 +3981,11 @@ function delete_user(stdClass $user) {
// Force logout - may fail if file based sessions used, sorry.
\core\session\manager::kill_user_sessions($user->id);
+ // Generate username from email address, or a fake email.
+ $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
+ $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
+
// Workaround for bulk deletes of users with the same email address.
- $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
$delname++;
}
diff --git a/lib/tests/moodlelib_test.php b/lib/tests/moodlelib_test.php
index <HASH>..<HASH> 100644
--- a/lib/tests/moodlelib_test.php
+++ b/lib/tests/moodlelib_test.php
@@ -1882,6 +1882,10 @@ class core_moodlelib_testcase extends advanced_testcase {
$user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
$user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
+ $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
+ $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
+ $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
+ $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
// Delete user and capture event.
$sink = $this->redirectEvents();
@@ -1947,6 +1951,30 @@ class core_moodlelib_testcase extends advanced_testcase {
$result = delete_user($admin);
$this->assertFalse($result);
+ // Simultaneously deleting users with identical email addresses.
+ $result1 = delete_user($usersharedemail1);
+ $result2 = delete_user($usersharedemail2);
+
+ $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
+ $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
+ $this->assertTrue($result1);
+ $this->assertTrue($result2);
+ $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
+ $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
+
+ // Simultaneously deleting users without email addresses.
+ $result1 = delete_user($useremptyemail1);
+ $result2 = delete_user($useremptyemail2);
+
+ $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
+ $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
+ $this->assertTrue($result1);
+ $this->assertTrue($result2);
+ $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
+ $useremptyemail1after->username);
+ $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
+ $useremptyemail2after->username);
+
$this->resetDebugging();
}
|
MDL-<I> user: Handle bulk delete of users without email addresses
|
moodle_moodle
|
train
|
1f6c6a918467e1ce197388f3277e8635fda36656
|
diff --git a/build_libtcod.py b/build_libtcod.py
index <HASH>..<HASH> 100644
--- a/build_libtcod.py
+++ b/build_libtcod.py
@@ -7,10 +7,6 @@ import platform
from cffi import FFI
module_name = 'tcod._libtcod'
-if platform.python_implementation() == 'CPython':
- module_name += '_cp%i%i' % sys.version_info[:2]
- if platform.architecture()[0] == '64bit':
- module_name += '_x64'
def _get_library_dirs_crossplatform():
bits, linkage = platform.architecture()
diff --git a/tcod/libtcod.py b/tcod/libtcod.py
index <HASH>..<HASH> 100644
--- a/tcod/libtcod.py
+++ b/tcod/libtcod.py
@@ -45,19 +45,7 @@ _lib_ctypes = _ctypes.CDLL(
_os.path.join(__path__[0],
_get_lib_path_crossplatform(), _get_lib_name())))
-# import the right .pyd file for this Python implementation
-try:
- import _libtcod # PyPy
-except ImportError:
- # get implementation specific version of _libtcod.pyd
- import importlib as _importlib
- _module_name = '._libtcod'
- if _platform.python_implementation() == 'CPython':
- _module_name += '_cp%i%i' % _sys.version_info[:2]
- if _platform.architecture()[0] == '64bit':
- _module_name += '_x64'
-
- _libtcod = _importlib.import_module(_module_name, 'tcod')
+import _libtcod
_ffi = ffi = _libtcod.ffi
_lib = lib = _libtcod.lib
|
quit messing around with the module name
|
libtcod_python-tcod
|
train
|
b82e960b9df746e9aca1265d8327128d6ddb47f0
|
diff --git a/lib/nearley.js b/lib/nearley.js
index <HASH>..<HASH> 100644
--- a/lib/nearley.js
+++ b/lib/nearley.js
@@ -356,7 +356,7 @@
// If there is more than one derivation, we only display the first one.
var stateStacks = expectantStates
.map(function(state) {
- return this.buildFirstStateStack(state, []);
+ return this.buildFirstStateStack(state, []) || [state];
}, this);
// Display each state that is expecting a terminal symbol next.
stateStacks.forEach(function(stateStack) {
|
avoid error while reporting errors with recursive grammars.
|
kach_nearley
|
train
|
bb1ca35be235c80505d729b3b29d28c5cb4fe970
|
diff --git a/jooby/src/main/java/org/jooby/RequestLogger.java b/jooby/src/main/java/org/jooby/RequestLogger.java
index <HASH>..<HASH> 100644
--- a/jooby/src/main/java/org/jooby/RequestLogger.java
+++ b/jooby/src/main/java/org/jooby/RequestLogger.java
@@ -250,9 +250,8 @@ public class RequestLogger implements Route.Handler {
sb.append(Q).append(req.method());
sb.append(SP);
sb.append(req.path());
- if (queryString && req.queryString().isPresent()) {
- sb.append(QUERY);
- sb.append(req.queryString().get());
+ if (queryString) {
+ req.queryString().ifPresent(s -> sb.append(QUERY).append(s));
}
sb.append(SP);
sb.append(req.protocol());
diff --git a/jooby/src/test/java/org/jooby/RequestLoggerTest.java b/jooby/src/test/java/org/jooby/RequestLoggerTest.java
index <HASH>..<HASH> 100644
--- a/jooby/src/test/java/org/jooby/RequestLoggerTest.java
+++ b/jooby/src/test/java/org/jooby/RequestLoggerTest.java
@@ -172,7 +172,7 @@ public class RequestLoggerTest {
private Block query(final String query) {
return unit -> {
Request req = unit.get(Request.class);
- expect(req.queryString()).andReturn(Optional.of(query)).atLeastOnce();
+ expect(req.queryString()).andReturn(Optional.of(query));
};
}
|
Refactor handling queryString in RequestLogger
|
jooby-project_jooby
|
train
|
1813184d805e6fe109a410667783d6457c96bced
|
diff --git a/src/main/java/com/googlecode/lanterna/terminal/ansi/ANSITerminal.java b/src/main/java/com/googlecode/lanterna/terminal/ansi/ANSITerminal.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/googlecode/lanterna/terminal/ansi/ANSITerminal.java
+++ b/src/main/java/com/googlecode/lanterna/terminal/ansi/ANSITerminal.java
@@ -228,32 +228,42 @@ public abstract class ANSITerminal extends StreamBasedTerminal implements Extend
@Override
public void iconify() throws IOException {
- throw new UnsupportedOperationException("Not implemented yet");
+ writeCSISequenceToTerminal((byte)'2', (byte)'t');
}
@Override
public void deiconify() throws IOException {
- throw new UnsupportedOperationException("Not implemented yet");
+ writeCSISequenceToTerminal((byte)'1', (byte)'t');
}
@Override
public void maximize() throws IOException {
- throw new UnsupportedOperationException("Not implemented yet");
+ writeCSISequenceToTerminal((byte)'9', (byte)';', (byte)'1', (byte)'t');
}
@Override
public void unmaximize() throws IOException {
- throw new UnsupportedOperationException("Not implemented yet");
+ writeCSISequenceToTerminal((byte)'9', (byte)';', (byte)'0', (byte)'t');
}
@Override
public void setMouseMovementCapturingEnabled(boolean enabled) throws IOException {
- throw new UnsupportedOperationException("Not implemented yet");
+ if(enabled) {
+ writeCSISequenceToTerminal((byte)'?', (byte)'1', (byte)'0', (byte)'0', (byte)'3', (byte)'h');
+ }
+ else {
+ writeCSISequenceToTerminal((byte)'?', (byte)'1', (byte)'0', (byte)'0', (byte)'3', (byte)'l');
+ }
}
@Override
- public void setMouseClicksCapturingEnabled(boolean enable) throws IOException {
- throw new UnsupportedOperationException("Not implemented yet");
+ public void setMouseClicksCapturingEnabled(boolean enabled) throws IOException {
+ if(enabled) {
+ writeCSISequenceToTerminal((byte)'?', (byte)'1', (byte)'0', (byte)'0', (byte)'0', (byte)'h');
+ }
+ else {
+ writeCSISequenceToTerminal((byte)'?', (byte)'1', (byte)'0', (byte)'0', (byte)'0', (byte)'l');
+ }
}
/**
|
Implementing a couple of weird Xterm extensions, even if the input system doesn't support them yet
|
mabe02_lanterna
|
train
|
1efbc2dc81b4e055bfcf5f3bb9fc262c03f832c0
|
diff --git a/webapps/client/scripts/pages/processInstance.js b/webapps/client/scripts/pages/processInstance.js
index <HASH>..<HASH> 100644
--- a/webapps/client/scripts/pages/processInstance.js
+++ b/webapps/client/scripts/pages/processInstance.js
@@ -679,12 +679,73 @@ define([
authentication: 'required',
resolve: {
processInstance: [
- 'ResourceResolver', 'ProcessInstanceResource',
- function(ResourceResolver, ProcessInstanceResource) {
+ 'ResourceResolver', 'ProcessInstanceResource', 'Uri', 'Views', 'Notifications', '$route', '$http', '$location',
+ function(ResourceResolver, ProcessInstanceResource, Uri, Views, Notifications, $route, $http, $location) {
+
return ResourceResolver.getByRouteParam('id', {
- name: 'process instance',
+ name: 'running process instance',
+
resolve: function(id) {
return ProcessInstanceResource.get({ id : id });
+ },
+
+ redirectTo: function (error) {
+ var id = $route.current.params['id'];
+
+ $http.get(Uri.appUri('engine://engine/:engine/history/process-instance/') + id)
+ .success (function(result) {
+
+ var path;
+ var search;
+
+ var status = 'Unable to display running process instance';
+ var message = 'Process instance with ID ' + id + ' has been completed. Redirecting to ';
+
+ var historyProvider = Views.getProvider({
+ id: 'history',
+ component: 'cockpit.processInstance.view'
+ });
+
+ if (historyProvider) {
+ var currentPath = $location.path();
+ // keep search params
+ search = $location.search();
+ path = '/process-instance/' + id + '/history';
+
+ message = message + 'historic process instance view.';
+ }
+ else {
+ path = '/process-definition/' + result.processDefinitionId;
+
+ message = message + 'process definition view.';
+ }
+
+ $location.path(path);
+ $location.search(search || {});
+ $location.replace();
+
+ Notifications.addMessage({
+ status: status,
+ message: message,
+ http: true,
+ exclusive: [ 'http' ],
+ duration: 5000
+ });
+
+ })
+ .error (function(error) {
+
+ $location.path('/dashboard');
+ $location.search({});
+ $location.replace();
+
+ Notifications.addError({
+ status: 'Failed to display running process instance',
+ message: 'No running process instance with ID ' + id,
+ http: true,
+ exclusive: [ 'http' ]
+ });
+ });
}
});
}]
|
fix(redirection): improve redirections
If someone tries to open an already completed process instance, then
* if the process definition id can be determined and the history plugin is available -> redirect to historic process instance view
* if the process definition id can be determined -> redirect to process definition view
* otherwise redirect to dashboard
related to CAM-<I>, CAM-<I>
|
camunda_camunda-bpm-platform
|
train
|
830a729843c3a9d0201940d5c195218dcba2f8d1
|
diff --git a/test/favicon.test.js b/test/favicon.test.js
index <HASH>..<HASH> 100644
--- a/test/favicon.test.js
+++ b/test/favicon.test.js
@@ -23,7 +23,7 @@ test('default favicon does not return an error, but a good response (200) and so
t.plan(6)
const defaultPath = './src'
const fastify = Fastify()
- t.tearDown(fastify.close.bind(fastify))
+ t.teardown(fastify.close.bind(fastify))
fastify.register(require('../')) // configure this plugin with its default options
@@ -54,7 +54,7 @@ test('return a favicon configured in a custom path', (t) => {
t.plan(6)
const pathSample = './test'
const fastify = Fastify()
- t.tearDown(fastify.close.bind(fastify))
+ t.teardown(fastify.close.bind(fastify))
fastify.register(require('../'), {
path: pathSample
})
@@ -87,7 +87,7 @@ test('return default favicon because that in the custom path is not found', (t)
const pathSample = './test/not-existing-img-path' // path that here does not exist, good for this test
const defaultPath = './src'
const fastify = Fastify()
- t.tearDown(fastify.close.bind(fastify))
+ t.teardown(fastify.close.bind(fastify))
fastify.register(require('../'), {
path: pathSample
})
|
update deprecated calls in tap tests
|
smartiniOnGitHub_fastify-favicon
|
train
|
5aeff2c7d2800a3bb1f2ca09ded460d104e81eab
|
diff --git a/src/Test.php b/src/Test.php
index <HASH>..<HASH> 100644
--- a/src/Test.php
+++ b/src/Test.php
@@ -176,6 +176,34 @@ abstract class Test extends \PHPUnit_Framework_TestCase {
});
}
+ function testUnreferencedDeferWatcherStillExecutes()
+ {
+ $invoked = false;
+ $this->start(function(Driver $loop) use (&$invoked) {
+ $watcher = $loop->defer(function () use (&$invoked) {
+ $invoked = true;
+ });
+ $loop->unreference($watcher);
+ $loop->defer(function () {
+ // just to keep loop running
+ });
+ });
+ $this->assertTrue($invoked);
+ }
+
+ function testLoopDoesNotBlockOnNegativeTimerExpiration()
+ {
+ $invoked = false;
+ $this->start(function(Driver $loop) use (&$invoked) {
+ $loop->delay(1, function () use (&$invoked) {
+ $invoked = true;
+ });
+
+ usleep(1000 * 10);
+ });
+ $this->assertTrue($invoked);
+ }
+
function testDisabledDeferReenableInSubsequentTick()
{
$this->expectOutputString("123");
|
Add tests to ensure unreferenced watchers are still executed and negative expiration doesn't create issues
|
amphp_amp
|
train
|
66ff78585109b4141125385802aa470300cb814c
|
diff --git a/filters/AuthFilter.php b/filters/AuthFilter.php
index <HASH>..<HASH> 100644
--- a/filters/AuthFilter.php
+++ b/filters/AuthFilter.php
@@ -32,9 +32,6 @@ class AuthFilter extends CFilter
/* @var $user CWebUser */
$user = Yii::app()->getUser();
- if ($user->isGuest)
- $user->loginRequired();
-
if (($module = $controller->getModule()) !== null)
{
$itemName .= $module->getId() . '.';
@@ -50,6 +47,9 @@ class AuthFilter extends CFilter
if ($user->checkAccess($itemName, $this->params))
return true;
+ if ($user->isGuest)
+ $user->loginRequired();
+
throw new CHttpException(401, 'Access denied.');
}
}
|
Moved guest check so as to not assume that unauthenticated user will not have permissions #<I>
|
crisu83_yii-auth
|
train
|
f3fa28099e2c4d027b21bc16a186bdf237948ead
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -2,9 +2,13 @@ import os
import sys
import codecs
from setuptools import setup
+from warnings import warn
+
+if sys.version_info < (3, 0, 0):
+ raise RuntimeError("ib_insync is for Python 3")
if sys.version_info < (3, 6, 0):
- raise RuntimeError("ib_insync requires Python 3.6 or higher")
+ warn("ib_insync requires Python 3.6 or higher")
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
|
relax python version to install
|
erdewit_ib_insync
|
train
|
7a46e5d40afae8c6b67415419b6426129f3970bd
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -148,7 +148,11 @@ function ApostropheSchemas(options, callback) {
if (field) {
field.group = group.name;
} else {
- throw new Error('Nonexistent field ' + name + ' referenced by groups option in schemas.compose');
+ // Tolerate nonexistent fields in groupFields. This
+ // will happen if a subclass uses removeFields and
+ // doesn't set up a new groupFields option, which
+ // is reasonable
+ return;
}
});
});
|
Tolerate nonexistent fields in groupFields so that removeFields doesn't trigger hassles
|
apostrophecms-legacy_apostrophe-schemas
|
train
|
9d4d6ea5e565c0b17465fd5402c02996bf7a870a
|
diff --git a/acceptance/tests/security/cve-2013-1640_facter_string.rb b/acceptance/tests/security/cve-2013-1640_facter_string.rb
index <HASH>..<HASH> 100644
--- a/acceptance/tests/security/cve-2013-1640_facter_string.rb
+++ b/acceptance/tests/security/cve-2013-1640_facter_string.rb
@@ -2,6 +2,10 @@
# template compilation on the master allowing remote code execution by
# any authenticated client.
test_name "CVE 2013-1640 Remote Code Execution" do
+
+ tag 'audit:high', # low risk, high (security) impact
+ 'audit:integration'
+
confine :except, :platform => 'windows'
confine :except, :platform => 'cisco_nexus' # See BKR-749
diff --git a/acceptance/tests/security/cve-2013-1652_improper_query_params.rb b/acceptance/tests/security/cve-2013-1652_improper_query_params.rb
index <HASH>..<HASH> 100644
--- a/acceptance/tests/security/cve-2013-1652_improper_query_params.rb
+++ b/acceptance/tests/security/cve-2013-1652_improper_query_params.rb
@@ -5,6 +5,10 @@ test_name "CVE 2013-1652 Improper query parameter validation" do
confine :except, :platform => /osx/ # see PUP-4820
confine :except, :platform => /aix/
+ tag 'audit:high', # risk low, high (security) impact
+ 'audit:integration',
+ 'server'
+
with_puppet_running_on master, {} do
# Ensure each agent has a signed cert
on agents, puppet('agent', "-t --server #{master}" )
diff --git a/acceptance/tests/security/cve-2013-1652_poison_other_node_cache.rb b/acceptance/tests/security/cve-2013-1652_poison_other_node_cache.rb
index <HASH>..<HASH> 100644
--- a/acceptance/tests/security/cve-2013-1652_poison_other_node_cache.rb
+++ b/acceptance/tests/security/cve-2013-1652_poison_other_node_cache.rb
@@ -1,5 +1,9 @@
test_name "CVE 2013-1652 Poison node cache" do
+ tag 'audit:high', # low risk, high (security) impact
+ 'audit:integration', # master side only
+ 'server'
+
step "Determine suitability of the test" do
skip_test( "This test will only run on Puppet 3.x" ) if
on(master, puppet('--version')).stdout =~ /\A2\./
diff --git a/acceptance/tests/security/cve-2013-2275_report_acl.rb b/acceptance/tests/security/cve-2013-2275_report_acl.rb
index <HASH>..<HASH> 100644
--- a/acceptance/tests/security/cve-2013-2275_report_acl.rb
+++ b/acceptance/tests/security/cve-2013-2275_report_acl.rb
@@ -1,4 +1,10 @@
test_name "(#19531) report save access control"
+
+tag 'audit:high', # low risk, high (security) impact
+ 'audit:refactor', # Use block style `test_name`
+ 'audit:integration', # issue completely on the server side
+ 'server'
+
step "Verify puppet only allows saving reports from the node matching the certificate"
fake_report = <<-EOYAML
diff --git a/acceptance/tests/security/cve-2013-4761_injection_of_class_names_loading_code.rb b/acceptance/tests/security/cve-2013-4761_injection_of_class_names_loading_code.rb
index <HASH>..<HASH> 100644
--- a/acceptance/tests/security/cve-2013-4761_injection_of_class_names_loading_code.rb
+++ b/acceptance/tests/security/cve-2013-4761_injection_of_class_names_loading_code.rb
@@ -1,6 +1,10 @@
test_name "CVE 2013-4761 Injection of bad class names causing code loading" do
confine :except, :platform => 'windows'
+ tag 'audit:high', # low risk, high (security) impact
+ 'audit:integration', # issue is completely on the master side
+ 'server'
+
testdir = create_tmpdir_for_user master, 'class-names-injection'
exploit_path = "#{testdir}/exploit.rb"
exploited_path = "#{testdir}/exploited"
|
(PUP-<I>) Audit Acceptance Tests - CVE tests
|
puppetlabs_puppet
|
train
|
eeb9fda8e27be6c5c0ff988e0cde2b3a489a2dca
|
diff --git a/actioncable/lib/action_cable/connection/base.rb b/actioncable/lib/action_cable/connection/base.rb
index <HASH>..<HASH> 100644
--- a/actioncable/lib/action_cable/connection/base.rb
+++ b/actioncable/lib/action_cable/connection/base.rb
@@ -48,11 +48,9 @@ module ActionCable
include InternalChannel
include Authorization
- attr_reader :server, :env, :subscriptions
+ attr_reader :server, :env, :subscriptions, :logger
delegate :worker_pool, :pubsub, to: :server
- attr_reader :logger
-
def initialize(server, env)
@server, @env = server, env
@@ -123,7 +121,6 @@ module ActionCable
transmit ActiveSupport::JSON.encode(identifier: ActionCable::INTERNAL[:identifiers][:ping], message: Time.now.to_i)
end
-
protected
# The request that initiated the WebSocket connection is available here. This gives access to the environment, cookies, etc.
def request
@@ -138,8 +135,6 @@ module ActionCable
request.cookie_jar
end
-
- protected
attr_reader :websocket
attr_reader :message_buffer
@@ -170,7 +165,6 @@ module ActionCable
disconnect if respond_to?(:disconnect)
end
-
def allow_request_origin?
return true if server.config.disable_request_forgery_protection
@@ -193,7 +187,6 @@ module ActionCable
[ 404, { 'Content-Type' => 'text/plain' }, [ 'Page not found' ] ]
end
-
# Tags are declared in the server but computed in the connection. This allows us per-connection tailored tags.
def new_tagged_logger
TaggedLoggerProxy.new server.logger,
diff --git a/actioncable/lib/action_cable/connection/subscriptions.rb b/actioncable/lib/action_cable/connection/subscriptions.rb
index <HASH>..<HASH> 100644
--- a/actioncable/lib/action_cable/connection/subscriptions.rb
+++ b/actioncable/lib/action_cable/connection/subscriptions.rb
@@ -49,7 +49,6 @@ module ActionCable
find(data).perform_action ActiveSupport::JSON.decode(data['data'])
end
-
def identifiers
subscriptions.keys
end
|
[ActionCable] remove not needed protected call and newlines
|
rails_rails
|
train
|
fa77b2307e7caab69b67757f03e2aebc4f8dbcd6
|
diff --git a/src/Element/Identify.php b/src/Element/Identify.php
index <HASH>..<HASH> 100644
--- a/src/Element/Identify.php
+++ b/src/Element/Identify.php
@@ -21,7 +21,7 @@ trait Identify
*/
public function name() : string
{
- return $this->attributes['name'];
+ return $this->attributes['name'] ?? '';
}
/**
|
might be unset, return empty string in that case
|
monolyth-php_formulaic
|
train
|
4b71d63806fbda8872f8f84cae47a01f22028a31
|
diff --git a/test/python/circuit/test_gate_definitions.py b/test/python/circuit/test_gate_definitions.py
index <HASH>..<HASH> 100644
--- a/test/python/circuit/test_gate_definitions.py
+++ b/test/python/circuit/test_gate_definitions.py
@@ -47,3 +47,35 @@ class TestGateDefinitions(QiskitTestCase):
circ.crz(1, 0, 1)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
+
+ def test_cswap_definition(self):
+ """Test cswap gate matrix and definition.
+ """
+ circ = QuantumCircuit(3)
+ circ.cswap(0, 1, 2)
+ decomposed_circ = circ.decompose()
+ self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
+
+ def test_cu1_defintion(self):
+ """Test cu1 gate matrix and definition.
+ """
+ circ = QuantumCircuit(2)
+ circ.cu1(1, 0, 1)
+ decomposed_circ = circ.decompose()
+ self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
+
+ def test_cu3_definition(self):
+ """Test cu3 gate matrix and definition.
+ """
+ circ = QuantumCircuit(2)
+ circ.cu3(1, 1, 1, 0, 1)
+ decomposed_circ = circ.decompose()
+ self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
+
+ def test_cx_definition(self):
+ """Test cx gate matrix and definition.
+ """
+ circ = QuantumCircuit(2)
+ circ.cx(0, 1)
+ decomposed_circ = circ.decompose()
+ self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
|
Added tests for definitions of cswap, cu1, cu3, cx (#<I>)
Partially fixes #<I>
Added in tests for cswap, cu1, cu3 and cx under test_gate_definitions
|
Qiskit_qiskit-terra
|
train
|
40818b78006be49b51de4bebc2d4bd28d1246500
|
diff --git a/src/Codeception/Command/WPBootstrap.php b/src/Codeception/Command/WPBootstrap.php
index <HASH>..<HASH> 100644
--- a/src/Codeception/Command/WPBootstrap.php
+++ b/src/Codeception/Command/WPBootstrap.php
@@ -101,12 +101,6 @@ class WPBootstrap extends Bootstrap
],
'modules' => [
'config' => [
- 'Db' => [
- 'dsn' => 'mysql:host=localhost;dbname=wordpress-tests',
- 'user' => 'root',
- 'password' => 'root',
- 'dump' => 'tests/_data/dump.sql'
- ],
'WPBrowser' => [
'url' => 'http://wp.local',
'adminUsername' => 'adminUsername',
|
removed the Db module config from the WPBootstrap command
|
lucatume_wp-browser
|
train
|
e366b6e25aae87624f2669900ab9cc4af4a9e1fa
|
diff --git a/src/Views/layouts/master.blade.php b/src/Views/layouts/master.blade.php
index <HASH>..<HASH> 100644
--- a/src/Views/layouts/master.blade.php
+++ b/src/Views/layouts/master.blade.php
@@ -116,7 +116,6 @@
<li><a href="{{ url('/auth/logout') }}"><i class="fa fa-fw fa-sign-out"></i> Logout</a></li>
</ul>
</li>
- <li><a href="#"></a></li>
@endif
</ul>
</div>
|
removed extra list-item that slipped into layouts.master
|
SmarchSoftware_watchtower
|
train
|
782cedbeebd59b25f957e33d62d82696289f10b6
|
diff --git a/src/Mmanos/Casset/CassetServiceProvider.php b/src/Mmanos/Casset/CassetServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Mmanos/Casset/CassetServiceProvider.php
+++ b/src/Mmanos/Casset/CassetServiceProvider.php
@@ -18,7 +18,7 @@ class CassetServiceProvider extends ServiceProvider {
*/
public function boot()
{
- $this->package('mmanos/casset');
+ $this->package('mmanos/laravel-casset');
}
/**
diff --git a/src/Mmanos/Casset/container.php b/src/Mmanos/Casset/container.php
index <HASH>..<HASH> 100644
--- a/src/Mmanos/Casset/container.php
+++ b/src/Mmanos/Casset/container.php
@@ -68,15 +68,15 @@ class Container
public function __construct($name)
{
$this->name = $name;
- $this->combine = \Config::get('casset::combine', true);
- $this->minify = \Config::get('casset::minify', true);
+ $this->combine = \Config::get('laravel-casset::combine', true);
+ $this->minify = \Config::get('laravel-casset::minify', true);
$this->public_path = public_path();
$this->assets_path = $this->public_path
. '/'
- . trim(\Config::get('casset::assets_dir', 'assets'), '/');
+ . trim(\Config::get('laravel-casset::assets_dir', 'assets'), '/');
$this->cache_path = $this->public_path
. '/'
- . trim(\Config::get('casset::cache_dir', 'assets/cache'), '/');
+ . trim(\Config::get('laravel-casset::cache_dir', 'assets/cache'), '/');
}
/**
|
Renamed registered package name with Laravel to fix issues with config names, etc...
|
mmanos_laravel-casset
|
train
|
16cae42f22a0e2de9b19b6ff566e03db07ff5b64
|
diff --git a/dolo/algos/dtcscc/perfect_foresight.py b/dolo/algos/dtcscc/perfect_foresight.py
index <HASH>..<HASH> 100644
--- a/dolo/algos/dtcscc/perfect_foresight.py
+++ b/dolo/algos/dtcscc/perfect_foresight.py
@@ -15,33 +15,6 @@ def _shocks_to_epsilons(model, shocks, T):
"""
n_e = len(model.calibration['shocks'])
- # flag to make sure we have constructed the epsilon matrix from the
- # `shocks` input
- _constructed_epsilon = False
-
- # read from calibration if not given
- if shocks is None:
- shocks = model.calibration["shocks"]
-
- # convert to array if a list was given
- if isinstance(shocks, list):
- shocks = np.asarray(shocks)
-
- # process array input.
- if isinstance(shocks, np.ndarray):
- if shocks.ndim == 1 and n_e > 1:
- msg = "Ambiguous specification of shocks. Input was 1d, but model\
- has {0} shocks. Use shocks as 2d array, dict, or DataFrame instead"
- raise ValueError(msg.format(n_e))
- shocks = shocks.reshape((-1, n_e))
-
- # until last period, exogenous shock takes its last value
- epsilons = np.zeros((T+1, n_e))
- epsilons[:(shocks.shape[0]-1), :] = shocks[1:, :]
- epsilons[(shocks.shape[0]-1):, :] = shocks[-1:, :]
-
- _constructed_epsilon = True
-
# if we have a DataFrame, convert it to a dict and rely on the method below
if isinstance(shocks, pd.DataFrame):
shocks = {k: shocks[k].tolist() for k in shocks.columns}
@@ -59,13 +32,21 @@ def _shocks_to_epsilons(model, shocks, T):
# otherwise set to value in calibration
epsilons[:, i] = model.calibration["shocks"][i]
- _constructed_epsilon = True
+ return epsilons
+
+ # read from calibration if not given
+ if shocks is None:
+ shocks = model.calibration["shocks"]
+
+ # now we just assume that shocks is array-like and try using the output of
+ # np.asarray(shocks)
+ shocks = np.asarray(shocks)
+ shocks = shocks.reshape((-1, n_e))
- if not _constructed_epsilon:
- msg = "Did not understand shocks. Expected type to be one of \
- {valid} but found {found}"
- raise ValueError(msg.format(valid="list, array, dict, or DataFrame",
- found=type(shocks)))
+ # until last period, exogenous shock takes its last value
+ epsilons = np.zeros((T+1, n_e))
+ epsilons[:(shocks.shape[0]-1), :] = shocks[1:, :]
+ epsilons[(shocks.shape[0]-1):, :] = shocks[-1:, :]
return epsilons
@@ -84,21 +65,16 @@ def deterministic_solve(model, shocks=None, start_states=None, T=100,
----------
model : NumericModel
"fg" or "fga" model to be solved
- shocks : list, ndarray, dict, or pandas.DataFrame
+ shocks : array-like, dict, or pandas.DataFrame
A specification of the shocks to the model. Can be any of the
following (note by "declaration order" below we mean the order
of `model.symbols["shocks"]`):
- - A list specifying a time series for each shock. If `model`
- has one shock, the values can be number. If `model` as more
- than one shock, the values should be lists or array-like
- sequences that specify the time series for different shocks
- in declaration order
- - A 1d numpy array specifying a time series for a single shock.
- Only valid in one shock models.
+ - A 1d numpy array-like specifying a time series for a single
+ shock, or all shocks stacked into a single array.
- A 2d numpy array where each column specifies the time series
for one of the shocks in declaration order. This must be an
- `N` by number of shocks matrix.
+ `N` by number of shocks 2d array.
- A dict where keys are strings found in
`model.symbols["shocks"]` and values are a time series of
values for that shock. For model shocks that do not appear in
|
ENH: remove explicit list doc and handling in perfect_foresight
|
EconForge_dolo
|
train
|
927f1ea1cd023a46321f1b9a6cca4d7e87fb783c
|
diff --git a/src/db/index.js b/src/db/index.js
index <HASH>..<HASH> 100644
--- a/src/db/index.js
+++ b/src/db/index.js
@@ -26,7 +26,7 @@ class Db extends EventEmitter {
this.setup = db.setup.bind(db);
}
- delete(_id, store, cb = () => {}) {
+ delete(_id, store, cb = () => { }) {
this.getUser("system", (err, user) => {
if (err) {
return cb(err, null);
@@ -229,10 +229,14 @@ class Db extends EventEmitter {
break;
default:
if (process.env.NODE_ENV === "test") {
- return cb(null, {
- "_id": userId,
- "roles": ["root"],
- });
+ if (userId === "UNKNOWN") {
+ return cb(null, null);
+ } else {
+ return cb(null, {
+ "_id": userId,
+ "roles": ["root"],
+ });
+ }
}
db.get(userId, "users", cb);
break;
diff --git a/src/taskRunner.js b/src/taskRunner.js
index <HASH>..<HASH> 100644
--- a/src/taskRunner.js
+++ b/src/taskRunner.js
@@ -25,7 +25,7 @@ module.exports.test = {
},
"validateTask": validateTask,
"runTask": runTask,
- "getUser": $db._getUser,
+ "getUser": $db.getUser,
};
function getTask() {
@@ -58,7 +58,12 @@ function runTask(task) {
sendTaskError(task, "Store not found");
return;
}
- $db._getUser(task.userId, (error, user) => {
+ $db.getUser(task.userId, (error, user) => {
+ if (user == null) {
+ sendTaskError(task, "User not found");
+ emitter.emit("taskUserNotFoundError", task);
+ return;
+ }
if (!auth(task, user, storeDesc)) {
sendTaskError(task, "Unauthorized");
emitter.emit("taskAuthorizationError", task);
diff --git a/tests/takRunnerTests.js b/tests/takRunnerTests.js
index <HASH>..<HASH> 100644
--- a/tests/takRunnerTests.js
+++ b/tests/takRunnerTests.js
@@ -93,6 +93,20 @@ describe("taskRunner", function () {
let c = wampMock.calls[taskUris.error][0];
assert.equal(c.args[1], "Store not found");
});
+ it("should call error 'User not found' when no store for task", function (done) {
+ let taskData = { "id": Math.random(), "userId": "UNKNOWN" };
+ var h = function (t) {
+ if (taskData.id === t.id) {
+ assert.equal(wampMock.getCallsCount(taskUris.error), 1);
+ let c = wampMock.calls[taskUris.error][0];
+ assert.equal(c.args[1], "User not found");
+ taskRunner.removeListener("taskUserNotFoundError", h);
+ done();
+ }
+ };
+ taskRunner.on("taskUserNotFoundError", h);
+ taskRunner.test.runTask(getTask(taskData));
+ });
it("should call error 'Unauthorized' when no access to store", function (done) {
let taskData = { "id": Math.random(), "store": "deniedStore1" };
var h = function (t) {
|
Add TaskRunner 'User not found' error handling
|
getblank_blank-node-worker
|
train
|
2727ff728097b1a8075c91de8d6b452a83384726
|
diff --git a/actor/appium/src/main/java/org/getopentest/appium/core/AppiumTestAction.java b/actor/appium/src/main/java/org/getopentest/appium/core/AppiumTestAction.java
index <HASH>..<HASH> 100644
--- a/actor/appium/src/main/java/org/getopentest/appium/core/AppiumTestAction.java
+++ b/actor/appium/src/main/java/org/getopentest/appium/core/AppiumTestAction.java
@@ -351,29 +351,12 @@ public abstract class AppiumTestAction extends TestAction {
}
protected void swipe(int fromX, int fromY, int toX, int toY, int durationMs) {
- // As of Appium 1.7.1, the TouchAction.moveTo() method assumes absolute
- // coordinates for Android and relative coordinates on iOS. The mess that
- // follows below is necessary to work around this inconsistency.
- if (AppiumHelper.isPlatform("ios") && AppiumHelper.getConfig().getBoolean("appium.useRelativeCoordsIos", true)) {
- int relativeX = toX - fromX;
- int relativeY = toY - fromY;
-
- (new TouchAction(driver))
- .press(PointOption.point(fromX, fromY))
- // We had to comment the next line to avoid an issue where the
- // swipe fails if the start position happens to overlap a button
- //.waitAction(WaitOptions.waitOptions(Duration.ofMillis(durationMs)))
- .moveTo(PointOption.point(relativeX, relativeY))
- .release()
- .perform();
- } else {
- (new TouchAction(driver))
- .press(PointOption.point(fromX, fromY))
- .waitAction(WaitOptions.waitOptions(Duration.ofMillis(durationMs)))
- .moveTo(PointOption.point(toX, toY))
- .release()
- .perform();
- }
+ (new TouchAction(driver))
+ .press(PointOption.point(fromX, fromY))
+ .waitAction(WaitOptions.waitOptions(Duration.ofMillis(durationMs)))
+ .moveTo(PointOption.point(toX, toY))
+ .release()
+ .perform();
}
/**
|
fix(appium): update iOS swipe logic as per Appium client <I>
|
mcdcorp_opentest
|
train
|
5c0a05bdecaf95b065645b1dceca45d03f3a541b
|
diff --git a/README.markdown b/README.markdown
index <HASH>..<HASH> 100644
--- a/README.markdown
+++ b/README.markdown
@@ -99,11 +99,17 @@ If you encounter any errors in the code, please file an issue: <https://github.c
### Version
-* Version: 0.9
-* Release Date: 2013-02-27
+* Version: 0.9.1
+* Release Date: 2013-03-03
### Revision History
+### Version 0.9.1
+
+* Release Date: 2013-03-03
+* Changes:
+ * Merged [pull request](https://github.com/quandyfactory/dict2xml/pull/5) from [regisd](https://github.com/regisd) to fix [issue #5](https://github.com/quandyfactory/dict2xml/issues/5), in which special XML characters were not being escaped properly.
+
### Version 0.9
* Release Date: 2013-02-27
diff --git a/dicttoxml.py b/dicttoxml.py
index <HASH>..<HASH> 100755
--- a/dicttoxml.py
+++ b/dicttoxml.py
@@ -4,7 +4,7 @@
"""
Converts a native Python dictionary into an XML string. Supports int, float, str, unicode, list, dict and arbitrary nesting.
"""
-__version__ = 0.9
+__version__ = 0.9.1
debug = False
def debug_notify(*args):
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,16 +1,16 @@
from distutils.core import setup
-version = '0.9'
+version = '0.91'
setup(
name = 'dicttoxml',
version = version,
description = 'Converts a native Python dictionary into an XML string.',
- long_description = """* Supports item (`int`, `float`, `bool`, `str`, `unicode`, `datetime`) and collection (`list`, `set` and `dict`) data types with arbitrary nesting for the collections. Datetime objects are converted to ISO format strings.
+ long_description = """* Supports item (`int`, `float`, `bool`, `str`, `unicode`, `datetime`, `none`) and collection (`list`, `set`, `tuple` and `dict`) data types with arbitrary nesting for the collections. Items with a `datetime` type are converted to ISO format strings. Items with a `none` type become empty XML elements.
-* The root object passed into the `dict2xml` function can be any of the following data types: `int`, `float`, `str`, `unicode`, `datetime`, `list`, `set`, `dict`.
+* The root object passed into the `dicttoxml` function can be any of the supported data types.
-* To satisfy XML syntax, by default it wraps all the dict keys/elements and values in a `<root> ... </root>` element. However, this can be disabled to create XML snippets.
+* To satisfy XML syntax, the method wraps all the dict keys/elements and values in a `<root> ... </root>` element. However, this can be disabled to create XML snippets.
* For lists of items, if each item is also a collection data type (`lists`, `dict`), the elements of that item are wrapped in a generic `<item> ... </item>` element.
|
v <I> merged pull request from regisd to fix issue #5 <URL>
|
quandyfactory_dicttoxml
|
train
|
6e1168ecda1c8d3bc8ea94e1230ccc1d351a5502
|
diff --git a/dht_test.go b/dht_test.go
index <HASH>..<HASH> 100644
--- a/dht_test.go
+++ b/dht_test.go
@@ -3,6 +3,7 @@ package dht
import (
"encoding/hex"
"errors"
+ "io"
"log"
"math/big"
"net"
@@ -266,11 +267,13 @@ func TestBadGetPeersResponse(t *testing.T) {
func TestBootstrapRace(t *testing.T) {
remotePc, err := inproc.ListenPacket("", "localhost:0")
require.NoError(t, err)
- serverPc, err := inproc.ListenPacket("", "localhost:0")
- require.NoError(t, err)
+ defer remotePc.Close()
+ serverPc := bootstrapRacePacketConn{
+ read: make(chan read),
+ }
t.Logf("remote addr: %s", remotePc.LocalAddr())
s, err := NewServer(&ServerConfig{
- Conn: serverPc,
+ Conn: &serverPc,
StartingNodes: addrResolver(remotePc.LocalAddr().String()),
QueryResendDelay: func() time.Duration { return 0 },
})
@@ -302,44 +305,50 @@ type emptyNetAddr struct{}
func (emptyNetAddr) Network() string { return "" }
func (emptyNetAddr) String() string { return "" }
-type writeErrorPacketConn struct {
+type read struct {
+ b []byte
+ addr net.Addr
+}
+
+type bootstrapRacePacketConn struct {
mu sync.Mutex
writes int
+ read chan read
}
-func (me writeErrorPacketConn) Close() error { return nil }
-func (me writeErrorPacketConn) LocalAddr() net.Addr { return emptyNetAddr{} }
-func (me *writeErrorPacketConn) ReadFrom([]byte) (int, net.Addr, error) { select {} }
-func (me writeErrorPacketConn) SetDeadline(time.Time) error { return nil }
-func (me writeErrorPacketConn) SetReadDeadline(time.Time) error { return nil }
-func (me writeErrorPacketConn) SetWriteDeadline(time.Time) error { return nil }
+func (me *bootstrapRacePacketConn) Close() error {
+ close(me.read)
+ return nil
+}
+func (me bootstrapRacePacketConn) LocalAddr() net.Addr { return emptyNetAddr{} }
+func (me *bootstrapRacePacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
+ r, ok := <-me.read
+ if !ok {
+ return 0, nil, io.EOF
+ }
+ copy(b, r.b)
+ log.Printf("reading %q from %s", r.b, r.addr)
+ return len(r.b), r.addr, nil
+}
+func (me bootstrapRacePacketConn) SetDeadline(time.Time) error { return nil }
+func (me bootstrapRacePacketConn) SetReadDeadline(time.Time) error { return nil }
+func (me bootstrapRacePacketConn) SetWriteDeadline(time.Time) error { return nil }
-func (me *writeErrorPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
+func (me *bootstrapRacePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
me.mu.Lock()
defer me.mu.Unlock()
me.writes++
log.Printf("wrote %d times", me.writes)
if me.writes == maxTransactionSends {
+ var m krpc.Msg
+ bencode.Unmarshal(b[:], &m)
+ m.Y = "r"
+ rb, err := bencode.Marshal(m)
+ if err != nil {
+ panic(err)
+ }
+ me.read <- read{rb, addr}
return 0, errors.New("write error")
}
return len(b), nil
}
-
-func TestBootstrapRaceWriteError(t *testing.T) {
- remotePc, err := inproc.ListenPacket("", "localhost:0")
- require.NoError(t, err)
- defer remotePc.Close()
- serverPc := writeErrorPacketConn{}
- t.Logf("remote addr: %s", remotePc.LocalAddr())
- s, err := NewServer(&ServerConfig{
- Conn: &serverPc,
- StartingNodes: addrResolver(remotePc.LocalAddr().String()),
- QueryResendDelay: func() time.Duration { return 0 },
- })
- require.NoError(t, err)
- defer s.Close()
- ts, err := s.Bootstrap()
- t.Logf("%#v", ts)
- require.NoError(t, err)
- time.Sleep(time.Second)
-}
|
Merge the BootstrapRace{,Write} tests
Combines the write error, response and timeout callbacks.
|
anacrolix_dht
|
train
|
e0d1aea2a31327b06d81d75d8cdbe514e38b5c45
|
diff --git a/aeron-archive/src/main/java/io/aeron/archive/CatalogTool.java b/aeron-archive/src/main/java/io/aeron/archive/CatalogTool.java
index <HASH>..<HASH> 100644
--- a/aeron-archive/src/main/java/io/aeron/archive/CatalogTool.java
+++ b/aeron-archive/src/main/java/io/aeron/archive/CatalogTool.java
@@ -126,7 +126,7 @@ public class CatalogTool
final int recordingFileCount = (int)((dataLength + segmentFileLength - 1) / segmentFileLength);
- final String prefix = recordingId + ".";
+ final String prefix = recordingId + "-";
final boolean[] filesFound = new boolean[recordingFileCount];
for (final String fileName : archiveDir.list((dir, name) -> name.startsWith(prefix)))
{
@@ -139,7 +139,6 @@ public class CatalogTool
catch (final Exception ex)
{
System.err.println("(recordingId=" + recordingId + ") ERR: malformed recording filename:" + fileName);
- ex.printStackTrace(System.err);
headerEncoder.valid(INVALID);
return;
}
|
[Java] minor fixes to CatalogTool
|
real-logic_aeron
|
train
|
38d5ae96f810eae9e44f4b5514cabcd54b4e2531
|
diff --git a/test/spec/helpers/lwrp_polyfill_spec.rb b/test/spec/helpers/lwrp_polyfill_spec.rb
index <HASH>..<HASH> 100644
--- a/test/spec/helpers/lwrp_polyfill_spec.rb
+++ b/test/spec/helpers/lwrp_polyfill_spec.rb
@@ -141,15 +141,6 @@ describe Poise::Helpers::LWRPPolyfill do
it { is_expected.to eq 'helper' }
end # /context with an intermediary class
- context 'with no new_resource' do
- provider(:poise_test, auto: false) do
- include described_class
- end
- subject { provider(:poise_test).new(nil, nil).load_current_resource }
- it { is_expected.to be_a Chef::Resource }
- it { is_expected.to_not be_a resource(:poise_test) }
- end # context with no new_resource
-
context 'calling super' do
provider(:poise_test, auto: false) do
include described_class
|
Remove this test.
It breaks in Chef <I> and it wasn't really a thing anyone should be doing anyway.
|
poise_poise
|
train
|
24e0c40498f51317865d00c479496818ab67dd5e
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -13,6 +13,12 @@ def fixture_file(filename)
File.read(file_path)
end
+RSpec.configure do |config|
+ config.filter_run focus: true
+ config.run_all_when_everything_filtered = true
+ config.treat_symbols_as_metadata_keys_with_true_values = true #rspec 3 default
+end
+
#######################
# Faked web responses #
#######################
|
ability to focus rspec on specific spec(s)
you can add the ":focus" option to specific specs so that
rspec only runs those. example:
it "should handle timeouts", :focus do
logger.should receive(:<<).with(an_instance_of(Timeout::Error))
MetaInspector::Request.new(url('<URL>), timeout: <I>, exception_log: logger)
end
|
jaimeiniesta_metainspector
|
train
|
874697673c6d29b27620e7b86754ee332d355527
|
diff --git a/app/controllers/rapidfire/surveys_controller.rb b/app/controllers/rapidfire/surveys_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/rapidfire/surveys_controller.rb
+++ b/app/controllers/rapidfire/surveys_controller.rb
@@ -51,7 +51,7 @@ module Rapidfire
def survey_params
if Rails::VERSION::MAJOR >= 4
- params.require(:survey).permit(:name, :introduction)
+ params.require(:survey).permit(:name, :introduction, :after_survey_content)
else
params[:survey]
end
diff --git a/app/models/rapidfire/survey.rb b/app/models/rapidfire/survey.rb
index <HASH>..<HASH> 100644
--- a/app/models/rapidfire/survey.rb
+++ b/app/models/rapidfire/survey.rb
@@ -6,7 +6,7 @@ module Rapidfire
validates :name, :presence => true
if Rails::VERSION::MAJOR == 3
- attr_accessible :name, :introduction
+ attr_accessible :name, :introduction, :after_survey_content
end
end
end
|
Ensure new field can be passed into the model
|
code-mancers_rapidfire
|
train
|
39dfbf2c29da93b0696f1f91a2f8ab64a6e1bf79
|
diff --git a/autofit/graphical/factor_graphs/factor.py b/autofit/graphical/factor_graphs/factor.py
index <HASH>..<HASH> 100644
--- a/autofit/graphical/factor_graphs/factor.py
+++ b/autofit/graphical/factor_graphs/factor.py
@@ -14,8 +14,8 @@ from autofit.graphical.factor_graphs.abstract import \
AbstractNode, FactorValue
)
from autofit.graphical.utils import aggregate, Axis
-from autofit.tools.cached_property import cached_property
from autofit.mapper.variable import Variable
+from autofit.tools.cached_property import cached_property
class AbstractFactor(AbstractNode, ABC):
@@ -187,7 +187,7 @@ class Factor(AbstractFactor):
arg: Variable(arg)
for arg
in args
- if arg not in kwargs and arg != "self"
+ if arg not in kwargs and arg != "self" and not arg.startswith("_")
}
}
@@ -504,7 +504,7 @@ class Factor(AbstractFactor):
return DeterministicFactor(
self._factor,
other,
- name=self.name,
+ name=self.name,
**self._kwargs
)
@@ -547,7 +547,7 @@ class DeterministicFactor(Factor):
factor: Callable,
variable: Variable,
*args: Variable,
- name: str = '',
+ name: str = '',
**kwargs: Variable
):
"""
@@ -568,7 +568,7 @@ class DeterministicFactor(Factor):
super().__init__(
factor,
*args,
- name=name or factor.__name__,
+ name=name or factor.__name__,
**kwargs
)
self._deterministic_variables = {
diff --git a/autofit/messages/normal.py b/autofit/messages/normal.py
index <HASH>..<HASH> 100644
--- a/autofit/messages/normal.py
+++ b/autofit/messages/normal.py
@@ -59,7 +59,7 @@ class NormalMessage(AbstractMessage):
)
def as_prior(self):
- from autofit.mapper.prior.prior import GaussianPrior
+ from autofit.mapper.prior.gaussian import GaussianPrior
return GaussianPrior(
mean=self.mu,
sigma=self.sigma
|
fixed creation of factor from prior (__call__ in message had additional 'variables' argument)
|
rhayes777_PyAutoFit
|
train
|
997f4f8dc4b22be880a0ca0cc6271729b7388094
|
diff --git a/tasks/noinfopath_config.js b/tasks/noinfopath_config.js
index <HASH>..<HASH> 100644
--- a/tasks/noinfopath_config.js
+++ b/tasks/noinfopath_config.js
@@ -2,8 +2,8 @@
* grunt-noinfopath-config
*
*
- * Copyright (c) 2017 Jeffrey A. Gochin
- * Licensed under the MIT license.
+ * Copyright (c) 2017 NoInfoPath Group, LLC.
+ * Licensed under the MIT license. (MIT)
*/
'use strict';
@@ -51,12 +51,14 @@ function configure_v2(grunt, task, file) {
file.src.forEach(function(srcFile){
- var slash = srcFile.lastIndexOf(process.platform.indexOf("win32") > -1 ? "\\" : "/") + 1,
- destFile = file.dest + srcFile.substring(0, srcFile.lastIndexOf(".tmpl")).substr(slash),
+ var win32 = process.platform.indexOf("win32") > -1,
+ srcFile2 = win32 ? srcFile.replace("/", "\\") : srcFile,
+ slash = srcFile2.lastIndexOf(win32 ? "\\" : "/") + 1,
+ destFile = (win32 ? file.dest.replace("/", "\\") : file.dest) + srcFile2.substring(0, srcFile2.lastIndexOf(".tmpl")).substr(slash),
configTmpl,
values = task.options().values;
- grunt.log.write("Processing template", srcFile, destFile, "... ");
+ grunt.log.write("Processing template:", srcFile2, "Output:", destFile, "... ");
try {
@@ -93,12 +95,12 @@ module.exports = function (grunt) {
grunt.registerMultiTask('noinfopath_config', 'Used for multi-target noinfopath deployments.', function () {
if(this.data.src) {
- grunt.log.writeln("Testing Version 1");
+ grunt.log.writeln("Using Version 1");
this.filesSrc.forEach(function (f) {
configure_v1(grunt, this, f);
}.bind(this));
} else {
- grunt.log.writeln("Testing Version 2");
+ grunt.log.writeln("Using Version 2");
this.files.forEach(function (file) {
configure_v2(grunt, this, file);
}.bind(this));
|
Adding support for Windows file system.
|
noInfoPath_grunt-noinfopath-config
|
train
|
7e033a7fcaf6de510a76e1b431c08b74ae375523
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -10,6 +10,20 @@ var HorsemanPromise = require('./HorsemanPromise.js');
var noop = function() {};
/**
+ * Check for npm PhantomJS
+ */
+var phantomjs;
+try {
+ phantomjs = require('phantomjs-prebuilt');
+} catch (err) {
+ try {
+ phantomjs = require('phantomjs');
+ } catch (err) {
+ phantomjs = {};
+ }
+}
+
+/**
* Default options.
*/
var DEFAULTS = {
@@ -22,7 +36,8 @@ var DEFAULTS = {
sslProtocol: "any", //sslv3, sslv2, tlsv1, any
injectJquery: true,
switchToNewTab: false,
- injectBluebird: false
+ injectBluebird: false,
+ phantomPath: phantomjs.path
};
|
Add support for npm PhantomJS package
Closes #<I>
|
johntitus_node-horseman
|
train
|
ed1242319cf4598adffb7040d377798c93b7dd40
|
diff --git a/samcli/lib/build/app_builder.py b/samcli/lib/build/app_builder.py
index <HASH>..<HASH> 100644
--- a/samcli/lib/build/app_builder.py
+++ b/samcli/lib/build/app_builder.py
@@ -221,6 +221,9 @@ class ApplicationBuilder(object):
manifest_path,
runtime):
+ if not self._container_manager.is_docker_reachable:
+ raise BuildError("Docker is unreachable. Docker needs to be running to build inside a container.")
+
# If we are printing debug logs in SAM CLI, the builder library should also print debug logs
log_level = LOG.getEffectiveLevel()
diff --git a/tests/unit/lib/build_module/test_app_builder.py b/tests/unit/lib/build_module/test_app_builder.py
index <HASH>..<HASH> 100644
--- a/tests/unit/lib/build_module/test_app_builder.py
+++ b/tests/unit/lib/build_module/test_app_builder.py
@@ -309,6 +309,22 @@ class TestApplicationBuilder_build_function_on_container(TestCase):
self.assertEquals(str(ctx.exception), msg)
self.container_manager.stop.assert_called_with(container_mock)
+ def test_must_raise_on_docker_not_running(self):
+ config = Mock()
+
+ self.container_manager.is_docker_reachable = False
+
+ with self.assertRaises(BuildError) as ctx:
+ self.builder._build_function_on_container(config,
+ "source_dir",
+ "artifacts_dir",
+ "scratch_dir",
+ "manifest_path",
+ "runtime")
+
+ self.assertEquals(str(ctx.exception),
+ "Docker is unreachable. Docker needs to be running to build inside a container.")
+
class TestApplicationBuilder_parse_builder_response(TestCase):
|
fix: Print error message when Docker is not running on `sam build --use-container` (#<I>)
|
awslabs_aws-sam-cli
|
train
|
346e8fb3bff90a3a2dd20381edbebae8495f21e3
|
diff --git a/core/src/main/java/com/google/bitcoin/core/FullPrunedBlockChain.java b/core/src/main/java/com/google/bitcoin/core/FullPrunedBlockChain.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/bitcoin/core/FullPrunedBlockChain.java
+++ b/core/src/main/java/com/google/bitcoin/core/FullPrunedBlockChain.java
@@ -223,12 +223,12 @@ public class FullPrunedBlockChain extends AbstractBlockChain {
}
// All values were already checked for being non-negative (as it is verified in Transaction.verify())
// but we check again here just for defence in depth. Transactions with zero output value are OK.
- if (valueOut.signum() < 0 || valueOut.compareTo(params.MAX_MONEY) > 0)
+ if (valueOut.signum() < 0 || valueOut.compareTo(NetworkParameters.MAX_MONEY) > 0)
throw new VerificationException("Transaction output value out of rage");
if (isCoinBase) {
coinbaseValue = valueOut;
} else {
- if (valueIn.compareTo(valueOut) < 0 || valueIn.compareTo(params.MAX_MONEY) > 0)
+ if (valueIn.compareTo(valueOut) < 0 || valueIn.compareTo(NetworkParameters.MAX_MONEY) > 0)
throw new VerificationException("Transaction input value out of range");
totalFees = totalFees.add(valueIn.subtract(valueOut));
}
@@ -240,7 +240,7 @@ public class FullPrunedBlockChain extends AbstractBlockChain {
listScriptVerificationResults.add(future);
}
}
- if (totalFees.compareTo(params.MAX_MONEY) > 0 || block.getBlockInflation(height).add(totalFees).compareTo(coinbaseValue) < 0)
+ if (totalFees.compareTo(NetworkParameters.MAX_MONEY) > 0 || block.getBlockInflation(height).add(totalFees).compareTo(coinbaseValue) < 0)
throw new VerificationException("Transaction fees out of range");
for (Future<VerificationException> future : listScriptVerificationResults) {
VerificationException e;
@@ -345,12 +345,12 @@ public class FullPrunedBlockChain extends AbstractBlockChain {
}
// All values were already checked for being non-negative (as it is verified in Transaction.verify())
// but we check again here just for defence in depth. Transactions with zero output value are OK.
- if (valueOut.signum() < 0 || valueOut.compareTo(params.MAX_MONEY) > 0)
+ if (valueOut.signum() < 0 || valueOut.compareTo(NetworkParameters.MAX_MONEY) > 0)
throw new VerificationException("Transaction output value out of rage");
if (isCoinBase) {
coinbaseValue = valueOut;
} else {
- if (valueIn.compareTo(valueOut) < 0 || valueIn.compareTo(params.MAX_MONEY) > 0)
+ if (valueIn.compareTo(valueOut) < 0 || valueIn.compareTo(NetworkParameters.MAX_MONEY) > 0)
throw new VerificationException("Transaction input value out of range");
totalFees = totalFees.add(valueIn.subtract(valueOut));
}
@@ -362,7 +362,7 @@ public class FullPrunedBlockChain extends AbstractBlockChain {
listScriptVerificationResults.add(future);
}
}
- if (totalFees.compareTo(params.MAX_MONEY) > 0 ||
+ if (totalFees.compareTo(NetworkParameters.MAX_MONEY) > 0 ||
newBlock.getHeader().getBlockInflation(newBlock.getHeight()).add(totalFees).compareTo(coinbaseValue) < 0)
throw new VerificationException("Transaction fees out of range");
txOutChanges = new TransactionOutputChanges(txOutsCreated, txOutsSpent);
diff --git a/core/src/main/java/com/google/bitcoin/core/Transaction.java b/core/src/main/java/com/google/bitcoin/core/Transaction.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/bitcoin/core/Transaction.java
+++ b/core/src/main/java/com/google/bitcoin/core/Transaction.java
@@ -1273,7 +1273,7 @@ public class Transaction extends ChildMessage implements Serializable {
throw new VerificationException("Transaction output negative");
valueOut = valueOut.add(output.getValue());
}
- if (valueOut.compareTo(params.MAX_MONEY) > 0)
+ if (valueOut.compareTo(NetworkParameters.MAX_MONEY) > 0)
throw new VerificationException("Total transaction output value greater than possible");
if (isCoinBase()) {
|
Access NetworkParameters.MAX_MONEY in a static way.
|
bitcoinj_bitcoinj
|
train
|
2910dee858bf608751125b1b111f91fef413c70c
|
diff --git a/executor/builder.go b/executor/builder.go
index <HASH>..<HASH> 100644
--- a/executor/builder.go
+++ b/executor/builder.go
@@ -4509,6 +4509,7 @@ func (b *executorBuilder) buildShuffle(v *plannercore.PhysicalShuffle) *ShuffleE
concurrency: v.Concurrency,
}
+ // 1. initialize the splitters
splitters := make([]partitionSplitter, len(v.ByItemArrays))
switch v.SplitterType {
case plannercore.PartitionHashSplitterType:
@@ -4524,6 +4525,7 @@ func (b *executorBuilder) buildShuffle(v *plannercore.PhysicalShuffle) *ShuffleE
}
shuffle.splitters = splitters
+ // 2. initialize the data sources (build the data sources from physical plan to executors)
shuffle.dataSources = make([]Executor, len(v.DataSources))
for i, dataSource := range v.DataSources {
shuffle.dataSources[i] = b.build(dataSource)
@@ -4532,13 +4534,24 @@ func (b *executorBuilder) buildShuffle(v *plannercore.PhysicalShuffle) *ShuffleE
}
}
+ // 3. initialize the workers
head := v.Children()[0]
+ // A `PhysicalShuffleReceiverStub` for every worker have the same `DataSource` but different `Receiver`.
+ // We preallocate `PhysicalShuffleReceiverStub`s here and reuse them below.
+ stubs := make([]*plannercore.PhysicalShuffleReceiverStub, 0, len(v.DataSources))
+ for _, dataSource := range v.DataSources {
+ stub := plannercore.PhysicalShuffleReceiverStub{
+ DataSource: dataSource,
+ }.Init(b.ctx, dataSource.Stats(), dataSource.SelectBlockOffset(), nil)
+ stub.SetSchema(dataSource.Schema())
+ stubs = append(stubs, stub)
+ }
shuffle.workers = make([]*shuffleWorker, shuffle.concurrency)
for i := range shuffle.workers {
receivers := make([]*shuffleReceiver, len(v.DataSources))
for j, dataSource := range v.DataSources {
receivers[j] = &shuffleReceiver{
- baseExecutor: newBaseExecutor(b.ctx, dataSource.Schema(), dataSource.ID()),
+ baseExecutor: newBaseExecutor(b.ctx, dataSource.Schema(), stubs[j].ID()),
}
}
@@ -4546,12 +4559,9 @@ func (b *executorBuilder) buildShuffle(v *plannercore.PhysicalShuffle) *ShuffleE
receivers: receivers,
}
- for j, dataSource := range v.DataSources {
- stub := plannercore.PhysicalShuffleReceiverStub{
- Receiver: (unsafe.Pointer)(receivers[j]),
- DataSource: dataSource,
- }.Init(b.ctx, dataSource.Stats(), dataSource.SelectBlockOffset(), nil)
- stub.SetSchema(dataSource.Schema())
+ for j := range v.DataSources {
+ stub := stubs[j]
+ stub.Receiver = (unsafe.Pointer)(receivers[j])
v.Tails[j].SetChildren(stub)
}
diff --git a/executor/explain_test.go b/executor/explain_test.go
index <HASH>..<HASH> 100644
--- a/executor/explain_test.go
+++ b/executor/explain_test.go
@@ -310,6 +310,7 @@ func TestCheckActRowsWithUnistore(t *testing.T) {
tk.MustExec("create table t_unistore_act_rows(a int, b int, index(a, b))")
tk.MustExec("insert into t_unistore_act_rows values (1, 0), (1, 0), (2, 0), (2, 1)")
tk.MustExec("analyze table t_unistore_act_rows")
+ tk.MustExec("set @@tidb_merge_join_concurrency= 5;")
type testStruct struct {
sql string
@@ -353,6 +354,14 @@ func TestCheckActRowsWithUnistore(t *testing.T) {
sql: "with cte(a) as (select a from t_unistore_act_rows) select (select 1 from cte limit 1) from cte;",
expected: []string{"4", "4", "4", "4", "4"},
},
+ {
+ sql: "select a, row_number() over (partition by b) from t_unistore_act_rows;",
+ expected: []string{"4", "4", "4", "4", "4", "4", "4"},
+ },
+ {
+ sql: "select /*+ merge_join(t1, t2) */ * from t_unistore_act_rows t1 join t_unistore_act_rows t2 on t1.b = t2.b;",
+ expected: []string{"10", "10", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4"},
+ },
}
// Default RPC encoding may cause statistics explain result differ and then the test unstable.
|
executor: fix wrong runtime stats for `ShuffleReceiver` (#<I>)
close pingcap/tidb#<I>
|
pingcap_tidb
|
train
|
4f50a706b43bac4dacc77ef8628369605e7d5aea
|
diff --git a/org.jgrapes.http/test/org/jgrapes/http/test/GetTest.java b/org.jgrapes.http/test/org/jgrapes/http/test/GetTest.java
index <HASH>..<HASH> 100644
--- a/org.jgrapes.http/test/org/jgrapes/http/test/GetTest.java
+++ b/org.jgrapes.http/test/org/jgrapes/http/test/GetTest.java
@@ -14,6 +14,7 @@ import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus;
import org.jdrupes.httpcodec.protocols.http.HttpResponse;
import org.jdrupes.httpcodec.protocols.http.fields.HttpField;
import org.jdrupes.httpcodec.protocols.http.fields.HttpMediaTypeField;
+import org.jdrupes.httpcodec.types.MediaType;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Component;
import org.jgrapes.core.Components;
@@ -64,8 +65,8 @@ public class GetTest {
response.setStatus(HttpStatus.OK);
response.setMessageHasBody(true);
HttpMediaTypeField media = new HttpMediaTypeField(
- HttpField.CONTENT_TYPE, "text", "plain");
- media.setParameter("charset", "utf-8");
+ HttpField.CONTENT_TYPE, MediaType
+ .fromString("text/plain; charset=utf-8"));
response.setField(media);
fire(new Response(response), channel);
try {
@@ -85,8 +86,8 @@ public class GetTest {
response.setStatus(HttpStatus.OK);
response.setMessageHasBody(true);
HttpMediaTypeField media = new HttpMediaTypeField(
- HttpField.CONTENT_TYPE, "text", "plain");
- media.setParameter("charset", "utf-8");
+ HttpField.CONTENT_TYPE, MediaType
+ .fromString("text/plain; charset=utf-8"));
response.setField(media);
fire(new Response(response), channel);
try {
|
Adapted to new media type API.
|
mnlipp_jgrapes
|
train
|
b8ff4220b310105c346720dff300155cf24aa2c5
|
diff --git a/packages/webpack-cli/lib/groups/runHelp.js b/packages/webpack-cli/lib/groups/runHelp.js
index <HASH>..<HASH> 100644
--- a/packages/webpack-cli/lib/groups/runHelp.js
+++ b/packages/webpack-cli/lib/groups/runHelp.js
@@ -93,7 +93,9 @@ const outputHelp = (args) => {
const negatedFlags = flags
.filter((flag) => flag.negative)
.reduce((allFlags, flag) => {
- return [...allFlags, { name: `no-${flag.name}`, description: `Negates ${flag.name}`, type: Boolean }];
+ // Use available description for built-in negated flags
+ const description = flag.negatedDescription ? flag.negatedDescription : `Negates ${flag.name}`;
+ return [...allFlags, { name: `no-${flag.name}`, description, type: Boolean }];
}, []);
const title = bold('⬡ ') + underline('webpack') + bold(' ⬡');
const desc = 'The build tool for modern web applications';
diff --git a/packages/webpack-cli/lib/utils/cli-flags.js b/packages/webpack-cli/lib/utils/cli-flags.js
index <HASH>..<HASH> 100644
--- a/packages/webpack-cli/lib/utils/cli-flags.js
+++ b/packages/webpack-cli/lib/utils/cli-flags.js
@@ -129,6 +129,7 @@ const builtInFlags = [
type: Boolean,
negative: true,
description: 'Enables Hot Module Replacement',
+ negatedDescription: 'Disables Hot Module Replacement',
link: 'https://webpack.js.org/concepts/hot-module-replacement/',
},
{
@@ -182,6 +183,7 @@ const builtInFlags = [
type: Boolean,
negative: true,
description: 'Enable colors on console',
+ negatedDescription: 'Disable colors on console',
},
// For webpack@4
@@ -217,6 +219,7 @@ const builtInFlags = [
negative: true,
alias: 'd',
description: 'Determine source maps to use',
+ negatedDescription: 'Do not generate source maps',
link: 'https://webpack.js.org/configuration/devtool/#devtool',
},
{
@@ -239,6 +242,7 @@ const builtInFlags = [
type: [String, Boolean],
negative: true,
description: 'It instructs webpack on how to treat the stats e.g. verbose',
+ negatedDescription: 'Disable stats output',
link: 'https://webpack.js.org/configuration/stats/#stats',
},
{
@@ -248,6 +252,7 @@ const builtInFlags = [
negative: true,
alias: 'w',
description: 'Watch for files changes',
+ negatedDescription: 'Do not watch for file changes',
link: 'https://webpack.js.org/configuration/watch/',
},
];
|
chore: better description for built-in negated flags (#<I>)
|
webpack_webpack-cli
|
train
|
ba13ae83dadbe4339a13bbf784a8dacd370082c2
|
diff --git a/src/Middleware/IpFilter.php b/src/Middleware/IpFilter.php
index <HASH>..<HASH> 100644
--- a/src/Middleware/IpFilter.php
+++ b/src/Middleware/IpFilter.php
@@ -31,6 +31,13 @@ final class IpFilter implements MiddlewareInterface
$this->clientIpAttribute = $clientIpAttribute;
}
+ public function withIpValidator(Ip $ipValidator): self
+ {
+ $new = clone $this;
+ $new->ipValidator = $ipValidator;
+ return $new;
+ }
+
/**
* Process an incoming server request.
*
|
Improve IpFilter middleware
|
yiisoft_yii-web
|
train
|
938e71b53a1d57073f1929fee6c927ab3a0e2149
|
diff --git a/command_line/run_autoencoder.py b/command_line/run_autoencoder.py
index <HASH>..<HASH> 100644
--- a/command_line/run_autoencoder.py
+++ b/command_line/run_autoencoder.py
@@ -128,7 +128,7 @@ if __name__ == '__main__':
for p in params:
np.save(FLAGS.save_parameters + '-' + p, params[p])
- # Save the predictions of the model
+ # Save the reconstructions of the model
if FLAGS.save_reconstructions:
print('Saving the reconstructions for the test set...')
np.save(FLAGS.save_reconstructions, dae.reconstruct(teX))
diff --git a/command_line/run_rbm.py b/command_line/run_rbm.py
index <HASH>..<HASH> 100644
--- a/command_line/run_rbm.py
+++ b/command_line/run_rbm.py
@@ -20,6 +20,8 @@ flags.DEFINE_string('valid_dataset', '', 'Path to valid set .npy file.')
flags.DEFINE_string('test_dataset', '', 'Path to test set .npy file.')
flags.DEFINE_string('cifar_dir', '', 'Path to the cifar 10 dataset directory.')
flags.DEFINE_boolean('restore_previous_model', False, 'If true, restore previous model corresponding to model name.')
+flags.DEFINE_string('save_reconstructions', '', 'Path to a .npy file to save the reconstructions of the model.')
+flags.DEFINE_string('save_parameters', '', 'Path to save the parameters of the model.')
flags.DEFINE_integer('seed', -1, 'Seed for the random generators (>= 0). Useful for testing hyperparameters.')
# RBM configuration
@@ -92,6 +94,18 @@ if __name__ == '__main__':
r.build_model(trX.shape[1])
r.fit(trX, teX, restore_previous_model=FLAGS.restore_previous_model)
+ # Save the model paramenters
+ if FLAGS.save_parameters:
+ print('Saving the parameters of the model...')
+ params = r.get_model_parameters()
+ for p in params:
+ np.save(FLAGS.save_parameters + '-' + p, params[p])
+
+ # Save the reconstructions of the model
+ if FLAGS.save_reconstructions:
+ print('Saving the reconstructions for the test set...')
+ np.save(FLAGS.save_reconstructions, r.reconstruct(teX))
+
# Encode the training data and store it
if FLAGS.encode_train:
print('Transforming training data...')
diff --git a/models/autoencoder_models/denoising_autoencoder.py b/models/autoencoder_models/denoising_autoencoder.py
index <HASH>..<HASH> 100644
--- a/models/autoencoder_models/denoising_autoencoder.py
+++ b/models/autoencoder_models/denoising_autoencoder.py
@@ -141,16 +141,16 @@ class DenoisingAutoencoder(model.Model):
if self.verbose == 1:
print("Validation cost at step %s: %s" % (epoch, err))
- def reconstruct(self, test_set):
+ def reconstruct(self, data):
""" Reconstruct the test set data using the learned model.
- :param test_set: Testing data. shape(n_test_samples, n_features)
+ :param data: Testing data. shape(n_test_samples, n_features)
:return: labels
"""
with tf.Session() as self.tf_session:
self.tf_saver.restore(self.tf_session, self.model_path)
- return self.decode.eval({self.input_data_corr: test_set})
+ return self.decode.eval({self.input_data_corr: data})
def build_model(self, n_features, W_=None, bh_=None, bv_=None):
diff --git a/models/rbm_models/rbm.py b/models/rbm_models/rbm.py
index <HASH>..<HASH> 100644
--- a/models/rbm_models/rbm.py
+++ b/models/rbm_models/rbm.py
@@ -264,6 +264,20 @@ class RBM(model.Model):
return encoded_data
+ def reconstruct(self, data):
+
+ """ Reconstruct the test set data using the learned model.
+ :param data: Testing data. shape(n_test_samples, n_features)
+ :return: labels
+ """
+
+ with tf.Session() as self.tf_session:
+
+ self.tf_saver.restore(self.tf_session, self.model_path)
+ hprobs, _ = self.sample_hidden_from_visible(data)
+ vprobs = self.sample_visible_from_hidden(hprobs, data.shape[1])
+ return vprobs.eval()
+
def load_model(self, shape, gibbs_sampling_steps, model_path):
""" Load a trained model from disk. The shape of the model
|
added save_parameters() and save_reconstructions() for rbm model
|
blackecho_Deep-Learning-TensorFlow
|
train
|
613c9335dfe5adbfa1925b1138f4b262d42c888d
|
diff --git a/cli.js b/cli.js
index <HASH>..<HASH> 100644
--- a/cli.js
+++ b/cli.js
@@ -127,7 +127,7 @@ var preprocess = function(file, pp, options, cb) {
// stdin would have been nice here, but not all preprocessors (less)
// accepts that, so we need to read the file both here and for the parser.
// Don't process SASS partials.
- if (file.match(/(^|\/)_.*\.s(c|s)ss$/) != null) {
+ if (file.match(/(^|\/)_.*\.s(c|a)ss$/) != null) {
process.nextTick(function() { cb(null, ''); });
} else if (pp != null) {
pp += ' ';
|
fixed sass regex typo
|
jacobrask_styledocco
|
train
|
aa3ce541fdc4986442bce73840d1b13f5e1279b5
|
diff --git a/ctypeslib/codegen/codegenerator.py b/ctypeslib/codegen/codegenerator.py
index <HASH>..<HASH> 100644
--- a/ctypeslib/codegen/codegenerator.py
+++ b/ctypeslib/codegen/codegenerator.py
@@ -106,6 +106,7 @@ class Generator(object):
self.enable_string_cast = lambda: True
import pkgutil
headers = pkgutil.get_data('ctypeslib', 'data/string_cast.tpl').decode()
+ headers = headers.replace('__POINTER_TYPE__', self.enable_pointer_type())
print(headers, file=self.imports)
return
diff --git a/ctypeslib/data/string_cast.tpl b/ctypeslib/data/string_cast.tpl
index <HASH>..<HASH> 100644
--- a/ctypeslib/data/string_cast.tpl
+++ b/ctypeslib/data/string_cast.tpl
@@ -13,6 +13,6 @@ def char_pointer_cast(string, encoding='utf-8'):
# In Python3, bytes has no encode attribute
pass
string = ctypes.c_char_p(string)
- return ctypes.cast(string, POINTER_T(ctypes.c_char))
+ return ctypes.cast(string, __POINTER_TYPE__(ctypes.c_char))
diff --git a/test/test_cross_arch.py b/test/test_cross_arch.py
index <HASH>..<HASH> 100644
--- a/test/test_cross_arch.py
+++ b/test/test_cross_arch.py
@@ -26,5 +26,7 @@ class CrossArchSimplerCode(ClangTest):
# print(self.text_output)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/test/test_pointer.py b/test/test_pointer.py
index <HASH>..<HASH> 100644
--- a/test/test_pointer.py
+++ b/test/test_pointer.py
@@ -37,6 +37,15 @@ class Pointer(ClangTest):
self.fail('member pointer')
#self.assertTrue(isinstance(self.namespace.member_pointer,POINTER_T) )
+ def test_same_arch_pointer(self):
+ self.convert('''
+ typedef char* PCHAR;
+ typedef void* PVOID;
+ ''')
+ print(self.text_output)
+ self.assertNotIn('POINTER_T', self.text_output)
+ # self.assertIn('POINTER_T', self.text_output)
+
if __name__ == "__main__":
unittest.main()
|
Improve the pointer type generation out of cross arch situations
|
trolldbois_ctypeslib
|
train
|
afb6a015ddd5a187d32ae5c6ade5fd846e8741cb
|
diff --git a/test/callback.js b/test/callback.js
index <HASH>..<HASH> 100644
--- a/test/callback.js
+++ b/test/callback.js
@@ -6,7 +6,6 @@ var assert = require('assert')
, bindings = require('bindings')({ module_root: __dirname, bindings: 'ffi_tests' })
describe('Callback', function () {
-
afterEach(gc)
it('should create a C function pointer from a JS function', function () {
@@ -50,7 +49,7 @@ describe('Callback', function () {
assert.equal(0, nul.address())
})
- it('should throw an Error when invoked through a ForeignFunction and throws', function () {
+ it.skip('should throw an Error when invoked through a ForeignFunction and throws', function () {
var cb = ffi.Callback('void', [ ], function () {
throw new Error('callback threw')
})
@@ -60,7 +59,7 @@ describe('Callback', function () {
}, /callback threw/)
})
- it('should throw an Error with a meaningful message when a type\'s "set()" throws', function () {
+ it.skip('should throw an Error with a meaningful message when a type\'s "set()" throws', function () {
var cb = ffi.Callback('int', [ ], function () {
return 'a string!?!?'
})
|
Skip some test for libuv upstream problems.
|
node-ffi-napi_node-ffi-napi
|
train
|
eff08c26eb39484133742bb1b02509947fcd1398
|
diff --git a/cli/commands.js b/cli/commands.js
index <HASH>..<HASH> 100644
--- a/cli/commands.js
+++ b/cli/commands.js
@@ -16,8 +16,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
let commands = {};
if (process.argv.indexOf('--blueprint') > -1) {
+ /* eslint-disable import/no-dynamic-require */
+ /* eslint-disable global-require */
commands = require(`generator-jhipster-${process.argv[process.argv.indexOf('--blueprint') + 1]}/commands`);
}
diff --git a/cli/utils.js b/cli/utils.js
index <HASH>..<HASH> 100644
--- a/cli/utils.js
+++ b/cli/utils.js
@@ -189,6 +189,7 @@ const createYeomanEnv = () => {
.filter(command => !SUB_GENERATORS[command].cliOnly)
.forEach(generator => {
if (SUB_GENERATORS[generator].blueprint) {
+ /* eslint-disable prettier/prettier */
env.register(require.resolve(`../node_modules/${SUB_GENERATORS[generator].blueprint}/generators/${generator}`), `${CLI_NAME}:${generator}`);
} else {
env.register(require.resolve(`../generators/${generator}`), `${CLI_NAME}:${generator}`);
diff --git a/test/cli/cli.spec.js b/test/cli/cli.spec.js
index <HASH>..<HASH> 100644
--- a/test/cli/cli.spec.js
+++ b/test/cli/cli.spec.js
@@ -36,4 +36,17 @@ describe('jhipster cli test', () => {
done();
});
});
+
+ it('should delegate to blueprint on blueprint command but will not find it', function(done) {
+ this.timeout(4000);
+
+ exec(`${cmd} foo --blueprint bar`, (error, stdout, stderr) => {
+ console.log(error);
+ expect(error).to.not.be.null;
+ expect(error.code).to.equal(1);
+ /* eslint-disable prettier/prettier */
+ expect(stderr.includes('Cannot find module \'generator-jhipster-bar/commands\'')).to.be.true;
+ done();
+ });
+ });
});
|
Enable blueprint to define custom subgenerator (test)
|
jhipster_generator-jhipster
|
train
|
7e1115c40aa1a99893900cae0dc986728d1e2c3f
|
diff --git a/src/test/java/org/dita/dost/util/XSpecTest.java b/src/test/java/org/dita/dost/util/XSpecTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/dita/dost/util/XSpecTest.java
+++ b/src/test/java/org/dita/dost/util/XSpecTest.java
@@ -34,9 +34,8 @@ public class XSpecTest {
public static Collection<Object[]> getFiles() {
final List<File> cases = new ArrayList<>();
findXSpec(new File("src/test").getAbsoluteFile(), cases);
- System.err.println(cases.toString());
- final List<Object[]> params = new ArrayList<Object[]>(cases.size());
+ final List<Object[]> params = new ArrayList<>(cases.size());
for (final File f : cases) {
final Object[] arr = new Object[]{f};
params.add(arr);
|
Remove STDERR debug output from unit test
|
dita-ot_dita-ot
|
train
|
3a26c5ecee3678fde13c36b209215f29c1ffa8c1
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ from setuptools import setup
setup(
name="threat_intel",
- version='0.1.22',
+ version='0.1.23',
provides=['threat_intel'],
author="Yelp Security",
url='https://github.com/Yelp/threat_intel',
|
Bumping the version to <I>
|
Yelp_threat_intel
|
train
|
9297fc2bd2eeb91e33457dd587a1203740d8d756
|
diff --git a/src/core/model/BLModel.php b/src/core/model/BLModel.php
index <HASH>..<HASH> 100644
--- a/src/core/model/BLModel.php
+++ b/src/core/model/BLModel.php
@@ -133,7 +133,9 @@ class BLModel implements \JsonSerializable
$params[] = $value;
}
$sql = 'INSERT INTO `' . self::table() . '` (' . join(',', $fields) . ') VALUES (' . join(',', $quests) . ');';
- BLSql::exec($sql, $params);
+ if (BLSql::exec($sql, $params)->rowCount() <= 0) {
+ return false;
+ }
$this->_dirty = [];
// save pk value
$this->_pkValue = BLSql::getHandle()->lastInsertId(self::pkField());
diff --git a/src/core/model/BLQuery.php b/src/core/model/BLQuery.php
index <HASH>..<HASH> 100644
--- a/src/core/model/BLQuery.php
+++ b/src/core/model/BLQuery.php
@@ -51,6 +51,30 @@ class BLQuery
return $models;
}
+ public function count()
+ {
+ $sql = 'SELECT count(1) FROM `' . $this->table . '`';
+ if (!empty($this->wheres)) {
+ $sql .= ' WHERE ' . join(' AND ', $this->wheres);
+ }
+ if (!empty($this->orders)) {
+ $sql .= ' ORDER BY ' . join(', ', $this->orders);
+ }
+ if (!empty($this->limit)) {
+ $sql .= ' LIMIT ' . $this->limit;
+ }
+ $result = BLSql::exec($sql, $this->params);
+ return $result->fetch(\PDO::FETCH_NUM)[0];
+ }
+
+ public function fields($fields)
+ {
+ if (is_array($fields)) {
+ $this->fields = $fields;
+ }
+ return $this;
+ }
+
/**
* where(field, op, value)
* OR where(field, value) (default op is "=")
diff --git a/src/ext/token/JWT.php b/src/ext/token/JWT.php
index <HASH>..<HASH> 100644
--- a/src/ext/token/JWT.php
+++ b/src/ext/token/JWT.php
@@ -32,13 +32,17 @@ class JWT extends BLToken
function unsignInternal($token)
{
- $parsed = (new Parser())->parse($token);
- $vd = new ValidationData();
- $vd->setCurrentTime(time());
- if (!$parsed->verify($this->getSigner(), BLConfig::get('token', 'options', 'key'))
- || !$parsed->validate($vd)) {
+ try {
+ $parsed = (new Parser())->parse($token);
+ $vd = new ValidationData();
+ $vd->setCurrentTime(time());
+ if (!$parsed->verify($this->getSigner(), BLConfig::get('token', 'options', 'key'))
+ || !$parsed->validate($vd)) {
+ return false;
+ };
+ return $parsed->getClaim('bl_data', false);
+ } catch (\Exception $e) {
return false;
- };
- return $parsed->getClaim('bl_data', false);
+ }
}
}
\ No newline at end of file
|
enhance model query, fix JWT
|
DeepAQ_BestLang
|
train
|
cb838a7760467d9ea153a012776de4561e222245
|
diff --git a/hydpy/models/hland/hland_parameters.py b/hydpy/models/hland/hland_parameters.py
index <HASH>..<HASH> 100644
--- a/hydpy/models/hland/hland_parameters.py
+++ b/hydpy/models/hland/hland_parameters.py
@@ -274,7 +274,7 @@ class Parameters(parametertools.Parameters):
con = self.control
der = self.derived
landzonearea = con.zonearea.values.copy()
- landzonearea[con.zonetype == ILAKE] = 0.
+ landzonearea[con.zonetype.values == ILAKE] = 0.
landarea = numpy.sum(landzonearea)
if landarea > 0.:
der.rellandzonearea(landzonearea/landarea)
@@ -341,8 +341,8 @@ class Parameters(parametertools.Parameters):
con = self.control
der = self.derived
soilzonearea = con.zonearea.values.copy()
- soilzonearea[con.zonetype == GLACIER] = 0.
- soilzonearea[con.zonetype == ILAKE] = 0.
+ soilzonearea[con.zonetype.values == GLACIER] = 0.
+ soilzonearea[con.zonetype.values == ILAKE] = 0.
soilarea = numpy.sum(soilzonearea)
if soilarea > 0.:
der.relsoilzonearea(soilzonearea/soilarea)
diff --git a/hydpy/models/hland/hland_states.py b/hydpy/models/hland/hland_states.py
index <HASH>..<HASH> 100644
--- a/hydpy/models/hland/hland_states.py
+++ b/hydpy/models/hland/hland_states.py
@@ -130,7 +130,7 @@ class LZ(sequencetools.StateSequence):
"""
if upper is None:
control = self.subseqs.seqs.model.parameters.control
- if not any(control.zonetype == ILAKE):
+ if not any(control.zonetype.values == ILAKE):
lower = 0.
sequencetools.StateSequence.trim(self, lower, upper)
|
Adapt base model `hland` (modules `hland_parameters` and `hland_states`) to commit #d<I>c5.
|
hydpy-dev_hydpy
|
train
|
d3fef40e8402be890fe7013ec5a38d575620b5e0
|
diff --git a/pycbc/ahope/segment_utils.py b/pycbc/ahope/segment_utils.py
index <HASH>..<HASH> 100644
--- a/pycbc/ahope/segment_utils.py
+++ b/pycbc/ahope/segment_utils.py
@@ -500,7 +500,14 @@ def create_segs_from_cats_job(cp, out_dir, ifoString, tag=None):
else:
proxy = "/tmp/x509up_u%d" % os.getuid()
proxyfile = os.path.join(out_dir, 'x509up.file')
- shutil.copyfile(proxy, proxyfile)
+ try:
+ shutil.copyfile(proxy, proxyfile)
+ except IOError:
+ raise RuntimeError('Cannot find certificate in %s. '
+ 'Make sure that ligo-proxy-init '
+ 'has been run.' % proxy)
+
+
job.add_condor_cmd('environment',
'USER=$ENV(USER);X509_USER_PROXY=%s' % proxyfile)
|
add error message when certificate is not found
|
gwastro_pycbc
|
train
|
46378b8f487ebeacbb429895d9e62986b4f23e8a
|
diff --git a/src/components/fab/QFab.js b/src/components/fab/QFab.js
index <HASH>..<HASH> 100644
--- a/src/components/fab/QFab.js
+++ b/src/components/fab/QFab.js
@@ -20,11 +20,12 @@ export default {
direction: {
type: String,
default: 'right'
- }
+ },
+ persistent: Boolean
},
watch: {
$route () {
- this.hide()
+ !this.persistent && this.hide()
}
},
created () {
|
feat: [Request] QFab prop to persist on route change #<I>
|
quasarframework_quasar
|
train
|
7cb3a6c235a0756affd12028b24455994f1bd2a4
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@
* Apply changeset when command is executed to update the aggregate's state.
+* Fix events applied in reverse order when reading from Eventstore.
+
## Version 0.4.0
diff --git a/lib/akasha/storage/http_event_store/client.rb b/lib/akasha/storage/http_event_store/client.rb
index <HASH>..<HASH> 100644
--- a/lib/akasha/storage/http_event_store/client.rb
+++ b/lib/akasha/storage/http_event_store/client.rb
@@ -135,7 +135,7 @@ module Akasha
req.headers['ES-LongPoll'] = poll if poll&.positive?
req.params['embed'] = 'body'
end
- to_events(resp.body['entries'])
+ to_events(resp.body['entries']).reverse!
end || []
end
diff --git a/spec/akasha/repository_spec.rb b/spec/akasha/repository_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/akasha/repository_spec.rb
+++ b/spec/akasha/repository_spec.rb
@@ -16,14 +16,29 @@ describe Akasha::Repository do
context 'for an existing aggregate' do
context 'within the same namespace' do
- before do
+ it 'loads the aggregate' do
item.name = 'foo'
subject.save_aggregate(item)
+ item = subject.load_aggregate(Item, 'item-1')
+ expect(item.name).to eq 'foo'
end
- it 'loads the aggregate' do
+ it 'applies events in the right order' do
+ item.name = 'foo'
+ item.name = 'bar'
+ subject.save_aggregate(item)
item = subject.load_aggregate(Item, 'item-1')
- expect(item.name).to eq 'foo'
+ expect(item.name).to eq 'bar'
+ end
+
+ it 'correctly handles pagination' do
+ 100.times do
+ item.name = 'foo'
+ end
+ item.name = 'bar'
+ subject.save_aggregate(item)
+ item = subject.load_aggregate(Item, 'item-1')
+ expect(item.name).to eq 'bar'
end
end
diff --git a/spec/akasha/storage/http_event_store/client_spec.rb b/spec/akasha/storage/http_event_store/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/akasha/storage/http_event_store/client_spec.rb
+++ b/spec/akasha/storage/http_event_store/client_spec.rb
@@ -16,7 +16,7 @@ describe Akasha::Storage::HttpEventStore::Client, integration: true do
it 'saves all events' do
subject.retry_append_to_stream(stream, events)
- expect(actual_events.map(&:name)).to eq events.map(&:name).reverse
+ expect(actual_events.map(&:name)).to eq events.map(&:name)
end
it 'can save event without data' do
@@ -51,7 +51,7 @@ describe Akasha::Storage::HttpEventStore::Client, integration: true do
it 'retrieves saved data oldest-first' do
expect(subject.retry_read_events_forward(stream, 0, 999).map(&:data))
- .to match [{ foo: 'bar' }, { baz: 'qux' }].reverse
+ .to match [{ foo: 'bar' }, { baz: 'qux' }]
end
it 'returns empty array if stream does not exist' do
|
Fix events applied in reverse order when reading from Eventstore.
|
bilus_akasha
|
train
|
ec3693b50d63a6607a4379503baddb1bb129c170
|
diff --git a/src/promise.js b/src/promise.js
index <HASH>..<HASH> 100644
--- a/src/promise.js
+++ b/src/promise.js
@@ -29,8 +29,7 @@
if ( number === 0 || number === Infinity || number === -Infinity ) {
return number;
}
- return number !== number || number === 0 ? 0 :
- ( number >= 0 ? 1 : -1 ) * Math.floor(Math.abs(number));
+ return ( number >= 0 ? 1 : -1 ) * Math.floor(Math.abs(number));
}
// 7.1.12 ToString
|
rm duplicate checks from ToInteger abstract operation
|
kevincennis_promise
|
train
|
c28f0b806b31b85270cf842f020f27480f2efc37
|
diff --git a/lib/async.js b/lib/async.js
index <HASH>..<HASH> 100644
--- a/lib/async.js
+++ b/lib/async.js
@@ -610,6 +610,7 @@
async.memoize = function (fn, hasher) {
var memo = {};
+ var queues = {};
hasher = hasher || function (x) {
return x;
};
@@ -620,10 +621,18 @@
if (key in memo) {
callback.apply(null, memo[key]);
}
+ else if (key in queues) {
+ queues[key].push(callback);
+ }
else {
+ queues[key] = [callback];
fn.apply(null, args.concat([function () {
memo[key] = arguments;
- callback.apply(null, arguments);
+ var q = queues[key];
+ delete queues[key];
+ for (var i = 0, l = q.length; i < l; i++) {
+ q[i].apply(null, arguments);
+ }
}]));
}
};
diff --git a/test/test-async.js b/test/test-async.js
index <HASH>..<HASH> 100644
--- a/test/test-async.js
+++ b/test/test-async.js
@@ -1231,6 +1231,24 @@ exports['memoize error'] = function (test) {
test.done();
};
+exports['memoize multiple calls'] = function (test) {
+ test.expect(3);
+ var fn = function (arg1, arg2, callback) {
+ test.ok(true);
+ setTimeout(function(){
+ callback(null, arg1, arg2);
+ }, 10);
+ };
+ var fn2 = async.memoize(fn);
+ fn2(1, 2, function(err, result) {
+ test.equal(result, 1, 2);
+ });
+ fn2(1, 2, function(err, result) {
+ test.equal(result, 1, 2);
+ test.done();
+ });
+};
+
exports['memoize custom hash function'] = function (test) {
test.expect(2);
var testerr = new Error('test');
|
memoize - handle multiple calls before completion
|
caolan_async
|
train
|
613c7b6db41610ee858b0a6b80c9e0ffc7aab08f
|
diff --git a/src/PatternLab/PatternData/Rules/PseudoPatternRule.php b/src/PatternLab/PatternData/Rules/PseudoPatternRule.php
index <HASH>..<HASH> 100644
--- a/src/PatternLab/PatternData/Rules/PseudoPatternRule.php
+++ b/src/PatternLab/PatternData/Rules/PseudoPatternRule.php
@@ -168,10 +168,10 @@ class PseudoPatternRule extends \PatternLab\PatternData\Rule {
}
// make sure the pattern data is an array before merging the data
- $patternStoreData["data"] = is_array($patternData) ? array_merge($patternDataBase, $patternData) : $patternDataBase;
+ $patternStoreData["data"] = is_array($patternData) ? array_replace_recursive($patternDataBase, $patternData) : $patternDataBase;
// if the pattern data store already exists make sure it is merged and overwrites this data
- $patternStoreData = (PatternData::checkOption($patternStoreKey)) ? array_merge(PatternData::getOption($patternStoreKey),$patternStoreData) : $patternStoreData;
+ $patternStoreData = (PatternData::checkOption($patternStoreKey)) ? array_replace_recursive((PatternData::getOption($patternStoreKey),$patternStoreData) : $patternStoreData;
PatternData::setOption($patternStoreKey, $patternStoreData);
}
|
making sure pseudo-patterns use array_replace_recursive() just like everywhere else
|
pattern-lab_patternlab-php-core
|
train
|
393930eff5ae2a133f11070b0e2946c5bee96163
|
diff --git a/src/main/java/org/redisson/client/handler/CommandDecoder.java b/src/main/java/org/redisson/client/handler/CommandDecoder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/redisson/client/handler/CommandDecoder.java
+++ b/src/main/java/org/redisson/client/handler/CommandDecoder.java
@@ -116,13 +116,16 @@ public class CommandDecoder extends ReplayingDecoder<State> {
} else {
decode(in, cmd, null, ctx.channel());
}
- } catch (IOException e) {
+ } catch (Exception e) {
cmd.tryFailure(e);
}
} else if (data instanceof CommandsData) {
CommandsData commands = (CommandsData)data;
-
- decodeCommandBatch(ctx, in, data, commands);
+ try {
+ decodeCommandBatch(ctx, in, data, commands);
+ } catch (Exception e) {
+ commands.getPromise().tryFailure(e);
+ }
return;
}
|
Fixed exceptions handling in CommandDecoder. #<I>
|
redisson_redisson
|
train
|
719f72e01918ceee51269aecea22728e63feeafb
|
diff --git a/src/org/jgroups/util/Util.java b/src/org/jgroups/util/Util.java
index <HASH>..<HASH> 100644
--- a/src/org/jgroups/util/Util.java
+++ b/src/org/jgroups/util/Util.java
@@ -164,7 +164,7 @@ public class Util {
try {
String tmp=System.getProperty(Global.DEFAULT_HEADERS);
- DEFAULT_HEADERS=tmp != null? new Integer(tmp) : 3;
+ DEFAULT_HEADERS=tmp != null? new Integer(tmp) : 4;
}
catch(Throwable t) {
throw new IllegalArgumentException(String.format("property %s has an incorrect value", Global.DEFAULT_HEADERS), t);
|
Changed the default number of headers in a Message from 3 to 4 (<URL>)
|
belaban_JGroups
|
train
|
995b9ec8ec4717beeaa8da39ba0c011625a92624
|
diff --git a/src/frontend/org/voltdb/iv2/RepairLog.java b/src/frontend/org/voltdb/iv2/RepairLog.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/iv2/RepairLog.java
+++ b/src/frontend/org/voltdb/iv2/RepairLog.java
@@ -35,6 +35,9 @@ public class RepairLog
// last seen truncation point.
long m_truncationPoint;
+ // is this a partition leader?
+ boolean m_isLeader = false;
+
// want voltmessage as payload with message-independent metadata.
static class Item
{
@@ -66,11 +69,17 @@ public class RepairLog
m_log = new LinkedList<Item>();
}
+ // leaders log differently
+ void setLeaderState(boolean isLeader)
+ {
+ m_isLeader = isLeader;
+ }
+
// Offer a new message to the repair log. This will truncate
// the repairLog if the message includes a truncation hint.
public void deliver(VoltMessage msg)
{
- if (msg instanceof Iv2InitiateTaskMessage) {
+ if (!m_isLeader && msg instanceof Iv2InitiateTaskMessage) {
final Iv2InitiateTaskMessage m = (Iv2InitiateTaskMessage)msg;
truncate(m.getTruncationHandle());
m_log.offer(new Item(m, m.getSpHandle()));
diff --git a/src/frontend/org/voltdb/iv2/SpInitiator.java b/src/frontend/org/voltdb/iv2/SpInitiator.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/iv2/SpInitiator.java
+++ b/src/frontend/org/voltdb/iv2/SpInitiator.java
@@ -88,6 +88,7 @@ public class SpInitiator implements Initiator, LeaderNoticeHandler
getInitiatorHSId(), m_initiatorMailbox);
Future<?> inaugurated = m_term.start(m_kfactorForStartup);
inaugurated.get();
+ m_repairLog.setLeaderState(true);
m_scheduler.setLeaderState(true);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Bad news.", true, e);
diff --git a/src/frontend/org/voltdb/iv2/SpScheduler.java b/src/frontend/org/voltdb/iv2/SpScheduler.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/iv2/SpScheduler.java
+++ b/src/frontend/org/voltdb/iv2/SpScheduler.java
@@ -197,6 +197,7 @@ public class SpScheduler extends Scheduler
}
// the initiatorHSId is the ClientInterface mailbox. Yeah. I know.
+ m_repairLogTruncationHandle = message.getSpHandle();
m_mailbox.send(message.getInitiatorHSId(), message);
}
diff --git a/src/frontend/org/voltdb/messaging/Iv2InitiateTaskMessage.java b/src/frontend/org/voltdb/messaging/Iv2InitiateTaskMessage.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/messaging/Iv2InitiateTaskMessage.java
+++ b/src/frontend/org/voltdb/messaging/Iv2InitiateTaskMessage.java
@@ -149,12 +149,10 @@ public class Iv2InitiateTaskMessage extends TransactionInfoBaseMessage {
public int getSerializedSize()
{
int msgsize = super.getSerializedSize();
- msgsize += 8; // m_clientInterfaceHandle
msgsize += 8; // m_truncationHandle
+ msgsize += 8; // m_clientInterfaceHandle
msgsize += 1; // is single partition flag
-
msgsize += m_invocation.getSerializedSize();
-
return msgsize;
}
|
Primary doesn't require repair log
... and can't truncate it (easily) if it has one.
|
VoltDB_voltdb
|
train
|
2dd11dc210ed11e6e694b71df279aa1437cea11c
|
diff --git a/src/Illuminate/Http/JsonResponse.php b/src/Illuminate/Http/JsonResponse.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Http/JsonResponse.php
+++ b/src/Illuminate/Http/JsonResponse.php
@@ -52,6 +52,10 @@ class JsonResponse extends BaseJsonResponse
? $data->toJson($this->jsonOptions)
: json_encode($data, $this->jsonOptions);
+ if (JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(json_last_error_msg());
+ }
+
return $this->update();
}
|
json_encode error checking
As Symfony does, it would be good to have a descriptive error message when json_encode fails (and returns false: <URL>" in Symfony\Component\HttpFoundation\JsonResponse::update due to content ($this->data) was false.
|
laravel_framework
|
train
|
e07aac61efc6a77fe58dbd99dca28a51504897b8
|
diff --git a/core/src/main/java/hudson/model/User.java b/core/src/main/java/hudson/model/User.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/model/User.java
+++ b/core/src/main/java/hudson/model/User.java
@@ -344,8 +344,12 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
if (u==null && (create || getConfigFileFor(id).exists())) {
User tmp = new User(id, fullName);
User prev = byName.putIfAbsent(idkey, u = tmp);
- if (prev!=null)
- u = prev; // if some has already put a value in the map, use it
+ if (prev != null) {
+ u = prev; // if some has already put a value in the map, use it
+ if (LOGGER.isLoggable(Level.FINE) && !fullName.equals(prev.getFullName())) {
+ LOGGER.log(Level.FINE, "mismatch on fullName (‘" + fullName + "’ vs. ‘" + prev.getFullName() + "’) for ‘" + id + "’", new Throwable());
+ }
+ }
}
return u;
}
|
[JENKINS-<I>] More logging at FINE in hudson.model.User.
Running hypothesis: something historically saved a user configuration file with a bogus fullName;
thereafter anyone calling User.get(correctFullName) will get a User with the old fullName.
This would make the bug unreproducible in fresh Jenkins installations.
|
jenkinsci_jenkins
|
train
|
36a8c5a43c6d2980aeb2b7393538e4c2e3bbd623
|
diff --git a/django_extensions/management/commands/shell_plus.py b/django_extensions/management/commands/shell_plus.py
index <HASH>..<HASH> 100644
--- a/django_extensions/management/commands/shell_plus.py
+++ b/django_extensions/management/commands/shell_plus.py
@@ -256,7 +256,13 @@ class Command(BaseCommand):
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(imported_objects).complete)
- readline.parse_and_bind("tab:complete")
+ # Enable tab completion on systems using libedit (e.g. macOS).
+ # These lines are copied from Lib/site.py on Python 3.4.
+ readline_doc = getattr(readline, '__doc__', '')
+ if readline_doc is not None and 'libedit' in readline_doc:
+ readline.parse_and_bind("bind ^I rl_complete")
+ else:
+ readline.parse_and_bind("tab:complete")
use_pythonrc = options['use_pythonrc']
no_startup = options['no_startup']
|
backport macos fix for tab completion
|
django-extensions_django-extensions
|
train
|
bcd67efbc789f33c1b1c1ede91257781acb1a372
|
diff --git a/test/test_time_parser.rb b/test/test_time_parser.rb
index <HASH>..<HASH> 100644
--- a/test/test_time_parser.rb
+++ b/test/test_time_parser.rb
@@ -1,6 +1,6 @@
-require_relative '../helper'
-require 'fluent/test/driver/parser'
-require 'fluent/plugin/parser'
+require_relative 'helper'
+require 'fluent/test'
+require 'fluent/time'
class TimeParserTest < ::Test::Unit::TestCase
def setup
@@ -8,38 +8,38 @@ class TimeParserTest < ::Test::Unit::TestCase
end
def test_call_with_parse
- parser = Fluent::Test::Driver::Parser.new(Fluent::Plugin::Parser::TimeParser.new(nil))
+ parser = Fluent::TimeParser.new
- assert(parser.instance.parse('2013-09-18 12:00:00 +0900').is_a?(Fluent::EventTime))
+ assert(parser.parse('2013-09-18 12:00:00 +0900').is_a?(Fluent::EventTime))
time = event_time('2013-09-18 12:00:00 +0900')
- assert_equal(time, parser.instance.parse('2013-09-18 12:00:00 +0900'))
+ assert_equal(time, parser.parse('2013-09-18 12:00:00 +0900'))
end
def test_parse_with_strptime
- parser = Fluent::Test::Driver::Parser.new(Fluent::Plugin::Parser::TimeParser.new('%d/%b/%Y:%H:%M:%S %z'))
+ parser = Fluent::TimeParser.new('%d/%b/%Y:%H:%M:%S %z')
- assert(parser.instance.parse('28/Feb/2013:12:00:00 +0900').is_a?(Fluent::EventTime))
+ assert(parser.parse('28/Feb/2013:12:00:00 +0900').is_a?(Fluent::EventTime))
time = event_time('28/Feb/2013:12:00:00 +0900', format: '%d/%b/%Y:%H:%M:%S %z')
- assert_equal(time, parser.instance.parse('28/Feb/2013:12:00:00 +0900'))
+ assert_equal(time, parser.parse('28/Feb/2013:12:00:00 +0900'))
end
def test_parse_nsec_with_strptime
- parser = Fluent::Test::Driver::Parser.new(Fluent::Plugin::Parser::TimeParser.new('%d/%b/%Y:%H:%M:%S:%N %z'))
+ parser = Fluent::TimeParser.new('%d/%b/%Y:%H:%M:%S:%N %z')
- assert(parser.instance.parse('28/Feb/2013:12:00:00:123456789 +0900').is_a?(Fluent::EventTime))
+ assert(parser.parse('28/Feb/2013:12:00:00:123456789 +0900').is_a?(Fluent::EventTime))
time = event_time('28/Feb/2013:12:00:00:123456789 +0900', format: '%d/%b/%Y:%H:%M:%S:%N %z')
- assert_equal_event_time(time, parser.instance.parse('28/Feb/2013:12:00:00:123456789 +0900'))
+ assert_equal_event_time(time, parser.parse('28/Feb/2013:12:00:00:123456789 +0900'))
end
def test_parse_with_invalid_argument
- parser = Fluent::Test::Driver::Parser.new(Fluent::Plugin::Parser::TimeParser.new(nil))
+ parser = Fluent::TimeParser.new
[[], {}, nil, true, 10000, //, ->{}, '', :symbol].each { |v|
- assert_raise Fluent::ParserError do
- parser.instance.parse(v)
+ assert_raise Fluent::TimeParser::TimeParseError do
+ parser.parse(v)
end
}
end
|
fix tests for new path and namespace
|
fluent_fluentd
|
train
|
b6fe463769a68519a4a36ab3a3f3731d466779ac
|
diff --git a/rapidoid-utils/src/main/java/org/rapidoid/util/Cls.java b/rapidoid-utils/src/main/java/org/rapidoid/util/Cls.java
index <HASH>..<HASH> 100644
--- a/rapidoid-utils/src/main/java/org/rapidoid/util/Cls.java
+++ b/rapidoid-utils/src/main/java/org/rapidoid/util/Cls.java
@@ -36,9 +36,13 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import org.rapidoid.log.Log;
+import org.rapidoid.var.Var;
+import org.rapidoid.var.Vars;
public class Cls {
@@ -794,7 +798,23 @@ public class Cls {
return true;
}
+ @SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> clazz) {
+
+ if (clazz == List.class) {
+ return (T) U.list();
+ } else if (clazz == Set.class) {
+ return (T) U.set();
+ } else if (clazz == Map.class) {
+ return (T) U.map();
+ } else if (clazz == ConcurrentMap.class) {
+ return (T) U.concurrentMap();
+ } else if (clazz == Var.class) {
+ return (T) Vars.var(null);
+ } else if (clazz == Object.class) {
+ return (T) new Object();
+ }
+
try {
Constructor<T> constr = clazz.getDeclaredConstructor();
boolean accessible = constr.isAccessible();
|
Improved Cls#newInstance to handle common abstract types.
|
rapidoid_rapidoid
|
train
|
7a3880aff8d0eda890978d05f33463bf6affd458
|
diff --git a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipFilter.java b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipFilter.java
index <HASH>..<HASH> 100644
--- a/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipFilter.java
+++ b/dropwizard-jetty/src/main/java/io/dropwizard/jetty/BiDiGzipFilter.java
@@ -112,22 +112,6 @@ public class BiDiGzipFilter extends IncludableGzipFilter {
this._excludedAgentPatterns = userAgentPatterns;
}
- public Set<String> getExcludedPaths() {
- return _excludedPaths;
- }
-
- public void setExcludedPaths(Set<String> paths) {
- this._excludedPaths = paths;
- }
-
- public Set<Pattern> getExcludedPathPatterns() {
- return _excludedPathPatterns;
- }
-
- public void setExcludedPathPatterns(Set<Pattern> patterns) {
- this._excludedPathPatterns = patterns;
- }
-
public String getVary() {
return _vary;
}
diff --git a/dropwizard-jetty/src/test/java/io/dropwizard/jetty/GzipFilterFactoryTest.java b/dropwizard-jetty/src/test/java/io/dropwizard/jetty/GzipFilterFactoryTest.java
index <HASH>..<HASH> 100644
--- a/dropwizard-jetty/src/test/java/io/dropwizard/jetty/GzipFilterFactoryTest.java
+++ b/dropwizard-jetty/src/test/java/io/dropwizard/jetty/GzipFilterFactoryTest.java
@@ -10,6 +10,8 @@ import org.junit.Test;
import javax.validation.Validation;
import java.io.File;
+import java.util.regex.Pattern;
+import java.util.zip.Deflater;
import static org.assertj.core.api.Assertions.assertThat;
@@ -19,9 +21,9 @@ public class GzipFilterFactoryTest {
@Before
public void setUp() throws Exception {
this.gzip = new ConfigurationFactory<>(GzipFilterFactory.class,
- Validation.buildDefaultValidatorFactory()
- .getValidator(),
- Jackson.newObjectMapper(), "dw")
+ Validation.buildDefaultValidatorFactory()
+ .getValidator(),
+ Jackson.newObjectMapper(), "dw")
.build(new File(Resources.getResource("yaml/gzip.yml").toURI()));
}
@@ -60,4 +62,21 @@ public class GzipFilterFactoryTest {
assertThat(gzip.getVary())
.isEqualTo("Accept-Encoding");
}
+
+ @Test
+ public void testBuild() {
+ final BiDiGzipFilter filter = gzip.build();
+
+ assertThat(filter.getMinGzipSize()).isEqualTo((int) gzip.getMinimumEntitySize().toBytes());
+ assertThat(filter.getBufferSize()).isEqualTo((int) gzip.getBufferSize().toBytes());
+ assertThat(filter.getExcludedAgents()).containsOnly("IE");
+ assertThat(filter.getExcludedAgentPatterns()).hasSize(1);
+ assertThat(filter.getExcludedAgentPatterns().iterator().next().pattern()).isEqualTo("OLD-2.+");
+ assertThat(filter.getMimeTypes()).containsOnly("text/plain");
+ assertThat(filter.getMethods()).containsOnly("GET", "POST");
+ assertThat(filter.getDeflateCompressionLevel()).isEqualTo(Deflater.DEFAULT_COMPRESSION);
+ assertThat(filter.isInflateNoWrap()).isTrue();
+ assertThat(filter.isDeflateNoWrap()).isTrue();
+ assertThat(filter.getVary()).isEqualTo("Accept-Encoding");
+ }
}
diff --git a/dropwizard-jetty/src/test/resources/yaml/gzip.yml b/dropwizard-jetty/src/test/resources/yaml/gzip.yml
index <HASH>..<HASH> 100644
--- a/dropwizard-jetty/src/test/resources/yaml/gzip.yml
+++ b/dropwizard-jetty/src/test/resources/yaml/gzip.yml
@@ -2,4 +2,6 @@ enabled: false
minimumEntitySize: 12KB
bufferSize: 32KB
excludedUserAgents: ["IE"]
+excludedUserAgentPatterns: ["OLD-2.+"]
compressedMimeTypes: ["text/plain"]
+includedMethods: ["GET", "POST"]
|
Add a test for building BiDiGzipFilter
|
dropwizard_dropwizard
|
train
|
23a7ff961a3cd6d192ad054b8623f25cdb57a993
|
diff --git a/app/helpers/effective_menus_helper.rb b/app/helpers/effective_menus_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/effective_menus_helper.rb
+++ b/app/helpers/effective_menus_helper.rb
@@ -3,7 +3,7 @@ module EffectiveMenusHelper
menu = Effective::Menu.find_by_title(menu) if menu.kind_of?(String)
return "<ul class='nav navbar-nav'><li>Menu '#{menu}' does not exist</li></ul>".html_safe if !menu.present?
- if (effectively_editting? rescue false)
+ if (effectively_editting? && EffectivePages.authorized?(:edit, Effective::Menu) rescue false)
options[:menu_id] = menu.id
form_for(menu, :url => '/') { |form| options[:form] = form }
end
|
require ability to edit menus before displaying form
|
code-and-effect_effective_pages
|
train
|
737d1d7c1f0853d84f697e98659323b0f9dc1e31
|
diff --git a/angr/analyses/bindiff.py b/angr/analyses/bindiff.py
index <HASH>..<HASH> 100644
--- a/angr/analyses/bindiff.py
+++ b/angr/analyses/bindiff.py
@@ -241,13 +241,13 @@ def compare_statement_dict(statement_1, statement_2):
class NormalizedBlock(object):
# block may span multiple calls
- def __init__(self, addr, function):
- addresses = [addr]
- if addr in function.merged_blocks:
- for a in function.merged_blocks[addr]:
- addresses.append(a)
+ def __init__(self, block, function):
+ addresses = [block.addr]
+ if block.addr in function.merged_blocks:
+ for a in function.merged_blocks[block.addr]:
+ addresses.append(a.addr)
- self.addr = addr
+ self.addr = block.addr
self.addresses = addresses
self.statements = []
self.all_constants = []
@@ -256,8 +256,8 @@ class NormalizedBlock(object):
self.blocks = []
self.instruction_addrs = []
- if addr in function.call_sites:
- self.call_targets = function.call_sites[addr]
+ if block.addr in function.call_sites:
+ self.call_targets = function.call_sites[block.addr]
self.jumpkind = None
@@ -295,7 +295,7 @@ class NormalizedFunction(object):
done = True
for node in self.graph.nodes():
try:
- bl = self.project.factory.block(node)
+ bl = self.project.factory.block(node.addr)
except AngrMemoryError:
continue
except AngrTranslationError:
@@ -303,7 +303,7 @@ class NormalizedFunction(object):
# merge if it ends with a single call, and the successor has only one predecessor and succ is after
successors = self.graph.successors(node)
if bl.vex.jumpkind == "Ijk_Call" and len(successors) == 1 and \
- len(self.graph.predecessors(successors[0])) == 1 and successors[0] > node:
+ len(self.graph.predecessors(successors[0])) == 1 and successors[0] > node.addr:
# add edges to the successors of its successor, and delete the original successors
succ = self.graph.successors(node)[0]
for s in self.graph.successors(succ):
@@ -646,8 +646,10 @@ class FunctionDiff(object):
Computes the diff of the functions and saves the result
"""
# get the attributes for all blocks
- l.debug("Computing diff of functions: %s, %s", hex(self._function_a.startpoint),
- hex(self._function_b.startpoint))
+ l.debug("Computing diff of functions: %s, %s",
+ ("%#x" % self._function_a.startpoint.addr) if self._function_a.startpoint is not None else "None",
+ ("%#x" % self._function_b.startpoint.addr) if self._function_b.startpoint is not None else "None"
+ )
self.attributes_a = self._compute_block_attributes(self._function_a)
self.attributes_b = self._compute_block_attributes(self._function_b)
@@ -722,9 +724,10 @@ class FunctionDiff(object):
self._unmatched_blocks_from_b = set(x for x in self._function_b.graph.nodes() if x not in matched_b)
@staticmethod
- def _get_ordered_successors(project, addr, succ):
+ def _get_ordered_successors(project, block, succ):
try:
# add them in order of the vex
+ addr = block.addr
succ = set(succ)
ordered_succ = []
bl = project.factory.block(addr)
@@ -1002,6 +1005,12 @@ class BinDiff(Analysis):
def _get_call_site_matches(self, func_a, func_b):
possible_matches = set()
+ # Make sure those functions are not SimProcedures
+ f_a = self.cfg_a.artifacts.functions.function(func_a)
+ f_b = self.cfg_b.artifacts.functions.function(func_b)
+ if f_a.startpoint is None or f_b.startpoint is None:
+ return possible_matches
+
fd = self.get_function_diff(func_a, func_b)
basic_block_matches = fd.block_matches
function_a = fd._function_a
|
Fix bindiff for new changes in this branch
|
angr_angr
|
train
|
765d9f607d2e4a4624fb1b72160274c46625cb4d
|
diff --git a/synapse/lib/stormtypes.py b/synapse/lib/stormtypes.py
index <HASH>..<HASH> 100644
--- a/synapse/lib/stormtypes.py
+++ b/synapse/lib/stormtypes.py
@@ -6684,7 +6684,7 @@ class CronJob(Prim):
user = self.valu.get('username')
view = self.valu.get('view')
if not view:
- view = await self.runt.snap.core.getView()
+ view = self.runt.snap.core.view.iden
laststart = self.valu.get('laststarttime')
lastend = self.valu.get('lastfinishtime')
diff --git a/synapse/tests/test_lib_storm.py b/synapse/tests/test_lib_storm.py
index <HASH>..<HASH> 100644
--- a/synapse/tests/test_lib_storm.py
+++ b/synapse/tests/test_lib_storm.py
@@ -627,6 +627,12 @@ class StormTest(s_t_utils.SynTest):
}
})
+ # force old-cron behavior which lacks a view
+ await core.nodes('cron.add --hourly 03 { inet:ipv4 }')
+ for (iden, cron) in core.agenda.list():
+ cron.view = None
+ await core.nodes('cron.list')
+
async def test_storm_wget(self):
async def _getRespFromSha(core, mesgs):
|
BUG: fix cron.list display output with old cron jobs that dont have a view (#<I>)
* BUG: fix cron.list with old cron jobs that dont have a view
|
vertexproject_synapse
|
train
|
65f601a99a0ca7ebacfda7a6becd8af9fe9eaacb
|
diff --git a/lib/puppet/transaction.rb b/lib/puppet/transaction.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/transaction.rb
+++ b/lib/puppet/transaction.rb
@@ -620,8 +620,11 @@ class Transaction
# Is this resource tagged appropriately?
def missing_tags?(resource)
- return false if self.ignore_tags? or tags.empty?
- return true unless resource.tagged?(tags)
+ not appropriately_tagged?(resource)
+ end
+
+ def appropriately_tagged?(resource)
+ self.ignore_tags? or tags.empty? or resource.tagged?(*tags)
end
# Are there any edges that target this resource?
diff --git a/lib/puppet/util/tagging.rb b/lib/puppet/util/tagging.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/util/tagging.rb
+++ b/lib/puppet/util/tagging.rb
@@ -21,8 +21,8 @@ module Puppet::Util::Tagging
end
# Are we tagged with the provided tag?
- def tagged?(tag)
- defined?(@tags) and @tags.include?(tag.to_s)
+ def tagged?(*tags)
+ not ( self.tags & tags.flatten.collect { |t| t.to_s } ).empty?
end
# Return a copy of the tag list, so someone can't ask for our tags
diff --git a/spec/unit/transaction.rb b/spec/unit/transaction.rb
index <HASH>..<HASH> 100755
--- a/spec/unit/transaction.rb
+++ b/spec/unit/transaction.rb
@@ -80,6 +80,16 @@ describe Puppet::Transaction do
@transaction.skip?(@resource).should be_true
end
+ it "should ask the resource if it's tagged with any of the tags" do
+ tags = ['one', 'two']
+ @transaction.stubs(:ignore_tags?).returns(false)
+ @transaction.stubs(:tags).returns(tags)
+
+ @resource.expects(:tagged?).with(*tags).returns(true)
+
+ @transaction.missing_tags?(@resource).should be_false
+ end
+
it "should skip not scheduled resources" do
@transaction.stubs(:scheduled?).returns(false)
@transaction.skip?(@resource).should be_true
diff --git a/spec/unit/util/tagging.rb b/spec/unit/util/tagging.rb
index <HASH>..<HASH> 100755
--- a/spec/unit/util/tagging.rb
+++ b/spec/unit/util/tagging.rb
@@ -89,4 +89,14 @@ describe Puppet::Util::Tagging, "when adding tags" do
it "should indicate when the object is not tagged with a provided tag" do
@tagger.should_not be_tagged("one")
end
+
+ it "should indicate when the object is tagged with any tag in an array" do
+ @tagger.tag("one")
+ @tagger.should be_tagged("one","two","three")
+ end
+
+ it "should indicate when the object is not tagged with any tag in an array" do
+ @tagger.tag("one")
+ @tagger.should_not be_tagged("two","three")
+ end
end
|
Fixing <I> Specifying multiple tags fails to apply any of them
Fix code that was passing an Array of code to a method that was
expecting a single tag.
Includes Markus's suggestions
|
puppetlabs_puppet
|
train
|
32199137b8782a3d41010179cadc3c241cd80806
|
diff --git a/environs/azure/storage.go b/environs/azure/storage.go
index <HASH>..<HASH> 100644
--- a/environs/azure/storage.go
+++ b/environs/azure/storage.go
@@ -7,6 +7,7 @@ import (
"io"
"launchpad.net/gwacl"
"launchpad.net/juju-core/environs"
+ "launchpad.net/juju-core/errors"
)
type azureStorage struct {
@@ -50,7 +51,11 @@ func (storage *azureStorage) Get(name string) (io.ReadCloser, error) {
if err != nil {
return nil, err
}
- return context.GetBlob(storage.getContainer(), name)
+ reader, err := context.GetBlob(storage.getContainer(), name)
+ if gwacl.IsNotFoundError(err) {
+ return nil, errors.NotFoundf("file '%s' not found", name)
+ }
+ return reader, err
}
// List is specified in the StorageReader interface.
diff --git a/environs/azure/storage_test.go b/environs/azure/storage_test.go
index <HASH>..<HASH> 100644
--- a/environs/azure/storage_test.go
+++ b/environs/azure/storage_test.go
@@ -9,6 +9,7 @@ import (
. "launchpad.net/gocheck"
"launchpad.net/gwacl"
"launchpad.net/juju-core/environs/config"
+ "launchpad.net/juju-core/errors"
"net/http"
"strings"
)
@@ -145,14 +146,21 @@ func (StorageSuite) TestGet(c *C) {
c.Check(string(data), Equals, blobContent)
}
+func (StorageSuite) TestGetReturnsNotFoundIf404(c *C) {
+ container := "container"
+ filename := "blobname"
+ response := makeResponse("not found", http.StatusNotFound)
+ azStorage, _ := makeAzureStorage(response, container)
+ _, err := azStorage.Get(filename)
+ c.Assert(err, NotNil)
+ c.Check(errors.IsNotFoundError(err), Equals, true)
+}
+
func (StorageSuite) TestPut(c *C) {
blobContent := "test blob"
container := "container"
filename := "blobname"
- response := &http.Response{
- Status: fmt.Sprintf("%d", http.StatusCreated),
- StatusCode: http.StatusCreated,
- }
+ response := makeResponse("", http.StatusCreated)
azStorage, transport := makeAzureStorage(response, container)
err := azStorage.Put(filename, strings.NewReader(blobContent), 10)
c.Assert(err, IsNil)
@@ -165,10 +173,7 @@ func (StorageSuite) TestPut(c *C) {
func (StorageSuite) TestRemove(c *C) {
container := "container"
filename := "blobname"
- response := &http.Response{
- Status: fmt.Sprintf("%d", http.StatusAccepted),
- StatusCode: http.StatusAccepted,
- }
+ response := makeResponse("", http.StatusAccepted)
azStorage, transport := makeAzureStorage(response, container)
err := azStorage.Remove(filename)
c.Assert(err, IsNil)
@@ -178,3 +183,12 @@ func (StorageSuite) TestRemove(c *C) {
c.Check(transport.Request.URL.String(), Matches, context.GetFileURL(container, filename)+"?.*")
c.Check(transport.Request.Method, Equals, "DELETE")
}
+
+func (StorageSuite) TestRemoveNonExistantBlobSucceeds(c *C) {
+ container := "container"
+ filename := "blobname"
+ response := makeResponse("", http.StatusNotFound)
+ azStorage, _ := makeAzureStorage(response, container)
+ err := azStorage.Remove(filename)
+ c.Assert(err, IsNil)
+}
|
Return NotFound error in Get. Add tests.
|
juju_juju
|
train
|
774399fd661ff5b6fba453891646001a79675535
|
diff --git a/libnetwork/networkdb/cluster.go b/libnetwork/networkdb/cluster.go
index <HASH>..<HASH> 100644
--- a/libnetwork/networkdb/cluster.go
+++ b/libnetwork/networkdb/cluster.go
@@ -184,7 +184,8 @@ func (nDB *NetworkDB) reapTableEntries() {
func (nDB *NetworkDB) gossip() {
networkNodes := make(map[string][]string)
nDB.RLock()
- for nid := range nDB.networks[nDB.config.NodeName] {
+ thisNodeNetworks := nDB.networks[nDB.config.NodeName]
+ for nid := range thisNodeNetworks {
networkNodes[nid] = nDB.networkNodes[nid]
}
@@ -195,8 +196,17 @@ func (nDB *NetworkDB) gossip() {
bytesAvail := udpSendBuf - compoundHeaderOverhead
nDB.RLock()
- broadcastQ := nDB.networks[nDB.config.NodeName][nid].tableBroadcasts
+ network, ok := thisNodeNetworks[nid]
nDB.RUnlock()
+ if !ok || network == nil {
+ // It is normal for the network to be removed
+ // between the time we collect the network
+ // attachments of this node and processing
+ // them here.
+ continue
+ }
+
+ broadcastQ := network.tableBroadcasts
if broadcastQ == nil {
logrus.Errorf("Invalid broadcastQ encountered while gossiping for network %s", nid)
diff --git a/libnetwork/networkdb/delegate.go b/libnetwork/networkdb/delegate.go
index <HASH>..<HASH> 100644
--- a/libnetwork/networkdb/delegate.go
+++ b/libnetwork/networkdb/delegate.go
@@ -146,6 +146,11 @@ func (nDB *NetworkDB) handleTableMessage(buf []byte) {
}
broadcastQ := n.tableBroadcasts
+
+ if broadcastQ == nil {
+ return
+ }
+
broadcastQ.QueueBroadcast(&tableEventMessage{
msg: buf,
id: tEvent.NetworkID,
|
Fix couple of panics in networkdb
|
moby_moby
|
train
|
46df160074d53841302848b9a8b90b0883bfb9ad
|
diff --git a/lib/phys/wave.js b/lib/phys/wave.js
index <HASH>..<HASH> 100644
--- a/lib/phys/wave.js
+++ b/lib/phys/wave.js
@@ -31,4 +31,101 @@ wave = exports;
wave.angularFrequency = function(T){
return ((2 * Math.Pi) / (T));
-};
\ No newline at end of file
+};
+
+/*
+* Displacement (x) of a particle from an arbitrarily defined equilibrium point at time = t
+@param {Number} Amplitude of oscillation (A)
+@param {Number} Angular frequency (ω)
+@param {Number} Time (t)
+@return {Number} x(t) = A * sin(ω*t)
+*/
+
+wave.displacement = function(m, ω, t ) {
+ return A * Math.sin(ω * t );
+};
+
+/*
+* Velocity (v) of a particle from an arbitrarily defined equilibrium point at time = t
+@param {Number} Angular frequency (ω)
+@param {Number} Amplitude of oscillation (A)
+@param {Number} Time (t)
+@return {Number} v(t) = ω * A * cos(ω*t)
+*/
+
+wave.velocity = function(ω, A, t ) {
+ return ω * A * Math.cos(ω * t );
+};
+
+/*
+* Acceleration (a) of a particle from an arbitrarily defined equilibrium point at time = t
+@param {Number} Angular frequency (ω)
+@param {Number} Amplitude of oscillation (A)
+@param {Number} Time (t)
+@return {Number} a(t) = -ω^2 * A * sin(ω*t)
+*/
+
+wave.acceleration = function(ω, A, t ) {
+ return (-1 * ω)^2 * A * Math.sin(ω * t );
+};
+
+/*
+* Kinetic energy (K) of a particle undergoing simple harmonic motion.
+@param {Number} Mass of particle (m)
+@param {Number} Angular frequency (ω)
+@param {Number} Amplitude of oscillation (A)
+@param {Number} Displacement from equilibrium point (x)
+@return {Number} K = 0.5 * m * ω^2 * (A^2 - x^2)
+*/
+
+wave.kineticEnergy = function(m, ω, A, x ) {
+ return (0.5 * m * ω^2 * (A^2 - x^2));
+};
+
+/*
+* Potential energy (U) of a particle undergoing simple harmonic motion.
+@param {Number} Mass of particle (m)
+@param {Number} Angular frequency (ω)
+@param {Number} Displacement from equilibrium point (x)
+@return {Number} K = 0.5 * m * ω^2 * x^2
+*/
+
+wave.potentialEnergy = function(m, ω, x ) {
+ return (0.5 * m * ω^2 * x^2);
+};
+
+/*
+* Total energy (E) of a particle undergoing simple harmonic motion.
+@param {Number} Mass of particle (m)
+@param {Number} Angular frequency (ω)
+@param {Number} Amplitude of oscillation (A)
+@return {Number} E = 0.5 * m * ω^2 * A^2
+*/
+
+wave.netEnergy = function(m, ω, A) {
+ return (0.5 * m * ω^2 * A^2);
+};
+
+/*
+* Wave Speed (v) Function
+@param {Number} Frequency (f)
+@param {Number} Wavelength (λ)
+@return {Number} ω = 2 pi / T
+*/
+
+wave.waveSpeed = function(frequency, wavelength) {
+ return frequency * wavelength;
+};
+
+
+/*
+* Refractive Index of an unknown material
+@param {Number} Wave speed in known medium (v1)
+@param {Number} Wave speed in unknown medium (v2)
+@param {Number} Refractive Index of known medium (n)
+@return {Number} n2 = (n1 * v1) / v2
+*/
+
+wave.refractiveIndex = function(v1, v2, n1) {
+ return (n1 * v1) / v2
+};
|
Added functions to wave.js
|
AbhiAgarwal_phys.js
|
train
|
75cf324322fafe9f2b3f92de369752f413886353
|
diff --git a/hugolib/site.go b/hugolib/site.go
index <HASH>..<HASH> 100644
--- a/hugolib/site.go
+++ b/hugolib/site.go
@@ -1711,6 +1711,8 @@ func (s *Site) newHomeNode() *Node {
n.IsHome = true
s.setURLs(n, "/")
n.Data["Pages"] = s.Pages
+ n.Date = s.Pages[0].Date
+ n.Lastmod = s.Pages[0].Lastmod
return n
}
|
Set Date and Lastmod for main home page
Fixes #<I>
|
gohugoio_hugo
|
train
|
663c65327becfa59c2a5a9f63a67b0eca9f7fcec
|
diff --git a/lib/jboss-cloud/appliance-image-customize.rb b/lib/jboss-cloud/appliance-image-customize.rb
index <HASH>..<HASH> 100644
--- a/lib/jboss-cloud/appliance-image-customize.rb
+++ b/lib/jboss-cloud/appliance-image-customize.rb
@@ -125,6 +125,13 @@ module JBossCloud
guestfs.rm_rf("/tmp/rpms")
@log.debug "Additional packages installed."
+ @log.debug "Changing configuration files using augeas..."
+ guestfs.aug_init( "/", 0 )
+ # disable password authentication
+ guestfs.aug_set( "/files/etc/ssh/sshd_config/PasswordAuthentication", "no" )
+ guestfs.aug_save
+ @log.debug "Augeas changes saved."
+
guestfs.close
@log.debug "EC2 image prepared!"
diff --git a/lib/jboss-cloud/appliance-image.rb b/lib/jboss-cloud/appliance-image.rb
index <HASH>..<HASH> 100644
--- a/lib/jboss-cloud/appliance-image.rb
+++ b/lib/jboss-cloud/appliance-image.rb
@@ -106,12 +106,10 @@ module JBossCloud
guestfs_helper.rebuild_rpm_database
# TODO remove this, http://oddthesis.lighthouseapp.com/projects/19748-jboss-cloud/tickets/95
- if guestfs.sh( "rpm -qa | grep httpd | wc -l" ).to_i > 0
- @log.debug "Applying APR/HTTPD workaround..."
- guestfs.sh( "yum -y remove apr" )
- guestfs.sh( "yum -y install mod_cluster --disablerepo=updates" )
- guestfs.sh( "/sbin/chkconfig httpd on" )
- @log.debug "Workaround applied."
+ if guestfs.sh( "rpm -qa | grep apr | wc -l" ).to_i > 0
+ @log.debug "Upgrading APR..."
+ guestfs.sh( "yum --enablerepo=updates-testing update apr" )
+ @log.debug "APR upgraded."
# clean RPM database one more time to leave image clean
guestfs_helper.rebuild_rpm_database
|
don't use password authentication, apr upgrade
|
boxgrinder_boxgrinder-build
|
train
|
21ba8b687fad3b645f52c47abeb3aae79577ff5f
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/StorageStartupMetadata.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/StorageStartupMetadata.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/StorageStartupMetadata.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/StorageStartupMetadata.java
@@ -354,6 +354,8 @@ public class StorageStartupMetadata {
final long xxHash = XX_HASH_64.hash(buffer, XX_HASH_OFFSET, buffer.capacity() - XX_HASH_OFFSET, XX_HASH_SEED);
buffer.putLong(0, xxHash);
- return buffer.rewind();
+ buffer.rewind();
+
+ return buffer;
}
}
|
Usage of JDK 9 API was removed.
|
orientechnologies_orientdb
|
train
|
48f4b60c5d9663f79abd4607f22aaabebe7324ae
|
diff --git a/source/awesome_tool/mvc/controllers/graphical_editor.py b/source/awesome_tool/mvc/controllers/graphical_editor.py
index <HASH>..<HASH> 100644
--- a/source/awesome_tool/mvc/controllers/graphical_editor.py
+++ b/source/awesome_tool/mvc/controllers/graphical_editor.py
@@ -926,6 +926,8 @@ class GraphicalEditorController(ExtendedController):
move_state(self.single_selection)
elif isinstance(self.single_selection, (DataPortModel, ScopedVariableModel)):
move_port(self.single_selection)
+ return True # Prevent shortcut from being passed to GTK
+ return False # Allow passing of shortcut
def _move_waypoint(self, new_pos, modifier_keys):
"""Moves the currently selected waypoint to the given position
diff --git a/source/awesome_tool/mvc/shortcut_manager.py b/source/awesome_tool/mvc/shortcut_manager.py
index <HASH>..<HASH> 100644
--- a/source/awesome_tool/mvc/shortcut_manager.py
+++ b/source/awesome_tool/mvc/shortcut_manager.py
@@ -74,11 +74,10 @@ class ShortcutManager():
self.accel_group.connect_group(keyval, modifier_mask, gtk.ACCEL_VISIBLE, callback)
def __on_shortcut(self, action, accel_group, window, key_value, modifier_mask):
- self.trigger_action(action, key_value, modifier_mask)
- if action in ['up', 'down', 'left', 'right']:
- # TODO: return True, if the controller implementing the action is focused
- return True
- return False
+ res = self.trigger_action(action, key_value, modifier_mask)
+ # If returning False, the shortcut is forwarded to GTK to be used for default actions (like copy and paste in
+ # a text field). If a controller wants to prevent this, it has to return True.
+ return res
def __get_action_for_shortcut(self, lookup_shortcut):
for action in self.__action_to_shortcuts:
@@ -127,13 +126,14 @@ class ShortcutManager():
:param modifier_mask: The modifier mask of the shortcut that caused the trigger
:return: The number of callback functions called
"""
- ctr = 0
+ res = False
if action in self.__action_to_callbacks:
for callback_function in self.__action_to_callbacks[action]:
- ctr += 1
try:
- callback_function(key_value, modifier_mask)
+ ret = callback_function(key_value, modifier_mask)
+ # If at least one controller returns True, the whole result becomes True
+ res |= (False if ret is None else ret)
except Exception as e:
logger.error('Exception while calling callback methods for action "{0}": {1} {2}'.format(
action, e.message, traceback.format_exc()))
- return ctr
+ return res
|
Allow controller to decide whether shortcuts are forwarded to GTK
If a controller returns True in a callback method for a shortcut, the shortcut is no
longer forwarded to GTK.
|
DLR-RM_RAFCON
|
train
|
215348e1e743e1aa0fbddb7be937f58144d6b0e9
|
diff --git a/h2o-py/h2o/frame.py b/h2o-py/h2o/frame.py
index <HASH>..<HASH> 100644
--- a/h2o-py/h2o/frame.py
+++ b/h2o-py/h2o/frame.py
@@ -1103,7 +1103,9 @@ class H2OFrame(object):
:param use: One of "everything", "complete.obs", or "all.obs".
:return: The covariance matrix of the columns in this H2OFrame.
"""
- return H2OFrame._expr(expr=ExprNode("var",self,self if y is None else y,use))._scalar()
+ fr = H2OFrame._expr(expr=ExprNode("var",self,self if y is None else y,use))
+ if self.nrow==1: return fr._scalar()
+ return fr._frame()
def sd(self):
"""
@@ -1486,11 +1488,11 @@ class H2OFrame(object):
##### WARNING: MAGIC REF COUNTING CODE BELOW.
##### CHANGE AT YOUR OWN RISK.
##### ALSO: DO NOT ADD METHODS BELOW THIS LINE (pretty please)
- def _eager(self, pytmp=True, scalar=False):
+ def _eager(self, top=True, scalar=False):
if self._id is None:
# top-level call to execute all subparts of self._ast
sb = self._ast._eager()
- if pytmp:
+ if top:
self._id = None if scalar else _py_tmp_key()
res = h2o.rapids(ExprNode._collapse_sb(sb), self._id)
if 'scalar' in res or "string" in res:
diff --git a/h2o-py/tests/pyunit_utils/utilsPY.py b/h2o-py/tests/pyunit_utils/utilsPY.py
index <HASH>..<HASH> 100644
--- a/h2o-py/tests/pyunit_utils/utilsPY.py
+++ b/h2o-py/tests/pyunit_utils/utilsPY.py
@@ -126,7 +126,6 @@ def np_comparison_check(h2o_data, np_data, num_elements):
if isinstance(np_val, np.bool_): np_val = bool(np_val) # numpy haz special bool type :(
assert np.absolute(h2o_val - np_val) < 1e-6, \
"failed comparison check! h2o computed {0} and numpy computed {1}".format(h2o_val, np_val)
-
def javapredict(algo, equality, train, test, x, y, **kwargs):
print "Creating model in H2O"
if algo == "gbm":
|
fix var to return scalar / frame based on nrow (since eager anyways, ok to call nrow)
|
h2oai_h2o-3
|
train
|
f8a72e6f56164610e0fffd54c5b1625e4d31a80d
|
diff --git a/src/main/java/com/couchbase/client/core/tracing/ThresholdLogReporter.java b/src/main/java/com/couchbase/client/core/tracing/ThresholdLogReporter.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/couchbase/client/core/tracing/ThresholdLogReporter.java
+++ b/src/main/java/com/couchbase/client/core/tracing/ThresholdLogReporter.java
@@ -33,6 +33,8 @@ import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import static com.couchbase.client.core.logging.RedactableArgument.system;
+
/**
* The {@link ThresholdLogReporter} retrieves spans from (usually) a {@link Tracer}
* and stores them for threshold-based aggregation and logging.
@@ -484,20 +486,20 @@ public class ThresholdLogReporter {
String spanId = span.request().operationId();
String operation_id = span.operationName() + (spanId == null ? "" : ":" + spanId);
- entry.put("operation_id", operation_id);
+ entry.put("operation_id", system(operation_id));
String local = span.request().lastLocalSocket();
String peer = span.request().lastRemoteSocket();
if (local != null) {
- entry.put("local_address", local);
+ entry.put("local_address", system(local));
}
if (peer != null) {
- entry.put("remote_address", peer);
+ entry.put("remote_address", system(peer));
}
String localId = span.request().lastLocalId();
if (localId != null) {
- entry.put("local_id", localId);
+ entry.put("local_id", system(localId));
}
String decode_duration = span.getBaggageItem(KEY_DECODE_MICROS);
@@ -627,20 +629,20 @@ public class ThresholdLogReporter {
String spanId = span.request().operationId();
String operation_id = span.operationName() + (spanId == null ? "" : ":" + spanId);
- entry.put("operation_id", operation_id);
+ entry.put("operation_id", system(operation_id));
String local = span.request().lastLocalSocket();
String peer = span.request().lastRemoteSocket();
if (local != null) {
- entry.put("local_address", local);
+ entry.put("local_address", system(local));
}
if (peer != null) {
- entry.put("remote_address", peer);
+ entry.put("remote_address", system(peer));
}
String localId = span.request().lastLocalId();
if (localId != null) {
- entry.put("local_id", localId);
+ entry.put("local_id", system(localId));
}
String decode_duration = span.getBaggageItem(KEY_DECODE_MICROS);
diff --git a/src/test/java/com/couchbase/client/core/tracing/ThresholdLogReporterTest.java b/src/test/java/com/couchbase/client/core/tracing/ThresholdLogReporterTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/couchbase/client/core/tracing/ThresholdLogReporterTest.java
+++ b/src/test/java/com/couchbase/client/core/tracing/ThresholdLogReporterTest.java
@@ -67,7 +67,7 @@ public class ThresholdLogReporterTest {
List<Map<String, Object>> top = (List<Map<String, Object>>) kvService.get("top");
assertEquals(1000000L, top.get(0).get("total_us"));
- assertEquals("get:0x1234", top.get(0).get("operation_id"));
+ assertEquals("get:0x1234", top.get(0).get("operation_id").toString());
} finally {
if (reporter != null) {
reporter.shutdown();
|
JVMCBC-<I>: Add log redaction to threshold log reporting.
This changeset adds log redaction to the threshold log reporter.
Note that right now these are only "system" log messages, and
the way it is currently implemented only user data is actually
redacted.
Once we enable system data in the future, it will just work.
Change-Id: I<I>dc9de1a<I>d<I>fc<I>f<I>a<I>dd<I>f
Reviewed-on: <URL>
|
couchbase_couchbase-jvm-core
|
train
|
9b661d0337e27a4db3a0bb9bc3fc4827c87462d6
|
diff --git a/args.js b/args.js
index <HASH>..<HASH> 100644
--- a/args.js
+++ b/args.js
@@ -4,7 +4,8 @@ const argsDefs = [
{ name: 'no-fixtures', alias: 'f', type: Boolean, defaultValue: false },
{ name: 'test', alias: 't', type: String, multiple: true, defaultValue: ['*'] },
{ name: 'ravendb-host', alias: 'h', type: String, defaultValue: 'localhost.fiddler' },
- { name: 'ravendb-port', alias: 'p', type: String, defaultValue: '8080' }
+ { name: 'ravendb-port', alias: 'p', type: String, defaultValue: '8080' },
+ { name: 'ravendb-certificate', alias: 'c', type: String, defaultValue: null }
];
module.exports = args(argsDefs, { partial: true });
\ No newline at end of file
diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -80,7 +80,8 @@ gulp.task('run:tests', ['clean', 'build:tests:args', 'build:tests'], () => {
.pipe(mocha({
"timeout": 10000,
"ravendb-host": args["ravendb-host"],
- "ravendb-port": args["ravendb-port"]
+ "ravendb-port": args["ravendb-port"],
+ "ravendb-certificate": args["ravendb-certificate"]
}))
.on('error', () => process.exit(-1));
});
diff --git a/test/TestBase.ts b/test/TestBase.ts
index <HASH>..<HASH> 100644
--- a/test/TestBase.ts
+++ b/test/TestBase.ts
@@ -6,6 +6,8 @@ import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as args from '../args';
import * as uuid from 'uuid';
+import * as path from 'path';
+import * as fs from 'fs';
import {RequestExecutor} from "../src/Http/Request/RequestExecutor";
import {IndexDefinition} from "../src/Database/Indexes/IndexDefinition";
import {CreateDatabaseOperation} from "../src/Database/Operations/CreateDatabaseOperation";
@@ -15,15 +17,42 @@ import {DeleteDatabaseOperation} from "../src/Database/Operations/DeleteDatabase
import {StringUtil} from "../src/Utility/StringUtil";
import {IDocumentStore} from "../src/Documents/IDocumentStore";
import {DocumentStore} from "../src/Documents/DocumentStore";
+import {CertificateType, Certificate} from "../src/Auth/Certificate";
+import {IStoreAuthOptions} from "../src/Auth/AuthOptions";
-const defaultUrl: string = StringUtil.format("http://{ravendb-host}:{ravendb-port}", args);
+const certificateFile: string = args['ravendb-certificate'];
const defaultDatabase: string = "NorthWindTest";
+const defaultUrl: string = StringUtil.format(
+ "{protocol}://{ravendb-host}:{ravendb-port}", {
+ ...args, protocol: !certificateFile
+ ? 'http' : 'https'
+ }
+);
let indexMap: string;
let index: IndexDefinition;
let requestExecutor: RequestExecutor;
let store: IDocumentStore;
let currentDatabase: string;
+let certificate: string = null;
+let certificateType: CertificateType = null;
+
+if (certificateFile) {
+ switch (path.extname(certificateFile)
+ .toLowerCase().substring(1)
+ ) {
+ case 'pem':
+ certificateType = Certificate.Pem;
+ break;
+ case 'pfx':
+ certificateType = Certificate.Pfx;
+ break;
+ }
+
+ if (certificateType) {
+ certificate = fs.readFileSync(certificateFile).toString();
+ }
+}
before(() => {
chai.use(chaiAsPromised);
@@ -32,10 +61,18 @@ before(() => {
beforeEach(async function() {
currentDatabase = `${defaultDatabase}__${uuid()}`;
+ let authOptions: IStoreAuthOptions = null;
const dbDoc: DatabaseDocument = new DatabaseDocument
(currentDatabase, {"Raven/DataDir": "test"});
- store = DocumentStore.create(defaultUrl, currentDatabase);
+ if (certificate) {
+ authOptions = {
+ type: certificateType,
+ certificate
+ };
+ }
+
+ store = DocumentStore.create(defaultUrl, currentDatabase, authOptions);
store.initialize();
await store.maintenance.server.send(new CreateDatabaseOperation(dbDoc));
|
- passing certificate to test runner
|
ravendb_ravendb-nodejs-client
|
train
|
9815d302a97e775ec36c149286529d3c91c65b19
|
diff --git a/ui/src/shared/components/Dygraph.js b/ui/src/shared/components/Dygraph.js
index <HASH>..<HASH> 100644
--- a/ui/src/shared/components/Dygraph.js
+++ b/ui/src/shared/components/Dygraph.js
@@ -27,7 +27,7 @@ export default class Dygraph extends Component {
constructor(props) {
super(props)
this.state = {
- synced: false,
+ isSynced: false,
}
// workaround for dygraph.updateOptions breaking legends
@@ -134,9 +134,9 @@ export default class Dygraph extends Component {
}
// Disallow screen overflow of legend
- const legendBottomClipped = graphBottom + legendHeight > screenHeight
+ const isLegendBottomClipped = graphBottom + legendHeight > screenHeight
- const legendTop = legendBottomClipped
+ const legendTop = isLegendBottomClipped
? graphHeight + 8 - legendHeight
: graphHeight + 8
@@ -219,9 +219,9 @@ export default class Dygraph extends Component {
}
sync() {
- if (this.props.synchronizer && !this.state.synced) {
+ if (this.props.synchronizer && !this.state.isSynced) {
this.props.synchronizer(this.dygraph)
- this.setState({synced: true})
+ this.setState({isSynced: true})
}
}
|
Update bool vars to use 'is' convention
|
influxdata_influxdb
|
train
|
150e339bd769a40a29812197868905c4b398dbf3
|
diff --git a/lib/fakeredis/version.rb b/lib/fakeredis/version.rb
index <HASH>..<HASH> 100644
--- a/lib/fakeredis/version.rb
+++ b/lib/fakeredis/version.rb
@@ -1,3 +1,3 @@
module FakeRedis
- VERSION = "0.1.2"
+ VERSION = "0.1.3"
end
|
Bumping to version <I>
|
guilleiguaran_fakeredis
|
train
|
fd4c5d21a54d12f0d5947ad67afc6133ffe09324
|
diff --git a/.eslintrc.js b/.eslintrc.js
index <HASH>..<HASH> 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -54,13 +54,10 @@ module.exports = {
"allowEmptyCatch": true
}
],
- "no-inner-declarations": [
- "error",
- "functions"
- ],
+ "no-inner-declarations": "off",
// (not in recommended)
// "no-extra-parens": "off",
- // "no-prototype-builtins": "off",
+ "no-prototype-builtins": "off",
"no-template-curly-in-string": "error",
"no-unsafe-negation": "error",
// "valid-jsdoc": "off",
@@ -95,7 +92,7 @@ module.exports = {
"no-global-assign": "error",
// "no-implicit-globals": "off",
"no-implied-eval": "error",
- "no-invalid-this": "error",
+ "no-invalid-this": "off",
"no-iterator": "error",
"no-labels": [
"error",
@@ -124,7 +121,7 @@ module.exports = {
// "no-unused-expressions": "off",
"no-useless-call": "error",
"no-useless-concat": "error",
- // "no-useless-escape": "off",
+ "no-useless-escape": "off",
"no-void": "error",
// "no-warning-comments": "off",
"no-with": "error",
@@ -276,6 +273,8 @@ module.exports = {
"error",
"never"
],
- "wrap-regex": "error"
+ // "wrap-regex": "error",
+ "no-control-regex": "off",
+ "import/no-duplicates": "off"
}
};
|
adjust .eslintrc.js to prevent unnecessary lint errors
(work in progress on Beautify TypeScript source code #<I>)
|
vivliostyle_vivliostyle.js
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.