hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
d6c4d0260cd062b2d5d57833bde567d3d604fceb
|
diff --git a/tests/TestCase/I18n/DateTest.php b/tests/TestCase/I18n/DateTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/I18n/DateTest.php
+++ b/tests/TestCase/I18n/DateTest.php
@@ -64,10 +64,6 @@ class DateTest extends TestCase
$expected = '1/14/10';
$this->assertEquals($expected, $result);
- $result = $time->i18nFormat(\IntlDateFormatter::FULL, null, 'es-ES');
- $expected = 'jueves, 14 de enero de 2010, 0:00:00 (GMT)';
- $this->assertEquals($expected, $result);
-
$format = [\IntlDateFormatter::NONE, \IntlDateFormatter::SHORT];
$result = $time->i18nFormat($format);
$expected = '12:00 AM';
@@ -82,8 +78,8 @@ class DateTest extends TestCase
$expected = 'jeudi 14 janvier 2010 00:00:00 UTC';
$this->assertEquals($expected, $result);
- $result = $time->i18nFormat(\IntlDateFormatter::FULL, null, 'es-ES');
- $expected = 'jueves, 14 de enero de 2010, 0:00:00 (GMT)';
+ $result = $time->i18nFormat(\IntlDateFormatter::FULL, null, 'de-DE');
+ $expected = 'Donnerstag, 14. Januar 2010 um 00:00:00 GMT';
$this->assertEquals($expected, $result, 'Default locale should not be used');
}
|
See if german dates don't vary with intl versions.
|
cakephp_cakephp
|
train
|
fb957845ac757cde42e95145deb80b72618d3a39
|
diff --git a/gwpy/io/datafind.py b/gwpy/io/datafind.py
index <HASH>..<HASH> 100755
--- a/gwpy/io/datafind.py
+++ b/gwpy/io/datafind.py
@@ -266,30 +266,30 @@ def reconnect(connection):
def _type_priority(ifo, ftype, trend=None):
- # HOFT types typically have small channel lists (so quick search)
- if HIGH_PRIORITY_TYPE.match(ftype): # HOFT types are small
- prio = 1
- # these types are bogus, or just unhelpful
- elif LOW_PRIORITY_TYPE.match(ftype):
- prio = 10
-
- # if channel is trend, promote trend type (otherwise demote)
- elif trend == 'm-trend' and MINUTE_TREND_TYPE.match(ftype):
- prio = 0
- elif MINUTE_TREND_TYPE.match(ftype):
- prio = 10
- elif trend == 's-trend' and SECOND_TREND_TYPE.match(ftype):
- prio = 0
- elif SECOND_TREND_TYPE.match(ftype):
- prio = 10
-
- # demote commissioning frames for LIGO
- elif ftype == '{}_C'.format(ifo):
- prio = 6
-
- # otherwise give a middle score
+ _priority = {
+ HIGH_PRIORITY_TYPE: 1,
+ LOW_PRIORITY_TYPE: 10,
+ MINUTE_TREND_TYPE: 10,
+ SECOND_TREND_TYPE: 10,
+ re.compile('[A-Z]\d_C'): 6,
+ }
+
+ # default priority
+ prio = 5
+
+ for trendname, trend_regex in [
+ ('m-trend', MINUTE_TREND_TYPE),
+ ('s-trend', SECOND_TREND_TYPE),
+ ]:
+ # if looking for a trend channel, prioritise the matching type
+ if trend == trendname and trend_regex.match(ftype):
+ prio = 0
+ break
else:
- prio = 5
+ # otherwise rank this type according to priority
+ for reg, prio in _priority.items():
+ if reg.match(ftype):
+ break
# use score and length of name, shorter names are typically better
return (prio, len(ftype))
|
gwpy.io: rework of datafind type priority matcher
|
gwpy_gwpy
|
train
|
6ea9a880dc434446c072ac23b1cab89ec3652140
|
diff --git a/daemon/changes.go b/daemon/changes.go
index <HASH>..<HASH> 100644
--- a/daemon/changes.go
+++ b/daemon/changes.go
@@ -9,5 +9,7 @@ func (daemon *Daemon) ContainerChanges(name string) ([]archive.Change, error) {
return nil, err
}
- return container.changes()
+ container.Lock()
+ defer container.Unlock()
+ return daemon.changes(container)
}
diff --git a/daemon/container.go b/daemon/container.go
index <HASH>..<HASH> 100644
--- a/daemon/container.go
+++ b/daemon/container.go
@@ -286,12 +286,6 @@ func (container *Container) Resize(h, w int) error {
return nil
}
-func (container *Container) changes() ([]archive.Change, error) {
- container.Lock()
- defer container.Unlock()
- return container.daemon.changes(container)
-}
-
func (container *Container) getImage() (*image.Image, error) {
if container.daemon == nil {
return nil, derr.ErrorCodeImageUnregContainer
|
Remove unnecessary `Container.changes` function.
|
containers_storage
|
train
|
b752f54661aa11ea235ed6c092a2b41188685e68
|
diff --git a/src/beat.js b/src/beat.js
index <HASH>..<HASH> 100644
--- a/src/beat.js
+++ b/src/beat.js
@@ -1,7 +1,7 @@
(function() {
- var Beat = function ( dance, freq, threshold, decay, onBeat, offBeat ) {
+ var Beat = function ( dance, frequency, threshold, decay, onBeat, offBeat ) {
this.dance = dance;
- this.freq = freq;
+ this.frequency = frequency;
this.threshold = threshold;
this.decay = decay;
this.onBeat = onBeat;
@@ -12,7 +12,7 @@
var _this = this;
this.dance.bind( 'update', function() {
if ( !_this.isOn ) { return; }
- var magnitude = _this.dance.spectrum()[ _this.freq ];
+ var magnitude = _this.dance.spectrum()[ _this.frequency ];
if ( magnitude >= _this.currentThreshold &&
magnitude >= _this.threshold ) {
_this.currentThreshold = magnitude;
|
Change Beat's instance property 'freq' to 'frequency' for more natural get/setting
|
jsantell_dancer.js
|
train
|
10100b7a3ba451f688bd4c64a81393d95f44b3ff
|
diff --git a/src/vis/vis.js b/src/vis/vis.js
index <HASH>..<HASH> 100644
--- a/src/vis/vis.js
+++ b/src/vis/vis.js
@@ -237,9 +237,7 @@ var VisModel = Backbone.Model.extend({
// Global variable for easier console debugging / testing
window.vis = this;
- _.defer(function () {
- this.trigger('load', this);
- }.bind(this));
+ this.trigger('load', this);
},
// we provide a method to set some new settings
|
Remove defer to make it works sync
|
CartoDB_carto.js
|
train
|
52e968455770b5108fc22710aa1845eddbd1f2f4
|
diff --git a/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLBindingSet.java b/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLBindingSet.java
index <HASH>..<HASH> 100644
--- a/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLBindingSet.java
+++ b/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLBindingSet.java
@@ -17,7 +17,7 @@ public class DelegatedIriSQLBindingSet extends AbstractOntopBindingSet implement
private final ImmutableMap<String, Integer> columnMap;
public DelegatedIriSQLBindingSet(List<MainTypeLangValues> row, ImmutableList<String> signature, ImmutableMap<String, Integer> columnMap,
- JDBC2ConstantConverter constantRetriever, ImmutableMap<String, Integer> columnMap1) {
+ JDBC2ConstantConverter constantRetriever) {
super(signature);
this.row = row;
this.constantRetriever = constantRetriever;
diff --git a/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLTupleResultSet.java b/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLTupleResultSet.java
index <HASH>..<HASH> 100644
--- a/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLTupleResultSet.java
+++ b/engine/system/sql/core/src/main/java/it/unibz/inf/ontop/answering/resultset/impl/DelegatedIriSQLTupleResultSet.java
@@ -55,7 +55,7 @@ public class DelegatedIriSQLTupleResultSet extends AbstractSQLTupleResultSet imp
SQLRowReader rowReader = new SQLRowReader();
try {
final List<MainTypeLangValues> cells = rowReader.read(rs, getColumnCount());
- return new DelegatedIriSQLBindingSet(cells, signature, columnMap, ontopConstantRetriever, columnMap);
+ return new DelegatedIriSQLBindingSet(cells, signature, columnMap, ontopConstantRetriever);
} catch (SQLException e) {
throw new OntopConnectionException(e);
}
|
Unnecessary argument of Ontop binding set
|
ontop_ontop
|
train
|
1c8d021a358fc6ee17da422ccd99fe570ce7912f
|
diff --git a/modules/backend/classes/NavigationManager.php b/modules/backend/classes/NavigationManager.php
index <HASH>..<HASH> 100644
--- a/modules/backend/classes/NavigationManager.php
+++ b/modules/backend/classes/NavigationManager.php
@@ -247,6 +247,15 @@ class NavigationManager
}
/**
+ * Removes a single main menu item
+ */
+ public function removeMainMenuItem($owner, $code)
+ {
+ $itemKey = $this->makeItemKey($owner, $code);
+ unset($this->items[$itemKey]);
+ }
+
+ /**
* Dynamically add an array of side menu items
* @param string $owner
* @param string $code
@@ -288,6 +297,20 @@ class NavigationManager
}
/**
+ * Removes a single main menu item
+ */
+ public function removeSideMenuItem($owner, $code, $sideCode)
+ {
+ $itemKey = $this->makeItemKey($owner, $code);
+ if (!isset($this->items[$itemKey])) {
+ return false;
+ }
+
+ $mainItem = $this->items[$itemKey];
+ unset($mainItem->sideMenu[$sideCode]);
+ }
+
+ /**
* Returns a list of the main menu items.
* @return array
*/
diff --git a/tests/unit/backend/classes/NavigationManagerTest.php b/tests/unit/backend/classes/NavigationManagerTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/backend/classes/NavigationManagerTest.php
+++ b/tests/unit/backend/classes/NavigationManagerTest.php
@@ -79,6 +79,51 @@ class NavigationManagerTest extends TestCase
$this->assertEquals(200, $items['categories']->order);
}
+ public function testAddMainMenuItems()
+ {
+ $manager = NavigationManager::instance();
+ $manager->addMainMenuItems('October.Tester', [
+ 'print' => [
+ 'label' => 'Print',
+ 'icon' => 'icon-print',
+ 'url' => 'javascript:window.print()'
+ ]
+ ]);
+
+ $items = $manager->listMainMenuItems();
+
+ $this->assertInternalType('array', $items);
+ $this->assertArrayHasKey('OCTOBER.TESTER.PRINT', $items);
+
+ $item = $items['OCTOBER.TESTER.PRINT'];
+ $this->assertEquals('print', $item->code);
+ $this->assertEquals('Print', $item->label);
+ $this->assertEquals('icon-print', $item->icon);
+ $this->assertEquals('javascript:window.print()', $item->url);
+ $this->assertEquals(500, $item->order);
+ $this->assertEquals('October.Tester', $item->owner);
+ }
+
+ public function testRemoveMainMenuItem()
+ {
+ $manager = NavigationManager::instance();
+ $manager->addMainMenuItems('October.Tester', [
+ 'close' => [
+ 'label' => 'Close',
+ 'icon' => 'icon-times',
+ 'url' => 'javascript:window.close()'
+ ]
+ ]);
+
+ $items = $manager->listMainMenuItems();
+ $this->assertArrayHasKey('OCTOBER.TESTER.CLOSE', $items);
+
+ $manager->removeMainMenuItem('October.Tester', 'close');
+
+ $items = $manager->listMainMenuItems();
+ $this->assertArrayNotHasKey('OCTOBER.TESTER.CLOSE', $items);
+ }
+
public function testAddSideMenuItems()
{
$manager = NavigationManager::instance();
@@ -116,4 +161,26 @@ class NavigationManagerTest extends TestCase
$this->assertContains('october.tester.access_foo', $items['foo']->permissions);
$this->assertContains('october.tester.access_bar', $items['foo']->permissions);
}
-}
\ No newline at end of file
+
+ public function testRemoveSideMenuItem()
+ {
+ $manager = NavigationManager::instance();
+ $manager->addSideMenuItems('October.Tester', 'blog', [
+ 'bar' => [
+ 'label' => 'Bar',
+ 'icon' => 'icon-bars',
+ 'url' => 'http://yahoo.com'
+ ]
+ ]);
+
+ $manager->setContext('October.Tester', 'blog');
+
+ $items = $manager->listSideMenuItems();
+ $this->assertArrayHasKey('bar', $items);
+
+ $manager->removeSideMenuItem('October.Tester', 'blog', 'bar');
+
+ $items = $manager->listSideMenuItems();
+ $this->assertArrayNotHasKey('bar', $items);
+ }
+}
|
Adds the ability to remove navigation items
Included tests
Refs #<I>
|
octobercms_october
|
train
|
31229360472c3e9b2f125676532c1899ab30a6f5
|
diff --git a/src/Google/Service/YouTube.php b/src/Google/Service/YouTube.php
index <HASH>..<HASH> 100644
--- a/src/Google/Service/YouTube.php
+++ b/src/Google/Service/YouTube.php
@@ -33,6 +33,9 @@ class Google_Service_YouTube extends Google_Service
/** Manage your YouTube account. */
const YOUTUBE =
"https://www.googleapis.com/auth/youtube";
+ /** Manage your YouTube account. */
+ const YOUTUBE_FORCE_SSL =
+ "https://www.googleapis.com/auth/youtube.force-ssl";
/** View your YouTube account. */
const YOUTUBE_READONLY =
"https://www.googleapis.com/auth/youtube.readonly";
|
Updated YouTube.php
This change has been generated by a script that has detected changes in the
discovery doc of the API.
Check <URL>
|
googleapis_google-api-php-client
|
train
|
c92a5672d02be0a322efe5e4bcb313649fa81439
|
diff --git a/src/software/amazon/ion/impl/LocalSymbolTable.java b/src/software/amazon/ion/impl/LocalSymbolTable.java
index <HASH>..<HASH> 100644
--- a/src/software/amazon/ion/impl/LocalSymbolTable.java
+++ b/src/software/amazon/ion/impl/LocalSymbolTable.java
@@ -327,7 +327,7 @@ final class LocalSymbolTable
// As per the Spec, other field types are treated as
// empty lists
if(foundLocalSymbolList){
- throw new IonException("Multiple symbol tables found.");
+ throw new IonException("Multiple symbol fields found within a single local symbol table.");
}
foundLocalSymbolList = true;
if (fieldType == IonType.LIST)
@@ -355,7 +355,7 @@ final class LocalSymbolTable
case IMPORTS_SID:
{
if(foundImportList){
- throw new IonException("Multiple import tables found.");
+ throw new IonException("Multiple imports fields found within a single local symbol table.");
}
foundImportList = true;
if (fieldType == IonType.LIST)
|
Rejects duplicate symbol/import fields in the symbol table declaration (#<I>)
|
amzn_ion-java
|
train
|
5303e40bed009ffd3ca6ef27697259197e12fe72
|
diff --git a/src/streamlink/plugins/bigo.py b/src/streamlink/plugins/bigo.py
index <HASH>..<HASH> 100644
--- a/src/streamlink/plugins/bigo.py
+++ b/src/streamlink/plugins/bigo.py
@@ -4,8 +4,8 @@ import struct
from streamlink import PluginError
from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
-from streamlink.stream import Stream
+from streamlink.plugin.api import http, useragents
+from streamlink.stream import Stream, HLSStream
class BigoStream(Stream):
@@ -51,6 +51,9 @@ class Bigo(Plugin):
_flashvars_re = flashvars = re.compile(
r'''^\s*(?<!<!--)<param.*value="tmp=(\d+)&channel=(\d+)&srv=(\d+\.\d+\.\d+\.\d+)&port=(\d+)"''',
re.M)
+ _video_re = re.compile(
+ r'^\s*(?<!<!--)<source id="videoSrc" src="(http://.*\.m3u8)"',
+ re.M)
@classmethod
def can_handle_url(cls, url):
@@ -59,13 +62,13 @@ class Bigo(Plugin):
def _get_streams(self):
page = http.get(self.url,
allow_redirects=True,
- headers={"User-Agent": "Mozilla/5.0 (MSIE 10.0; Windows NT 6.1; Trident/5.0)"})
- flashvars = self._flashvars_re.search(page.text)
- if not flashvars:
+ headers={"User-Agent": useragents.IPHONE_6})
+ videomatch = self._video_re.search(page.text)
+ if not videomatch:
return
- sid, uid, ip, port = flashvars.groups()
- yield "live", BigoStream(self.session, sid, uid, ip, port)
+ videourl = videomatch.group(1)
+ yield "live", HLSStream(self.session, videourl)
__plugin__ = Bigo
|
bigo: add support for hls streams
This is a fix for issue #<I> since FLV streaming is broken
|
streamlink_streamlink
|
train
|
1b7e6fbde9e612584a3f4d11f56f3f384cce17d1
|
diff --git a/vault/mount.go b/vault/mount.go
index <HASH>..<HASH> 100644
--- a/vault/mount.go
+++ b/vault/mount.go
@@ -58,19 +58,25 @@ func (t *MountTable) Clone() *MountTable {
// MountEntry is used to represent a mount table entry
type MountEntry struct {
- Path string `json:"path"` // Mount Path
- Type string `json:"type"` // Logical backend Type
- Description string `json:"description"` // User-provided description
- UUID string `json:"uuid"` // Barrier view UUID
+ Path string `json:"path"` // Mount Path
+ Type string `json:"type"` // Logical backend Type
+ Description string `json:"description"` // User-provided description
+ UUID string `json:"uuid"` // Barrier view UUID
+ Options map[string]string `json:"options"` // Backend configuration
}
// Returns a deep copy of the mount entry
func (e *MountEntry) Clone() *MountEntry {
+ optClone := make(map[string]string)
+ for k, v := range e.Options {
+ optClone[k] = v
+ }
return &MountEntry{
Path: e.Path,
Type: e.Type,
Description: e.Description,
UUID: e.UUID,
+ Options: optClone,
}
}
|
vault: Adding options to mount table
|
hashicorp_vault
|
train
|
0b9fb9f8939e3aeec2fda88875d4abbce4aecf3c
|
diff --git a/test/helpers/docker.go b/test/helpers/docker.go
index <HASH>..<HASH> 100644
--- a/test/helpers/docker.go
+++ b/test/helpers/docker.go
@@ -150,8 +150,10 @@ func (s *SSHMeta) GatherDockerLogs() {
}
commands := map[string]string{}
for _, k := range res.ByLines() {
- key := fmt.Sprintf("docker logs %s", k)
- commands[key] = fmt.Sprintf("container_%s.log", k)
+ if k != "" {
+ key := fmt.Sprintf("docker logs %s", k)
+ commands[key] = fmt.Sprintf("container_%s.log", k)
+ }
}
testPath, err := CreateReportDirectory()
|
test/helpers: make sure that key is non-empty for running `docker logs`
|
cilium_cilium
|
train
|
1398a56afa78d41ddb67424b1defad026ffb2f55
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -17,6 +17,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+from collections import defaultdict
from distutils.cmd import Command
from distutils.command.build import build
from distutils.command.upload import upload
@@ -31,18 +32,17 @@ import sys
version = '0.11.2'
# get gphoto2 library config
-gphoto2_version = str(subprocess.check_output(
+gphoto2_version = '.'.join(subprocess.check_output(
['pkg-config', '--modversion', 'libgphoto2'],
- universal_newlines=True)).strip().split('.')
-gphoto2_include = subprocess.check_output(
- ['pkg-config', '--cflags-only-I', 'libgphoto2'],
- universal_newlines=True).strip().split()
-gphoto2_libs = str(subprocess.check_output(
- ['pkg-config', '--libs-only-l', 'libgphoto2'],
- universal_newlines=True)).strip().split()
-gphoto2_lib_dirs = str(subprocess.check_output(
- ['pkg-config', '--libs-only-L', 'libgphoto2'],
- universal_newlines=True)).strip().split()
+ universal_newlines=True).split('.')[:2])
+gphoto2_flags = defaultdict(list)
+for flag in subprocess.check_output(
+ ['pkg-config', '--cflags', '--libs', 'libgphoto2'],
+ universal_newlines=True).split():
+ gphoto2_flags[flag[:2]].append(flag)
+gphoto2_include = gphoto2_flags['-I']
+gphoto2_libs = gphoto2_flags['-l']
+gphoto2_lib_dirs = gphoto2_flags['-L']
for n in range(len(gphoto2_include)):
if gphoto2_include[n].endswith('/gphoto2'):
gphoto2_include[n] = gphoto2_include[n][:-len('/gphoto2')]
@@ -55,7 +55,7 @@ mod_names.sort()
# create extension modules list
ext_modules = []
-mod_src_dir = os.path.join('src', 'swig-gp' + '.'.join(gphoto2_version[:2]))
+mod_src_dir = os.path.join('src', 'swig-gp' + gphoto2_version)
extra_compile_args = [
'-O3', '-Wno-unused-variable', '-Wno-strict-prototypes', '-Werror']
libraries = list(map(lambda x: x.replace('-l', ''), gphoto2_libs))
@@ -87,7 +87,7 @@ class build_swig(Command):
def run(self):
# get gphoto2 versions to be swigged
- gp_versions = ['.'.join(gphoto2_version[:2])]
+ gp_versions = [gphoto2_version]
if os.path.isdir('include'):
for name in os.listdir('include'):
match = re.match('gphoto2-(\d\.\d)', name)
|
Reduce number of pkg-config calls in setup.py
|
jim-easterbrook_python-gphoto2
|
train
|
0823f34866de5585d580a650b4e68b8ccd089dbe
|
diff --git a/test/unit/query/integrator.js b/test/unit/query/integrator.js
index <HASH>..<HASH> 100644
--- a/test/unit/query/integrator.js
+++ b/test/unit/query/integrator.js
@@ -43,8 +43,8 @@ describe('integrator', function () {
describe(':: N..M :: ',function () {
var fixtures = {
- joins: require('../../support/fixtures/integrator/n..m.joins.js'),
- cache: require('../../support/fixtures/integrator/cache')
+ joins: _.cloneDeep(require('../../support/fixtures/integrator/n..m.joins.js')),
+ cache: _.cloneDeep(require('../../support/fixtures/integrator/cache'))
};
var results;
@@ -88,7 +88,6 @@ describe('integrator', function () {
_.each(aliases, function (alias) {
result[alias].should.be.ok;
- result[alias].should.be.ok;
});
});
@@ -97,6 +96,10 @@ describe('integrator', function () {
return results.length === _.pluck(results, alias).length;
}).should.be.true;
});
+
+ it('should not include extraneous attributes', function () {
+ console.log('n..m::\n',results[0]);
+ });
});
});
@@ -110,8 +113,8 @@ describe('integrator', function () {
var results;
var fixtures = {
- joins: require('../../support/fixtures/integrator/n..1.joins.js'),
- cache: require('../../support/fixtures/integrator/cache')
+ joins: _.cloneDeep(require('../../support/fixtures/integrator/n..1.joins.js')),
+ cache: _.cloneDeep(require('../../support/fixtures/integrator/cache'))
};
before(function (done){
@@ -168,12 +171,12 @@ describe('integrator', function () {
- describe(':: 1..N ::',function () {
+ describe(':: multiple populates ::',function () {
var results;
var fixtures = {
- joins: require('../../support/fixtures/integrator/n..1.joins.js'),
- cache: require('../../support/fixtures/integrator/cache')
+ joins: _.cloneDeep(require('../../support/fixtures/integrator/multiple.joins.js')),
+ cache: _.cloneDeep(require('../../support/fixtures/integrator/cache'))
};
before(function (done){
|
Use cloneDeep in tests to ensure protection against interference.
|
balderdashy_waterline
|
train
|
b9efc06a61853c91ee101289718171de05357ac7
|
diff --git a/paymentwall/pingback.py b/paymentwall/pingback.py
index <HASH>..<HASH> 100644
--- a/paymentwall/pingback.py
+++ b/paymentwall/pingback.py
@@ -88,7 +88,12 @@ class Pingback(Paymentwall):
def get_type(self):
if 'type' in self.parameters:
- if self.parameters['type'] in [self.PINGBACK_TYPE_REGULAR, self.PINGBACK_TYPE_GOODWILL, self.PINGBACK_TYPE_NEGATIVE]:
+ try:
+ type_parameter = int(self.parameters['type'])
+ except ValueError:
+ return None
+
+ if type_parameter in [self.PINGBACK_TYPE_REGULAR, self.PINGBACK_TYPE_GOODWILL, self.PINGBACK_TYPE_NEGATIVE]:
return self.parameters['type']
def get_user_id(self):
@@ -160,4 +165,4 @@ class Pingback(Paymentwall):
base_string += secret
- return self.hash(base_string, 'sha256') if int(version) == self.SIGNATURE_VERSION_3 else self.hash(base_string, 'md5')
\ No newline at end of file
+ return self.hash(base_string, 'sha256') if int(version) == self.SIGNATURE_VERSION_3 else self.hash(base_string, 'md5')
|
Fix a typing bug in Pingback.get_type()
Parameters are expected to be strings, but in doesn't do implicit type
casts, so we need to do it explicitly.
|
paymentwall_paymentwall-python
|
train
|
7ac7d041a2c970481ff4eed604f15637031c0f3b
|
diff --git a/lib/dm-core/spec/shared/adapter_spec.rb b/lib/dm-core/spec/shared/adapter_spec.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/spec/shared/adapter_spec.rb
+++ b/lib/dm-core/spec/shared/adapter_spec.rb
@@ -22,30 +22,30 @@ share_examples_for 'An Adapter' do
end
end
+
before :all do
- raise '+@adapter+ should be defined in before block' unless instance_variable_get('@adapter')
- # NOTICE: this is a hack
- # To support adapters which need own resource mixins we do not include DataMapper::Resource
- # in the Heffalump directly. Adapters like dm-mongo-adapter can set @dm_resource_module in a before
- # block. Same with the :id Property
- dm_resource_module = @dm_resource_module || DataMapper::Resource
- dm_serial_property = @dm_serial_property || DataMapper::Property::Serial
-
- class ::Heffalump; end
-
- Heffalump.send :include,dm_resource_module
- Heffalump.property :id, dm_serial_property
-
- class ::Heffalump
- property :color, String
- property :num_spots, Integer
- property :striped, Boolean
+ raise '+#adapter+ should be defined in a let(:adapter) block' unless respond_to?(:adapter)
+ raise '+#repository+ should be defined in a let(:repository) block' unless respond_to?(:repository)
+
+ if respond_to?(:heffalump_model)
+ Object.const_set 'Heffalump', heffalump_model
+ else
+ # This is the default Heffalup model. You can replace it with your own
+ # (using let/let!) # but # be shure the replacement provides the required
+ # properties.
+ class Heffalump
+ include DataMapper::Resource
+ property :id, Serial
+ property :color, String
+ property :num_spots, Integer
+ property :striped, Boolean
+ end
end
DataMapper.finalize
# create all tables and constraints before each spec
- if @repository.respond_to?(:auto_migrate!)
+ if repository.respond_to?(:auto_migrate!)
Heffalump.auto_migrate!
end
end
@@ -249,8 +249,8 @@ share_examples_for 'An Adapter' do
describe 'regexp' do
before do
- if (defined?(DataMapper::Adapters::SqliteAdapter) && @adapter.kind_of?(DataMapper::Adapters::SqliteAdapter) ||
- defined?(DataMapper::Adapters::SqlserverAdapter) && @adapter.kind_of?(DataMapper::Adapters::SqlserverAdapter))
+ if (defined?(DataMapper::Adapters::SqliteAdapter) && adapter.kind_of?(DataMapper::Adapters::SqliteAdapter) ||
+ defined?(DataMapper::Adapters::SqlserverAdapter) && adapter.kind_of?(DataMapper::Adapters::SqlserverAdapter))
pending 'delegate regexp matches to same system that the InMemory and YAML adapters use'
end
end
|
Using let blocks to configure shared adapter spec
|
datamapper_dm-core
|
train
|
b3bdc5f35d71d592ab8104ea630a971ba7d2bff1
|
diff --git a/src/org/jblas/DoubleMatrix.java b/src/org/jblas/DoubleMatrix.java
index <HASH>..<HASH> 100644
--- a/src/org/jblas/DoubleMatrix.java
+++ b/src/org/jblas/DoubleMatrix.java
@@ -91,8 +91,8 @@ import java.util.List;
* <tr><th>Method<th>Description
* <tr><td>DoubleMatrix(m)<td>Constructs a column vector.
* <tr><td>DoubleMatrix(new double[] {value1, value2, ...})<td>Constructs a column vector.
- * <tr><td>DoubleMatrix.zeros(m) <td>Initial values set to 1.0.
- * <tr><td>DoubleMatrix.ones(m) <td>Initial values set to 0.0.
+ * <tr><td>DoubleMatrix.zeros(m) <td>Initial values set to 0.0.
+ * <tr><td>DoubleMatrix.ones(m) <td>Initial values set to 1.0.
* <tr><td>DoubleMatrix.rand(m) <td>Values drawn at random between 0.0 and 1.0.
* <tr><td>DoubleMatrix.randn(m) <td>Values drawn from normal distribution.
* </table>
@@ -835,6 +835,7 @@ public class DoubleMatrix implements Serializable {
}
}
+
/** Set elements in linear ordering in the specified indices. */
public DoubleMatrix put(int[] indices, DoubleMatrix x) {
if (x.isScalar()) {
diff --git a/src/org/jblas/FloatMatrix.java b/src/org/jblas/FloatMatrix.java
index <HASH>..<HASH> 100644
--- a/src/org/jblas/FloatMatrix.java
+++ b/src/org/jblas/FloatMatrix.java
@@ -91,8 +91,8 @@ import java.util.List;
* <tr><th>Method<th>Description
* <tr><td>FloatMatrix(m)<td>Constructs a column vector.
* <tr><td>FloatMatrix(new float[] {value1, value2, ...})<td>Constructs a column vector.
- * <tr><td>FloatMatrix.zeros(m) <td>Initial values set to 1.0f.
- * <tr><td>FloatMatrix.ones(m) <td>Initial values set to 0.0f.
+ * <tr><td>FloatMatrix.zeros(m) <td>Initial values set to 0.0f.
+ * <tr><td>FloatMatrix.ones(m) <td>Initial values set to 1.0f.
* <tr><td>FloatMatrix.rand(m) <td>Values drawn at random between 0.0f and 1.0f.
* <tr><td>FloatMatrix.randn(m) <td>Values drawn from normal distribution.
* </table>
@@ -835,6 +835,7 @@ public class FloatMatrix implements Serializable {
}
}
+
/** Set elements in linear ordering in the specified indices. */
public FloatMatrix put(int[] indices, FloatMatrix x) {
if (x.isScalar()) {
|
Fixed a typo in the javadoc reported by @argoneus
|
jblas-project_jblas
|
train
|
046e9077ed933bebebb4b9777aaa61d612582889
|
diff --git a/tests/core/opcodes/test_opcodes.py b/tests/core/opcodes/test_opcodes.py
index <HASH>..<HASH> 100644
--- a/tests/core/opcodes/test_opcodes.py
+++ b/tests/core/opcodes/test_opcodes.py
@@ -1191,6 +1191,7 @@ def test_balance(vm_class, code, expect_exception, expect_gas_used):
),
3 + 700,
),
+ # first sload should use the cold cost
(
BerlinVM,
assemble(
@@ -1198,7 +1199,7 @@ def test_balance(vm_class, code, expect_exception, expect_gas_used):
0x0,
opcode_values.SLOAD,
),
- 3 + 800,
+ 3 + 2100,
),
# querying the same address twice results in a
# cold cost and a warm cost
|
Update Berlin test with new sload cost
|
ethereum_py-evm
|
train
|
846a550db0ba709a92b09434f38e241b122aa942
|
diff --git a/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php b/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php
+++ b/src/Viserio/Provider/Twig/Provider/ConsoleCommandsServiceProvider.php
@@ -5,9 +5,9 @@ namespace Viserio\Provider\Twig\Provider;
use Interop\Container\ServiceProvider;
use Psr\Container\ContainerInterface;
use Viserio\Bridge\Twig\Command\DebugCommand;
-use Viserio\Bridge\Twig\Command\LintCommand;
use Viserio\Component\Console\Application;
use Viserio\Provider\Twig\Command\CleanCommand;
+use Viserio\Provider\Twig\Command\LintCommand;
class ConsoleCommandsServiceProvider implements ServiceProvider
{
@@ -34,11 +34,14 @@ class ConsoleCommandsServiceProvider implements ServiceProvider
$console = is_callable($getPrevious) ? $getPrevious() : $getPrevious;
if ($console !== null) {
- $console->addCommands([
- new CleanCommand(),
- new DebugCommand(),
- new LintCommand(),
- ]);
+ $console->add(new CleanCommand());
+
+ if (class_exists(DebugCommand::class)) {
+ $console->addCommands([
+ new DebugCommand(),
+ new LintCommand(),
+ ]);
+ }
}
return $console;
diff --git a/src/Viserio/Provider/Twig/Provider/TwigServiceProvider.php b/src/Viserio/Provider/Twig/Provider/TwigServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Viserio/Provider/Twig/Provider/TwigServiceProvider.php
+++ b/src/Viserio/Provider/Twig/Provider/TwigServiceProvider.php
@@ -32,14 +32,14 @@ class TwigServiceProvider implements
public function getServices()
{
return [
- LoaderInterface::class => [self::class, 'createTwigLoader'],
- TwigLoader::class => function (ContainerInterface $container) {
+ LoaderInterface::class => [self::class, 'createTwigLoader'],
+ TwigLoader::class => function (ContainerInterface $container) {
return $container->get(LoaderInterface::class);
},
- TwigEnvironment::class => [self::class, 'createTwigEnvironment'],
- FactoryContract::class => [self::class, 'extendViewFactory'],
- EngineResolver::class => [self::class, 'extendEngineResolver'],
- TwigEngine::class => [self::class, 'createTwigEngine'],
+ TwigEnvironment::class => [self::class, 'createTwigEnvironment'],
+ FactoryContract::class => [self::class, 'extendViewFactory'],
+ EngineResolver::class => [self::class, 'extendEngineResolver'],
+ TwigEngine::class => [self::class, 'createTwigEngine'],
];
}
diff --git a/src/Viserio/Provider/Twig/composer.json b/src/Viserio/Provider/Twig/composer.json
index <HASH>..<HASH> 100644
--- a/src/Viserio/Provider/Twig/composer.json
+++ b/src/Viserio/Provider/Twig/composer.json
@@ -19,7 +19,6 @@
],
"require": {
"php" : "^7.1",
- "viserio/twig-bridge" : "self.version",
"viserio/contracts" : "self.version",
"viserio/view" : "self.version"
},
@@ -27,7 +26,9 @@
"container-interop/service-provider" : "^0.3",
"mockery/mockery" : "^0.9",
"narrowspark/testing-helper" : "^3.0",
- "phpunit/phpunit" : "^6.0"
+ "phpunit/phpunit" : "^6.0",
+ "viserio/console" : "self.version",
+ "viserio/twig-bridge" : "self.version"
},
"autoload": {
"psr-4": {
@@ -42,6 +43,8 @@
},
"suggest": {
"container-interop/service-provider" : "Required to use service-provider (^0.3).",
+ "viserio/twig-bridge" : "Required to use the twig extensions, commands for lint and debug (self.version).",
+ "viserio/console" : "Required to use the commands (self.version)."
},
"extra": {
"branch-alias": {
|
fix twig provider service and command provider
|
narrowspark_framework
|
train
|
49075113b7468684a4fb9f90dbd3c9922824cfff
|
diff --git a/chef-expander/lib/chef/expander/vnode_supervisor.rb b/chef-expander/lib/chef/expander/vnode_supervisor.rb
index <HASH>..<HASH> 100644
--- a/chef-expander/lib/chef/expander/vnode_supervisor.rb
+++ b/chef-expander/lib/chef/expander/vnode_supervisor.rb
@@ -65,7 +65,7 @@ module Chef
@awaiting_parent_death = EM.add_periodic_timer(1) do
unless Process.ppid == @original_ppid
@awaiting_parent_death.cancel
- stop_gracefully("master process death")
+ stop_immediately("master process death")
end
end
end
|
CHEF-<I>: call #stop_immediately: if we get here our parent has died and all bets are off.
|
chef_chef
|
train
|
aebe621795d3e41de968998a740644322c2fce72
|
diff --git a/app/helpers/effective_regions_helper.rb b/app/helpers/effective_regions_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/effective_regions_helper.rb
+++ b/app/helpers/effective_regions_helper.rb
@@ -28,7 +28,10 @@ module EffectiveRegionsHelper
end
def effectively_editting?
- @effectively_editting ||= request.fullpath.include?('edit=true')
+ @effectively_editting ||= (
+ request.fullpath.include?('edit=true') &&
+ (EffectiveRegions.authorized?(controller, :edit, Effective::Region.new()) rescue false)
+ )
end
private
|
Include authorization in effectively_editting? check
|
code-and-effect_effective_regions
|
train
|
ba909dbc3005e602c8c01e9f06d1955bc2f47352
|
diff --git a/gsmmodem/modem.py b/gsmmodem/modem.py
index <HASH>..<HASH> 100644
--- a/gsmmodem/modem.py
+++ b/gsmmodem/modem.py
@@ -407,7 +407,7 @@ class GsmModem(SerialComms):
:rtype: list
"""
self.log.debug('write: %s', data)
- responseLines = SerialComms.write(self, data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq)
+ responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq)
if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load)
time.sleep(self._writeWait)
if waitForResponse:
|
Little fix to refers to SerialComms.write with super()
|
faucamp_python-gsmmodem
|
train
|
897093d2aadfabf572fc62b1c1450cac1ac156bd
|
diff --git a/ezp/Persistence/Storage/Legacy/EzcDbHandler.php b/ezp/Persistence/Storage/Legacy/EzcDbHandler.php
index <HASH>..<HASH> 100644
--- a/ezp/Persistence/Storage/Legacy/EzcDbHandler.php
+++ b/ezp/Persistence/Storage/Legacy/EzcDbHandler.php
@@ -108,7 +108,7 @@ class EzcDbHandler
*/
public function getAutoIncrementValue( $table, $column )
{
- return null;
+ return "null";
}
/**
|
Make this still work with SQLite and MySQL
|
ezsystems_ezpublish-kernel
|
train
|
c6d4f41744e87c92d2e6e418091d5f9cc8701072
|
diff --git a/src/SwaggerCombine.js b/src/SwaggerCombine.js
index <HASH>..<HASH> 100644
--- a/src/SwaggerCombine.js
+++ b/src/SwaggerCombine.js
@@ -70,6 +70,7 @@ class SwaggerCombine {
})
.then(apis => {
this.schemas = apis.filter(api => !!api);
+ this.apis = this.apis.filter((_api, idx) => !!apis[idx]);
return this;
});
}
diff --git a/test/integration.spec.js b/test/integration.spec.js
index <HASH>..<HASH> 100644
--- a/test/integration.spec.js
+++ b/test/integration.spec.js
@@ -69,6 +69,16 @@ describe('[Integration] SwaggerCombine.js', () => {
return swaggerCombine(basicConfig, { continueOnError: true });
});
+ it('filters api definitions to match filtered schemas', () => {
+ nock('http://petstore.swagger.io')
+ .get('/v2/swagger.json')
+ .reply(500);
+
+ return swaggerCombine(basicConfig, { continueOnError: true }).then(schema => {
+ expect(schema.paths['/bahn/betriebsstellen']).to.not.be.undefined;
+ });
+ });
+
it('filters out excluded paths', () =>
swaggerCombine(filterConfig).then(schema => {
expect(schema.paths['/pet'].put).to.not.be.ok;
|
fix: filters down api definitions if schemas are filtered
This fixes an issue where api definitions are mapped to the
wrong schema, because the index of the api definition is used to map
it to the index of the schema.
For example when the first defined api is down, the schema for the second
service would still be mapped to the first and thus receive the wrong
basePath (and other options).
|
maxdome_swagger-combine
|
train
|
bf4f119c0294477c0bcb7225b207f430f485136c
|
diff --git a/docs/victory-area/docs.js b/docs/victory-area/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-area/docs.js
+++ b/docs/victory-area/docs.js
@@ -17,6 +17,8 @@ class Docs extends React.Component {
scope={{merge, React, ReactDOM, VictoryArea, VictoryStack, VictoryGroup, VictoryScatter}}
playgroundtheme="elegant"
customRenderers={merge(ecologyPlaygroundLoading, appendLinkIcon)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-axis/docs.js b/docs/victory-axis/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-axis/docs.js
+++ b/docs/victory-axis/docs.js
@@ -17,6 +17,8 @@ class Docs extends React.Component {
scope={{range, random, React, ReactDOM, VictoryAxis}}
playgroundtheme="elegant"
customRenderers={merge(appendLinkIcon, ecologyPlaygroundLoading)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-bar/docs.js b/docs/victory-bar/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-bar/docs.js
+++ b/docs/victory-bar/docs.js
@@ -21,6 +21,8 @@ class Docs extends React.Component {
}}
playgroundtheme="elegant"
customRenderers={merge(appendLinkIcon, ecologyPlaygroundLoading)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-candlestick/docs.js b/docs/victory-candlestick/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-candlestick/docs.js
+++ b/docs/victory-candlestick/docs.js
@@ -23,6 +23,8 @@ class Docs extends React.Component {
}}
playgroundtheme="elegant"
customRenderers={merge(appendLinkIcon, ecologyPlaygroundLoading)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-chart/docs.js b/docs/victory-chart/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-chart/docs.js
+++ b/docs/victory-chart/docs.js
@@ -24,6 +24,8 @@ class Docs extends React.Component {
}}
playgroundtheme="elegant"
customRenderers={merge(appendLinkIcon, ecologyPlaygroundLoading)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-errorbar/docs.js b/docs/victory-errorbar/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-errorbar/docs.js
+++ b/docs/victory-errorbar/docs.js
@@ -23,6 +23,8 @@ class Docs extends React.Component {
}}
playgroundtheme="elegant"
customRenderers={merge(appendLinkIcon, ecologyPlaygroundLoading)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-line/docs.js b/docs/victory-line/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-line/docs.js
+++ b/docs/victory-line/docs.js
@@ -17,6 +17,8 @@ class Docs extends React.Component {
scope={{ merge, random, React, ReactDOM, VictoryLine, VictoryScatter }}
playgroundtheme="elegant"
customRenderers={merge(appendLinkIcon, ecologyPlaygroundLoading)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-scatter/docs.js b/docs/victory-scatter/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-scatter/docs.js
+++ b/docs/victory-scatter/docs.js
@@ -22,6 +22,8 @@ class Docs extends React.Component {
scope={{merge, range, random, React, ReactDOM, symbolData, VictoryScatter}}
playgroundtheme="elegant"
customRenderers={merge(appendLinkIcon, ecologyPlaygroundLoading)}
+ exportGist
+ copyToClipboard
/>
<Style rules={VictoryTheme}/>
</div>
|
pass ecology props to enable copy/gist
|
FormidableLabs_victory
|
train
|
1892b6ce9c14cdca54b62288c0b0b2571e1c6fef
|
diff --git a/CHANGES b/CHANGES
index <HASH>..<HASH> 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,12 @@
+Asterisk-Java 1.0.0
+ Warning:
+ Values for event properties of type String that match one of the null
+ literals used by Asterisk are automatically set to null in A-J 1.0.0.
+ The null literals are:
+ "<unknown>", "unknown", "none", "<none>", "-none-", "(none)",
+ "<not set>", "(not set)", "<no name>", "n/a" and "<null>".
+
+
Asterisk-Java 0.3.1
* [AJ-81] - executeCliCommand() always executes "show voicemail users"
* [AJ-86] - getChannelByName doesn't return the latest channel
diff --git a/src/main/java/org/asteriskjava/util/AstUtil.java b/src/main/java/org/asteriskjava/util/AstUtil.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/asteriskjava/util/AstUtil.java
+++ b/src/main/java/org/asteriskjava/util/AstUtil.java
@@ -1,7 +1,6 @@
package org.asteriskjava.util;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.*;
/**
* Some static utility methods to imitate Asterisk specific logic.
@@ -15,28 +14,28 @@ import java.util.List;
*/
public class AstUtil
{
- private static final List<String> TRUE_LITERALS;
- private static final List<String> NULL_LITERALS;
+ private static final Set<String> TRUE_LITERALS;
+ private static final Set<String> NULL_LITERALS;
static
{
- TRUE_LITERALS = new ArrayList<String>(20);
+ TRUE_LITERALS = new HashSet<String>(20);
TRUE_LITERALS.add("yes");
TRUE_LITERALS.add("true");
TRUE_LITERALS.add("y");
TRUE_LITERALS.add("t");
TRUE_LITERALS.add("1");
TRUE_LITERALS.add("on");
- TRUE_LITERALS.add("Enabled");
+ TRUE_LITERALS.add("enabled");
- NULL_LITERALS = new ArrayList<String>(20);
+ NULL_LITERALS = new HashSet<String>(20);
NULL_LITERALS.add("<unknown>");
NULL_LITERALS.add("unknown");
NULL_LITERALS.add("none"); // VarSet event in pbx.c
NULL_LITERALS.add("<none>");
NULL_LITERALS.add("-none-");
- NULL_LITERALS.add("(None)");
- NULL_LITERALS.add("<Not set>");
+ NULL_LITERALS.add("(none)");
+ NULL_LITERALS.add("<not set>");
NULL_LITERALS.add("(not set)");
NULL_LITERALS.add("<no name>");
NULL_LITERALS.add("n/a"); // channel in AgentsEvent
@@ -87,15 +86,7 @@ public class AstUtil
return false;
}
- for (String literal : TRUE_LITERALS)
- {
- if (literal.equalsIgnoreCase(s))
- {
- return true;
- }
- }
-
- return false;
+ return TRUE_LITERALS.contains(s.toLowerCase(Locale.US));
}
/**
@@ -186,14 +177,6 @@ public class AstUtil
return true;
}
- for (String literal : NULL_LITERALS)
- {
- if (literal.equalsIgnoreCase(s))
- {
- return true;
- }
- }
-
- return false;
+ return NULL_LITERALS.contains(s.toLowerCase(Locale.US));
}
}
diff --git a/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java b/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java
+++ b/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java
@@ -390,4 +390,18 @@ public class EventBuilderImplTest extends TestCase
assertEquals("Transit property not set correctly", 12.3456,
((RtpReceiverStatEvent) event).getTransit());
}
+
+ public void testBuildEventWithNullLiteral()
+ {
+ Map<String, String> properties = new HashMap<String, String>();
+ CdrEvent event;
+
+ properties.put("event", "Cdr");
+ properties.put("channel", "<none>");
+ event = (CdrEvent) eventBuilder.buildEvent(this, properties);
+
+ assertNotNull(event);
+ assertEquals("Returned event is of wrong type", CdrEvent.class, event.getClass());
+ assertNull("Property with value \"<none>\" is not null", event.getChannel());
+ }
}
|
[AJ-<I>] Added comment for CHANGELOG and test case
|
asterisk-java_asterisk-java
|
train
|
6a15e08ed5db02861b4b545149119af55bfc9f56
|
diff --git a/salt/modules/boto_apigateway.py b/salt/modules/boto_apigateway.py
index <HASH>..<HASH> 100644
--- a/salt/modules/boto_apigateway.py
+++ b/salt/modules/boto_apigateway.py
@@ -547,7 +547,7 @@ def update_api_key_description(apiKey, description, region=None, key=None, keyid
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
response = _api_key_patch_replace(conn, apiKey, '/description', description)
- return {'updated': True, 'apiKey': response}
+ return {'updated': True, 'apiKey': _convert_datetime_str(response)}
except ClientError as e:
return {'updated': False, 'error': salt.utils.boto3.get_error(e)}
@@ -565,7 +565,7 @@ def enable_api_key(apiKey, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
response = _api_key_patch_replace(conn, apiKey, '/enabled', 'True')
- return {'apiKey': response}
+ return {'apiKey': _convert_datetime_str(response)}
except ClientError as e:
return {'error': salt.utils.boto3.get_error(e)}
@@ -583,7 +583,7 @@ def disable_api_key(apiKey, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
response = _api_key_patch_replace(conn, apiKey, '/enabled', 'False')
- return {'apiKey': response}
+ return {'apiKey': _convert_datetime_str(response)}
except ClientError as e:
return {'error': salt.utils.boto3.get_error(e)}
@@ -603,7 +603,7 @@ def associate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, ke
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
pvlist = [('/stages', stagekey) for stagekey in stagekeyslist]
response = _api_key_patch_add(conn, apiKey, pvlist)
- return {'associated': True, 'apiKey': response}
+ return {'associated': True, 'apiKey': _convert_datetime_str(response)}
except ClientError as e:
return {'associated': False, 'error': salt.utils.boto3.get_error(e)}
|
minor formatting of responses for ApiKey resource.
|
saltstack_salt
|
train
|
3f136782ee6443f065afdc017b5a6e77b1bce64a
|
diff --git a/blockstack_client/backend/drivers/__init__.py b/blockstack_client/backend/drivers/__init__.py
index <HASH>..<HASH> 100644
--- a/blockstack_client/backend/drivers/__init__.py
+++ b/blockstack_client/backend/drivers/__init__.py
@@ -28,4 +28,4 @@ import blockstack_resolver
import blockstack_server
import http
-from common import index_settings_get_index_manifest_url
+from common import index_settings_get_index_manifest_url, ConcurrencyViolationException
diff --git a/blockstack_client/backend/drivers/test.py b/blockstack_client/backend/drivers/test.py
index <HASH>..<HASH> 100644
--- a/blockstack_client/backend/drivers/test.py
+++ b/blockstack_client/backend/drivers/test.py
@@ -28,6 +28,7 @@ import sys
import json
import traceback
import logging
+import time
from common import *
from ConfigParser import SafeConfigParser
|
expose ConcurrencyViolationException
|
blockstack_blockstack-core
|
train
|
de360d55cc81eb37d90008cddfbd940bd28e5628
|
diff --git a/src/org/opencms/loader/CmsImageScaler.java b/src/org/opencms/loader/CmsImageScaler.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/loader/CmsImageScaler.java
+++ b/src/org/opencms/loader/CmsImageScaler.java
@@ -29,6 +29,7 @@ package org.opencms.loader;
import com.alkacon.simapi.RenderSettings;
import com.alkacon.simapi.Simapi;
+import com.alkacon.simapi.CmykJpegReader.ByteArrayImageInputStream;
import com.alkacon.simapi.filter.GrayscaleFilter;
import com.alkacon.simapi.filter.ShadowFilter;
@@ -44,13 +45,17 @@ import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import java.awt.Color;
+import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
@@ -204,10 +209,16 @@ public class CmsImageScaler {
init();
try {
- // read the scaled image
- BufferedImage image = Simapi.read(content);
- m_height = image.getHeight();
- m_width = image.getWidth();
+ Dimension dim = getImageDimensions(rootPath, content);
+ if (dim != null) {
+ m_width = dim.width;
+ m_height = dim.height;
+ } else {
+ // read the scaled image
+ BufferedImage image = Simapi.read(content);
+ m_height = image.getHeight();
+ m_width = image.getWidth();
+ }
} catch (Exception e) {
// nothing we can do about this, keep the original properties
if (LOG.isDebugEnabled()) {
@@ -341,6 +352,41 @@ public class CmsImageScaler {
}
/**
+ * Gets image dimensions for given file
+ * @param imgFile image file
+ * @return dimensions of image
+ * @throws IOException if the file is not a known image
+ */
+ public static Dimension getImageDimensions(String path, byte[] content) throws IOException {
+
+ String name = CmsResource.getName(path);
+ int pos = name.lastIndexOf(".");
+ if (pos == -1) {
+ LOG.warn("Couldn't determine image dimensions for " + path);
+ return null;
+ }
+ String suffix = name.substring(pos + 1);
+ Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
+ while (iter.hasNext()) {
+ ImageReader reader = iter.next();
+ try {
+ ByteArrayImageInputStream stream = new ByteArrayImageInputStream(content);
+ reader.setInput(stream);
+ int minIndex = reader.getMinIndex();
+ int width = reader.getWidth(minIndex);
+ int height = reader.getHeight(minIndex);
+ return new Dimension(width, height);
+ } catch (IOException e) {
+ LOG.warn("Problem determining image size for " + path + ": " + e.getLocalizedMessage(), e);
+ } finally {
+ reader.dispose();
+ }
+ }
+ LOG.warn("Couldn't determine image dimensions for " + path);
+ return null;
+ }
+
+ /**
* Adds a filter name to the list of filters that should be applied to the image.<p>
*
* @param filter the filter name to add
@@ -1618,6 +1664,12 @@ public class CmsImageScaler {
return result;
}
+ private Dimension getDimensionsWithSimapi(byte[] content) throws Exception {
+
+ BufferedImage image = Simapi.read(content);
+ return new Dimension(image.getWidth(), image.getHeight());
+ }
+
/**
* Initializes the members with the default values.<p>
*/
|
Improved image size detection performance in image scaler.
|
alkacon_opencms-core
|
train
|
825202294729cd86c364bb369441a037fad42dd4
|
diff --git a/provision/docker/scheduler.go b/provision/docker/scheduler.go
index <HASH>..<HASH> 100644
--- a/provision/docker/scheduler.go
+++ b/provision/docker/scheduler.go
@@ -108,6 +108,20 @@ func (segregatedScheduler) Nodes() ([]cluster.Node, error) {
return result, nil
}
+func (segregatedScheduler) GetNode(id string) (node, error) {
+ conn, err := db.Conn()
+ if err != nil {
+ return node{}, err
+ }
+ defer conn.Close()
+ var n node
+ err = conn.Collection(schedulerCollection).FindId(id).One(&n)
+ if err == mgo.ErrNotFound {
+ return node{}, errNodeNotFound
+ }
+ return n, nil
+}
+
// AddNodeToScheduler adds a new node to the scheduler, registering for use in
// the given team. The team parameter is optional, when set to "", the node
// will be used as a fallback node.
diff --git a/provision/docker/scheduler_test.go b/provision/docker/scheduler_test.go
index <HASH>..<HASH> 100644
--- a/provision/docker/scheduler_test.go
+++ b/provision/docker/scheduler_test.go
@@ -162,6 +162,33 @@ func (s *SchedulerSuite) TestSchedulerNodes(c *gocheck.C) {
c.Assert(nodes, gocheck.DeepEquals, expected)
}
+func (s *SchedulerSuite) TestSchedulerGetNode(c *gocheck.C) {
+ coll := s.storage.Collection(schedulerCollection)
+ err := coll.Insert(
+ node{ID: "server0", Address: "http://localhost:8080", Team: "tsuru"},
+ node{ID: "server1", Address: "http://localhost:8081", Team: "tsuru"},
+ node{ID: "server2", Address: "http://localhost:8082", Team: "tsuru"},
+ )
+ c.Assert(err, gocheck.IsNil)
+ defer coll.RemoveAll(bson.M{"_id": bson.M{"$in": []string{"server0", "server1", "server2"}}})
+ var tests = []struct {
+ input string
+ expected node
+ err error
+ }{
+ {"server0", node{ID: "server0", Address: "http://localhost:8080", Team: "tsuru"}, nil},
+ {"server1", node{ID: "server1", Address: "http://localhost:8081", Team: "tsuru"}, nil},
+ {"server2", node{ID: "server2", Address: "http://localhost:8082", Team: "tsuru"}, nil},
+ {"server102", node{}, errNodeNotFound},
+ }
+ var scheduler segregatedScheduler
+ for _, t := range tests {
+ nd, err := scheduler.GetNode(t.input)
+ c.Check(err, gocheck.Equals, t.err)
+ c.Check(nd, gocheck.DeepEquals, t.expected)
+ }
+}
+
func (s *SchedulerSuite) TestAddNodeToScheduler(c *gocheck.C) {
coll := s.storage.Collection(schedulerCollection)
nd := cluster.Node{ID: "server0", Address: "http://localhost:8080"}
|
provision/docker: add method GetNode to segregatedScheduler
Related to #<I>.
|
tsuru_tsuru
|
train
|
d0d9f4064896c3ca77ee58fac2ebb3ba53428e0c
|
diff --git a/lib/discourse/preview/example.rb b/lib/discourse/preview/example.rb
index <HASH>..<HASH> 100644
--- a/lib/discourse/preview/example.rb
+++ b/lib/discourse/preview/example.rb
@@ -2,7 +2,7 @@ module Discourse
module Oneboxer
class Preview
class Example
- TEMPLATE = "blah {{header}} blah"
+ TEMPLATE = "<!DOCTYPE html>\n<html><body><div class='onebox'>{{{header}}}</div></body></html>\n"
def initialize(html)
@body = html
diff --git a/spec/support/html_spec_helper.rb b/spec/support/html_spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/support/html_spec_helper.rb
+++ b/spec/support/html_spec_helper.rb
@@ -15,3 +15,4 @@ module HTMLSpecHelper
body("<div class='onebox'>#{html}</div>")
end
end
+
\ No newline at end of file
|
make test pass add triple mustaches to prevent escaping
|
discourse_onebox
|
train
|
2feb20d30a08e77efb411adfc0edc81892e50bcd
|
diff --git a/rootpy/logger/magic.py b/rootpy/logger/magic.py
index <HASH>..<HASH> 100644
--- a/rootpy/logger/magic.py
+++ b/rootpy/logger/magic.py
@@ -45,6 +45,11 @@ _keep_alive = []
ON_RTD = os.environ.get('READTHEDOCS', None) == 'True'
+def libcore():
+ if sys.platform == "darwin":
+ return "libCore.dylib"
+ return "libCore.so"
+
def get_seh():
"""
Makes a function which can be used to set the ROOT error handler with a
@@ -55,13 +60,10 @@ def get_seh():
ErrorHandlerFunc_t = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_bool,
ctypes.c_char_p, ctypes.c_char_p)
-
- libCore = ctypes.util.find_library("Core")
- if not libCore:
- log.warning("Unable to find libCore. Disabling magic.")
- return lambda x: x
- dll = ctypes.cdll.LoadLibrary(libCore)
+ dll = ctypes.cdll.LoadLibrary(libcore())
+ assert dll, "Can't find `libCore` shared library. Possible bug?"
+
SetErrorHandler = dll._Z15SetErrorHandlerPFvibPKcS0_E
assert SetErrorHandler, ("Couldn't find SetErrorHandler, please submit a "
"bug report to rootpy.")
|
Use cdll.LoadLibrary to locate shared libraries
|
rootpy_rootpy
|
train
|
aa2e3cb3f28e84de2f3f70a4ec99f838cc10956d
|
diff --git a/full/src/test/java/apoc/uuid/UUIDMultiDbTest.java b/full/src/test/java/apoc/uuid/UUIDMultiDbTest.java
index <HASH>..<HASH> 100644
--- a/full/src/test/java/apoc/uuid/UUIDMultiDbTest.java
+++ b/full/src/test/java/apoc/uuid/UUIDMultiDbTest.java
@@ -104,8 +104,7 @@ public class UUIDMultiDbTest {
};
long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5);
- System.out.println("timeout = " + timeout);
- while (!nodeHasUUID.get() || System.currentTimeMillis() > timeout) {
+ while (System.currentTimeMillis() < timeout && !nodeHasUUID.get()) {
session.writeTransaction(tx -> {
Map<String, Object> p = Collections.<String, Object>emptyMap();
resultConsumer.accept(tx.run(call, p).list().stream().map(Record::asMap).collect(Collectors.toList()).iterator());
@@ -117,7 +116,8 @@ public class UUIDMultiDbTest {
Thread.sleep(100);
}
}
- assertTrue(nodeHasUUID.get());
+ assertTrue("UUID not set on node after 5 seconds", nodeHasUUID.get());
}
}
+
}
|
aaarh, my boolean logic was very bad
|
neo4j-contrib_neo4j-apoc-procedures
|
train
|
18e270dfa1e831f63988ad1ca0175aabb640c881
|
diff --git a/main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java b/main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java
index <HASH>..<HASH> 100644
--- a/main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java
+++ b/main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java
@@ -1970,7 +1970,6 @@ public class SARLJvmModelInferrer extends XtendJvmModelInferrer {
setBody(bodyOperation, source.getExpression());
// Annotations
translateAnnotationsTo(source.getAnnotations(), bodyOperation);
- appendGeneratedAnnotation(bodyOperation, context);
if (context.getGeneratorConfig2().isGeneratePureAnnotation()
&& !this.services.getExpressionHelper().hasSideEffects(source.getExpression())) {
addAnnotationSafe(bodyOperation, Pure.class);
|
[lang] Do not attach @SyntheticMember to the behavior unit functions.
|
sarl_sarl
|
train
|
68ce1dd4d5a2498bae42b1ecca8453777d08f53d
|
diff --git a/src/Consumer/Api/Subscription/Entity.php b/src/Consumer/Api/Subscription/Entity.php
index <HASH>..<HASH> 100644
--- a/src/Consumer/Api/Subscription/Entity.php
+++ b/src/Consumer/Api/Subscription/Entity.php
@@ -52,7 +52,7 @@ class Entity extends ConsumerApiAbstract
$resource->addMethod(Resource\Factory::getMethod('GET')
->setSecurity(Authorization::CONSUMER, ['consumer'])
- ->addResponse(200, $this->schemaManager->getSchema(Schema\Subscription\Collection::class))
+ ->addResponse(200, $this->schemaManager->getSchema(Schema\Subscription::class))
);
$resource->addMethod(Resource\Factory::getMethod('PUT')
diff --git a/src/Consumer/Schema/Subscription.php b/src/Consumer/Schema/Subscription.php
index <HASH>..<HASH> 100644
--- a/src/Consumer/Schema/Subscription.php
+++ b/src/Consumer/Schema/Subscription.php
@@ -34,6 +34,13 @@ class Subscription extends SchemaAbstract
{
public function getDefinition()
{
+ $sb = $this->getSchemaBuilder('Consumer Subscription Response');
+ $sb->integer('status');
+ $sb->integer('code');
+ $sb->integer('attempts');
+ $sb->string('executeDate');
+ $response = $sb->getProperty();
+
$sb = $this->getSchemaBuilder('Consumer Subscription');
$sb->integer('id');
$sb->integer('status');
@@ -41,6 +48,8 @@ class Subscription extends SchemaAbstract
->setMinLength(3);
$sb->string('endpoint')
->setMinLength(8);
+ $sb->arrayType('responses')
+ ->setItems($response);
return $sb->getProperty();
}
|
subscription add response to schema and fix entity schema
|
apioo_fusio-impl
|
train
|
9bba9f5b1cd8d392754f6e0414cba5c58c7c3e80
|
diff --git a/src/infi/projector/first_run/with_environment_python.py b/src/infi/projector/first_run/with_environment_python.py
index <HASH>..<HASH> 100644
--- a/src/infi/projector/first_run/with_environment_python.py
+++ b/src/infi/projector/first_run/with_environment_python.py
@@ -12,7 +12,7 @@ def append_src_to_python_path():
def get_dependencies():
from infi.projector.helper.utils import open_buildout_configfile
with open_buildout_configfile() as buildout:
- exec 'dependencies = {}'.format(buildout.get("project", "install_requires"))
+ exec 'dependencies = {0}'.format(buildout.get("project", "install_requires"))
return dependencies
def is_dependency_installed(dependency):
@@ -32,7 +32,7 @@ def check_for_dependencies():
missing_dependencies = [dependency for dependency in get_dependencies()
if not is_dependency_installed(dependency)]
if missing_dependencies:
- print 'Please install the following dependencies: {}'.format(' '.join(missing_dependencies))
+ print 'Please install the following dependencies: {0}'.format(' '.join(missing_dependencies))
raise SystemExit(1)
def build_scripts():
diff --git a/src/infi/projector/first_run/without_environment_python.py b/src/infi/projector/first_run/without_environment_python.py
index <HASH>..<HASH> 100644
--- a/src/infi/projector/first_run/without_environment_python.py
+++ b/src/infi/projector/first_run/without_environment_python.py
@@ -5,14 +5,14 @@ USE_ISOLATED_PYTHON = '--use-isolated-python' in sys.argv
IN_VIRTUALENV = hasattr(sys, 'real_prefix')
BUILDOUT = path.join("bin", "buildout")
COMMANDS = [
- "python {} bootstrap.py -d".format('' if IN_VIRTUALENV else '-S'),
- "{} -s buildout:develop= install setup.py __version__.py".format(BUILDOUT),
- "{} -s install development-scripts".format(BUILDOUT)
+ "python {0} bootstrap.py -d".format('' if IN_VIRTUALENV else '-S'),
+ "{0} -s buildout:develop= install setup.py __version__.py".format(BUILDOUT),
+ "{0} -s install development-scripts".format(BUILDOUT)
]
if USE_ISOLATED_PYTHON:
- COMMANDS.insert(2, "{} bootstrap.py -d".format(path.join("parts", "python", "bin",
- "python{}".format('.exe' if name == 'nt' else ''))))
- COMMANDS.insert(2, "{} -s install isolated-python".format(BUILDOUT))
+ COMMANDS.insert(2, "{0} bootstrap.py -d".format(path.join("parts", "python", "bin",
+ "python{0}".format('.exe' if name == 'nt' else ''))))
+ COMMANDS.insert(2, "{0} -s install isolated-python".format(BUILDOUT))
CACHE_DIST = path.join(".cache", "dist")
if not path.exists(CACHE_DIST):
|
TRIVIAL Fixing first_run/*_environment_python.py to work with Python <I>
|
Infinidat_infi.projector
|
train
|
ad9aba2748c2fd63996fe90bb891fa86ad5d9f05
|
diff --git a/src/link/worker.js b/src/link/worker.js
index <HASH>..<HASH> 100644
--- a/src/link/worker.js
+++ b/src/link/worker.js
@@ -13,10 +13,10 @@ fdom.link = fdom.link || {};
* @constructor
*/
fdom.link.Worker = function(id) {
+ fdom.Link.call(this);
if (id) {
- this.manifest = id.substr(id.lastIndexOf('/') + 1);
+ this.id = id;
}
- fdom.Link.call(this);
};
/**
@@ -47,7 +47,7 @@ fdom.link.Worker.prototype.stop = function() {
* @return {String} the description of this port.
*/
fdom.link.Worker.prototype.toString = function() {
- return "[Worker" + this.id + "]";
+ return "[Worker " + this.id + "]";
};
/**
@@ -78,7 +78,7 @@ fdom.link.Worker.prototype.setupWorker = function() {
worker = new Worker(this.config.source);
} else {
blob = new window.Blob([this.config.src], {type: 'text/javascript'});
- worker = new Worker(window.URL.createObjectURL(blob) + '#' + this.manifest);
+ worker = new Worker(window.URL.createObjectURL(blob) + '#' + this.id);
}
worker.addEventListener('error', function(err) {
fdom.debug.error(err, this.toString());
diff --git a/src/port-module.js b/src/port-module.js
index <HASH>..<HASH> 100644
--- a/src/port-module.js
+++ b/src/port-module.js
@@ -158,7 +158,7 @@ fdom.port.Module.prototype.start = function() {
}
if (this.controlChannel) {
this.loadLinks();
- this.port = new fdom.link[this.config.portType](this.manifestId);
+ this.port = new fdom.link[this.config.portType](this.manifest.name);
// Listen to all port messages.
this.port.on(this.emitMessage.bind(this));
// Tell the local port to ask us for help.
|
worker names set as manifest short names.
close #<I>
|
freedomjs_freedom
|
train
|
bbc6da318902ea06f7ebe3ab19ad900335e1524f
|
diff --git a/packages/core/src/middleware.js b/packages/core/src/middleware.js
index <HASH>..<HASH> 100644
--- a/packages/core/src/middleware.js
+++ b/packages/core/src/middleware.js
@@ -55,7 +55,11 @@ export function createAPIMiddleware(adapter) {
}
}
- next(action);
+ if (request) {
+ next({ ...action, payload: request });
+ } else {
+ next(action);
+ }
if (action.type !== ACTION_FETCH_START) return;
|
fix: dispatch the resolved start acion
|
tungv_redux-api-call
|
train
|
4683211d6bb5acc36c393ff1350069486d60764f
|
diff --git a/edx_rest_framework_extensions/__init__.py b/edx_rest_framework_extensions/__init__.py
index <HASH>..<HASH> 100644
--- a/edx_rest_framework_extensions/__init__.py
+++ b/edx_rest_framework_extensions/__init__.py
@@ -1,3 +1,3 @@
""" edx Django REST Framework extensions. """
-__version__ = '1.5.4' # pragma: no cover
+__version__ = '1.5.5' # pragma: no cover
diff --git a/edx_rest_framework_extensions/jwt_decoder.py b/edx_rest_framework_extensions/jwt_decoder.py
index <HASH>..<HASH> 100644
--- a/edx_rest_framework_extensions/jwt_decoder.py
+++ b/edx_rest_framework_extensions/jwt_decoder.py
@@ -120,7 +120,7 @@ def _set_token_defaults(token):
def _set_filters(token, token_version):
"""
We can safely default to an empty list of filters since
- previously created tokens were either "restricted" (always
+ previously created tokens were either "restricted" (always
expired) or had full access.
"""
if token_version < Version(JwtTokenVersion.added_filters):
diff --git a/edx_rest_framework_extensions/middleware.py b/edx_rest_framework_extensions/middleware.py
index <HASH>..<HASH> 100644
--- a/edx_rest_framework_extensions/middleware.py
+++ b/edx_rest_framework_extensions/middleware.py
@@ -59,7 +59,13 @@ class EnsureJWTAuthSettingsMiddleware(object):
view_class.permission_classes += tuple(classes_to_add)
def process_view(self, request, view_func, view_args, view_kwargs): # pylint: disable=unused-argument
- view_class = getattr(view_func, 'view_class', view_func)
+ # Views as functions store the view's class in the 'view_class' attribute.
+ # Viewsets store the view's class in the 'cls' attribute.
+ view_class = getattr(
+ view_func,
+ 'view_class',
+ getattr(view_func, 'cls', view_func),
+ )
view_authentication_classes = getattr(view_class, 'authentication_classes', tuple())
if self._includes_base_class(view_authentication_classes, BaseJSONWebTokenAuthentication):
diff --git a/edx_rest_framework_extensions/tests/test_middleware.py b/edx_rest_framework_extensions/tests/test_middleware.py
index <HASH>..<HASH> 100644
--- a/edx_rest_framework_extensions/tests/test_middleware.py
+++ b/edx_rest_framework_extensions/tests/test_middleware.py
@@ -11,6 +11,7 @@ from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework.decorators import api_view
from rest_framework.views import APIView
+from rest_framework.viewsets import ViewSet
from ..middleware import EnsureJWTAuthSettingsMiddleware
from ..permissions import (
@@ -56,24 +57,38 @@ class TestEnsureJWTAuthSettingsMiddleware(TestCase):
@ddt.data(
*product(
- (True, False),
+ ('view_set', 'class_view', 'function_view'),
(True, False),
(True, False),
)
)
@ddt.unpack
- def test_api_views(self, use_function_view, include_jwt_auth, include_required_perm):
+ def test_api_views(self, view_type, include_jwt_auth, include_required_perm):
@some_auth_decorator(include_jwt_auth, include_required_perm)
class SomeClassView(APIView):
pass
+ @some_auth_decorator(include_jwt_auth, include_required_perm)
+ class SomeClassViewSet(ViewSet):
+ pass
+
@api_view(["GET"])
@some_auth_decorator(include_jwt_auth, include_required_perm)
def some_function_view(request):
pass
- view = some_function_view if use_function_view else SomeClassView
- view_class = view.view_class if use_function_view else view
+ views = dict(
+ class_view=SomeClassView,
+ view_set=SomeClassViewSet.as_view({'get': 'list'}),
+ function_view=some_function_view,
+ )
+ view_classes = dict(
+ class_view=SomeClassView,
+ view_set=views['view_set'].cls,
+ function_view=views['function_view'].view_class,
+ )
+ view = views[view_type]
+ view_class = view_classes[view_type]
# verify pre-conditions
self._assert_included(
|
Fix EnsureJWTAuthSettingsMiddleware to support ViewSets
|
edx_edx-drf-extensions
|
train
|
760a4ec0d35f80bb7aa7089753643ba4c298d62b
|
diff --git a/src/core/lombok/javac/JavacAST.java b/src/core/lombok/javac/JavacAST.java
index <HASH>..<HASH> 100644
--- a/src/core/lombok/javac/JavacAST.java
+++ b/src/core/lombok/javac/JavacAST.java
@@ -125,6 +125,8 @@ public class JavacAST extends AST<JavacAST, JavacNode, JCTree> {
String nm = Source.instance(context).name();
int underscoreIdx = nm.indexOf('_');
if (underscoreIdx > -1) return Integer.parseInt(nm.substring(underscoreIdx + 1));
+ // assume java9+
+ return Integer.parseInt(nm);
} catch (Exception ignore) {}
return 6;
}
|
Parsing for source level broken under JDK9 due to change in 1.X->X versioning by oracle.
|
rzwitserloot_lombok
|
train
|
3d86d31b9f1b1e1632f66cc6cd2c3a94051a1d0b
|
diff --git a/exec.go b/exec.go
index <HASH>..<HASH> 100644
--- a/exec.go
+++ b/exec.go
@@ -162,7 +162,10 @@ func execProcess(context *cli.Context) (int, error) {
if err != nil {
return -1, err
}
- bundle := utils.SearchLabels(state.Config.Labels, "bundle")
+ bundle, ok := utils.SearchLabels(state.Config.Labels, "bundle")
+ if !ok {
+ return -1, errors.New("bundle not found in labels")
+ }
p, err := getProcess(context, bundle)
if err != nil {
return -1, err
diff --git a/libcontainer/utils/utils.go b/libcontainer/utils/utils.go
index <HASH>..<HASH> 100644
--- a/libcontainer/utils/utils.go
+++ b/libcontainer/utils/utils.go
@@ -132,19 +132,16 @@ func WithProcfd(root, unsafePath string, fn func(procfd string) error) error {
return fn(procfd)
}
-// SearchLabels searches a list of key-value pairs for the provided key and
-// returns the corresponding value. The pairs must be separated with '='.
-func SearchLabels(labels []string, query string) string {
- for _, l := range labels {
- parts := strings.SplitN(l, "=", 2)
- if len(parts) < 2 {
- continue
- }
- if parts[0] == query {
- return parts[1]
+// SearchLabels searches through a list of key=value pairs for a given key,
+// returning its value, and the binary flag telling whether the key exist.
+func SearchLabels(labels []string, key string) (string, bool) {
+ key += "="
+ for _, s := range labels {
+ if strings.HasPrefix(s, key) {
+ return s[len(key):], true
}
}
- return ""
+ return "", false
}
// Annotations returns the bundle path and user defined annotations from the
diff --git a/libcontainer/utils/utils_test.go b/libcontainer/utils/utils_test.go
index <HASH>..<HASH> 100644
--- a/libcontainer/utils/utils_test.go
+++ b/libcontainer/utils/utils_test.go
@@ -8,22 +8,28 @@ import (
)
var labelTest = []struct {
- labels []string
- query string
- expectedValue string
+ labels []string
+ query string
+ expVal string
+ expOk bool
}{
- {[]string{"bundle=/path/to/bundle"}, "bundle", "/path/to/bundle"},
- {[]string{"test=a", "test=b"}, "bundle", ""},
- {[]string{"bundle=a", "test=b", "bundle=c"}, "bundle", "a"},
- {[]string{"", "test=a", "bundle=b"}, "bundle", "b"},
- {[]string{"test", "bundle=a"}, "bundle", "a"},
- {[]string{"test=a", "bundle="}, "bundle", ""},
+ {[]string{"bundle=/path/to/bundle"}, "bundle", "/path/to/bundle", true},
+ {[]string{"test=a", "test=b"}, "bundle", "", false},
+ {[]string{"bundle=a", "test=b", "bundle=c"}, "bundle", "a", true},
+ {[]string{"", "test=a", "bundle=b"}, "bundle", "b", true},
+ {[]string{"test", "bundle=a"}, "bundle", "a", true},
+ {[]string{"test=a", "bundle="}, "bundle", "", true},
}
func TestSearchLabels(t *testing.T) {
for _, tt := range labelTest {
- if v := SearchLabels(tt.labels, tt.query); v != tt.expectedValue {
- t.Errorf("expected value '%s' for query '%s'; got '%s'", tt.expectedValue, tt.query, v)
+ v, ok := SearchLabels(tt.labels, tt.query)
+ if ok != tt.expOk {
+ t.Errorf("expected ok: %v, got %v", tt.expOk, ok)
+ continue
+ }
+ if v != tt.expVal {
+ t.Errorf("expected value '%s' for query '%s'; got '%s'", tt.expVal, tt.query, v)
}
}
}
|
libct/utils: SearchLabels: optimize
Using strings.Split generates temporary strings for GC to collect.
Rewrite the function to not do that.
Also, add a second return value, so that the caller can distinguish
between an empty value found and no key found cases.
Fix the test accordingly.
|
opencontainers_runc
|
train
|
2d71d509f6118e7bf8c9986bd856032c51828a31
|
diff --git a/lib/gclitest/helpers.js b/lib/gclitest/helpers.js
index <HASH>..<HASH> 100644
--- a/lib/gclitest/helpers.js
+++ b/lib/gclitest/helpers.js
@@ -235,44 +235,44 @@ exports.check = function(checks) {
}
if (assignment == null) {
- test.ok(false, 'Unknown parameter: ' + paramName);
+ test.ok(false, 'Unknown arg: ' + paramName);
return;
}
if (check.value) {
test.is(assignment.value,
check.value,
- 'checkStatus value for ' + paramName);
+ 'arg[\'' + paramName + '\'].value');
}
if (check.name) {
test.is(assignment.value.name,
check.name,
- 'checkStatus name for ' + paramName);
+ 'arg[\'' + paramName + '\'].name');
}
if (check.type) {
test.is(assignment.arg.type,
check.type,
- 'checkStatus type for ' + paramName);
+ 'arg[\'' + paramName + '\'].type');
}
if (check.arg) {
test.is(assignment.arg.toString(),
check.arg,
- 'checkStatus arg for ' + paramName);
+ 'arg[\'' + paramName + '\'].arg');
}
if (check.status) {
test.is(assignment.getStatus().toString(),
check.status,
- 'checkStatus status for ' + paramName);
+ 'arg[\'' + paramName + '\'].status');
}
if (check.message) {
test.is(assignment.getMessage(),
check.message,
- 'checkStatus message for ' + paramName);
+ 'arg[\'' + paramName + '\'].message');
}
});
}
diff --git a/lib/gclitest/mockCommands.js b/lib/gclitest/mockCommands.js
index <HASH>..<HASH> 100644
--- a/lib/gclitest/mockCommands.js
+++ b/lib/gclitest/mockCommands.js
@@ -57,6 +57,7 @@ exports.setup = function() {
canon.addCommand(exports.tselarr);
canon.addCommand(exports.tsm);
canon.addCommand(exports.tsg);
+ canon.addCommand(exports.tscook);
};
exports.shutdown = function() {
@@ -80,6 +81,7 @@ exports.shutdown = function() {
canon.removeCommand(exports.tselarr);
canon.removeCommand(exports.tsm);
canon.removeCommand(exports.tsg);
+ canon.removeCommand(exports.tscook);
types.deregisterType(exports.optionType);
types.deregisterType(exports.optionValue);
@@ -299,5 +301,45 @@ exports.tsg = {
exec: createExec('tsg')
};
+exports.tscook = {
+ name: 'tscook',
+ description: 'param group test to catch problems with cookie command',
+ params: [
+ {
+ name: 'key',
+ type: 'string',
+ description: 'tscookKeyDesc'
+ },
+ {
+ name: 'value',
+ type: 'string',
+ description: 'tscookValueDesc'
+ },
+ {
+ group: 'tscookOptionsDesc',
+ params: [
+ {
+ name: 'path',
+ type: 'string',
+ defaultValue: '/',
+ description: 'tscookPathDesc'
+ },
+ {
+ name: 'domain',
+ type: 'string',
+ defaultValue: null,
+ description: 'tscookDomainDesc'
+ },
+ {
+ name: 'secure',
+ type: 'boolean',
+ description: 'tscookSecureDesc'
+ }
+ ]
+ }
+ ],
+ exec: createExec('tscook')
+};
+
});
diff --git a/lib/gclitest/testIncomplete.js b/lib/gclitest/testIncomplete.js
index <HASH>..<HASH> 100644
--- a/lib/gclitest/testIncomplete.js
+++ b/lib/gclitest/testIncomplete.js
@@ -152,6 +152,40 @@ exports.testCompleted = function(options) {
}
});
+ helpers.setInput('tscook key value --path path --');
+ helpers.check({
+ input: 'tscook key value --path path --',
+ markup: 'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVII',
+ directTabText: 'domain',
+ arrowTabText: '',
+ status: 'ERROR',
+ emptyParameters: [ ],
+ args: {
+ key: { value: 'key', status: 'VALID' },
+ value: { value: 'value', status: 'VALID' },
+ path: { value: 'path', status: 'VALID' },
+ domain: { value: undefined, status: 'VALID' },
+ secure: { value: false, status: 'VALID' }
+ }
+ });
+
+ helpers.setInput('tscook key value --path path --domain domain --');
+ helpers.check({
+ input: 'tscook key value --path path --domain domain --',
+ markup: 'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVII',
+ directTabText: 'secure',
+ arrowTabText: '',
+ status: 'ERROR',
+ emptyParameters: [ ],
+ args: {
+ key: { value: 'key', status: 'VALID' },
+ value: { value: 'value', status: 'VALID' },
+ path: { value: 'path', status: 'VALID' },
+ domain: { value: 'domain', status: 'VALID' },
+ secure: { value: false, status: 'VALID' }
+ }
+ });
+
// Expand out to christmas tree command line
};
|
complete-<I>: Tests for above changes
|
joewalker_gcli
|
train
|
5c67f5476a91b302c900614723f8cb84a4d97d95
|
diff --git a/tests/xapian_tests/tests/xapian_query.py b/tests/xapian_tests/tests/xapian_query.py
index <HASH>..<HASH> 100644
--- a/tests/xapian_tests/tests/xapian_query.py
+++ b/tests/xapian_tests/tests/xapian_query.py
@@ -61,10 +61,10 @@ class XapianSearchQueryTestCase(TestCase):
self.sq.add_filter(SQ(content='world'))
self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((hello AND world))')
- # def test_build_query_multiple_words_not(self):
- # self.sq.add_filter(~SQ(content='hello'))
- # self.sq.add_filter(~SQ(content='world'))
- # self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query((NOT hello NOT world))')
+ def test_build_query_multiple_words_not(self):
+ self.sq.add_filter(~SQ(content='hello'))
+ self.sq.add_filter(~SQ(content='world'))
+ self.assertEqual(self.sq.build_query().get_description(), 'Xapian::Query(((<alldocuments> AND_NOT hello) AND (<alldocuments> AND_NOT world)))')
# def test_build_query_multiple_words_or(self):
# self.sq.add_filter('content', 'hello', use_or=True)
diff --git a/xapian_backend.py b/xapian_backend.py
index <HASH>..<HASH> 100755
--- a/xapian_backend.py
+++ b/xapian_backend.py
@@ -15,7 +15,7 @@
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
__author__ = 'David Sauve'
-__version__ = (1, 0, 0, 'beta')
+__version__ = (2, 0, 0, 'alpha')
import datetime
import cPickle as pickle
@@ -29,7 +29,7 @@ from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_unicode, force_unicode
-from haystack.backends import BaseSearchBackend, BaseSearchQuery, log_query
+from haystack.backends import BaseSearchBackend, BaseSearchQuery, SearchNode, log_query
from haystack.exceptions import MissingDependency
from haystack.fields import DateField, DateTimeField, IntegerField, FloatField, BooleanField, MultiValueField
from haystack.models import SearchResult
@@ -936,19 +936,32 @@ class SearchQuery(BaseSearchQuery):
def build_query(self):
if not self.query_filter:
- query = xapian.Query('')
+ return xapian.Query('')
else:
- query_list = []
-
- for child in self.query_filter.children:
+ return self._query_from_search_node(self.query_filter)
+
+ def _query_from_search_node(self, search_node, is_not=False):
+ query_list = []
+
+ for child in search_node.children:
+ if isinstance(child, SearchNode):
+ query_list.append(
+ xapian.Query(
+ xapian.Query.OP_AND,
+ self._query_from_search_node(child, child.negated)
+ )
+ )
+ else:
expression, value = child
- query_list.append(value)
+ if is_not:
+ # DS_TODO: This can almost definitely be improved.
+ query_list.append(xapian.Query(xapian.Query.OP_AND_NOT, '', value))
+ else:
+ query_list.append(xapian.Query(value))
- query = xapian.Query(xapian.Query.OP_AND, query_list)
-
- return query
+ return xapian.Query(xapian.Query.OP_AND, query_list)
- def build_query_fragment(self, field, filter_type, value):
+ def build_sub_query(self, value):
return xapian.Query(value)
#
|
Four tests passing now. Recursively parsing the search nodes and negated on NOT as required.
|
notanumber_xapian-haystack
|
train
|
d05060f1bbd8a213b977838d5a67327206b9c3e4
|
diff --git a/onecodex/api_v0.py b/onecodex/api_v0.py
index <HASH>..<HASH> 100644
--- a/onecodex/api_v0.py
+++ b/onecodex/api_v0.py
@@ -5,7 +5,7 @@ import json
import os
import requests
import sys
-import threading
+from threading import BoundedSemaphore, Thread
import urlparse
@@ -17,6 +17,7 @@ else:
BASE_URL = urlparse.urlparse(BASE_API)
BASE_URL = BASE_URL._replace(path='/').geturl()
+DEFAULT_THREADS = 4
def pprint(j, args):
@@ -39,6 +40,11 @@ def upload(args):
"""
creds = (args.credentials['api_key'], '')
+ if args.threads:
+ semaphore = BoundedSemaphore(args.max_threads)
+ if args.max_threads != DEFAULT_THREADS:
+ print "Uploading with up to %d threads." % args.max_threads
+
# Get the initially needed routes
r0 = requests.get(BASE_API + 'presign_upload', auth=creds)
if r0.status_code != 200:
@@ -54,8 +60,8 @@ def upload(args):
for f in args.file:
if args.threads: # parallel uploads
# Multi-threaded uploads
- t = threading.Thread(target=upload_helper,
- args=(f, s3_url, signing_url, callback_url, creds))
+ t = Thread(target=upload_helper,
+ args=(f, s3_url, signing_url, callback_url, creds, semaphore))
upload_threads.append(t)
t.start()
else: # serial uploads
@@ -66,8 +72,12 @@ def upload(args):
ut.join()
-def upload_helper(f, s3_url, signing_url, callback_url, creds):
+def upload_helper(f, s3_url, signing_url, callback_url, creds,
+ semaphore=None):
# First get the signing form data
+ if semaphore is not None:
+ semaphore.acquire()
+
r1 = requests.post(signing_url, data={"filename": f},
auth=creds)
if r1.status_code != 200:
@@ -93,6 +103,9 @@ def upload_helper(f, s3_url, signing_url, callback_url, creds):
print "Failed to upload: %s" % f
sys.exit(1)
+ if semaphore is not None:
+ semaphore.release()
+
# Helper for /route/UUID pattern
def api_helper(args, route):
diff --git a/onecodex/cli.py b/onecodex/cli.py
index <HASH>..<HASH> 100644
--- a/onecodex/cli.py
+++ b/onecodex/cli.py
@@ -3,6 +3,7 @@ import argparse
import sys
from onecodex.auth import OneCodexAuth
from onecodex import api_v0 as api
+from onecodex.api_v0 import DEFAULT_THREADS
from onecodex import version
@@ -25,6 +26,7 @@ class OneCodexArgParser(argparse.ArgumentParser):
version.API_LINK),
'api_key': 'Manually provide a One Codex Beta API key',
'threads': 'Use multiple background threads to upload files',
+ 'max_threads': 'Specify a different max # of upload threads (defaults to 4)',
'file': 'One or more FASTA or FASTQ files to upload. Optionally gzip-compressed.',
'samples': 'One or more Samples to lookup. If absent returns all Samples.',
'analyses': 'One or more Analyses to lookup. If absent returns all Analyses.',
@@ -37,7 +39,10 @@ class OneCodexArgParser(argparse.ArgumentParser):
self._optionals.title = 'One Codex Options'
self.add_argument('--no-pretty-print', dest='pprint',
action="store_false", help=self.HELP['api_key'])
- self.add_argument('--threads', action='store_true', help=self.HELP['threads'])
+ self.add_argument('--no-threads', dest='threads',
+ action='store_false', help=self.HELP['threads'])
+ self.add_argument('--max-threads', default=DEFAULT_THREADS,
+ type=int, help=self.HELP['max_threads'])
self.add_argument('--api-key', help=self.HELP['api_key'])
self.add_argument('--version', action='version',
version=self.HELP['version'])
|
Add thread pool (BoundedSemaphore) for uploads
|
onecodex_onecodex
|
train
|
6b619d8adfdf461167c6a006b23562077bbeefc3
|
diff --git a/demo/index.php b/demo/index.php
index <HASH>..<HASH> 100755
--- a/demo/index.php
+++ b/demo/index.php
@@ -687,22 +687,22 @@ echo '=> '.var_export($command->run($pwd),1);
<?php
echo '$str="what ever";'."\n";
echo '$salt = "g(UmYZ[?25=%Fns8kK}&UrzRGPp?A-^gV}BP@!?c;f,Vl}X(Ob,pZ~=ABSXv_9yZ";'."\n";
-echo '$encryptor = new Library\Crypt($salt);'."\n";
+echo '$encryptor = new Library\Tool\Encrypt($salt);'."\n";
$str="what ever";
$salt = "g(UmYZ[?25=%Fns8kK}&UrzRGPp?A-^gV}BP@!?c;f,Vl}X(Ob,pZ~=ABSXv_9yZ";
-$encryptor = new Library\Crypt($salt);
+$encryptor = new Library\Tool\Encrypt($salt);
echo "\n";
echo '$crypted = $encryptor->crypt($str);'."\n";
echo 'echo $crypted;'."\n";
-$crypted = $encryptor->crypt($str);
+$crypted = $encryptor->encrypt($str);
echo '=> '.$crypted."\n";
echo "\n";
echo '$uncrypted = $encryptor->uncrypt($crypted);'."\n";
echo 'echo $uncrypted;'."\n";
-$uncrypted = $encryptor->uncrypt($crypted);
+$uncrypted = $encryptor->decrypt($crypted);
echo '=> '.$uncrypted."\n";
?>
</pre>
|
update demo with last classes renaming
|
atelierspierrot_library
|
train
|
89d22e64da675a1a45c6382993fa769c333161a9
|
diff --git a/src/jquery.contextMenu.js b/src/jquery.contextMenu.js
index <HASH>..<HASH> 100755
--- a/src/jquery.contextMenu.js
+++ b/src/jquery.contextMenu.js
@@ -1004,7 +1004,7 @@ var // currently active contextMenu trigger
},
layer: function(opt, zIndex) {
// add transparent layer for click area
- return opt.$layer = $('<div id="context-menu-layer" style="position:fixed; z-index:' + zIndex + '; top:0; left:0; opacity: 0;"></div>')
+ return opt.$layer = $('<div id="context-menu-layer" style="position:fixed; z-index:' + zIndex + '; top:0; left:0; opacity: 0; filter: alpha(opacity=0); background-color: #000;"></div>')
.css({height: $win.height(), width: $win.width(), display: 'block'})
.data('contextMenuRoot', opt)
.insertBefore(this)
|
Fix for Ie8
If there is an input box of combo box on the screen and it receives
focus before clicking on the invisible dismissal layer
(#context-menu-layer) the context menu won't disappear. I've added a IE
specific opacity filter and background color of white to
#context-menu-layer so the layer receives a click and properly
dismisses the context menu.
|
swisnl_jQuery-contextMenu
|
train
|
7c991d7b74274455a54bde9467ce1b20d85805cf
|
diff --git a/lib/xml-request.js b/lib/xml-request.js
index <HASH>..<HASH> 100644
--- a/lib/xml-request.js
+++ b/lib/xml-request.js
@@ -100,7 +100,11 @@ exports.xmlRequest = function(options, callback) {
request.post(reqOptions, function(error, response) {
- debug('response', {statusCode: response.statusCode, body: response.body});
+ debug('response', error ? {error: error} : {statusCode: response.statusCode, body: response.body});
+
+ if (error) {
+ return callback(error);
+ }
// this is tricky -- API should return 200 with body in every valid scenario,
// so a non-200 probably means something's wrong on the client side with the request.
|
oops - wasn't catching response errors in callback, fixed.
|
benbuckman_nodejs-ebay-api
|
train
|
095542f1fe6327ce3caefe86a0217b99901695cb
|
diff --git a/js/bittrex.js b/js/bittrex.js
index <HASH>..<HASH> 100644
--- a/js/bittrex.js
+++ b/js/bittrex.js
@@ -1236,14 +1236,10 @@ module.exports = class bittrex extends Exchange {
sign (path, api = 'v3', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.implodeParams (this.urls['api'][api], {
'hostname': this.hostname,
- }) + '/' + this.version + '/';
- if (api === 'public') {
- url += this.implodeParams (path, params);
- params = this.omit (params, this.extractParams (path));
- if (Object.keys (params).length) {
- url += '?' + this.urlencode (params);
- }
- } else if (api === 'private') {
+ }) + '/';
+ if (api === 'private') {
+ url += this.version + '/';
+ this.checkRequiredCredentials ();
url += this.implodeParams (path, params);
params = this.omit (params, this.extractParams (path));
let hashString = '';
@@ -1276,18 +1272,14 @@ module.exports = class bittrex extends Exchange {
headers['Content-Type'] = 'application/json';
}
} else {
- this.checkRequiredCredentials ();
- url += api + '/';
- const request = {
- 'apikey': this.apiKey,
- };
- const disableNonce = this.safeValue (this.options, 'disableNonce');
- if ((disableNonce === undefined) || !disableNonce) {
- request['nonce'] = this.nonce ();
+ if (api === 'public') {
+ url += this.version + '/';
+ }
+ url += this.implodeParams (path, params);
+ params = this.omit (params, this.extractParams (path));
+ if (Object.keys (params).length) {
+ url += '?' + this.urlencode (params);
}
- url += path + '?' + this.urlencode (this.extend (request, params));
- const signature = this.hmac (this.encode (url), this.encode (this.secret), 'sha512');
- headers = { 'apisign': signature };
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
@@ -1369,8 +1361,4 @@ module.exports = class bittrex extends Exchange {
}
}
}
-
- async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
- return await this.fetch2 (path, api, method, params, headers, body);
- }
};
|
bittrex sign() v3 edits
|
ccxt_ccxt
|
train
|
26c2f4d794a0ae546d1fcb3250142cda494d2c49
|
diff --git a/airflow/www/static/js/task-instances.js b/airflow/www/static/js/task-instances.js
index <HASH>..<HASH> 100644
--- a/airflow/www/static/js/task-instances.js
+++ b/airflow/www/static/js/task-instances.js
@@ -44,11 +44,13 @@ function generateTooltipDateTimes(startDate, endDate, dagTZ) {
let tooltipHTML = '<br><strong>UTC:</strong><br>';
tooltipHTML += makeDateTimeHTML(startDate, endDate);
- // Generate User's Local Start and End Date
- startDate.tz(localTZ);
- tooltipHTML += `<br><strong>Local: ${startDate.format(tzFormat)}</strong><br>`;
- const localEndDate = endDate && endDate instanceof moment ? endDate.tz(localTZ) : endDate;
- tooltipHTML += makeDateTimeHTML(startDate, localEndDate);
+ // Generate User's Local Start and End Date, unless it's UTC
+ if (localTZ !== 'UTC') {
+ startDate.tz(localTZ);
+ tooltipHTML += `<br><strong>Local: ${startDate.format(tzFormat)}</strong><br>`;
+ const localEndDate = endDate && endDate instanceof moment ? endDate.tz(localTZ) : endDate;
+ tooltipHTML += makeDateTimeHTML(startDate, localEndDate);
+ }
// Generate DAG's Start and End Date
if (dagTZ !== 'UTC' && dagTZ !== localTZ) {
|
Only show User's local timezone if it's not UTC (#<I>)
|
apache_airflow
|
train
|
b805d79d9e71417c3e7c266d45adc9eae2214fda
|
diff --git a/src/frontend/org/voltdb/groovy/GroovyCodeBlockCompiler.java b/src/frontend/org/voltdb/groovy/GroovyCodeBlockCompiler.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/groovy/GroovyCodeBlockCompiler.java
+++ b/src/frontend/org/voltdb/groovy/GroovyCodeBlockCompiler.java
@@ -45,7 +45,8 @@ public class GroovyCodeBlockCompiler {
imports.addStaticStars("org.voltdb.VoltProcedure","org.voltdb.VoltType");
conf.addCompilationCustomizers(imports);
- conf.getOptimizationOptions().put("indy", true);
+ // conf.getOptimizationOptions().put("int", false);
+ // conf.getOptimizationOptions().put("indy", true);
conf.setScriptBaseClass(DelegatingScript.class.getName());
File groovyOut = new File("groovyout");
|
disable invoke dynamic as it is not buying us anything at this juncture
|
VoltDB_voltdb
|
train
|
1c4d39df8e3fee03867c584fdbd5866b3f7fb760
|
diff --git a/lib/spaceship/base.rb b/lib/spaceship/base.rb
index <HASH>..<HASH> 100644
--- a/lib/spaceship/base.rb
+++ b/lib/spaceship/base.rb
@@ -18,14 +18,14 @@ module Spaceship
def remap_keys!(attrs)
return if attr_mapping.nil?
- @attr_mapping.each do |from, to|
+ attr_mapping.each do |from, to|
attrs[to] = attrs.delete(from)
end
end
- def attr_mapping(attrs = nil)
- if attrs
- @attr_mapping = attrs
+ def attr_mapping(attr_map = nil)
+ if attr_map
+ @attr_mapping = attr_map
else
@attr_mapping ||= ancestors[1].attr_mapping rescue nil
end
|
rename params for better readability
|
fastlane_fastlane
|
train
|
4f655ffe7bb41beafc59c3cda12bbb0ebe37fbf9
|
diff --git a/driver_wasapi_windows.go b/driver_wasapi_windows.go
index <HASH>..<HASH> 100644
--- a/driver_wasapi_windows.go
+++ b/driver_wasapi_windows.go
@@ -229,7 +229,7 @@ func (c *wasapiContext) initOnCOMThread() error {
func (c *wasapiContext) loopOnRenderThread() error {
for {
- evt, err := windows.WaitForSingleObject(c.sampleReadyEvent, 2000)
+ evt, err := windows.WaitForSingleObject(c.sampleReadyEvent, windows.INFINITE)
if err != nil {
return err
}
|
windows: bug fix: timeout at WaitForSingleObject
|
hajimehoshi_oto
|
train
|
ed1ac40c30d8e47d6ecebbf880a2877b4ddf56ba
|
diff --git a/packages/hemera/lib/index.js b/packages/hemera/lib/index.js
index <HASH>..<HASH> 100644
--- a/packages/hemera/lib/index.js
+++ b/packages/hemera/lib/index.js
@@ -1022,24 +1022,31 @@ class Hemera extends EventEmitter {
}
}
- return new Promise((resolve, reject) => {
- // create new execution context
- let ctx = this.createContext()
- ctx._pattern = pattern
- ctx._prevContext = this
- ctx._cleanPattern = Util.cleanFromSpecialVars(pattern)
- ctx._response = new ClientResponse()
- ctx._request = new ClientRequest()
- ctx._isServer = false
- ctx._execute = (err, result) => {
- if (ctx._actCallback) {
- if (this._config.generators) {
+ // create new execution context
+ let ctx = this.createContext()
+ ctx._pattern = pattern
+ ctx._prevContext = this
+ ctx._cleanPattern = Util.cleanFromSpecialVars(pattern)
+ ctx._response = new ClientResponse()
+ ctx._request = new ClientRequest()
+ ctx._isServer = false
+
+ if (cb) {
+ if (this._config.generators) {
+ ctx._actCallback = Co.wrap(cb.bind(ctx))
+ } else {
+ ctx._actCallback = cb.bind(ctx)
+ }
+ }
+
+ if (this._config.generators) {
+ ctx._extensions.onClientPreRequest.invoke(ctx, onPreRequestHandler)
+
+ return new Promise((resolve, reject) => {
+ ctx._execute = (err, result) => {
+ if (ctx._actCallback) {
ctx._actCallback(err, result).then(x => resolve(x)).catch(x => reject(x))
} else {
- ctx._actCallback(err, result)
- }
- } else {
- if (this._config.generators) {
if (err) {
reject(err)
} else {
@@ -1047,18 +1054,16 @@ class Hemera extends EventEmitter {
}
}
}
- }
+ })
+ }
- if (cb) {
- if (this._config.generators) {
- ctx._actCallback = Co.wrap(cb.bind(ctx))
- } else {
- ctx._actCallback = cb.bind(ctx)
- }
+ ctx._execute = (err, result) => {
+ if (ctx._actCallback) {
+ ctx._actCallback(err, result)
}
+ }
- ctx._extensions.onClientPreRequest.invoke(ctx, onPreRequestHandler)
- })
+ ctx._extensions.onClientPreRequest.invoke(ctx, onPreRequestHandler)
}
/**
@@ -1094,7 +1099,7 @@ class Hemera extends EventEmitter {
self.emit('clientResponseError', error)
self.log.fatal(error)
- // let it crash
+ // let it crash
if (self._config.crashOnFatal) {
self.fatal()
}
|
dont return promise when generators is set to false
|
hemerajs_hemera
|
train
|
bce500dc377a337db11ba481545d4eeecf914290
|
diff --git a/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java b/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java
index <HASH>..<HASH> 100644
--- a/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java
+++ b/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java
@@ -3122,8 +3122,12 @@ public class JdbcCpoAdapter extends CpoAdapterCache implements CpoAdapter {
for(int i=1; i<=rsmd.getColumnCount(); i++) {
JdbcCpoAttribute attribute = new JdbcCpoAttribute();
attribute.setDataName(rsmd.getColumnLabel(i));
- attribute.setDbTable(rsmd.getTableName(i));
attribute.setDbColumn(rsmd.getColumnName(i));
+ try {
+ attribute.setDbTable(rsmd.getTableName(i));
+ } catch (Exception e) {
+ // do nothing if this call is not supported
+ }
JavaSqlType<?> javaSqlType = metaDescriptor.getJavaSqlType(rsmd.getColumnType(i));
attribute.setDataType(javaSqlType.getJavaSqlTypeName());
|
added a try catch for an unsupported calls by cassandra
|
synchronoss_cpo-api
|
train
|
53076a3b83d99d10b9f2c990f2906eb7ec1f9f24
|
diff --git a/modules/utils.js b/modules/utils.js
index <HASH>..<HASH> 100644
--- a/modules/utils.js
+++ b/modules/utils.js
@@ -464,7 +464,11 @@ exports.isHTTPResource = isHTTPResource;
function isJsFile(file) {
"use strict";
var ext = fileExt(file);
- return isString(ext, "string") && ['js', 'coffee'].indexOf(ext) !== -1;
+ var valid = Object.keys(require.extensions).map(function (val) {
+ return val.replace(/^\./, '');
+ });
+ valid.splice(valid.indexOf('json'), 1);
+ return isString(ext, "string") && valid.indexOf(ext) !== -1;
}
exports.isJsFile = isJsFile;
diff --git a/tests/suites/require.js b/tests/suites/require.js
index <HASH>..<HASH> 100644
--- a/tests/suites/require.js
+++ b/tests/suites/require.js
@@ -15,11 +15,15 @@ casper.test.begin('Javascript module loading', 1, function(test) {
casper.test.begin('CoffeeScript module loading', 1, function(test) {
var csmod;
- try {
- csmod = require(fs.pathJoin(modroot, 'csmodule'));
- test.assertTrue(csmod.ok, 'require() patched version can load a coffeescript module');
- } catch (e) {
- test.fail('require() patched version can load a coffeescript module');
+ if (Object.keys(require.extensions).indexOf('.coffee') !== -1) {
+ try {
+ csmod = require(fs.pathJoin(modroot, 'csmodule'));
+ test.assertTrue(csmod.ok, 'require() patched version can load a coffeescript module');
+ } catch (e) {
+ test.fail('require() patched version can load a coffeescript module');
+ }
+ } else {
+ test.pass();
}
test.done();
});
diff --git a/tests/suites/utils.js b/tests/suites/utils.js
index <HASH>..<HASH> 100644
--- a/tests/suites/utils.js
+++ b/tests/suites/utils.js
@@ -314,7 +314,7 @@ casper.test.begin('isJsFile() tests', 5, function(test) {
'': false,
'toto.png': false,
'plop': false,
- 'gniii.coffee': true,
+ 'gniii.coffee': Object.keys(require.extensions).indexOf('.coffee') !== -1,
'script.js': true
};
for (var testCase in testCases) {
|
Allow the engine to define the available filetypes
isJsFile now checks require.extensions (minus json) to determine valid
javascript extensions
Modified tests so that they accomodate engines (PhantomJSv2) that don't
support coffeescript
|
casperjs_casperjs
|
train
|
949a2223a864bebdf1b2ec32bedef4f4577aeeea
|
diff --git a/src/streamlink/stream/hls_playlist.py b/src/streamlink/stream/hls_playlist.py
index <HASH>..<HASH> 100644
--- a/src/streamlink/stream/hls_playlist.py
+++ b/src/streamlink/stream/hls_playlist.py
@@ -1,4 +1,5 @@
import re
+import logging
from binascii import unhexlify
from collections import namedtuple
@@ -6,6 +7,8 @@ from itertools import starmap
from streamlink.compat import urljoin, urlparse
+log = logging.getLogger(__name__)
+
__all__ = ["load", "M3U8Parser"]
@@ -251,6 +254,7 @@ class M3U8Parser(object):
return self.m3u8
else:
if not line.startswith("#EXTM3U"):
+ log.warning("Malformed HLS Playlist. Expected #EXTM3U, but got {0}".format(line[:250]))
raise ValueError("Missing #EXTM3U header")
parse_line = self.parse_line
|
stream.hls_playlist: Add extra logging for invalid #EXTM3U line (#<I>)
I have added extra logging to the the HLS playlist parser to show what the first line was in case it's not the expected #EXTM3U
|
streamlink_streamlink
|
train
|
ffc5fd3f77e7604a2a8414836e3a69b7c1ba07dd
|
diff --git a/lib/drizzlepac/util.py b/lib/drizzlepac/util.py
index <HASH>..<HASH> 100644
--- a/lib/drizzlepac/util.py
+++ b/lib/drizzlepac/util.py
@@ -506,7 +506,7 @@ def getSectionName(configObj,stepnum):
""" Return section label based on step number.
"""
for key in configObj.keys():
- if key.find('STEP '+str(stepnum)) >= 0:
+ if key.find('STEP '+str(stepnum)+':') >= 0:
return key
def getConfigObjPar(configObj, parname):
|
bugfix: code was confusing section 3 with section 3a
git-svn-id: <URL>
|
spacetelescope_drizzlepac
|
train
|
1e657e500981865f11eac4dc30fdb43f3c47bdb4
|
diff --git a/lib/chefspec/matchers/subscribes_matcher.rb b/lib/chefspec/matchers/subscribes_matcher.rb
index <HASH>..<HASH> 100644
--- a/lib/chefspec/matchers/subscribes_matcher.rb
+++ b/lib/chefspec/matchers/subscribes_matcher.rb
@@ -23,6 +23,10 @@ module ChefSpec::Matchers
@instance.delayed
end
+ if @before
+ @instance.before
+ end
+
if resource
runner = resource.run_context.node.runner
expected = runner.find_resource(@expected_resource_type, @expected_resource_name)
@@ -48,6 +52,11 @@ module ChefSpec::Matchers
self
end
+ def before
+ @before = true
+ self
+ end
+
def description
@instance.description
end
|
Add :before timer support to SubscriptionsMatcher
|
chefspec_chefspec
|
train
|
b2748b3d5a65c2ccebf6f4b4a5d9a6cfad5a6907
|
diff --git a/haproxy_exporter.go b/haproxy_exporter.go
index <HASH>..<HASH> 100644
--- a/haproxy_exporter.go
+++ b/haproxy_exporter.go
@@ -26,6 +26,7 @@ const (
// HAProxy 1.5
// pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt,comp_in,comp_out,comp_byp,comp_rsp,lastsess,
expectedCsvFieldCount = 52
+ statusField = 17
)
var (
@@ -321,6 +322,16 @@ func (e *Exporter) setMetrics(csvRows <-chan []string) {
}
}
+func parseStatusField(value string) int64 {
+ switch value {
+ case "UP", "UP 1/3", "UP 2/3", "OPEN", "no check":
+ return 1
+ case "DOWN", "DOWN 1/2", "NOLB", "MAINT":
+ return 0
+ }
+ return 0
+}
+
func (e *Exporter) exportCsvFields(metrics map[int]*prometheus.GaugeVec, csvRow []string, labels ...string) {
for fieldIdx, metric := range metrics {
valueStr := csvRow[fieldIdx]
@@ -329,19 +340,11 @@ func (e *Exporter) exportCsvFields(metrics map[int]*prometheus.GaugeVec, csvRow
}
var value int64
- var err error
- switch valueStr {
- // UP or UP going down
- case "UP", "UP 1/3", "UP 2/3":
- value = 1
- // DOWN or DOWN going up
- case "DOWN", "DOWN 1/2":
- value = 0
- case "OPEN":
- value = 0
- case "no check":
- continue
+ switch fieldIdx {
+ case statusField:
+ value = parseStatusField(valueStr)
default:
+ var err error
value, err = strconv.ParseInt(valueStr, 10, 64)
if err != nil {
log.Printf("Error while parsing CSV field value %s: %v", valueStr, err)
diff --git a/haproxy_exporter_test.go b/haproxy_exporter_test.go
index <HASH>..<HASH> 100644
--- a/haproxy_exporter_test.go
+++ b/haproxy_exporter_test.go
@@ -163,6 +163,34 @@ func TestDeadline(t *testing.T) {
}
}
+func TestParseStatusField(t *testing.T) {
+ tests := []struct {
+ input string
+ want int64
+ }{
+ {"UP", 1},
+ {"UP 1/3", 1},
+ {"UP 2/3", 1},
+ {"OPEN", 1},
+ {"no check", 1},
+ {"DOWN", 0},
+ {"DOWN 1/2", 0},
+ {"NOLB", 0},
+ {"MAINT", 0}, // prometheus/haproxy_exporter#35
+ {"unknown", 0},
+ }
+
+ for _, tt := range tests {
+ if have := parseStatusField(tt.input); tt.want != have {
+ t.Errorf("want status value %d for input %s, have %s",
+ tt.want,
+ tt.input,
+ have,
+ )
+ }
+ }
+}
+
func BenchmarkExtract(b *testing.B) {
config, err := ioutil.ReadFile("test/haproxy.csv")
if err != nil {
|
Fix status field parsing
Handles instance MAINT status as down. Fixes #<I>.
|
prometheus_haproxy_exporter
|
train
|
9f6127f16fb1f75e7ed28fd439a1a8b88e442496
|
diff --git a/models.py b/models.py
index <HASH>..<HASH> 100644
--- a/models.py
+++ b/models.py
@@ -344,19 +344,24 @@ class MixtureDistribution(Mixture, GibbsSampling, MeanField, MeanFieldSVI, Distr
self.labels_list = []
def get_vlb(self):
+ from warnings import warn
+ warn('Pretty sure this is missing a term, VLB is wrong but updates are fine') # TODO
vlb = 0.
+ # vlb += self._labels_vlb # TODO this part is wrong! we need weights passed in again
vlb += self.weights.get_vlb()
vlb += sum(c.get_vlb() for c in self.components)
return vlb
def expected_log_likelihood(self,x):
- lognorm = np.logaddexp.reduce(self.weights.alpha_mf)
+ lognorm = np.logaddexp.reduce(self.weights._alpha_mf)
return sum(np.exp(a - lognorm) * c.expected_log_likelihood(x)
- for a, c in zip(self.weights.alpha_mf, self.components))
+ for a, c in zip(self.weights._alpha_mf, self.components))
def meanfieldupdate(self,data,weights,**kwargs):
# NOTE: difference from parent's method is the inclusion of weights
- data = data if isinstance(data,list) else [data]
+ if not isinstance(data,(list,tuple)):
+ data = [data]
+ weights = [weights]
old_labels = self.labels_list
self.labels_list = []
@@ -364,23 +369,27 @@ class MixtureDistribution(Mixture, GibbsSampling, MeanField, MeanFieldSVI, Distr
self.add_data(d,z=np.empty(d.shape[0])) # NOTE: dummy
self.meanfield_update_labels()
- for l in self.labels_list:
- l.r *= weights[:,na] # here's where the weights are used
+ for l, w in zip(self.labels_list,weights):
+ l.r *= w[:,na] # here's where the weights are used
self.meanfield_update_parameters()
+ # self._labels_vlb = sum(l.get_vlb() for l in self.labels_list) # TODO hack
+
self.labels_list = old_labels
def meanfield_sgdstep(self,minibatch,weights,minibatchfrac,stepsize):
# NOTE: difference from parent's method is the inclusion of weights
- minibatch = minibatch if isinstance(minibatch,list) else [minibatch]
+ if not isinstance(minibatch,list):
+ minibatch = [minibatch]
+ weights = [weights]
mb_labels_list = []
for data in minibatch:
self.add_data(data,z=np.empty(data.shape[0])) # NOTE: dummy
mb_labels_list.append(self.labels_list.pop())
- for l in mb_labels_list:
+ for l, w in zip(mb_labels_list,weights):
l.meanfieldupdate()
- l.r *= weights[:,na] # here's where weights are used
+ l.r *= w[:,na] # here's where weights are used
self._meanfield_sgdstep_parameters(mb_labels_list,minibatchfrac,stepsize)
|
fix mixturedistribution SVI
|
mattjj_pybasicbayes
|
train
|
611694edd96f1c2d058257c0fe4c0dd032361d54
|
diff --git a/TodoList.py b/TodoList.py
index <HASH>..<HASH> 100644
--- a/TodoList.py
+++ b/TodoList.py
@@ -64,19 +64,19 @@ class TodoList(object):
dep_id = p_todo.tag_value('id')
# maintain dependency graph
if dep_id:
- self._depgraph.add_node(p_todo.attributes['number'])
+ self._depgraph.add_node(self.number(p_todo))
# connect all tasks we have in memory so far that refer to this
# task
for dep in \
[dep for dep in self._todos if dep.has_tag('p', dep_id)]:
- self._depgraph.add_edge(p_todo.attributes['number'], dep.attributes['number'], dep_id)
+ self._depgraph.add_edge(self.number(p_todo), self.number(dep), dep_id)
for child in p_todo.tag_values('p'):
parent = self.todo_by_dep_id(child)
if parent:
- self._depgraph.add_edge(parent.attributes['number'], p_todo.attributes['number'], child)
+ self._depgraph.add_edge(self.number(parent), self.number(p_todo), child)
def add(self, p_src):
""" Given a todo string, parse it and put it to the end of the list. """
@@ -117,10 +117,10 @@ class TodoList(object):
if todo:
for child in self.children(p_number):
- self.remove_dependency(todo.attributes['number'], child.attributes['number'])
+ self.remove_dependency(self.number(todo), self.number(child))
for parent in self.parents(p_number):
- self.remove_dependency(parent.attributes['number'], todo.attributes['number'])
+ self.remove_dependency(self.number(parent), self.number(todo))
del self._todos[p_number - 1]
@@ -272,7 +272,7 @@ class TodoList(object):
"""
for todo in self._todos:
- todo.attributes['parents'] = self.parents(todo.attributes['number'])
+ todo.attributes['parents'] = self.parents(self.number(todo))
def is_dirty(self):
return self.dirty
@@ -290,6 +290,9 @@ class TodoList(object):
todo.set_priority(p_priority)
self.dirty = True
+ def number(self, p_todo):
+ return p_todo.attributes['number'] # TODO: do the lookup
+
def __str__(self):
return '\n'.join(pretty_print_list(self._todos))
|
Create access function for the todo number.
A step to get rid of todo.attributes["number"].
|
bram85_topydo
|
train
|
026c7688600c1e5dc885313543e46b5c4a6b7d2e
|
diff --git a/app/models/cms/page.rb b/app/models/cms/page.rb
index <HASH>..<HASH> 100644
--- a/app/models/cms/page.rb
+++ b/app/models/cms/page.rb
@@ -48,7 +48,7 @@ class Cms::Page < ActiveRecord::Base
:presence => true
validates :slug,
:presence => true,
- :format => /^\p{Alnum}[\.\p{Alnum}_-]*$/i,
+ :format => /^\p{Alnum}[\.\p{Alnum}\p{Mark}_-]*$/i,
:uniqueness => { :scope => :parent_id },
:unless => lambda{ |p| p.site && (p.site.pages.count == 0 || p.site.pages.root == self) }
validates :layout,
diff --git a/test/unit/models/page_test.rb b/test/unit/models/page_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/models/page_test.rb
+++ b/test/unit/models/page_test.rb
@@ -56,7 +56,15 @@ class CmsPageTest < ActiveSupport::TestCase
page.slug = 'acción'
assert page.valid?
end
-
+
+ def test_validation_of_slug_allows_unicode_accent_characters
+ page = cms_pages(:child)
+ thai_character_ko_kai = "\u0e01"
+ thai_character_mai_tho = "\u0E49"
+ page.slug = thai_character_ko_kai + thai_character_mai_tho
+ assert page.valid?
+ end
+
def test_label_assignment
page = cms_sites(:default).pages.new(
:slug => 'test',
|
Allow Unicode accent characters in slug name
|
comfy_comfortable-mexican-sofa
|
train
|
ce3062586e9edceab2c86c8168ae7de691470a30
|
diff --git a/lib/uv-rays/http_endpoint.rb b/lib/uv-rays/http_endpoint.rb
index <HASH>..<HASH> 100644
--- a/lib/uv-rays/http_endpoint.rb
+++ b/lib/uv-rays/http_endpoint.rb
@@ -192,7 +192,7 @@ module UV
def close_connection
return if @connection.nil?
- @connection.close_connection(:after_writing)
+ @connection.close_connection(@parser.request)
stop_timer
@connection = nil
end
|
(http) keep track of connection to request mapping
|
cotag_uv-rays
|
train
|
76adc424f27a13c8babd4787bbf45dee03d0a07e
|
diff --git a/riemann/examples/p2pkh_tx_ex.py b/riemann/examples/p2pkh_tx_ex.py
index <HASH>..<HASH> 100644
--- a/riemann/examples/p2pkh_tx_ex.py
+++ b/riemann/examples/p2pkh_tx_ex.py
@@ -46,11 +46,11 @@ tx_in = simple.unsigned_input(tx_outpoint, sequence=0xFFFFFFFE)
receiving_address = 'bc1qss5rslea60lftfe7pyk32s9j9dtr7z7mrqud3g'
# Bitcoin (satoshis) to send
-value = 100000
+input_value = 100000
# Allocate Bitcoin (satoshis) for miner
tx_fee = 3100
-tx_out = simple.output(value - tx_fee, receiving_address)
+tx_out = simple.output(input_value - tx_fee, receiving_address)
# Completely optional memo
tx_return_output = tb.make_op_return_output('made with ❤ by riemann'.encode('utf-8'))
@@ -62,7 +62,7 @@ tx_return_output = tb.make_op_return_output('made with ❤ by riemann'.encode('u
tx = simple.unsigned_tx([tx_in], [tx_out, tx_return_output])
-# Genearte Signed Tx
+# Generate Signed Tx
# https://blockchain.info/tx/1e7acd3d4715054c8fb0fdea25c5c704986006d2c6f30b0782e9b36a7ee072ef
# With the p2pkh output script from address, create the the sighash to be signed
@@ -71,7 +71,7 @@ sighash = tx.sighash_all(index=0, script=addresses.to_output_script(address))
# Declare SIGHASH_ALL type
SIGHASH_ALL = 0x01
-# Create script signature by signing the tx with private key
+# Sign the tx with private key
# Assumes private_key is of type class bitcoin.wallet.CKey from python-bitcoinlib
sig = private_key.sign(sighash) + bytes([SIGHASH_ALL])
@@ -83,7 +83,17 @@ tx_signed_input = simple.p2pkh_input(
sequence=0xFFFFFFFE)
# Recreate tx with the signed tx input
-tx_signed_tx = tx.copy(tx_ins=[tx_signed_input])
+tx_signed = tx.copy(tx_ins=[tx_signed_input])
+tx_signed_hex = tx_signed.hex()
+print(tx_signed_hex)
# Transaction hash
-tx_hash = tx_signed_tx.tx_id.hex()
+tx_hash = tx_signed.tx_id.hex()
+
+# Resources to decode transaction (tx_signed_hex)
+# https://blockchain.info/decode-tx
+# https://live.blockcypher.com/btc/decodetx/
+
+# Resources to broadcast transaction (tx_signed_hex)
+# https://blockchain.info/pushtx
+# https://live.blockcypher.com/btc/pushtx/
|
Addressed p2pkh comments.
|
summa-tx_riemann
|
train
|
ae63380d51460d313ce1ebd6817eb931ee90448c
|
diff --git a/bosh-dev/lib/bosh/dev/build.rb b/bosh-dev/lib/bosh/dev/build.rb
index <HASH>..<HASH> 100644
--- a/bosh-dev/lib/bosh/dev/build.rb
+++ b/bosh-dev/lib/bosh/dev/build.rb
@@ -1,8 +1,8 @@
-require 'bosh/dev/pipeline'
require 'bosh/stemcell/stemcell'
require 'bosh/stemcell/archive_filename'
require 'bosh/stemcell/infrastructure'
require 'bosh/dev/download_adapter'
+require 'bosh/dev/upload_adapter'
module Bosh::Dev
class Build
@@ -21,11 +21,13 @@ module Bosh::Dev
def initialize(number)
@number = number
@job_name = ENV.to_hash.fetch('JOB_NAME')
- @pipeline = Pipeline.new(build_id: number.to_s)
end
- def upload(release)
- pipeline.s3_upload(release.tarball, release_path)
+ def upload(release, options = {})
+ bucket = 'bosh-ci-pipeline'
+ key = File.join(number.to_s, release_path)
+ upload_adapter = options.fetch(:upload_adapter) { UploadAdapter.new }
+ upload_adapter.upload(bucket_name: bucket, key: key, body: File.open(release.tarball), public: true)
end
def download_release
@@ -91,7 +93,7 @@ module Bosh::Dev
private
- attr_reader :pipeline, :job_name
+ attr_reader :job_name
def light_stemcell
infrastructure = Bosh::Stemcell::Infrastructure.for('aws')
diff --git a/bosh-dev/spec/bosh/dev/build_spec.rb b/bosh-dev/spec/bosh/dev/build_spec.rb
index <HASH>..<HASH> 100644
--- a/bosh-dev/spec/bosh/dev/build_spec.rb
+++ b/bosh-dev/spec/bosh/dev/build_spec.rb
@@ -5,7 +5,6 @@ module Bosh::Dev
describe Build do
include FakeFS::SpecHelpers
- let(:fake_pipeline) { instance_double('Bosh::Dev::Pipeline', s3_url: 's3://FAKE_BOSH_CI_PIPELINE_BUCKET/') }
let(:job_name) { 'current_job' }
let(:download_directory) { '/FAKE/CUSTOM/WORK/DIRECTORY' }
@@ -17,8 +16,6 @@ module Bosh::Dev
'CANDIDATE_BUILD_NUMBER' => 'candidate',
'JOB_NAME' => job_name
)
-
- Bosh::Dev::Pipeline.stub(new: fake_pipeline)
end
describe '.candidate' do
@@ -49,11 +46,22 @@ module Bosh::Dev
describe '#upload' do
let(:release) { double(tarball: 'release-tarball.tgz') }
+ let(:upload_adapter) { instance_double('Bosh::Dev::UploadAdapter') }
+ let(:io) { double }
+
+ it 'uploads the release with its build number' do
+ File.stub(:open).with(release.tarball) { io }
+ upload_adapter.should_receive(:upload).with(bucket_name: 'bosh-ci-pipeline', key: '123/release/bosh-123.tgz', body: io, public: true)
+
+ subject.upload(release, upload_adapter: upload_adapter)
+ end
- it 'uploads the release to the pipeline bucket with its build number' do
- fake_pipeline.should_receive(:s3_upload).with('release-tarball.tgz', 'release/bosh-123.tgz')
+ context 'when the file does not exist' do
+
+ it 'raises an error' do
+ expect { subject.upload(release, upload_adapter: upload_adapter) }.to raise_error(Errno::ENOENT)
+ end
- subject.upload(release)
end
end
|
Use UploadAdapter in Build.
Remove Pipeline from Build.
|
cloudfoundry_bosh
|
train
|
3a445c4c15ee377e96f841c7c34371b32c7dea34
|
diff --git a/packages/application-shell/src/test-utils/test-utils.js b/packages/application-shell/src/test-utils/test-utils.js
index <HASH>..<HASH> 100644
--- a/packages/application-shell/src/test-utils/test-utils.js
+++ b/packages/application-shell/src/test-utils/test-utils.js
@@ -38,7 +38,7 @@ const defaultProject = {
name: 'Test with big data',
countries: ['de', 'en'],
currencies: ['EUR', 'GBP'],
- languages: ['de', 'en-GB'],
+ languages: ['de', 'en-GB', 'en'],
owner: {
id: 'project-id-1',
},
diff --git a/packages/application-shell/src/test-utils/test-utils.spec.js b/packages/application-shell/src/test-utils/test-utils.spec.js
index <HASH>..<HASH> 100644
--- a/packages/application-shell/src/test-utils/test-utils.spec.js
+++ b/packages/application-shell/src/test-utils/test-utils.spec.js
@@ -143,7 +143,7 @@ describe('ApplicationContext', () => {
name: 'Test with big data',
countries: ['de', 'en'],
currencies: ['EUR', 'GBP'],
- languages: ['de', 'en-GB'],
+ languages: ['de', 'en-GB', 'en'],
owner: {
id: 'project-id-1',
},
|
data locale should be one of the project languages (#<I>)
* data locale should be one of the project languages
this leads to tests failing when using 'LocalizedTextInput.createLocalizedString' because we pass the locales from the project and then in the test we check the locale the user chose.
* add 'en' to list of languages in project
* Update test-utils.spec.js
|
commercetools_merchant-center-application-kit
|
train
|
f4415d8503224d587e27abbecb3931ea08b7278e
|
diff --git a/lib/Collection/QueryType/Handler/ContentSearchHandler.php b/lib/Collection/QueryType/Handler/ContentSearchHandler.php
index <HASH>..<HASH> 100644
--- a/lib/Collection/QueryType/Handler/ContentSearchHandler.php
+++ b/lib/Collection/QueryType/Handler/ContentSearchHandler.php
@@ -91,6 +91,7 @@ class ContentSearchHandler implements QueryTypeHandlerInterface
}
$locationQuery = $this->buildLocationQuery($query, $parentLocation);
+ $locationQuery->performCount = false;
$locationQuery->offset = $offset;
$locationQuery->limit = $limit;
|
Do not perform count in query type getValues method, it is not needed
|
netgen-layouts_layouts-ezplatform
|
train
|
c40558ef5205f7f5d902ccdaa2218c301ae5e7d0
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -67,8 +67,8 @@ Installs routes as defined in opts into a restify server, invokes the callback
when done.
* `opts`: The options object containing
* `opts.server` The restify server to install the routes on to.
- * `opts.config` The POJO of the enroute config.
- * `opts.configPath` The path to the enroute config on disk.
+ * `[opts.config]` The POJO of the enroute config.
+ * `[opts.configPath]` The path to the enroute config on disk.
* `cb` The callback. Returns `Error` if there's an error installing the routes.
Note only one of `opts.config` or `opts.configPath` is needed. The module will
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -7,6 +7,9 @@ var install = require('./install');
var parser = require('./parser');
/**
+ * Installs configuration driven routes onto a restify server. Note only one of
+ * opts.config or opts.configPath is needed.
+ *
* exports
*
* @param {object} opts Options object.
diff --git a/lib/parser.js b/lib/parser.js
index <HASH>..<HASH> 100644
--- a/lib/parser.js
+++ b/lib/parser.js
@@ -19,7 +19,8 @@ module.exports = {
/**
* Parse and validate a enroute config. This will verify that the config
- * is valid and return a POJO with the properties.
+ * is valid and return a POJO with the properties. Note only one of opts.config
+ * or opts.configPath is needed.
*
* @param {object} opts The options object
* @param {string} [opts.config] The POJO of the config you want to validate.
|
be explicit about the mutually exclusive nature of config and configPath
|
restify_enroute
|
train
|
67b87a0ea0fe359264806494ee789368607a43d8
|
diff --git a/telethon/sessions/sqlite.py b/telethon/sessions/sqlite.py
index <HASH>..<HASH> 100644
--- a/telethon/sessions/sqlite.py
+++ b/telethon/sessions/sqlite.py
@@ -1,5 +1,6 @@
import datetime
import os
+import time
from telethon.tl import types
from .memory import MemorySession, _SentFileType
@@ -17,7 +18,7 @@ except ImportError as e:
sqlite3_err = type(e)
EXTENSION = '.session'
-CURRENT_VERSION = 6 # database version
+CURRENT_VERSION = 7 # database version
class SQLiteSession(MemorySession):
@@ -84,7 +85,8 @@ class SQLiteSession(MemorySession):
hash integer not null,
username text,
phone integer,
- name text
+ name text,
+ date integer
)"""
,
"""sent_files (
@@ -148,6 +150,9 @@ class SQLiteSession(MemorySession):
# hashes for User and Channel are wrong, so drop them off.
old += 1
c.execute('delete from entities')
+ if old == 6:
+ old += 1
+ c.execute("alter table entities add column date integer")
c.close()
@@ -264,10 +269,9 @@ class SQLiteSession(MemorySession):
# Entity processing
def process_entities(self, tlo):
- """Processes all the found entities on the given TLObject,
- unless .enabled is False.
-
- Returns True if new input entities were added.
+ """
+ Processes all the found entities on the given TLObject,
+ unless .save_entities is False.
"""
if not self.save_entities:
return
@@ -278,8 +282,10 @@ class SQLiteSession(MemorySession):
c = self._cursor()
try:
+ now_tup = (int(time.time()),)
+ rows = [row + now_tup for row in rows]
c.executemany(
- 'insert or replace into entities values (?,?,?,?,?)', rows)
+ 'insert or replace into entities values (?,?,?,?,?,?)', rows)
finally:
c.close()
@@ -288,8 +294,25 @@ class SQLiteSession(MemorySession):
'select id, hash from entities where phone = ?', phone)
def get_entity_rows_by_username(self, username):
- return self._execute(
- 'select id, hash from entities where username = ?', username)
+ c = self._cursor()
+ try:
+ results = c.execute(
+ 'select id, hash, date from entities where username = ?',
+ (username,)
+ ).fetchall()
+
+ if not results:
+ return None
+
+ # If there is more than one result for the same username, evict the oldest one
+ if len(results) > 1:
+ results.sort(key=lambda t: t[2] or 0)
+ c.executemany('update entities set username = null where id = ?',
+ [(t[0],) for t in results[:-1]])
+
+ return results[-1][0], results[-1][1]
+ finally:
+ c.close()
def get_entity_rows_by_name(self, name):
return self._execute(
|
Evict old cached usernames in case of collision
|
LonamiWebs_Telethon
|
train
|
3b70453c32b4ae792ffa61ecc9aabb2e9766f27d
|
diff --git a/filter-widget/filter-widget.js b/filter-widget/filter-widget.js
index <HASH>..<HASH> 100644
--- a/filter-widget/filter-widget.js
+++ b/filter-widget/filter-widget.js
@@ -220,6 +220,16 @@ export let ViewModel = CanMap.extend({
};
}) : null;
}
+ },
+ /**
+ * If true, existing filters will be replaced rather than concatenated
+ * when the addFilter method is called
+ * @property {Boolean} filter-widget.ViewModel.replaceExisting
+ * @parent filter-widget.ViewModel.props
+ */
+ replaceExisting: {
+ value: false,
+ type: 'boolean'
}
},
/**
@@ -280,14 +290,20 @@ export let ViewModel = CanMap.extend({
filters = [obj];
}
- //start batch process
- can.batch.start();
- filters.forEach(f => {
- this.attr('filters').push(f);
- });
- this.attr('formObject', null);
- //end batch process
- can.batch.stop();
+ if (this.attr('replaceExisting')) {
+ this.attr('filters').replace(filters);
+ } else {
+
+ //start batch process
+ //concat array doesn't seem to update correctly
+ can.batch.start();
+ filters.forEach(f => {
+ this.attr('filters').push(f);
+ });
+ this.attr('formObject', null);
+ //end batch process
+ can.batch.stop();
+ }
return false;
}
diff --git a/filter-widget/filter-widget.test.js b/filter-widget/filter-widget.test.js
index <HASH>..<HASH> 100644
--- a/filter-widget/filter-widget.test.js
+++ b/filter-widget/filter-widget.test.js
@@ -94,6 +94,16 @@ test('addFilter()', assert => {
assert.equal(vm.attr('filters').length, 1, 'filters should been added');
});
+test('addFilter() with replaceExisting', assert => {
+ vm.addFilter(null, null, null, filter);
+ vm.addFilter(null, null, null, filter);
+ assert.equal(vm.attr('filters').length, 2, 'filters should been added');
+
+ vm.attr('replaceExisting', true);
+ vm.addFilter(null, null, null, filter);
+ assert.equal(vm.attr('filters').length, 1, 'filters should been replaced');
+});
+
test('addFilter() with filterFactory', assert => {
vm.attr('fields', [{
name: 'test',
|
Adds the replaceExisting property to the view model
|
roemhildtg_can-crud
|
train
|
b9d2de3d07d2dbc40d7205e41ed0583d34e32efa
|
diff --git a/deployments/pathmap-migrator/src/main/java/org/commonjava/indy/pathmap/migrate/MigrateCmd.java b/deployments/pathmap-migrator/src/main/java/org/commonjava/indy/pathmap/migrate/MigrateCmd.java
index <HASH>..<HASH> 100644
--- a/deployments/pathmap-migrator/src/main/java/org/commonjava/indy/pathmap/migrate/MigrateCmd.java
+++ b/deployments/pathmap-migrator/src/main/java/org/commonjava/indy/pathmap/migrate/MigrateCmd.java
@@ -39,6 +39,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import static org.commonjava.indy.pathmap.migrate.Util.FAILED_PATHS_FILE;
+import static org.commonjava.indy.pathmap.migrate.Util.STATUS_FILE;
import static org.commonjava.indy.pathmap.migrate.Util.TODO_FILES_DIR;
public class MigrateCmd
@@ -114,7 +115,34 @@ public class MigrateCmd
private void init( MigrateOptions options )
{
- new Timer().schedule( new UpdateProgressTask( options ), 30000L, 30000L );
+ // Reload last processed paths count
+ Path statusFilePath = Paths.get( options.getWorkDir(), STATUS_FILE );
+ File statusFile = statusFilePath.toFile();
+ if ( statusFile.exists() )
+ {
+ try (BufferedReader reader = new BufferedReader( new FileReader( statusFile ) ))
+ {
+ String line = reader.readLine();
+ while ( line != null )
+ {
+ if ( line.trim().startsWith( "Processed" ) )
+ {
+ this.processedCount.set( Integer.parseInt( line.split( ":" )[1].trim() ) );
+ break;
+ }
+ line = reader.readLine();
+ }
+ Files.delete( statusFilePath );
+ }
+ catch ( IOException | NumberFormatException e )
+ {
+ e.printStackTrace();
+ }
+ }
+
+ final long period = 15000L;
+ // Trigger progress update task.
+ new Timer().schedule( new UpdateProgressTask( options ), period, period );
}
private void storeFailedPaths( MigrateOptions options, List<String> failedPaths )
@@ -152,7 +180,7 @@ public class MigrateCmd
public void run()
{
int currentProcessedCnt = MigrateCmd.this.processedCount.get();
- Path statusFilePath = Paths.get( options.getWorkDir(), Util.STATUS_FILE );
+ Path statusFilePath = Paths.get( options.getWorkDir(), STATUS_FILE );
File statusFile = statusFilePath.toFile();
int totalCnt = 0;
if ( statusFile.exists() )
@@ -164,8 +192,10 @@ public class MigrateCmd
{
if ( line.trim().startsWith( "Total" ) )
{
- totalCnt = Integer.parseInt( line.split( ":" )[1] );
+ totalCnt = Integer.parseInt( line.split( ":" )[1].trim() );
+ break;
}
+ line = reader.readLine();
}
Files.delete( statusFilePath );
}
@@ -175,7 +205,7 @@ public class MigrateCmd
}
}
- double progress = currentProcessedCnt / totalCnt;
+ double progress = (double) currentProcessedCnt / (double) totalCnt;
String progressString = new DecimalFormat( "##.##" ).format( progress );
try
|
Add reload processed count for next migrate from failure (#<I>)
|
Commonjava_indy
|
train
|
e0a568e281235fbe80103756866b26ab410a73a4
|
diff --git a/cache/classes/definition.php b/cache/classes/definition.php
index <HASH>..<HASH> 100644
--- a/cache/classes/definition.php
+++ b/cache/classes/definition.php
@@ -265,6 +265,8 @@ class cache_definition {
* @throws coding_exception
*/
public static function load($id, array $definition, $datasourceaggregate = null) {
+ global $CFG;
+
if (!array_key_exists('mode', $definition)) {
throw new coding_exception('You must provide a mode when creating a cache definition');
}
@@ -349,6 +351,12 @@ class cache_definition {
if (!is_null($overrideclass)) {
if (!is_null($overrideclassfile)) {
+ if (strpos($overrideclassfile, $CFG->dirroot) !== 0) {
+ $overrideclassfile = $CFG->dirroot.'/'.$overrideclassfile;
+ }
+ if (strpos($overrideclassfile, '../') !== false) {
+ throw new coding_exception('No path craziness allowed within override class file path.');
+ }
if (!file_exists($overrideclassfile)) {
throw new coding_exception('The override class file does not exist.');
}
@@ -366,13 +374,19 @@ class cache_definition {
if (!is_null($datasource)) {
if (!is_null($datasourcefile)) {
+ if (strpos($datasourcefile, $CFG->dirroot) !== 0) {
+ $datasourcefile = $CFG->dirroot.'/'.$datasourcefile;
+ }
+ if (strpos($datasourcefile, '../') !== false) {
+ throw new coding_exception('No path craziness allowed within data source file path.');
+ }
if (!file_exists($datasourcefile)) {
- throw new coding_exception('The override class file does not exist.');
+ throw new coding_exception('The data source class file does not exist.');
}
require_once($datasourcefile);
}
if (!class_exists($datasource)) {
- throw new coding_exception('The override class does not exist.');
+ throw new coding_exception('The data source class does not exist.');
}
if (!array_key_exists('cache_data_source', class_implements($datasource))) {
throw new coding_exception('Cache data source classes must implement the cache_data_source interface');
diff --git a/cache/tests/cache_test.php b/cache/tests/cache_test.php
index <HASH>..<HASH> 100644
--- a/cache/tests/cache_test.php
+++ b/cache/tests/cache_test.php
@@ -319,7 +319,8 @@ class cache_phpunit_tests extends advanced_testcase {
'mode' => cache_store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'datasourcetest',
- 'datasource' => 'cache_phpunit_dummy_datasource'
+ 'datasource' => 'cache_phpunit_dummy_datasource',
+ 'datasourcefile' => 'cache/tests/fixtures/lib.php'
));
$cache = cache::make('phpunit', 'datasourcetest');
@@ -347,7 +348,8 @@ class cache_phpunit_tests extends advanced_testcase {
'mode' => cache_store::MODE_APPLICATION,
'component' => 'phpunit',
'area' => 'overridetest',
- 'overrideclass' => 'cache_phpunit_dummy_overrideclass'
+ 'overrideclass' => 'cache_phpunit_dummy_overrideclass',
+ 'overrideclassfile' => 'cache/tests/fixtures/lib.php'
));
$cache = cache::make('phpunit', 'overridetest');
$this->assertInstanceOf('cache_phpunit_dummy_overrideclass', $cache);
|
MDL-<I> cache: Fixed up inclusion path for overrideclassfile and datasourcefile
|
moodle_moodle
|
train
|
76ad8f8b15a93671f78a6847bc80537d03c6d960
|
diff --git a/lib/parslet/atoms/base.rb b/lib/parslet/atoms/base.rb
index <HASH>..<HASH> 100644
--- a/lib/parslet/atoms/base.rb
+++ b/lib/parslet/atoms/base.rb
@@ -47,8 +47,9 @@ class Parslet::Atoms::Base
# to provide a good error message (even asking down below)
if !prefix_parse && !source.eof?
old_pos = source.pos
- source.error(
- "Don't know what to do with #{source.read(10).to_s.inspect}", old_pos).
+ Parslet::Cause.format(
+ source, old_pos,
+ "Don't know what to do with #{source.read(10).to_s.inspect}").
raise(Parslet::UnconsumedInput)
end
diff --git a/lib/parslet/atoms/context.rb b/lib/parslet/atoms/context.rb
index <HASH>..<HASH> 100644
--- a/lib/parslet/atoms/context.rb
+++ b/lib/parslet/atoms/context.rb
@@ -11,8 +11,6 @@ module Parslet::Atoms
@reporter = reporter
end
- attr_accessor :reporter
-
# Caches a parse answer for obj at source.pos. Applying the same parslet
# at one position of input always yields the same result, unless the input
# has changed.
@@ -42,10 +40,17 @@ module Parslet::Atoms
return result
end
+ # Report an error at a given position.
+ # @see ErrorReporter
+ #
def err_at(*args)
return [false, @reporter.err_at(*args)] if @reporter
return [false, nil]
end
+
+ # Report an error.
+ # @see ErrorReporter
+ #
def err(*args)
return [false, @reporter.err(*args)] if @reporter
return [false, nil]
diff --git a/lib/parslet/cause.rb b/lib/parslet/cause.rb
index <HASH>..<HASH> 100644
--- a/lib/parslet/cause.rb
+++ b/lib/parslet/cause.rb
@@ -7,8 +7,8 @@ module Parslet
# override the position of the +source+. This method returns an object
# that can be turned into a string using #to_s.
#
- def self.format(source, pos, str)
- self.new(str, source, pos)
+ def self.format(source, pos, str, children=nil)
+ self.new(str, source, pos, children || [])
end
# Make the uninitialized value for #children to be the empty array, but
diff --git a/lib/parslet/error_reporter.rb b/lib/parslet/error_reporter.rb
index <HASH>..<HASH> 100644
--- a/lib/parslet/error_reporter.rb
+++ b/lib/parslet/error_reporter.rb
@@ -3,20 +3,16 @@ module Parslet
# Produces an instance of Fail and returns it.
#
- def err(source, str, children=nil)
- cause = source.error(str)
- cause.children = children || []
-
- return cause
+ def err(source, message, children=nil)
+ position = source.pos
+ Cause.format(source, position, message, children)
end
# Produces an instance of Fail and returns it.
#
- def err_at(source, str, pos, children=nil)
- cause = source.error(str, pos)
- cause.children = children || []
-
- return cause
+ def err_at(source, message, pos, children=nil)
+ position = pos
+ Cause.format(source, position, message, children)
end
end
diff --git a/lib/parslet/source.rb b/lib/parslet/source.rb
index <HASH>..<HASH> 100644
--- a/lib/parslet/source.rb
+++ b/lib/parslet/source.rb
@@ -48,17 +48,6 @@ module Parslet
def line_and_column(position=nil)
@line_cache.line_and_column(position || self.pos)
end
-
- # Formats an error cause at the current position or at the position given
- # by pos. If pos is nil, the current source position will be the error
- # position.
- #
- def error(message, error_pos=nil)
- real_pos = (error_pos||self.pos)
-
- Cause.format(self, real_pos, message)
- end
-
private
def read_slice(needed)
start = @io.pos
|
- removes a bit of method indirection
|
kschiess_parslet
|
train
|
d3f7a3ad33225e82486b8c0c3fd8e8c411173c55
|
diff --git a/src/com/opera/core/systems/runner/launcher/OperaLauncherRunner.java b/src/com/opera/core/systems/runner/launcher/OperaLauncherRunner.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/runner/launcher/OperaLauncherRunner.java
+++ b/src/com/opera/core/systems/runner/launcher/OperaLauncherRunner.java
@@ -54,10 +54,10 @@ public class OperaLauncherRunner implements OperaRunner{
if(settings.getOperaLauncherBinary() == null)
throw new WebDriverException("Launcher not available, please set it in path or use the JAR file");
-
+
if(settings.getOperaBinaryLocation() == null)
throw new WebDriverException("You need to set Opera's path to use opera-launcher");
-
+
if(this.settings.doRunOperaLauncherFromOperaDriver()){
List<String> stringArray = new ArrayList<String>();
@@ -74,17 +74,16 @@ public class OperaLauncherRunner implements OperaRunner{
stringArray.add("-bin");
stringArray.add(this.settings.getOperaBinaryLocation());
- // Enable auto test mode, always starts Opera on opera:debug and prevents
- // interrupting diagloges appearing
- stringArray.add("-autotestmode");
StringTokenizer tokanizer = new StringTokenizer(this.settings.getOperaBinaryArguments(), " ");
while(tokanizer.hasMoreTokens()){
stringArray.add(tokanizer.nextToken());
}
-
+
+ // Enable auto test mode, always starts Opera on opera:debug and prevents
+ // interrupting dialogues appearing
if (!stringArray.contains("-autotestmode"))
stringArray.add("-autotestmode");
-
+
launcherRunner = new OperaLauncherBinary(this.settings.getOperaLauncherBinary(),stringArray.toArray(new String[stringArray.size()]));
}
|
Remove duplicated addition of -autotestmode
|
operasoftware_operaprestodriver
|
train
|
32c6c2c9d75972b83159660c7ace39ab14ee115d
|
diff --git a/lib/magent.rb b/lib/magent.rb
index <HASH>..<HASH> 100644
--- a/lib/magent.rb
+++ b/lib/magent.rb
@@ -18,7 +18,7 @@ require 'magent/processor'
require 'magent/async'
require 'magent/async_channel'
-require 'magent/railtie' if defined?(Rails)
+require 'magent/railtie' if defined?(Rails) && Rails.version >= "3.0.0"
if defined?(EventMachine::WebSocket)
require 'magent/web_socket_server'
diff --git a/lib/magent/railtie.rb b/lib/magent/railtie.rb
index <HASH>..<HASH> 100644
--- a/lib/magent/railtie.rb
+++ b/lib/magent/railtie.rb
@@ -1,7 +1,7 @@
require 'magent'
require 'rails'
-module MyPlugin
+module Magent
class Railtie < Rails::Railtie
rake_tasks do
load "tasks/magent.rake"
|
railtie is only supported on rails >= <I>
|
dcu_magent
|
train
|
b9bc441fdec5e8a5a1c4285d724dd43b327b4cf8
|
diff --git a/tf_models/rbm_models/rbm.py b/tf_models/rbm_models/rbm.py
index <HASH>..<HASH> 100644
--- a/tf_models/rbm_models/rbm.py
+++ b/tf_models/rbm_models/rbm.py
@@ -185,7 +185,7 @@ class RBM(object):
negative = tf.matmul(tf.transpose(vprobs), hprobs1)
- self.w_upd8 = self.W.assign_add(self.learning_rate * (positive - negative))
+ self.w_upd8 = self.W.assign_add(self.learning_rate * (positive - negative)/tf.shape(self.input_data)[0])
self.bh_upd8 = self.bh_.assign_add(self.learning_rate * tf.reduce_mean(hprobs0 - hprobs1, 0))
self.bv_upd8 = self.bv_.assign_add(self.learning_rate * tf.reduce_mean(self.input_data - vprobs, 0))
|
Fix little issue that might lead to parameters blow up easily while learning_rate not small enough.
|
blackecho_Deep-Learning-TensorFlow
|
train
|
330b65f61eea6e95578f3adf7ea69da85624a4cf
|
diff --git a/tests/integration/modules/test_pkg.py b/tests/integration/modules/test_pkg.py
index <HASH>..<HASH> 100644
--- a/tests/integration/modules/test_pkg.py
+++ b/tests/integration/modules/test_pkg.py
@@ -27,20 +27,19 @@ class PkgModuleTest(ModuleCase, SaltReturnAssertsMixin):
@classmethod
def setUpClass(cls):
cls.ctx = {}
+ cls.pkg = 'htop'
+ if salt.utils.platform.is_windows():
+ cls.pkg = 'putty'
+ elif salt.utils.platform.is_darwin():
+ os_release = cls.run_function('grains.get', ['osrelease'])
+ if int(os_release.split('.')[1]) >= 13:
+ cls.pkg = 'wget'
def setUp(self):
if 'refresh' not in self.ctx:
self.run_function('pkg.refresh_db')
self.ctx['refresh'] = True
- self.pkg = 'htop'
- if salt.utils.platform.is_windows():
- self.pkg = 'putty'
- elif salt.utils.platform.is_darwin():
- os_release = self.run_function('grains.get', ['osrelease'])
- if int(os_release.split('.')[1]) >= 13:
- self.pkg = 'wget'
-
@requires_salt_modules('pkg.list_pkgs')
def test_list(self):
'''
|
Set the installed package once in setUpClass not SetUp
|
saltstack_salt
|
train
|
6d981b457994d824dd591819cfb93365ae524025
|
diff --git a/Carew/Event/Listener/Body/Toc.php b/Carew/Event/Listener/Body/Toc.php
index <HASH>..<HASH> 100644
--- a/Carew/Event/Listener/Body/Toc.php
+++ b/Carew/Event/Listener/Body/Toc.php
@@ -32,7 +32,7 @@ class Toc implements EventSubscriberInterface
$urls = array();
// hack to keep twig statements in local $urls variable because DOMDocument encode attributes value
- $body = preg_replace_callback('/(?P<attr>href|src)="(?P<url>.*)"/', function ($matches) use (&$urls) {
+ $body = preg_replace_callback('/(?P<attr>href|src)="(?P<url>[^"]*)"/', function ($matches) use (&$urls) {
$urls[] = $matches['url'];
return sprintf('%s="%s"', $matches['attr'], '%%%%%%%%%%%%%%%%%%%%');
diff --git a/Carew/Tests/Event/Listener/Body/TocTest.php b/Carew/Tests/Event/Listener/Body/TocTest.php
index <HASH>..<HASH> 100644
--- a/Carew/Tests/Event/Listener/Body/TocTest.php
+++ b/Carew/Tests/Event/Listener/Body/TocTest.php
@@ -92,4 +92,21 @@ EOL;
$this->assertSame($body, $document->getBody());
}
+
+
+ public function testOnDocumentDoesNotLinkWithDoubleQuote()
+ {
+ $document = new Document();
+ $document->setPath('index.html');
+ $body = '<a href="https://google.com">"google.com"</a>';
+ $document->setBody($body);
+
+ $event = new CarewEvent($document);
+
+ $toc = new Toc();
+ $toc->onDocument($event);
+
+ $this->assertSame($body, $document->getBody());
+ }
+
}
|
Fixed issue with link / toc / title with double quote
|
carew_carew
|
train
|
92650cd29c4d9f72f20b593279b02124a429a982
|
diff --git a/contrib/externs/webassembly.js b/contrib/externs/webassembly.js
index <HASH>..<HASH> 100644
--- a/contrib/externs/webassembly.js
+++ b/contrib/externs/webassembly.js
@@ -159,14 +159,17 @@ WebAssembly.Table.prototype.grow = function(delta) {};
*/
WebAssembly.Table.prototype.length;
+/** @typedef {function(...)} */
+var TableFunction;
+
/**
* @param {number} index
- * @return {function(...)}
+ * @return {TableFunction}
*/
WebAssembly.Table.prototype.get = function(index) {};
/**
* @param {number} index
- * @param {?function(...)} value
+ * @param {?TableFunction} value
*/
WebAssembly.Table.prototype.set = function(index, value) {};
|
Use a typedef for representing function put on Table object.
The main reason of doing this is for allowing Elemental2 to generate the same type for Table.get and Table.set methods.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
7c63b5215fda598213fc36d581075eb7ebb60c80
|
diff --git a/core/src/test/java/hudson/FilePathTest.java b/core/src/test/java/hudson/FilePathTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/hudson/FilePathTest.java
+++ b/core/src/test/java/hudson/FilePathTest.java
@@ -35,7 +35,6 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
-import org.junit.Assert;
import org.apache.commons.io.output.NullOutputStream;
/**
@@ -82,8 +81,8 @@ public class FilePathTest extends TestCase {
File tmp = File.createTempFile("testCopyTo","");
FilePath f = new FilePath(french,tmp.getPath());
f.copyTo(new NullStream());
- Assert.assertTrue("target does not exist", tmp.exists());
- Assert.assertTrue("could not delete target " + tmp.getPath(), tmp.delete());
+ assertTrue("target does not exist", tmp.exists());
+ assertTrue("could not delete target " + tmp.getPath(), tmp.delete());
}
/**
@@ -92,15 +91,15 @@ public class FilePathTest extends TestCase {
*/
public void testCopyTo2() throws Exception {
for (int j=0; j<2500; j++) {
- File tmp = File.createTempFile("testCopyTo","");
+ File tmp = File.createTempFile("testCopyFrom","");
FilePath f = new FilePath(tmp);
File tmp2 = File.createTempFile("testCopyTo","");
FilePath f2 = new FilePath(british,tmp.getPath());
f.copyTo(f2);
- Assert.assertTrue("could not delete target " + tmp.getPath(), tmp.delete());
- Assert.assertTrue("could not delete target " + tmp2.getPath(), tmp2.delete());
+ assertTrue("could not delete target " + tmp.getPath(), tmp.delete());
+ assertTrue("could not delete target " + tmp2.getPath(), tmp2.delete());
}
}
|
redundant reference to the Assert class.
renamed a file so that we can see which one is refusing to be deleted.
git-svn-id: <URL>
|
jenkinsci_jenkins
|
train
|
7c4bbe5534fcf1f0673c37b419d0c807f6f4a3ab
|
diff --git a/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/MultipartResource.java b/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/MultipartResource.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/MultipartResource.java
+++ b/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/MultipartResource.java
@@ -169,8 +169,8 @@ public class MultipartResource extends Application {
@FormParam("file2") String part2,
@FormParam("notAFile") String part3,
@FormParam("noSpecifiedContentType") String part4) throws IOException {
- assertEquals(Util.toString(Util.xmlFile()).trim(), part1.trim());
- assertEquals(Util.toString(Util.asciidocFile()).trim(), part2.trim());
+ assertEquals(Util.removeLineFeeds(Util.toString(Util.xmlFile()).trim()), Util.removeLineFeeds(part1.trim()));
+ assertEquals(Util.removeLineFeeds(Util.toString(Util.asciidocFile()).trim()), Util.removeLineFeeds(part2.trim()));
assertEquals("This is not a file...", part3.trim());
assertEquals("No content type specified", part4.trim());
return "SUCCESS";
diff --git a/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/Util.java b/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/Util.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/Util.java
+++ b/dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/multipart/src/com/ibm/ws/jaxrs/fat/multipart/Util.java
@@ -123,18 +123,6 @@ public class Util {
.collect(Collectors.joining("\n"));
System.out.println("Util.toString " + str);
return str;
- /*
- StringBuilder sb = new StringBuilder();
- byte[] buf = new byte[1024];
- int bytesRead = 0;
- while (bytesRead > -1) {
- bytesRead = is.read(buf);
- sb.append(new String(buf, 0, bytesRead));
- }
- String str = sb.toString();
- System.out.println("Util.toString " + str);
- return str;
- */
}
static String getPartName(IAttachment part) {
@@ -185,4 +173,9 @@ public class Util {
return closed;
}
}
+
+ static String removeLineFeeds(String original) {
+ String updated = original.replaceAll("\n", "");
+ return updated.replaceAll("\r", "");
+ }
}
|
Remove line feed chars ('\n' and '\r') when comparing multi-line strings
|
OpenLiberty_open-liberty
|
train
|
0ede0d0f3fcbb2b238f59bef7258819233380528
|
diff --git a/src/js/table/Table.js b/src/js/table/Table.js
index <HASH>..<HASH> 100644
--- a/src/js/table/Table.js
+++ b/src/js/table/Table.js
@@ -88,7 +88,9 @@ module.exports = createReactClass({
*/
componentWillReceiveProps() {
var table = TableStore.getInstance(this.props.componentId);
- table.onDataReceived(table.getData());
+ if(table.getDataCount()) {
+ table.onDataReceived(table.getData());
+ }
},
/**
diff --git a/src/js/table/tests/Table.test.js b/src/js/table/tests/Table.test.js
index <HASH>..<HASH> 100644
--- a/src/js/table/tests/Table.test.js
+++ b/src/js/table/tests/Table.test.js
@@ -202,11 +202,21 @@ describe('Table', function() {
describe('componentWillReceiveProps', function() {
it('should call table onDataReceived', function() {
var tableInstance = TableStore.getInstance(id);
+ spyOn(tableInstance, 'getDataCount').and.returnValue({data: 'data'});
spyOn(tableInstance, 'onDataReceived').and.callFake(function() {return;});
spyOn(tableInstance, 'getData').and.callFake(function() {return;});
table.componentWillReceiveProps();
expect(tableInstance.onDataReceived.calls.count()).toEqual(1);
});
+
+ it('should not call table onDataReceived if there is no data', function() {
+ var tableInstance = TableStore.getInstance(id);
+ spyOn(tableInstance, 'getDataCount').and.returnValue(null);
+ spyOn(tableInstance, 'onDataReceived');
+ spyOn(tableInstance, 'getData');
+ table.componentWillReceiveProps();
+ expect(tableInstance.onDataReceived.calls.count()).toEqual(0);
+ });
});
describe('componentWillUnmount function', function() {
|
Update componentWillReceiveProps
|
dataminr_react-components
|
train
|
11bcb8007b8fef21e01addea57977d16aca5078e
|
diff --git a/go/cmd/vttablet/vttablet.go b/go/cmd/vttablet/vttablet.go
index <HASH>..<HASH> 100644
--- a/go/cmd/vttablet/vttablet.go
+++ b/go/cmd/vttablet/vttablet.go
@@ -167,13 +167,19 @@ func initAgent(dbcfgs dbconfigs.DBConfigs, mycnf *mysqlctl.Mycnf) {
bindAddr := fmt.Sprintf(":%v", *port)
- // Action agent listens to changes in zookeeper and makes modifcations to this
- // tablet.
+ // Action agent listens to changes in zookeeper and makes
+ // modifcations to this tablet.
agent := tabletmanager.NewActionAgent(zconn, *tabletPath, *mycnfFile, *dbconfigs.DbConfigsFile, *dbconfigs.DbCredentialsFile)
- agent.AddChangeCallback(func(tablet tabletmanager.Tablet) {
- if tablet.IsServingType() {
+ agent.AddChangeCallback(func(oldTablet, newTablet tabletmanager.Tablet) {
+ if newTablet.IsServingType() {
if dbcfgs.App.Dbname == "" {
- dbcfgs.App.Dbname = tablet.DbName()
+ dbcfgs.App.Dbname = newTablet.DbName()
+ }
+ // Transitioning from replica to master, first disconnect
+ // existing connections. "false" indicateds that clients must
+ // re-resolve their endpoint before reconnecting.
+ if newTablet.Type == tabletmanager.TYPE_MASTER && oldTablet.Type != tabletmanager.TYPE_MASTER {
+ ts.DisallowQueries(false)
}
ts.AllowQueries(dbcfgs.App)
} else {
@@ -187,8 +193,8 @@ func initAgent(dbcfgs dbconfigs.DBConfigs, mycnf *mysqlctl.Mycnf) {
mysqld := mysqlctl.NewMysqld(mycnf, dbcfgs.Dba, dbcfgs.Repl)
- // The TabletManager rpc service allow other processes to query for management
- // related data. It might be co-registered with the query server.
+ // The TabletManager service exports read-only management related
+ // data.
tm := tabletmanager.NewTabletManager(bindAddr, nil, mysqld)
rpc.Register(tm)
}
diff --git a/go/vt/tabletmanager/agent.go b/go/vt/tabletmanager/agent.go
index <HASH>..<HASH> 100644
--- a/go/vt/tabletmanager/agent.go
+++ b/go/vt/tabletmanager/agent.go
@@ -37,7 +37,7 @@ import (
// Each TabletChangeCallback must be idempotent and "threadsafe". The
// agent will execute these in a new goroutine each time a change is
// triggered.
-type TabletChangeCallback func(tablet Tablet)
+type TabletChangeCallback func(oldTablet, newTablet Tablet)
type ActionAgent struct {
zconn zk.Conn
@@ -148,15 +148,20 @@ func (agent *ActionAgent) dispatchAction(actionPath string) error {
relog.Info("agent action completed %v %s", actionPath, stdOut)
+ // Save the old tablet so callbacks can have a better idea of the precise
+ // nature of the transition.
+ oldTablet := agent.Tablet().Tablet
+
// Actions should have side effects on the tablet, so reload the data.
if err := agent.readTablet(); err != nil {
- relog.Warning("failed rereading tablet after action: %v %v", actionPath, err)
+ relog.Warning("failed rereading tablet after action - services may be inconsistent: %v %v", actionPath, err)
} else {
agent.mutex.Lock()
+ // Access directly since we have the lock.
+ newTablet := agent._tablet.Tablet
for _, f := range agent.changeCallbacks {
relog.Info("running tablet callback: %v %v", actionPath, f)
- // Access directly since we have the lock.
- go f(*agent._tablet.Tablet)
+ go f(*oldTablet, *newTablet)
}
agent.mutex.Unlock()
}
|
force clients to properly reresolve and reconnect when a replica transitions to a master
|
vitessio_vitess
|
train
|
40e16890026ac71203a3f77a42e8112aae65b7e1
|
diff --git a/src/Folour/Flavy/Extensions/Base.php b/src/Folour/Flavy/Extensions/Base.php
index <HASH>..<HASH> 100644
--- a/src/Folour/Flavy/Extensions/Base.php
+++ b/src/Folour/Flavy/Extensions/Base.php
@@ -60,7 +60,7 @@ class Base extends Commands
public function formats()
{
if($this->_info['formats'] === null) {
- $data = $this->runCmd('get_formats', [$this->config['ffmpeg']]);
+ $data = $this->runCmd('get_formats', [$this->config['ffmpeg_path']]);
if(is_array($data)) {
$this->_info['formats'] = array_combine($data['format'], $data['mux']);
}
@@ -82,7 +82,7 @@ class Base extends Commands
public function encoders()
{
if($this->_info['encoders']['audio'] === []) {
- $data = $this->runCmd('get_encoders', [$this->config['ffmpeg']]);
+ $data = $this->runCmd('get_encoders', [$this->config['ffmpeg_path']]);
if(is_array($data)) {
foreach($data['type'] as $key => $type) {
$this->_info['encoders'][($type == 'A' ? 'audio' : 'video')][] = $data['format'][$key];
@@ -106,7 +106,7 @@ class Base extends Commands
public function decoders()
{
if($this->_info['decoders']['audio'] === []) {
- $data = $this->runCmd('get_decoders', [$this->config['ffmpeg']]);
+ $data = $this->runCmd('get_decoders', [$this->config['ffmpeg_path']]);
if(is_array($data)) {
foreach($data['type'] as $key => $type) {
$this->_info['decoders'][($type == 'A' ? 'audio' : 'video')][] = $data['format'][$key];
|
fix config key for ffmpeg binary path on Base class
|
folour_flavy
|
train
|
b85d3266834c9668244699785952d03b206700b1
|
diff --git a/ndb/tasklets.py b/ndb/tasklets.py
index <HASH>..<HASH> 100644
--- a/ndb/tasklets.py
+++ b/ndb/tasklets.py
@@ -566,7 +566,7 @@ class MultiFuture(Future):
mfut.complete()
fut = mfut
elif not isinstance(fut, Future):
- raise TypeError('Expected Future received %r' % fut)
+ raise TypeError('Expected Future, received %s: %r' % (type(fut), fut))
if self._full:
raise RuntimeError('MultiFuture cannot add a dependent once complete.')
self._results.append(fut)
|
Improve error message when non-Future received.
|
GoogleCloudPlatform_datastore-ndb-python
|
train
|
3605818d8292bc00dee1be1f97833a1639a3c053
|
diff --git a/src/sos/tasks.py b/src/sos/tasks.py
index <HASH>..<HASH> 100644
--- a/src/sos/tasks.py
+++ b/src/sos/tasks.py
@@ -720,8 +720,8 @@ def check_task(task, hint={}) -> Dict[str, Union[str, Dict[str, float]]]:
env.logger.warning(f'Task {task} considered as aborted due to inactivity for more than {int(elapsed)} seconds.')
tf.add_outputs()
- remove_task_files(
- task, ['.sh', '.job_id', '.out', '.err', '.pulse'])
+ #remove_task_files(
+ # task, ['.sh', '.job_id', '.out', '.err', '.pulse'])
return dict(status='aborted', files={task_file: os.stat(task_file).st_mtime,
pulse_file: 0})
except:
|
Keep files for aborted jobs for testing
|
vatlab_SoS
|
train
|
f7ab114d36b0c06132b482c0b0bd6a494ff025dc
|
diff --git a/src/Symfony/Component/HttpFoundation/FileBag.php b/src/Symfony/Component/HttpFoundation/FileBag.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/HttpFoundation/FileBag.php
+++ b/src/Symfony/Component/HttpFoundation/FileBag.php
@@ -86,13 +86,14 @@ class FileBag extends ParameterBag
}
if ($keys != $this->fileKeys) {
$file = array_map(array($this, 'convertFileInformation'), $file);
- } else
+ } else {
if ($file['error'] === UPLOAD_ERR_NO_FILE) {
$file = null;
} else {
$file = new UploadedFile($file['tmp_name'], $file['name'],
$file['type'], $file['size'], $file['error']);
}
+ }
}
return $file;
}
|
[HttpFoundation] Fixed missing curly brackets
|
symfony_symfony
|
train
|
c9cd30ec1c4f53ead4bfcf14852de07fbfff4fc2
|
diff --git a/Todos/todo.py b/Todos/todo.py
index <HASH>..<HASH> 100644
--- a/Todos/todo.py
+++ b/Todos/todo.py
@@ -173,6 +173,8 @@ def check_ids(ctx, param, value):
@click.option('--what', is_flag=True, default=False,
help='show current use todo file\'s name')
@click.option('--use', help='use `name` file to store your todos')
+@click.option('--done', is_flag=True, default=False,
+ help='show all done todos')
@click.option('-n', '--new', help='new todo')
@click.option('-c', '--complete_ids', type=str, callback=check_ids,
help='complete todo by id(s)'
@@ -183,7 +185,7 @@ def check_ids(ctx, param, value):
help='show all todos')
@click.option('--clear', is_flag=True, default=False,
help='clear all todos, need confirm!!')
-def todos(what, use, new, complete_ids, remove, all, clear):
+def todos(what, use, done, new, complete_ids, remove, all, clear):
setup_logging()
if use:
set_todo_file(use)
@@ -210,6 +212,8 @@ def todos(what, use, new, complete_ids, remove, all, clear):
else:
if all:
t.show_all_todos()
+ elif done:
+ t.show_done_todos()
else:
t.show_waiting_todos()
except Exception as e:
|
support show all done todos
|
MrKiven_Todo.py
|
train
|
a445d73510f4a815b7b559adf604041e91952fbf
|
diff --git a/pynexus/pynexus.py b/pynexus/pynexus.py
index <HASH>..<HASH> 100644
--- a/pynexus/pynexus.py
+++ b/pynexus/pynexus.py
@@ -19,6 +19,7 @@
#
##############################################################################
+import atexit
from jsocket import JSocketDecoder
import json
from multiprocessing import Queue
@@ -177,9 +178,12 @@ class NexusConn:
self.startWorker(self.recvWorker)
self.startWorker(self.mainWorker)
+ atexit.register(self.cancel)
+
def startWorker(self, target):
pipe = Queue()
worker = threading.Thread(target=target, args=(pipe,))
+ worker.daemon = True
worker.start()
self.workers.append((worker, pipe))
@@ -354,6 +358,8 @@ class Client:
self.nexusConn = NexusConn(self.socket)
self.nexusConn.login(nexusURL.username, nexusURL.password)
+ atexit.register(self.close)
+
def taskPush(self, method, params, timeout=0, priority=0, detach=False):
return self.nexusConn.taskPush(method, params, timeout=timeout, priority=priority, detach=detach)
@@ -365,8 +371,9 @@ class Client:
def close(self):
self.cancel()
- self.socket.close()
- self.socket = None
+ if self.socket:
+ self.socket.close()
+ self.socket = None
class Task:
|
Close opened connections automatically at exit using atexit module and daemon threads
|
jaracil_nxpy
|
train
|
b45c1f4f9decf2e2a12ffeccf3ddfb182d1925bd
|
diff --git a/src/main/java/org/sonar/plugins/pmd/PmdExecutor.java b/src/main/java/org/sonar/plugins/pmd/PmdExecutor.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/sonar/plugins/pmd/PmdExecutor.java
+++ b/src/main/java/org/sonar/plugins/pmd/PmdExecutor.java
@@ -28,7 +28,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-import net.sourceforge.pmd.PMD;
+import net.sourceforge.pmd.PMDVersion;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleSet;
@@ -71,7 +71,7 @@ public class PmdExecutor {
}
public Report execute() {
- final Profiler profiler = Profiler.create(LOGGER).startInfo("Execute PMD " + PMD.VERSION);
+ final Profiler profiler = Profiler.create(LOGGER).startInfo("Execute PMD " + PMDVersion.VERSION);
final ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
try (URLClassLoader classLoader = createClassloader()) {
|
Replaced the deprecated usage of PMD#VERSION.
|
jensgerdes_sonar-pmd
|
train
|
a63bb8f315501ebd75c770c26c776e275b8ef1f9
|
diff --git a/cdpybio/gencode.py b/cdpybio/gencode.py
index <HASH>..<HASH> 100644
--- a/cdpybio/gencode.py
+++ b/cdpybio/gencode.py
@@ -60,6 +60,79 @@ def make_gffutils_db(gtf, db):
infer_gene_extent=False)
return out_db
+def make_promoter_bed(gtf, up=2000, down=200, feature='transcript', out=None):
+ """
+ Make a bed file with promoters for transcripts or genes from the Gencode GTF
+ file.
+
+ Parameters
+ ----------
+ gtf : str
+ Filename of the Gencode gtf file.
+
+ up : int
+ Number of bases to add upstream of the transcription start site.
+
+ down : int
+ Number of bases to add downstream of the transcription start site.
+
+ feature : str
+ Either transcript or gene. If transcript, promoters, for each transcript
+ will be included. If gene, a promoter for each gene entry in the GTF
+ will be included.
+
+ out : str
+ If provided, the bed file will be written to a file with this name.
+
+ Returns
+ -------
+ bed : pybedtools.BedTool
+ A sorted pybedtools BedTool object.
+
+ """
+ import HTSeq
+ import itertools as it
+
+ plus_feats = []
+ minus_feats = []
+ if feature == 'transcript':
+ feat_id = 'transcript_id'
+ elif feature == 'gene':
+ feat_id = 'gene_id'
+
+ gtf = it.islice(HTSeq.GFF_Reader(gtf), None)
+ line = gtf.next()
+ while line != '':
+ if line.type == feature:
+ if line.iv.strand == '+':
+ plus_feats.append(
+ ('\t'.join([line.iv.chrom, str(line.iv.start - 1),
+ str(line.iv.end),
+ '{}_promoter'.format(line.attr[feat_id]),
+ line.iv.strand])))
+ elif line.iv.strand == '-':
+ minus_feats.append(
+ ('\t'.join([line.iv.chrom, str(line.iv.start - 1),
+ str(line.iv.end),
+ '{}_promoter'.format(line.attr[feat_id]),
+ line.iv.strand])))
+ try:
+ line = gtf.next()
+ except StopIteration:
+ line = ''
+
+ plus = pbt.BedTool('\n'.join(plus_feats) + '\n', from_string=True)
+ minus = pbt.BedTool('\n'.join(minus_feats) + '\n', from_string=True)
+ plus = plus.slop(l=up, r=down, g=pbt.chromsizes('hg19'))
+ minus = minus.slop(l=down, r=up, g=pbt.chromsizes('hg19'))
+
+ bt = plus.cat(minus, postmerge=False)
+ # We'll sort so bedtools operations can be done faster.
+ bt = bt.sort()
+ if out:
+ bt.saveas(out)
+ return bt
+
def make_feature_bed(gtf, feature, out=None):
"""
Make a bed file with the start and stop coordinates for all of a particular
@@ -112,7 +185,6 @@ def make_feature_bed(gtf, feature, out=None):
bt.saveas(out)
return bt
-
def make_gene_bed(fn, out=None):
"""
Make a bed file with the start and stop coordinates for each gene. Since
|
Added method to identify promoters
|
cdeboever3_cdpybio
|
train
|
e15a290d86dc1f06fe3142ca957270dd264be993
|
diff --git a/lib/poolparty/helpers/provisioners/master.rb b/lib/poolparty/helpers/provisioners/master.rb
index <HASH>..<HASH> 100644
--- a/lib/poolparty/helpers/provisioners/master.rb
+++ b/lib/poolparty/helpers/provisioners/master.rb
@@ -26,15 +26,14 @@ module PoolParty
install_poolparty,
setup_poolparty,
start_puppetmaster,
- clean_master_certs,
+ create_local_node,
restart_puppetd,
- clean_master_certs
+ start_puppetmaster
] << configure_tasks
end
def configure_tasks
[
- create_local_node,
move_templates,
create_poolparty_manifest,
restart_puppetd
|
Rephrasing the provisioning process to clear the certs to begin with
|
auser_poolparty
|
train
|
28e5b5071e725baea8237c7f9b7168a5ba68bd0f
|
diff --git a/GDAX/Ticker.py b/GDAX/Ticker.py
index <HASH>..<HASH> 100644
--- a/GDAX/Ticker.py
+++ b/GDAX/Ticker.py
@@ -27,7 +27,8 @@ class Ticker(WebsocketClient):
if self._log_to:
pickle.dump(message, self._log_to)
- self._current_ticker = message
+ if 'type' in message and message['type'] == 'match':
+ self._current_ticker = message
def get_current_ticker(self):
return self._current_ticker
|
Only take match messages as per API doc, no volume info for now
|
danpaquin_coinbasepro-python
|
train
|
9368da77e2564168e877f86ddca48c474b1b55cb
|
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -32,11 +32,13 @@
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
- 'sphinx.ext.doctest',
- 'sphinx.ext.intersphinx',
- 'sphinx.ext.todo',
- 'sphinx.ext.viewcode',
- 'sphinx.ext.githubpages']
+ 'sphinx.ext.doctest',
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.todo',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.githubpages',
+ 'sphinx.ext.napoleon',
+ ]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@@ -88,7 +90,9 @@ todo_include_todos = True
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
-html_theme = 'alabaster'
+import sphinx_rtd_theme
+html_theme = 'sphinx_rtd_theme'
+html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
@@ -181,6 +185,18 @@ epub_copyright = copyright
epub_exclude_files = ['search.html']
+# -- Options for Napoleon ----------------------------------------------
+napoleon_google_docstring = True
+napoleon_numpy_docstring = True
+napoleon_include_init_with_doc = False
+napoleon_include_private_with_doc = False
+napoleon_include_special_with_doc = True
+napoleon_use_admonition_for_examples = False
+napoleon_use_admonition_for_notes = False
+napoleon_use_admonition_for_references = False
+napoleon_use_ivar = False
+napoleon_use_param = True
+napoleon_use_rtype = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
|
Updates sphinx conf
Adds napoleon and rtd theme.
|
jfear_sramongo
|
train
|
fd2899e991995981c795928a3821dc9bf87b73b9
|
diff --git a/state/state_test.go b/state/state_test.go
index <HASH>..<HASH> 100644
--- a/state/state_test.go
+++ b/state/state_test.go
@@ -4680,6 +4680,7 @@ func (s *StateSuite) TestWatchAPIHostPortsForAgents(c *gc.C) {
mgmtHP,
}})
c.Assert(err, jc.ErrorIsNil)
+ wc.AssertOneChange()
// This should cause no change to APIHostPortsForAgents.
// We expect only one watcher notification.
@@ -4695,8 +4696,7 @@ func (s *StateSuite) TestWatchAPIHostPortsForAgents(c *gc.C) {
},
}})
c.Assert(err, jc.ErrorIsNil)
-
- wc.AssertOneChange()
+ wc.AssertNoChange()
// Stop, check closed.
statetesting.AssertStop(c, w)
|
Fixes test assertions for watching APIHostPortsForAgents.
|
juju_juju
|
train
|
6a1633d269c56dac723714722189b016ec8e5fc0
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -81,22 +81,6 @@ Temper1Connector.prototype.connect = function() {
// Open the device
this.device = new HID.HID(element.path);
- // this.device.on("data", function(data) {
- // console.log(data);
-
- // var hiByte = data[2];
- // var loByte = data[3];
-
- // var sign = hiByte & (1 << 7);
- // var temp = ((hiByte & 0x7F) << 8) | loByte;
-
- // if (sign) {
- // temp = -temp;
- // }
-
- // console.log(temp * 125.0 / 32000.0);
- // });
-
// Set the result
result = this.messages.connected;
}
@@ -113,12 +97,16 @@ Temper1Connector.prototype.connect = function() {
/**
* Send a command to the USB device
*/
-Temper1Connector.prototype.command = function(command) {
- var result = this.messages.success;
+Temper1Connector.prototype.command = function(command, callback) {
+ var result = this.messages.success,
+ callback = callback || null,
+ temperature = null
+ ;
// Do nothing if no device is connected & the command is not "connect"
if (this.device == null && command !== 'connect') {
- result = this.messages.notConnected;
+ // Try to connect
+ result = this.connect();
// Execute a command if a device is connected
} else {
@@ -133,9 +121,11 @@ Temper1Connector.prototype.command = function(command) {
// Stop everything the device is doing right now
case 'read' :
+
this.device.write(this.options.read);
this.device.read(function(error, data) {
+ // Transform the temperature
var hiByte = data[2];
var loByte = data[3];
@@ -145,10 +135,12 @@ Temper1Connector.prototype.command = function(command) {
if (sign) {
temp = -temp;
}
-
- // console.log(temp * 125.0 / 32000.0);
- result = temp * 125.0 / 32000.0
+ // Calculate it
+ temperature = temp * 125.0 / 32000.0;
+
+ // Send the temperature via callback
+ callback(temperature);
});
break;
@@ -173,6 +165,10 @@ Temper1Connector.prototype.command = function(command) {
}
+ if (temperature != null) {
+ result = temperature;
+ }
+
return result;
};
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -17,5 +17,7 @@
},
"engines": {
"node": ">=0.10"
+ },
+ "devDependencies": {
}
}
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -1,22 +1,36 @@
var myTemper1Connector = require("..");
+console.log('connecting');
+
+
+
+
+// Connect to device
var result = myTemper1Connector.connect();
+console.log('connected');
+
+
-setInterval(function() {
- myTemper1Connector.command("read");
-}, 2500);
-// console.log("Devices found:"+devices[0]);
-// thermometers.readTemperature(devices[0], function(err, value) {
-// console.log("Result:"+value);
-// });
+// Initial value
+var result = myTemper1Connector.command("read", function(value) {
+ console.log(value);
+});
+
+console.log(result);
+
+
+
+
+
+// New value every x ms
+setInterval(function() {
+ // Read the current value
+ result = myTemper1Connector.command("read", function(value) {
+ console.log(value);
+ });
-// var assert = require("assert");
+ console.log(result);
-// describe('result', function(){
-// it('should return -1 when the value is not present', function(){
-// assert.equal(-1, [1,2,3].indexOf(5));
-// assert.equal(-1, [1,2,3].indexOf(0));
-// })
-// })
\ No newline at end of file
+}, 500);
\ No newline at end of file
|
Added callback, test and improved the connect().
|
TimPietrusky_temper1-connector
|
train
|
2d70dc9c43831232a26dcdd01565df6c596ca977
|
diff --git a/src/dimensions.js b/src/dimensions.js
index <HASH>..<HASH> 100644
--- a/src/dimensions.js
+++ b/src/dimensions.js
@@ -8,14 +8,14 @@ jQuery.each([ "Height", "Width" ], function( i, name ) {
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function() {
return this[0] ?
- parseFloat( jQuery.css( this[0], type, "padding" ), 10 ) :
+ parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
return this[0] ?
- parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ), 10 ) :
+ parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
@@ -50,7 +50,7 @@ jQuery.each([ "Height", "Width" ], function( i, name ) {
// Get or set width or height on the element
size === undefined ?
// Get width or height on the element
- parseFloat( jQuery.css( elem, type ), 10 ) :
+ parseFloat( jQuery.css( elem, type ) ) :
// Set the width or height on the element (default to pixels if value is unitless)
this.css( type, typeof size === "string" ? size : size + "px" );
diff --git a/src/effects.js b/src/effects.js
index <HASH>..<HASH> 100644
--- a/src/effects.js
+++ b/src/effects.js
@@ -316,7 +316,7 @@ jQuery.fx.prototype = {
return this.elem[ this.prop ];
}
- var r = parseFloat( jQuery.css( this.elem, this.prop ), 10 );
+ var r = parseFloat( jQuery.css( this.elem, this.prop ) );
return r && r > -10000 ? r : 0;
},
|
Derp, had parseInt on the brain. Thanks karbassi in <I>eb9d<I>db<I>c6ced<I>fcd<I>bff9ec7f1.
|
jquery_jquery
|
train
|
98ea33c89a1cd19468fa33987f97ff080ba6c080
|
diff --git a/src/knockout-froala.js b/src/knockout-froala.js
index <HASH>..<HASH> 100644
--- a/src/knockout-froala.js
+++ b/src/knockout-froala.js
@@ -72,7 +72,7 @@
var editorValue = editorInstance.html.get();
// avoid any un-necessary updates
- if( editorValue !== modelValue && typeof modelValue === 'string' ) {
+ if( editorValue !== modelValue && (typeof modelValue === 'string' || modelValue === null)) {
editorInstance.html.set( modelValue );
}
}
|
Update editor when model value is null.
|
froala_knockout-froala
|
train
|
19021e194bd89b68c0dec8cb9a1a75fd49de6fe6
|
diff --git a/cmd2.py b/cmd2.py
index <HASH>..<HASH> 100755
--- a/cmd2.py
+++ b/cmd2.py
@@ -566,17 +566,17 @@ def _push_readline_history(history, clear_history=True):
readline.add_history(line)
-def _complete_from_cmd(cmd, text, line, begidx, endidx):
+def _complete_from_cmd(cmd_obj, text, line, begidx, endidx):
"""Complete as though the user was typing inside cmd's cmdloop()"""
from itertools import takewhile
command_subcommand_params = line.split(None, 3)
if len(command_subcommand_params) < (3 if text else 2):
- return cmd.completenames(text)
+ return cmd_obj.completenames(text)
command, subcommand = command_subcommand_params[:2]
n = len(command) + sum(1 for _ in takewhile(str.isspace, line))
- cfun = getattr(cmd, 'complete_' + subcommand, cmd.complete)
+ cfun = getattr(cmd_obj, 'complete_' + subcommand, cmd_obj.complete)
return cfun(text, line[n:], begidx - n, endidx - n)
@@ -609,7 +609,7 @@ class AddSubmenu(object):
command,
aliases=(),
reformat_prompt="{super_prompt}>> {sub_prompt}",
- shared_attributes={},
+ shared_attributes=None,
require_predefined_shares=True,
create_subclass=False
):
@@ -652,11 +652,11 @@ class AddSubmenu(object):
raise AttributeError("The shared attribute '{attr}' is not defined in {cmd}. Either define {attr} "
"in {cmd} or set require_predefined_shares=False."
.format(cmd=submenu.__class__.__name__, attr=attr))
- self.shared_attributes = shared_attributes
+ self.shared_attributes = {} if shared_attributes is None else shared_attributes
self.create_subclass = create_subclass
- def __call__(self, Cmd):
+ def __call__(self, cmd_obj):
"""Creates a subclass of Cmd wherein the given submenu can be accessed via the given command"""
def enter_submenu(parent_cmd, line):
"""
@@ -721,8 +721,8 @@ class AddSubmenu(object):
else:
delattr(submenu, attr)
- original_do_help = Cmd.do_help
- original_complete_help = Cmd.complete_help
+ original_do_help = cmd_obj.do_help
+ original_complete_help = cmd_obj.complete_help
def help_submenu(_self, line):
"""
@@ -738,8 +738,8 @@ class AddSubmenu(object):
"""autocomplete to match help_submenu()'s behavior"""
tokens = line.split(None, 1)
if len(tokens) == 2 and (
- tokens[1].startswith(self.command) or
- any(tokens[1].startswith(alias) for alias in self.aliases)
+ not (not tokens[1].startswith(self.command) and not any(
+ tokens[1].startswith(alias) for alias in self.aliases))
):
return self.submenu.complete_help(
text,
@@ -751,11 +751,11 @@ class AddSubmenu(object):
return original_complete_help(_self, text, line, begidx, endidx)
if self.create_subclass:
- class _Cmd(Cmd):
+ class _Cmd(cmd_obj):
do_help = help_submenu
complete_help = _complete_submenu_help
else:
- _Cmd = Cmd
+ _Cmd = cmd_obj
_Cmd.do_help = help_submenu
_Cmd.complete_help = _complete_submenu_help
@@ -764,9 +764,9 @@ class AddSubmenu(object):
setattr(_Cmd, 'complete_' + self.command, complete_submenu)
# Create additional bindings for aliases
- for alias in self.aliases:
- setattr(_Cmd, 'do_' + alias, enter_submenu)
- setattr(_Cmd, 'complete_' + alias, complete_submenu)
+ for _alias in self.aliases:
+ setattr(_Cmd, 'do_' + _alias, enter_submenu)
+ setattr(_Cmd, 'complete_' + _alias, complete_submenu)
return _Cmd
|
Changed arg name in _complete_from_cmd() so it doesn't shadow name from outer scope.
Changed default arg for shared_attributes to None instead of a dict (bad because mutable)
Changed arg name in __call__() so it doesn't shadow name from outer scope.
|
python-cmd2_cmd2
|
train
|
5044ad053e8f554594d64f091c3c34973f5f71cd
|
diff --git a/util/types/mydecimal_test.go b/util/types/mydecimal_test.go
index <HASH>..<HASH> 100644
--- a/util/types/mydecimal_test.go
+++ b/util/types/mydecimal_test.go
@@ -259,25 +259,13 @@ func (s *testMyDecimalSuite) TestShift(c *C) {
wordBufLen = maxWordBufLen
}
-func (s *testMyDecimalSuite) TestRound(c *C) {
- type tcase struct {
+func (s *testMyDecimalSuite) TestRoundWithHalfEven(c *C) {
+ tests := []struct {
input string
scale int
output string
err error
- }
- var doTest = func(c *C, tests []tcase) {
- for _, ca := range tests {
- var dec MyDecimal
- dec.FromString([]byte(ca.input))
- var rounded MyDecimal
- err := dec.Round(&rounded, ca.scale, ModeHalfEven)
- c.Check(err, Equals, ca.err)
- result := rounded.ToString()
- c.Check(string(result), Equals, ca.output)
- }
- }
- tests := []tcase{
+ }{
{"123456789.987654321", 1, "123456790.0", nil},
{"15.1", 0, "15", nil},
{"15.5", 0, "16", nil},
@@ -294,7 +282,85 @@ func (s *testMyDecimalSuite) TestRound(c *C) {
{".999", 0, "1", nil},
{"999999999", -9, "1000000000", nil},
}
- doTest(c, tests)
+
+ for _, ca := range tests {
+ var dec MyDecimal
+ dec.FromString([]byte(ca.input))
+ var rounded MyDecimal
+ err := dec.Round(&rounded, ca.scale, ModeHalfEven)
+ c.Check(err, Equals, ca.err)
+ result := rounded.ToString()
+ c.Check(string(result), Equals, ca.output)
+ }
+}
+
+func (s *testMyDecimalSuite) TestRoundWithTruncate(c *C) {
+ tests := []struct {
+ input string
+ scale int
+ output string
+ err error
+ }{
+ {"123456789.987654321", 1, "123456789.9", nil},
+ {"15.1", 0, "15", nil},
+ {"15.5", 0, "15", nil},
+ {"15.9", 0, "15", nil},
+ {"-15.1", 0, "-15", nil},
+ {"-15.5", 0, "-15", nil},
+ {"-15.9", 0, "-15", nil},
+ {"15.1", 1, "15.1", nil},
+ {"-15.1", 1, "-15.1", nil},
+ {"15.17", 1, "15.1", nil},
+ {"15.4", -1, "10", nil},
+ {"-15.4", -1, "-10", nil},
+ {"5.4", -1, "0", nil},
+ {".999", 0, "0", nil},
+ {"999999999", -9, "0", nil},
+ }
+ for _, ca := range tests {
+ var dec MyDecimal
+ dec.FromString([]byte(ca.input))
+ var rounded MyDecimal
+ err := dec.Round(&rounded, ca.scale, ModeTruncate)
+ c.Check(err, Equals, ca.err)
+ result := rounded.ToString()
+ c.Check(string(result), Equals, ca.output)
+ }
+}
+
+func (s *testMyDecimalSuite) TestRoundWithCeil(c *C) {
+ tests := []struct {
+ input string
+ scale int
+ output string
+ err error
+ }{
+ {"123456789.987654321", 1, "123456790.0", nil},
+ {"15.1", 0, "16", nil},
+ {"15.5", 0, "16", nil},
+ {"15.9", 0, "16", nil},
+ //TODO:fix me
+ {"-15.1", 0, "-16", nil},
+ {"-15.5", 0, "-16", nil},
+ {"-15.9", 0, "-16", nil},
+ {"15.1", 1, "15.1", nil},
+ {"-15.1", 1, "-15.1", nil},
+ {"15.17", 1, "15.2", nil},
+ {"15.4", -1, "20", nil},
+ {"-15.4", -1, "-20", nil},
+ {"5.4", -1, "10", nil},
+ {".999", 0, "1", nil},
+ {"999999999", -9, "1000000000", nil},
+ }
+ for _, ca := range tests {
+ var dec MyDecimal
+ dec.FromString([]byte(ca.input))
+ var rounded MyDecimal
+ err := dec.Round(&rounded, ca.scale, modeCeiling)
+ c.Check(err, Equals, ca.err)
+ result := rounded.ToString()
+ c.Check(string(result), Equals, ca.output)
+ }
}
func (s *testMyDecimalSuite) TestFromString(c *C) {
|
types/mydecimal_test: add tests for round with different round_mode (#<I>)
|
pingcap_tidb
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.