hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
d22935e6160302eb711ee0a107b51bc01f03f193
|
diff --git a/src/lang/nl/lfm.php b/src/lang/nl/lfm.php
index <HASH>..<HASH> 100644
--- a/src/lang/nl/lfm.php
+++ b/src/lang/nl/lfm.php
@@ -39,6 +39,7 @@ return [
'message-name' => 'Mapnaam:',
'message-rename' => 'Hernoemen naar:',
'message-extension_not_found' => 'Installeer de GD of Imagick extensie om afbeeldingen te kunnen bewerken.',
+ 'message-drop' => 'Of sleep bestanden naar hier om te uploaden',
'error-rename' => 'Bestandsnaam is al in gebruik!',
'error-file-empty' => 'U dient een bestand te kiezen!',
|
[FIX] Added message-drop NL translation to fix undefined
|
UniSharp_laravel-filemanager
|
train
|
8d3b9c320572b2f531232cd8618a43c9065235fb
|
diff --git a/lib/fog/aws/beanstalk.rb b/lib/fog/aws/beanstalk.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/aws/beanstalk.rb
+++ b/lib/fog/aws/beanstalk.rb
@@ -67,7 +67,6 @@ module Fog
require 'fog/core/parser'
@use_iam_profile = options[:use_iam_profile]
- setup_credentials(options)
@connection_options = options[:connection_options] || {}
options[:region] ||= 'us-east-1'
@@ -79,6 +78,9 @@ module Fog
@connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
@instrumentor = options[:instrumentor]
@instrumentor_name = options[:instrumentor_name] || 'fog.aws.beanstalk'
+
+ @region = options[:region]
+ setup_credentials(options)
end
def reload
@@ -98,7 +100,7 @@ module Fog
@aws_session_token = options[:aws_session_token]
@aws_credentials_expire_at = options[:aws_credentials_expire_at]
- @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key)
+ @signer = Fog::AWS::SignatureV4.new( @aws_access_key_id, @aws_secret_access_key, @region, 'elasticbeanstalk')
end
def request(params)
@@ -107,12 +109,13 @@ module Fog
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
- body = AWS.signed_params(
+ body, headers = AWS.signed_params_v4(
params,
+ { 'Content-Type' => 'application/x-www-form-urlencoded' },
{
- :aws_access_key_id => @aws_access_key_id,
+ :signer => @signer,
:aws_session_token => @aws_session_token,
- :hmac => @hmac,
+ :method => "POST",
:host => @host,
:path => @path,
:port => @port,
@@ -122,18 +125,18 @@ module Fog
if @instrumentor
@instrumentor.instrument("#{@instrumentor_name}.request", params) do
- _request(body, idempotent, parser)
+ _request(body, headers, idempotent, parser)
end
else
- _request(body, idempotent, parser)
+ _request(body, headers, idempotent, parser)
end
end
- def _request(body, idempotent, parser)
+ def _request(body, headers, idempotent, parser)
@connection.request({
:body => body,
:expects => 200,
- :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
+ :headers => headers,
:idempotent => idempotent,
:method => 'POST',
:parser => parser
|
[AWS|Elasticbeanstalk] Use Signature v4
|
fog_fog
|
train
|
13fbb967367406ef111a4079b19019115096d63e
|
diff --git a/cmd/namespace-lock.go b/cmd/namespace-lock.go
index <HASH>..<HASH> 100644
--- a/cmd/namespace-lock.go
+++ b/cmd/namespace-lock.go
@@ -133,31 +133,31 @@ type nsLockMap struct {
// Indicates if namespace is part of a distributed setup.
isDistXL bool
lockMap map[nsParam]*nsLock
- lockMapMutex sync.Mutex
+ lockMapMutex sync.RWMutex
}
// Lock the namespace resource.
func (n *nsLockMap) lock(volume, path string, lockSource, opsID string, readLock bool, timeout time.Duration) (locked bool) {
var nsLk *nsLock
- n.lockMapMutex.Lock()
+ n.lockMapMutex.Lock()
param := nsParam{volume, path}
nsLk, found := n.lockMap[param]
if !found {
- nsLk = &nsLock{
+ n.lockMap[param] = &nsLock{
RWLockerSync: func() RWLockerSync {
if n.isDistXL {
return dsync.NewDRWMutex(pathJoin(volume, path), globalDsync)
}
return &lsync.LRWMutex{}
}(),
- ref: 0,
+ ref: 1,
}
- n.lockMap[param] = nsLk
+ nsLk = n.lockMap[param]
+ } else {
+ // Update ref count here to avoid multiple races.
+ nsLk.ref++
}
- nsLk.ref++ // Update ref count here to avoid multiple races.
-
- // Unlock map before Locking NS which might block.
n.lockMapMutex.Unlock()
// Locking here will block (until timeout).
@@ -168,44 +168,44 @@ func (n *nsLockMap) lock(volume, path string, lockSource, opsID string, readLock
}
if !locked { // We failed to get the lock
- n.lockMapMutex.Lock()
- defer n.lockMapMutex.Unlock()
-
- nsLk.ref-- // Decrement ref count since we failed to get the lock
+ // Decrement ref count since we failed to get the lock
+ n.lockMapMutex.Lock()
+ nsLk.ref--
if nsLk.ref == 0 {
// Remove from the map if there are no more references.
delete(n.lockMap, param)
}
+ n.lockMapMutex.Unlock()
}
return
}
// Unlock the namespace resource.
func (n *nsLockMap) unlock(volume, path, opsID string, readLock bool) {
- // nsLk.Unlock() will not block, hence locking the map for the
- // entire function is fine.
- n.lockMapMutex.Lock()
- defer n.lockMapMutex.Unlock()
-
param := nsParam{volume, path}
- if nsLk, found := n.lockMap[param]; found {
- if readLock {
- nsLk.RUnlock()
- } else {
- nsLk.Unlock()
- }
- if nsLk.ref == 0 {
- logger.LogIf(context.Background(), errors.New("Namespace reference count cannot be 0"))
- }
- if nsLk.ref != 0 {
- nsLk.ref--
- }
+ n.lockMapMutex.RLock()
+ nsLk, found := n.lockMap[param]
+ n.lockMapMutex.RUnlock()
+ if !found {
+ return
+ }
+ if readLock {
+ nsLk.RUnlock()
+ } else {
+ nsLk.Unlock()
+ }
+ n.lockMapMutex.Lock()
+ if nsLk.ref == 0 {
+ logger.LogIf(context.Background(), errors.New("Namespace reference count cannot be 0"))
+ } else {
+ nsLk.ref--
if nsLk.ref == 0 {
// Remove from the map if there are no more references.
delete(n.lockMap, param)
}
}
+ n.lockMapMutex.Unlock()
}
// Lock - locks the given resource for writes, using a previously
|
Hold locks granularly in nslockMap (#<I>)
With benchmarks increases the performance for small files
by almost 4x times the previous releases.
|
minio_minio
|
train
|
89bd644e6151a1db783212672e5460a1494fe7fc
|
diff --git a/linshareapi/cache.py b/linshareapi/cache.py
index <HASH>..<HASH> 100644
--- a/linshareapi/cache.py
+++ b/linshareapi/cache.py
@@ -51,7 +51,7 @@ class Cache(object):
familly -- each kind of resource must have its own kind of familly.
discriminant -- how to store different data in the same familly.
it will be used to compute a different cache key.
- arguments -- add all the arguments (query params) of the
+ arguments -- Flag: add all the arguments (query params) of the
current function as discriminant for cache key
cache_duration -- Time to live for the cache.
"""
@@ -172,7 +172,7 @@ class CacheManager(object):
res = "/".join(res)
if not os.path.isdir(res):
os.makedirs(res)
- self.log.debug("cachedir :" + str(res))
+ self.log.debug("cachedir : %s", str(res))
return res
def _get_cachefile(self, key, group=None):
@@ -187,9 +187,12 @@ class CacheManager(object):
def has_key(self, key, group=None, cache_duration=None):
if self._has_key(key, group):
cachefile = self._get_cachefile(key, group)
+ file_size = os.stat(cachefile).st_size
+ if file_size == 0:
+ return False
file_time = os.stat(cachefile).st_mtime
form = "{da:%Y-%m-%d %H:%M:%S}"
- self.log.debug("cached data : " + str(
+ self.log.debug("cached data : %s", str(
form.format(da=datetime.datetime.fromtimestamp(file_time))))
if not cache_duration:
cache_duration = self.cache_duration
@@ -236,7 +239,9 @@ class CacheManager(object):
self.log.debug("caching data : %s : %s", group, key)
cachefile = self._get_cachefile(key, group)
with open(cachefile, 'wb') as fde:
- json.dump(data, fde)
+ # json.dump(data, fde)
+ data = json.dumps(data)
+ fde.write(data.encode('utf-8'))
class Time(object):
|
Fix cache manager (encoding issue and file size issue)
|
fred49_linshare-api
|
train
|
a06334083c77ad188f79869073404ea132241397
|
diff --git a/lib/bigIpCluster.js b/lib/bigIpCluster.js
index <HASH>..<HASH> 100644
--- a/lib/bigIpCluster.js
+++ b/lib/bigIpCluster.js
@@ -543,7 +543,26 @@ BigIpCluster.prototype.joinCluster = function(deviceGroup, remoteHost, remoteUse
.catch(function(err) {
this.logger.info("Sync not yet complete.");
this.logger.verbose("Sync Error", err);
- deferred.reject();
+
+ if (err && err.recommendedAction) {
+ // In some cases, sync complete tells us to sync a different group
+ if (err.recommendedAction.sync) {
+ this.logger.info("Following recommended action. Syncing group " + err.recommendedAction.sync);
+ remoteBigIp.cluster.sync('to-group', err.recommendedAction.sync, true, util.NO_RETRY)
+ .then(function() {
+ return this.syncComplete(SYNC_COMPLETE_RETRY);
+ })
+ .then(function() {
+ deferred.resolve();
+ })
+ .catch(function() {
+ deferred.reject();
+ });
+ }
+ }
+ else {
+ deferred.reject();
+ }
}.bind(this))
.done();
@@ -732,7 +751,7 @@ BigIpCluster.prototype.sync = function(direction, deviceGroup, forceFullLoadPush
* @param {Integer} [retryOptions.retryIntervalMs] - Milliseconds between retries. Default 10000.
*
* @returns {Promise} A promise which is resolved if sync is complete,
- * or rejected if not or on error.
+ * or rejected on error or recommended action.
*/
BigIpCluster.prototype.syncComplete = function(retryOptions) {
retryOptions = retryOptions || util.DEFAULT_RETRY;
@@ -744,11 +763,39 @@ BigIpCluster.prototype.syncComplete = function(retryOptions) {
return this.core.list('/tm/cm/sync-status', undefined, util.NO_RETRY);
}.bind(this))
.then(function(response) {
- if (response.entries["https://localhost/mgmt/tm/cm/sync-status/0"].nestedStats.entries.color.description === 'green') {
+ var mainStats = response.entries["https://localhost/mgmt/tm/cm/sync-status/0"].nestedStats.entries;
+ var toGroupTag = "to group ";
+ var detailedStats;
+ var detailKeys;
+ var description;
+ var rejectReason;
+ var toGroupIndex;
+ var i;
+
+ if (mainStats.color.description === 'green') {
deferred.resolve();
}
else {
- deferred.reject();
+ // Look for a recommended action
+ detailedStats = mainStats["https://localhost/mgmt/tm/cm/syncStatus/0/details"].nestedStats.entries;
+ detailKeys = Object.keys(detailedStats);
+ for (i = 0; i < detailKeys.length; ++i) {
+ description = detailedStats[detailKeys[i]].nestedStats.entries.details.description;
+ if (description.indexOf("Recommended action") !== -1) {
+ // If found, look for the group to sync.
+ toGroupIndex = description.indexOf(toGroupTag);
+ if (toGroupIndex !== -1) {
+ rejectReason = {
+ recommendedAction: {
+ sync: description.substring(toGroupIndex + toGroupTag.length)
+ }
+ };
+ }
+ break;
+ }
+ }
+
+ deferred.reject(rejectReason);
}
})
.catch(function(err) {
diff --git a/lib/util.js b/lib/util.js
index <HASH>..<HASH> 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -75,7 +75,7 @@ module.exports = {
setTimeout(_tryUntil, interval, maxRetries, interval, funcToTry, deferred);
}
else {
- this.logger.verbose('Giving up after max tries.');
+ this.logger.verbose('Max tries reached.');
deferred.reject(err);
}
}.bind(this))
diff --git a/scripts/runScript.js b/scripts/runScript.js
index <HASH>..<HASH> 100644
--- a/scripts/runScript.js
+++ b/scripts/runScript.js
@@ -61,8 +61,6 @@
.option('-o, --output <file>', 'Log to file as well as console. This is the default if background process is spawned. Default is ' + DEFAULT_LOG_FILE)
.parse(argv);
- options.port = options.port || 443;
-
loggerOptions.console = true;
loggerOptions.logLevel = options.logLevel;
|
Follow recommended sync action reported by sync-status
|
F5Networks_f5-cloud-libs
|
train
|
526c343192e696696a9c87efc65612f92dcf1dee
|
diff --git a/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/util/UserAgent.java b/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/util/UserAgent.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/util/UserAgent.java
+++ b/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/util/UserAgent.java
@@ -17,6 +17,7 @@
package org.cloudfoundry.reactor.util;
import io.netty.handler.codec.http.HttpHeaderNames;
+import reactor.ipc.netty.http.client.HttpClient;
import reactor.ipc.netty.http.client.HttpClientRequest;
import java.util.Optional;
@@ -29,7 +30,7 @@ public final class UserAgent {
/**
* The {@code User-Agent}
*/
- public static final String USER_AGENT = String.format("Cloud Foundry Java Client/%s", version());
+ public static final String USER_AGENT = String.format("CloudFoundryJavaClient/%s ReactorNetty/%s", javaClientVersion(), reactorNettyVersion());
private UserAgent() {
}
@@ -44,9 +45,14 @@ public final class UserAgent {
return request.header(HttpHeaderNames.USER_AGENT, USER_AGENT);
}
- private static String version() {
+ private static String javaClientVersion() {
return Optional.ofNullable(UserAgent.class.getPackage().getImplementationVersion())
.orElse("unknown");
}
+ private static String reactorNettyVersion() {
+ return Optional.ofNullable(HttpClient.class.getPackage().getImplementationVersion())
+ .orElse("unknown");
+ }
+
}
|
Add Reactor Netty to User Agent Header
Previously the UserAgent header only container the version of the client.
Since the version of Reactor Netty is so critical to the operation of the
client, it should also be exposed. This change ensures that it is.
|
cloudfoundry_cf-java-client
|
train
|
794866fb34bc11c87754b6edf700790dc5fa03d5
|
diff --git a/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/BoxDateFormat.java b/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/BoxDateFormat.java
index <HASH>..<HASH> 100644
--- a/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/BoxDateFormat.java
+++ b/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/BoxDateFormat.java
@@ -49,13 +49,28 @@ public final class BoxDateFormat {
private static ConcurrentHashMap<String,TimeZone> mTimeZones = new ConcurrentHashMap<String, TimeZone>(10);
private static final int MILLIS_PER_HOUR = 1000 * 60 * 60;
- private static TimeZone getTimeZone(final String offset){
+ private static final int MILLIS_PER_MINUTE = 1000 * 60;
+ private static TimeZone getTimeZone(final String offset) {
TimeZone cached = mTimeZones.get(offset);
- if (cached != null){
+ if (cached != null) {
return cached;
}
- Integer offsetHours = Integer.parseInt(offset.substring(0, 3));
- TimeZone zone = new SimpleTimeZone(offsetHours * MILLIS_PER_HOUR, offset);
+ int parseOffset = 0;
+ // Fix for devices that run on Java6, as the parseInt from Integer class cannot handle
+ // the plus sign ("+") on the beginning.
+ if(offset.charAt(0) == '+') {
+ parseOffset++;
+ }
+ Integer offsetHours = Integer.parseInt(offset.substring(parseOffset, 3));
+ // Parse any minute offset as well
+ Integer offsetMinutes = Integer.parseInt((offset.substring(4)));
+ int offsetMiliSec = offsetHours * MILLIS_PER_HOUR;
+ if (offsetHours < 0) {
+ offsetMiliSec -= (offsetMinutes * MILLIS_PER_MINUTE);
+ } else {
+ offsetMiliSec += (offsetMinutes * MILLIS_PER_MINUTE);
+ }
+ TimeZone zone = new SimpleTimeZone(offsetMiliSec, offset);
mTimeZones.put(offset, zone);
return zone;
}
|
AND-<I> - Fix integer parsing when starts with + sign
On older devices, the java6 library could not handle the + sign
as the initial character when parsing a string into an int.
This change should fix that for all versions.
|
box_box-android-sdk
|
train
|
fe339498950254822261969511abfb47033e2d15
|
diff --git a/tools/checkdistro.php b/tools/checkdistro.php
index <HASH>..<HASH> 100644
--- a/tools/checkdistro.php
+++ b/tools/checkdistro.php
@@ -123,6 +123,8 @@ if ($handle = opendir(APP_ROOT.'/sample/distrotest')) {
echo "<td>Distro Icon</td>";
echo "<td>Distro Name (no lsb_release)</td>";
echo "<td>Distro Icon (no lsb_release)</td>";
+ echo "<td>Distro Name (no lsb_release and no /etc/lsb-release)</td>";
+ echo "<td>Distro Icon (no lsb_release and no /etclsb-release)</td>";
echo "</tr>";
while (false !== ($entry = readdir($handle))) {
if (($entry!=".")&&($entry!="..")) {
@@ -132,7 +134,9 @@ if ($handle = opendir(APP_ROOT.'/sample/distrotest')) {
$log_file=APP_ROOT.'/sample/distrotest/'.$entry.'/'.$sentry;
echo "<tr>";
echo "<td>".$entry.'/'.$sentry."</td>";
+
$lsb = true;
+ $lsbfile = true;
$sys=$system->getSys();
$distro=$sys->getDistribution();
if ($distro == 'Linux')
@@ -149,7 +153,28 @@ if ($handle = opendir(APP_ROOT.'/sample/distrotest')) {
echo $icon."</td>";
$sys->setDistribution("");
$sys->setDistributionIcon("");
+
$lsb = false;
+ $lsbfile = true;
+ $sys=$system->getSys();
+ $distro=$sys->getDistribution();
+ if ($distro == 'Linux')
+ echo "<td style='color:red'>";
+ else
+ echo "<td>";
+ echo $distro."</td>";
+ $icon=$sys->getDistributionIcon();
+ if ($icon != $entry.'.png')
+ echo "<td style='color:red'>";
+ else
+ echo "<td>";
+ echo "<img src=\"../gfx/images/".$icon."\" height=\"16\" width=\"16\">";
+ echo $icon."</td>";
+ $sys->setDistribution("");
+ $sys->setDistributionIcon("");
+
+ $lsb = false;
+ $lsbfile = false;
$sys=$system->getSys();
$distro=$sys->getDistribution();
if ($distro == 'Linux')
@@ -166,6 +191,7 @@ if ($handle = opendir(APP_ROOT.'/sample/distrotest')) {
echo $icon."</td>";
$sys->setDistribution("");
$sys->setDistributionIcon("");
+
echo "</tr>";
}
}
|
check distro if no /etc/lsb-release
|
phpsysinfo_phpsysinfo
|
train
|
0da6d669ac5246ba5a5b86ea8d09052cb3cb999b
|
diff --git a/lib/schedule.js b/lib/schedule.js
index <HASH>..<HASH> 100644
--- a/lib/schedule.js
+++ b/lib/schedule.js
@@ -149,7 +149,7 @@ Job.prototype.schedule = function(spec) {
} catch (err) {
var type = typeof spec;
- if (type === 'string') {
+ if ((type === 'string') || (type === 'number')) {
spec = new Date(spec);
}
diff --git a/test/date-convenience-methods-test.js b/test/date-convenience-methods-test.js
index <HASH>..<HASH> 100644
--- a/test/date-convenience-methods-test.js
+++ b/test/date-convenience-methods-test.js
@@ -45,6 +45,21 @@ module.exports = {
clock.tick(1250);
}
},
+ "UTC": {
+ "Should accept a valid UTC date in milliseconds": function(test) {
+ test.expect(1);
+
+ schedule.scheduleJob(new Date(Date.now() + 1000).getTime(), function() {
+ test.ok(true);
+ });
+
+ setTimeout(function() {
+ test.done();
+ }, 1250);
+
+ clock.tick(1250);
+ }
+ },
tearDown: function(cb) {
clock.restore();
cb();
|
src: accept UTC dates in milliseconds
- Add a new test.
|
node-schedule_node-schedule
|
train
|
86a25c3fd267b9dcc2719c2e4ef9e4d2a797dee1
|
diff --git a/src/com/backendless/FootprintsManager.java b/src/com/backendless/FootprintsManager.java
index <HASH>..<HASH> 100644
--- a/src/com/backendless/FootprintsManager.java
+++ b/src/com/backendless/FootprintsManager.java
@@ -244,6 +244,7 @@ public class FootprintsManager
if( newEntity instanceof BackendlessUser )
{
newEntityField = ((BackendlessUser) newEntity).getProperty( key );
+
if( newEntityField == null )
newEntityField = ((BackendlessUser) newEntity).getProperty( upperKey );
}
@@ -294,9 +295,14 @@ public class FootprintsManager
if( newEntity instanceof BackendlessUser )
{
Object newObjectArray = ((BackendlessUser) newEntity).getProperty( key );
+
if( newObjectArray == null )
newObjectArray = ((BackendlessUser) newEntity).getProperty( upperKey );
- newObjectCollection = newObjectArray == null ? new ArrayList() : Arrays.asList( newObjectArray );
+
+ if( newObjectArray == null )
+ newObjectCollection = new ArrayList();
+ else
+ newObjectCollection = Arrays.asList( (Object[]) newObjectArray );
}
else
{
@@ -315,9 +321,18 @@ public class FootprintsManager
if( oldEntity instanceof BackendlessUser )
{
Object oldObjectArray = ((BackendlessUser) oldEntity).getProperty( key );
+
if( oldObjectArray == null )
oldObjectArray = ((BackendlessUser) oldEntity).getProperty( upperKey );
- oldObjectCollection = oldObjectArray == null ? new ArrayList() : Arrays.asList( oldObjectArray );
+
+ if( oldObjectArray == null )
+ oldObjectCollection = new ArrayList();
+ else if( oldObjectArray instanceof Collection )
+ oldObjectCollection = (Collection) oldObjectArray;
+ else if( oldObjectArray.getClass().isArray() )
+ oldObjectCollection = Arrays.asList( (Object[]) oldObjectArray );
+ else
+ throw new RuntimeException( "unexpected data type - " + oldObjectArray.getClass() );
}
else
{
|
fixed a problem with footprint restore. Problem occurred when a returned top level BackendlessUser object had a collection of child related objects
|
Backendless_Android-SDK
|
train
|
5b78ca048a2a03576262c0a88ea56c90525449f7
|
diff --git a/lib/builder/android/index.js b/lib/builder/android/index.js
index <HASH>..<HASH> 100644
--- a/lib/builder/android/index.js
+++ b/lib/builder/android/index.js
@@ -9,7 +9,6 @@ module.exports = exports = AndroidBuilder
AndroidBuilder.prototype = BaseBuilder.prototype
function AndroidBuilder (opts) {
- this.opts = opts
this.platform = 'android'
BaseBuilder.call(this, opts)
diff --git a/lib/builder/base.js b/lib/builder/base.js
index <HASH>..<HASH> 100644
--- a/lib/builder/base.js
+++ b/lib/builder/base.js
@@ -13,6 +13,7 @@ var _merge = require('lodash/object/merge')
module.exports = exports = Builder
function Builder (opts) {
+ this.opts = opts
if (!this.platform) {
this.platform = 'base'
}
diff --git a/lib/builder/ios/index.js b/lib/builder/ios/index.js
index <HASH>..<HASH> 100644
--- a/lib/builder/ios/index.js
+++ b/lib/builder/ios/index.js
@@ -9,7 +9,6 @@ module.exports = exports = IosBuilder
IosBuilder.prototype = BaseBuilder.prototype
function IosBuilder (opts) {
- this.opts = opts
this.platform = 'ios'
BaseBuilder.call(this, opts)
|
Add this.opts for all platforms via base.js
|
vigour-io_wrapper
|
train
|
8783b97f53c9249df086a978b581bb5cd22b42ff
|
diff --git a/DrdPlus/Person/Health/WoundOrigin.php b/DrdPlus/Person/Health/WoundOrigin.php
index <HASH>..<HASH> 100644
--- a/DrdPlus/Person/Health/WoundOrigin.php
+++ b/DrdPlus/Person/Health/WoundOrigin.php
@@ -18,6 +18,14 @@ class WoundOrigin extends StringEnum
}
/**
+ * @return bool
+ */
+ public function isMechanicalStabWoundOrigin()
+ {
+ return $this->is(self::getMechanicalStabWoundOrigin());
+ }
+
+ /**
* @return WoundOrigin
*/
public static function getMechanicalCutWoundOrigin()
@@ -26,6 +34,14 @@ class WoundOrigin extends StringEnum
}
/**
+ * @return bool
+ */
+ public function isMechanicalCutWoundOrigin()
+ {
+ return $this->is(self::getMechanicalCutWoundOrigin());
+ }
+
+ /**
* @return WoundOrigin
*/
public static function getMechanicalCrushWoundOrigin()
@@ -34,6 +50,14 @@ class WoundOrigin extends StringEnum
}
/**
+ * @return bool
+ */
+ public function isMechanicalCrushWoundOrigin()
+ {
+ return $this->is(self::getMechanicalCrushWoundOrigin());
+ }
+
+ /**
* @return WoundOrigin
*/
public static function getElementalWoundOrigin()
@@ -42,6 +66,14 @@ class WoundOrigin extends StringEnum
}
/**
+ * @return bool
+ */
+ public function isElementalWoundOrigin()
+ {
+ return $this->is(self::getElementalWoundOrigin());
+ }
+
+ /**
* @return WoundOrigin
*/
public static function getPsychicalWoundOrigin()
@@ -49,6 +81,22 @@ class WoundOrigin extends StringEnum
return static::getEnum(WoundsOriginCodes::PSYCHICAL);
}
+ /**
+ * @return bool
+ */
+ public function isPsychicalWoundOrigin()
+ {
+ return $this->is(self::getPsychicalWoundOrigin());
+ }
+
+ /**
+ * @return bool
+ */
+ public function isExtraOrdinaryWoundOrigin()
+ {
+ return !$this->isOrdinaryWoundOrigin();
+ }
+
const ORDINARY = 'ordinary';
/**
@@ -60,6 +108,14 @@ class WoundOrigin extends StringEnum
}
/**
+ * @return bool
+ */
+ public function isOrdinaryWoundOrigin()
+ {
+ return $this->is(self::getOrdinaryWoundOrigin());
+ }
+
+ /**
* @param bool|float|int|object|string $enumValue
* @return string
* @throws \DrdPlus\Person\Health\Exceptions\UnknownWoundOriginCode
|
Wound origin can be easily tested for specific origin
|
drdplusinfo_health
|
train
|
c9a2f27e8027e2c16f8501237aaa70f4eeb45685
|
diff --git a/mod/scorm/datamodels/scormlib.php b/mod/scorm/datamodels/scormlib.php
index <HASH>..<HASH> 100644
--- a/mod/scorm/datamodels/scormlib.php
+++ b/mod/scorm/datamodels/scormlib.php
@@ -190,7 +190,7 @@ function scorm_parse_scorm($pkgdir,$scormid) {
$xmlstring = file_get_contents($manifestfile);
$objXML = new xml2Array();
$manifests = $objXML->parse($xmlstring);
- // print_r($manifests);
+ //print_r($manifests);
$scoes = new stdClass();
$scoes->version = '';
$scoes = scorm_get_manifest($manifests,$scoes);
@@ -200,7 +200,8 @@ function scorm_parse_scorm($pkgdir,$scormid) {
foreach ($scoes->elements as $manifest => $organizations) {
foreach ($organizations as $organization => $items) {
foreach ($items as $identifier => $item) {
- $newitem = new stdClass();
+ // This new db mngt will support all SCORM future extensions
+ /*$newitem = new stdClass();
$newitem->scorm = $scormid;
$newitem->manifest = $manifest;
$newitem->organization = $organization;
@@ -228,8 +229,19 @@ function scorm_parse_scorm($pkgdir,$scormid) {
$data->value = $item->$optionaldata;
$dataid = insert_record('scorm_scoes_data');
}
- }
+ } */
+ $item->scorm = $scormid;
+ $item->manifest = $manifest;
+ $item->organization = $organization;
+ if ($olditemid = scorm_array_search('identifier',$item->identifier,$olditems)) {
+ $item->id = $olditemid;
+ $id = update_record('scorm_scoes',$item);
+ unset($olditems[$olditemid]);
+ } else {
+ $id = insert_record('scorm_scoes',$item);
+ }
+
if (($launch == 0) && ((empty($scoes->defaultorg)) || ($scoes->defaultorg == $identifier))) {
$launch = $id;
}
@@ -239,7 +251,7 @@ function scorm_parse_scorm($pkgdir,$scormid) {
if (!empty($olditems)) {
foreach($olditems as $olditem) {
delete_records('scorm_scoes','id',$olditem->id);
- delete_records('scorm_scoes_data','scoid',$olditem->id);
+ //delete_records('scorm_scoes_data','scoid',$olditem->id);
delete_records('scorm_scoes_track','scoid',$olditem->id);
}
}
|
Downgraded a new feature to fix the module
|
moodle_moodle
|
train
|
255dc1c44bb352784a8f3c484c2365440bb7c6f3
|
diff --git a/lib/Cake/I18n/Multibyte.php b/lib/Cake/I18n/Multibyte.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/I18n/Multibyte.php
+++ b/lib/Cake/I18n/Multibyte.php
@@ -772,7 +772,6 @@ class Multibyte {
$length = count($utf8Map);
$lowerCase = array();
- $matched = false;
for ($i = 0 ; $i < $length; $i++) {
$char = $utf8Map[$i];
@@ -819,7 +818,6 @@ class Multibyte {
$utf8Map = Multibyte::utf8($string);
$length = count($utf8Map);
- $matched = false;
$replaced = array();
$upperCase = array();
@@ -947,7 +945,6 @@ class Multibyte {
}
$string = Multibyte::utf8($string);
- $stringCount = count($string);
for ($i = 1; $i <= $start; $i++) {
unset($string[$i - 1]);
@@ -1068,7 +1065,6 @@ class Multibyte {
* @return array
*/
private static function __find($char, $type = 'lower') {
- $value = false;
$found = array();
if (!isset(self::$__codeRange[$char])) {
$range = self::__codepoint($char);
|
Unused variables in I<I>n removed
|
cakephp_cakephp
|
train
|
a3a3eb797f83a0a86b50e7b9685536e28951d489
|
diff --git a/test/geocoders/nominatim.py b/test/geocoders/nominatim.py
index <HASH>..<HASH> 100644
--- a/test/geocoders/nominatim.py
+++ b/test/geocoders/nominatim.py
@@ -55,7 +55,8 @@ class BaseNominatimTestCase(with_metaclass(ABCMeta, object)):
{"query": "second street", "limit": 4, "exactly_one": False},
{}
)
- self.assertEqual(4, len(result))
+ self.assertGreaterEqual(len(result), 3) # PickPoint sometimes returns 3
+ self.assertGreaterEqual(4, len(result))
@patch.object(geopy.geocoders.options, 'default_user_agent',
'mocked_user_agent/0.0.0')
|
Fix flaky PickPoint test with limit=4 which might return page of 3 items
|
geopy_geopy
|
train
|
0c8b6418902e7635276c16ebe7afe02fa0c8518e
|
diff --git a/src/de/mrapp/android/preference/activity/PreferenceFragment.java b/src/de/mrapp/android/preference/activity/PreferenceFragment.java
index <HASH>..<HASH> 100644
--- a/src/de/mrapp/android/preference/activity/PreferenceFragment.java
+++ b/src/de/mrapp/android/preference/activity/PreferenceFragment.java
@@ -17,6 +17,9 @@
*/
package de.mrapp.android.preference.activity;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
@@ -29,6 +32,8 @@ import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
+import static de.mrapp.android.preference.activity.util.Condition.ensureNotNull;
+
/**
* A fragment, which allows to show multiple preferences. Additionally, a
* button, which allows to restore the preferences' default values, can be
@@ -70,6 +75,12 @@ public class PreferenceFragment extends android.preference.PreferenceFragment {
private int buttonBarSeparatorColor;
/**
+ * A set, which contains the listeners, which should be notified, when the
+ * preferences' default values should be restored.
+ */
+ private Set<DefaultValueListener> defaultValueListeners = new LinkedHashSet<DefaultValueListener>();
+
+ /**
* Inflates the view group, which contains the button, which allows to
* restore the preferences' default values.
*/
@@ -99,7 +110,9 @@ public class PreferenceFragment extends android.preference.PreferenceFragment {
@Override
public void onClick(final View v) {
- restoreDefaults();
+ if (notifyOnRestoreDefaultValues()) {
+ restoreDefaults();
+ }
}
};
@@ -154,6 +167,23 @@ public class PreferenceFragment extends android.preference.PreferenceFragment {
}
/**
+ * Notifies all registered listeners, that the preferences' default values
+ * should be restored.
+ *
+ * @return True, if restoring the preferences' default values should be
+ * proceeded, false otherwise
+ */
+ private boolean notifyOnRestoreDefaultValues() {
+ boolean result = true;
+
+ for (DefaultValueListener listener : defaultValueListeners) {
+ result &= listener.onRestoreDefaultValues(this);
+ }
+
+ return result;
+ }
+
+ /**
* Restores the default values of all preferences, which are contained by
* the fragment.
*/
@@ -164,6 +194,35 @@ public class PreferenceFragment extends android.preference.PreferenceFragment {
}
/**
+ * Adds a new listener, which should be notified, when the preferences'
+ * default values should be restored, to the fragment.
+ *
+ * @param listener
+ * The listener, which should be added as an instance of the type
+ * {@link DefaultValueListener}. The listener may not be null
+ */
+ public final void addDefaultValueListener(
+ final DefaultValueListener listener) {
+ ensureNotNull(listener, "The listener may not be null");
+ this.defaultValueListeners.add(listener);
+ }
+
+ /**
+ * Removes a specific listener, which should not be notified anymore, when
+ * the preferences' default values should be restored, from the fragment.
+ *
+ * @param listener
+ * The listener, which should be removed as an instance of the
+ * type {@link DefaultValueListener}. The listener may not be
+ * null
+ */
+ public final void removeDefaultValueListener(
+ final DefaultValueListener listener) {
+ ensureNotNull(listener, "The listener may not be null");
+ this.defaultValueListeners.remove(listener);
+ }
+
+ /**
* Returns, whether the button, which allows to restore the preferences'
* default values, is currently shown, or not.
*
|
Added the possibility to register listeners, which are notified when the default values should be restored.
|
michael-rapp_AndroidPreferenceActivity
|
train
|
06a6357570823477a98ed30c716e842a62fbb0b8
|
diff --git a/src/Plugin/Block/LocationPopupLink.php b/src/Plugin/Block/LocationPopupLink.php
index <HASH>..<HASH> 100644
--- a/src/Plugin/Block/LocationPopupLink.php
+++ b/src/Plugin/Block/LocationPopupLink.php
@@ -4,7 +4,6 @@ namespace Drupal\ygs_popups\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
-use Drupal\ygs_alters\AnonymousStartSession;
/**
* Block with popup link.
@@ -16,7 +15,6 @@ use Drupal\ygs_alters\AnonymousStartSession;
* )
*/
class LocationPopupLink extends BlockBase {
- use AnonymousStartSession;
/**
* {@inheritdoc}
|
[YGS-<I>] Get rid of AnonymousStartSession trait
|
ymcatwincities_openy
|
train
|
ac01544909bf3e69f9b5f2b91d0ef8a9c06ec7c7
|
diff --git a/sharding-scaling-mysql/src/main/java/info/avalon566/shardingscaling/mysql/binlog/codec/MySQLBinlogEventPacketDecoder.java b/sharding-scaling-mysql/src/main/java/info/avalon566/shardingscaling/mysql/binlog/codec/MySQLBinlogEventPacketDecoder.java
index <HASH>..<HASH> 100644
--- a/sharding-scaling-mysql/src/main/java/info/avalon566/shardingscaling/mysql/binlog/codec/MySQLBinlogEventPacketDecoder.java
+++ b/sharding-scaling-mysql/src/main/java/info/avalon566/shardingscaling/mysql/binlog/codec/MySQLBinlogEventPacketDecoder.java
@@ -119,6 +119,8 @@ public final class MySQLBinlogEventPacketDecoder extends ByteToMessageDecoder {
DeleteRowsEvent result = new DeleteRowsEvent();
result.setTableName(binlogContext.getFullTableName(rowsEvent.getTableId()));
result.setBeforeColumns(rowsEvent.getColumnValues1());
+ result.setFileName(binlogContext.getFileName());
+ result.setPosition(binlogEventHeader.getEndLogPos());
return result;
}
@@ -130,6 +132,8 @@ public final class MySQLBinlogEventPacketDecoder extends ByteToMessageDecoder {
result.setTableName(binlogContext.getFullTableName(rowsEvent.getTableId()));
result.setBeforeColumns(rowsEvent.getColumnValues1());
result.setAfterColumns(rowsEvent.getColumnValues2());
+ result.setFileName(binlogContext.getFileName());
+ result.setPosition(binlogEventHeader.getEndLogPos());
return result;
}
@@ -140,6 +144,8 @@ public final class MySQLBinlogEventPacketDecoder extends ByteToMessageDecoder {
WriteRowsEvent result = new WriteRowsEvent();
result.setTableName(binlogContext.getFullTableName(rowsEvent.getTableId()));
result.setAfterColumns(rowsEvent.getColumnValues1());
+ result.setFileName(binlogContext.getFileName());
+ result.setPosition(binlogEventHeader.getEndLogPos());
return result;
}
|
Fix binlog event packet decoder
|
apache_incubator-shardingsphere
|
train
|
16e86bc0c0e416071fbabbd5f22be0cb115e4364
|
diff --git a/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerPatterns.php b/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerPatterns.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerPatterns.php
+++ b/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerPatterns.php
@@ -44,7 +44,7 @@ class TokenizerPatterns
$this->nonAsciiPattern = '[^\x00-\x7F]';
$this->nmCharPattern = '[_a-z0-9-]|'.$this->escapePattern.'|'.$this->nonAsciiPattern;
$this->nmStartPattern = '[_a-z]|'.$this->escapePattern.'|'.$this->nonAsciiPattern;
- $this->identifierPattern = '(?:'.$this->nmStartPattern.')(?:'.$this->nmCharPattern.')*';
+ $this->identifierPattern = '-?(?:'.$this->nmStartPattern.')(?:'.$this->nmCharPattern.')*';
$this->hashPattern = '#((?:'.$this->nmCharPattern.')+)';
$this->numberPattern = '[+-]?(?:[0-9]*\.[0-9]+|[0-9]+)';
$this->quotedStringPattern = '([^\n\r\f%s]|'.$this->stringEscapePattern.')*';
diff --git a/src/Symfony/Component/CssSelector/Tests/Parser/ParserTest.php b/src/Symfony/Component/CssSelector/Tests/Parser/ParserTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/CssSelector/Tests/Parser/ParserTest.php
+++ b/src/Symfony/Component/CssSelector/Tests/Parser/ParserTest.php
@@ -186,6 +186,7 @@ class ParserTest extends TestCase
array('foo:after', 'Element[foo]', 'after'),
array('foo::selection', 'Element[foo]', 'selection'),
array('lorem#ipsum ~ a#b.c[href]:empty::selection', 'CombinedSelector[Hash[Element[lorem]#ipsum] ~ Pseudo[Attribute[Class[Hash[Element[a]#b].c][href]]:empty]]', 'selection'),
+ array('video::-webkit-media-controls', 'Element[video]', '-webkit-media-controls'),
);
}
|
[CssSelector] Fix CSS identifiers parsing - they can start with dash
|
symfony_symfony
|
train
|
68f022d61e1631132c0aef89645e24b0f1cc9215
|
diff --git a/src/test/java/com/suse/salt/netapi/examples/Calls.java b/src/test/java/com/suse/salt/netapi/examples/Calls.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/suse/salt/netapi/examples/Calls.java
+++ b/src/test/java/com/suse/salt/netapi/examples/Calls.java
@@ -40,18 +40,18 @@ public class Calls {
// Get the grains from a list of minions
Target<List<String>> minionList = new MinionList("minion1", "minion2");
- Map<String, Result<Map<String, Object>>> grainResults =
- Grains.items(false).callSync(
- client, minionList, USER, PASSWORD, AuthModule.AUTO);
+ Map<String, Result<Map<String, Object>>> grainResults = Grains.items(false)
+ .callSync(client, minionList, USER, PASSWORD, AuthModule.AUTO);
grainResults.forEach((minion, grains) -> {
System.out.println("\n--> Listing grains for '" + minion + "':\n");
- String message = grains.fold(
- Object::toString,
- m -> m.entrySet().stream()
- .map(e -> e.getKey() + ": " + e.getValue())
- .collect(Collectors.joining("\n"))
+ String grainsOutput = grains.fold(
+ error -> "Error: " + error.toString(),
+ grainsMap -> grainsMap.entrySet().stream()
+ .map(e -> e.getKey() + ": " + e.getValue())
+ .collect(Collectors.joining("\n"))
);
+ System.out.println(grainsOutput);
});
// Call a wheel function: list accepted and pending minion keys
|
Reformat the examples in Calls.java
|
SUSE_salt-netapi-client
|
train
|
6b10576fae1d802ea743a7bd1186edf7312af261
|
diff --git a/src/views/thread.blade.php b/src/views/thread.blade.php
index <HASH>..<HASH> 100644
--- a/src/views/thread.blade.php
+++ b/src/views/thread.blade.php
@@ -35,9 +35,16 @@
@endif
@if ($thread->canReply)
- <div class="btn-group" role="group">
- <a href="{{ $thread->replyRoute }}" class="btn btn-default">{{ trans('forum::base.new_reply') }}</a>
- <a href="#quick-reply" class="btn btn-default">{{ trans('forum::base.quick_reply') }}</a>
+ <div class="row">
+ <div class="col-xs-4">
+ <div class="btn-group" role="group">
+ <a href="{{ $thread->replyRoute }}" class="btn btn-default">{{ trans('forum::base.new_reply') }}</a>
+ <a href="#quick-reply" class="btn btn-default">{{ trans('forum::base.quick_reply') }}</a>
+ </div>
+ </div>
+ <div class="col-xs-8 text-right">
+ {!! $thread->pageLinks !!}
+ </div>
</div>
@endif
@@ -59,7 +66,7 @@
</tbody>
</table>
-{{ $thread->pageLinks }}
+{!! $thread->pageLinks !!}
@if ($thread->canReply)
<h3>{{ trans('forum::base.quick_reply') }}</h3>
|
Don't escape thread pagination output
|
Riari_laravel-forum
|
train
|
cdbf9532af1fa794e16ac474f5dd0b6d5e159a2c
|
diff --git a/src/adapters/criteo.js b/src/adapters/criteo.js
index <HASH>..<HASH> 100644
--- a/src/adapters/criteo.js
+++ b/src/adapters/criteo.js
@@ -54,8 +54,6 @@ var CriteoAdapter = function CriteoAdapter() {
adResponse.bidderCode = 'criteo';
adResponse.keys = content.split(';');
-
- //bidmanager.addBidResponse(existingBid.placementCode, adResponse);
} else {
// Indicate an ad was not returned
adResponse = bidfactory.createBid(2);
|
actually removing the second addBidResponse from criteo bidder, not jsut commented out
|
prebid_Prebid.js
|
train
|
37e26d40923c856c54101222321ae17e443842a7
|
diff --git a/src/main/java/com/zaxxer/hikari/HikariConfig.java b/src/main/java/com/zaxxer/hikari/HikariConfig.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/zaxxer/hikari/HikariConfig.java
+++ b/src/main/java/com/zaxxer/hikari/HikariConfig.java
@@ -436,6 +436,11 @@ public class HikariConfig implements HikariConfigMBean
return isRecordMetrics;
}
+ /**
+ * Currently not supported.
+ * @param recordMetrics
+ */
+ @Deprecated
public void setRecordMetrics(boolean recordMetrics)
{
this.isRecordMetrics = recordMetrics;
|
Discourage users from turning on metrics until they do something useful.
|
brettwooldridge_HikariCP
|
train
|
44af44ffa97aed0e2809775abb1c8828c8c6d22b
|
diff --git a/it/utils_for_tests.go b/it/utils_for_tests.go
index <HASH>..<HASH> 100644
--- a/it/utils_for_tests.go
+++ b/it/utils_for_tests.go
@@ -143,6 +143,7 @@ func SetupApp(t *testing.T, bundle *smith_v1.Bundle, serviceCatalog, createBundl
loggerConfig := zap.NewDevelopmentConfig()
loggerConfig.DisableCaller = true
+ loggerConfig.DisableStacktrace = true
logger, err := loggerConfig.Build()
require.NoError(t, err)
defer logger.Sync()
|
Disable stacktraces in logs in tests
|
atlassian_smith
|
train
|
23a96a543ec17d3ac961331a4ccc52be444f83c9
|
diff --git a/openquake/engine/engine2.py b/openquake/engine/engine2.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/engine2.py
+++ b/openquake/engine/engine2.py
@@ -76,6 +76,15 @@ def prepare_user(user_name):
return user
+def get_current_user():
+ """
+ Utilty function for getting the :class:`openquake.engine.db.models.OqUser`
+ for the the current user. If the user record doesn't exist, it will be
+ created.
+ """
+ return prepare_user(getpass.getuser())
+
+
def parse_config(source, force_inputs=False):
"""Parse a dictionary of parameters from an INI-style config file.
|
engine2:
Added a util function for getting the current OqUser.
|
gem_oq-engine
|
train
|
24f5e326dfe239573e918fdc17aab9c428cd5012
|
diff --git a/photutils/psf/sandbox.py b/photutils/psf/sandbox.py
index <HASH>..<HASH> 100644
--- a/photutils/psf/sandbox.py
+++ b/photutils/psf/sandbox.py
@@ -181,10 +181,8 @@ class DiscretePRF(Fittable2DModel):
size as the PRF image.
mode : {'mean', 'median'}
One of the following modes to combine the extracted PRFs:
- * 'mean': Take the pixelwise mean of the extracted
- PRFs.
- * 'median': Take the pixelwise median of the extracted
- PRFs.
+ * 'mean': Take the pixelwise mean of the extracted PRFs.
+ * 'median': Take the pixelwise median of the extracted PRFs.
subsampling : int
Factor of subsampling of the PRF (default = 1).
fix_nan : bool
|
Retain typesetting improvements that were made in models.py
|
astropy_photutils
|
train
|
72c1231db8d47e15b36417d060083c0b2f46cecd
|
diff --git a/lib/queue.js b/lib/queue.js
index <HASH>..<HASH> 100644
--- a/lib/queue.js
+++ b/lib/queue.js
@@ -16,6 +16,10 @@ function Queue(connection, name, options) {
this.options = options;
this.collection = connection.db.collection(this.options.collection);
+
+ if(!options.dontCreateIndex){
+ this.ensureIndex();
+ }
}
Queue.prototype.job = function(data) {
@@ -48,4 +52,10 @@ Queue.prototype.dequeue = function(callback) {
callback(null, self.job(doc));
});
+};
+
+Queue.prototype.ensureIndex = function(){
+ //Ensures there's a reasonable index for the poling dequeue
+ //Status is first b/c querying by status = queued should be very selective
+ this.collection.ensureIndex({ status: 1, queue: 1, enqueued: 1 });
};
\ No newline at end of file
|
Create index automatically for poling dequeue query
|
scttnlsn_monq
|
train
|
3235a27667278433254ed7fcab886cdaa89fb905
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -83,7 +83,9 @@ create(parent)
Creates a new object instance and sets it's internal prototype to the parent
argument provided. This is based on [Crockford's Object.create()][#create] but
-will use the native `Object.create()` if present.
+will use the native `Object.create()` if present. Unlike Object.create() this
+function will always return a new object even if a non object is provided as an
+argument.
[#create]: http://javascript.crockford.com/prototypal.html
diff --git a/inheritance-test.js b/inheritance-test.js
index <HASH>..<HASH> 100644
--- a/inheritance-test.js
+++ b/inheritance-test.js
@@ -60,6 +60,9 @@ vows.describe('inheritance').addBatch({
assert.equal(instance.a, parent.a);
assert.equal(instance.b, parent.b);
assert.equal(instance.c, parent.c);
+ },
+ 'it should return a plain object if non object is passed': function () {
+ assert.deepEqual(create(), {});
}
},
'mixin()': {
diff --git a/inheritance.js b/inheritance.js
index <HASH>..<HASH> 100644
--- a/inheritance.js
+++ b/inheritance.js
@@ -7,8 +7,7 @@
var _inherit = exports.inherit,
_create = exports.create,
- _mixin = exports.mixin,
- create;
+ _mixin = exports.mixin;
/* Public: Extends an object with the properties on successive arguments.
*
@@ -50,12 +49,14 @@
/* Used to create a new object in case calling the parent has side effects */
function DummyObject() {}
- /* Public: Creates a new object that inherits from the parent argument.
+ /* Public: Creates a new object that inherits from the proto argument.
*
* This function will use Object.create() if it exists otherwise falls back
* to using a dummy constructor function to create a new object instance.
+ * Unlike Object.create() this function will always return a new object even
+ * if a non object is provided as an argument.
*
- * parent - An object to use for the new objects internal prototype.
+ * proto - An object to use for the new objects internal prototype.
*
* Examples
*
@@ -67,10 +68,17 @@
*
* Returns a newly created object.
*/
- create = exports.create = Object.create || function create(parent) {
- DummyObject.prototype = parent || Object.prototype;
+ function create(proto) {
+ if (typeof proto !== 'object') {
+ return {};
+ }
+ else if (Object.create) {
+ return Object.create(proto);
+ }
+ DummyObject.prototype = proto;
return new DummyObject();
- };
+ }
+ exports.create = create;
/* Removes the create function from the exports object and returns it. */
exports.create.noConflict = function () {
|
Now always returning an object from create()
|
aron_soak.js
|
train
|
19384a066d5993e32d53cae32d12cfd5dce4ea6e
|
diff --git a/pywws/WeatherStation.py b/pywws/WeatherStation.py
index <HASH>..<HASH> 100755
--- a/pywws/WeatherStation.py
+++ b/pywws/WeatherStation.py
@@ -508,7 +508,7 @@ class weather_station(object):
}
reading_format['3080'] = {
'illuminance' : (16, 'u3', 0.1),
- 'uv' : (19, 'ub', None),
+ 'uv' : (19, 'ub', None),
}
reading_format['3080'].update(reading_format['1080'])
lo_fix_format = {
|
Cosmetic source code change (column alignment).
|
jim-easterbrook_pywws
|
train
|
2135673995d7e50ff2198a8fd95550a2558a6aca
|
diff --git a/Kwf/Form/Field/DateSelect.php b/Kwf/Form/Field/DateSelect.php
index <HASH>..<HASH> 100644
--- a/Kwf/Form/Field/DateSelect.php
+++ b/Kwf/Form/Field/DateSelect.php
@@ -54,6 +54,7 @@ class Kwf_Form_Field_DateSelect extends Kwf_Form_Field_SimpleAbstract
$ret['html'] .= ">{$i}</option>";
}
$ret['html'] .= "</select>";
+ $ret['html'] = '<div class="outerSelect">'.$ret['html'].'</div><div class="outerSelect">';
$months = array(
$kwfTrl->trlKwf('January', array(), $this->_language),
@@ -78,6 +79,7 @@ class Kwf_Form_Field_DateSelect extends Kwf_Form_Field_SimpleAbstract
$ret['html'] .= ">{$months[$i-1]}</option>";
}
$ret['html'] .= "</select>";
+ $ret['html'] = $ret['html'].'</div><div class="outerSelect">';
$ret['html'] .= "<select name=\"{$name}_year\">";
$ret['html'] .= "<option value=\"\">{$kwfTrl->trlKwf('Year', array(), $this->_language)}</option>";
@@ -87,6 +89,7 @@ class Kwf_Form_Field_DateSelect extends Kwf_Form_Field_SimpleAbstract
$ret['html'] .= ">{$i}</option>";
}
$ret['html'] .= "</select>";
+ $ret['html'] = $ret['html'].'</div>';
return $ret;
}
}
|
div around select in DataSelect Helper
|
koala-framework_koala-framework
|
train
|
7a6846c6ae9829d2fe93bc401acb361940bdae09
|
diff --git a/package/yapsy/PluginManager.py b/package/yapsy/PluginManager.py
index <HASH>..<HASH> 100644
--- a/package/yapsy/PluginManager.py
+++ b/package/yapsy/PluginManager.py
@@ -476,7 +476,9 @@ class PluginManager(object):
if "__init__" in os.path.basename(candidate_filepath):
sys.path.append(plugin_info.path)
try:
- candidateMainFile = open(candidate_filepath+".py","r")
+ candidateMainFile = open(candidate_filepath+".py","r")
+ # TODO: make sure that we can get proper traceback
+ # info even when using exec(f.read())
exec(candidateMainFile.read(),candidate_globals)
except Exception as e:
logging.warning("Unable to execute the code in plugin: %s" % candidate_filepath)
|
a little warning about a potential bug
--HG--
branch : python3-transition
|
benhoff_pluginmanager
|
train
|
590492e59b4aef98cafdf1a6c28fdbac8d522c28
|
diff --git a/internal/service/ram/tags_gen.go b/internal/service/ram/tags_gen.go
index <HASH>..<HASH> 100644
--- a/internal/service/ram/tags_gen.go
+++ b/internal/service/ram/tags_gen.go
@@ -6,6 +6,7 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ram"
+ "github.com/aws/aws-sdk-go/service/ram/ramiface"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
)
@@ -41,7 +42,7 @@ func KeyValueTags(tags []*ram.Tag) tftags.KeyValueTags {
// UpdateTags updates ram service tags.
// The identifier is typically the Amazon Resource Name (ARN), although
// it may also be a different identifier depending on the service.
-func UpdateTags(conn *ram.RAM, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error {
+func UpdateTags(conn ramiface.RAMAPI, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error {
oldTags := tftags.New(oldTagsMap)
newTags := tftags.New(newTagsMap)
|
gen/tags: Use interface type as generated AWS Go SDK v1 client type for ram.
|
terraform-providers_terraform-provider-aws
|
train
|
85158798ca438c1dafc84036d13c2988c934f02f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -44,10 +44,10 @@ setup(
"requests>=2.25,<3",
"wheel",
"python-gitlab>=2,<4",
+ # tomlkit used to be pinned to 0.7.0
# See https://github.com/relekang/python-semantic-release/issues/336
# and https://github.com/relekang/python-semantic-release/pull/337
- # for why tomlkit is pinned
- "tomlkit==0.7.0",
+ "tomlkit>=0.10.0,<0.11.0",
"dotty-dict>=1.3.0,<2",
"dataclasses==0.8; python_version < '3.7.0'",
],
|
chore(dependencies): unpin tomlkit dependency (#<I>)
- tests for a tomlkit regression don't fail anymore with newer tomlkit
- keep comment in setup.py about tomlkit being pinned at some point in time
refs #<I>
|
relekang_python-semantic-release
|
train
|
18e6fec6771ea3888bc3df3ca7467fcaa7cfeea0
|
diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -3,6 +3,8 @@
"description": "Llum (light in catalan language) illuminates your Laravel projects.",
"keywords": ["laravel","scaffold","boilerplate"],
"license": "MIT",
+ "prefer-stable": true,
+ "minimum-stability": "dev",
"authors": [
{
"name": "Sergi Tur Badenas",
diff --git a/src/Console/LlumCommand.php b/src/Console/LlumCommand.php
index <HASH>..<HASH> 100644
--- a/src/Console/LlumCommand.php
+++ b/src/Console/LlumCommand.php
@@ -114,6 +114,20 @@ abstract class LlumCommand extends Command
$this->config = $this->obtainConfig();
}
+ /**
+ * Initialize command
+ *
+ * @param InputInterface $input
+ * @param OutputInterface $output
+ */
+ protected function initialize(InputInterface $input, OutputInterface $output)
+ {
+ parent::initialize($input, $output);
+ if ($input->hasOption('dev')) {
+ $this->installDev = true;
+ }
+ }
+
/*
* gets dev option
*
@@ -132,10 +146,9 @@ abstract class LlumCommand extends Command
private function requireComposerPackage($package)
{
$composer = $this->findComposer();
-
$process = new Process($composer.' require '.$package.'' . $this->getDevOption(),
null, null, null, null);
- $this->output->writeln('<info>Running composer require '.$package.'</info>');
+ $this->output->writeln('<info>Running composer require '.$package. $this->getDevOption().'</info>');
$process->run(function ($type, $line) {
$this->output->write($line);
});
diff --git a/src/Console/PackageCommand.php b/src/Console/PackageCommand.php
index <HASH>..<HASH> 100644
--- a/src/Console/PackageCommand.php
+++ b/src/Console/PackageCommand.php
@@ -2,6 +2,8 @@
namespace Acacha\Llum\Console;
+use Symfony\Component\Console\Input\InputOption;
+
/**
* Class PackageCommand.
*/
@@ -43,9 +45,16 @@ class PackageCommand extends LlumCommand
protected $method = 'package';
/**
- * Install development version
- *
- * @var bool
+ * Configure the command options.
*/
- protected $installDev = false;
+ protected function configure()
+ {
+ parent::configure();
+ $this->addOption(
+ 'dev',
+ 'd',
+ InputOption::VALUE_NONE,
+ 'If set, dev-master branch of package will be installed'
+ );
+ }
}
|
testing minimum stability to allow installation of dev-master
|
acacha_llum
|
train
|
f7fb1537d8abacab7d92319db5345d7dd2c91b37
|
diff --git a/byml_to_yml.py b/byml_to_yml.py
index <HASH>..<HASH> 100755
--- a/byml_to_yml.py
+++ b/byml_to_yml.py
@@ -15,4 +15,4 @@ class Dumper(yaml.Dumper):
with open(sys.argv[1], "rb") as file:
data = file.read()
root = byml.Byml(data).parse()
- yaml.dump(root, sys.stdout, Dumper=Dumper)
+ yaml.dump(root, sys.stdout, Dumper=Dumper, allow_unicode=True)
|
yml: Allow dumping with unicode characters
|
zeldamods_byml-v2
|
train
|
4f72e79120a4f964330d10c8ebe9aceb2b5761a7
|
diff --git a/tpl/collections/collections.go b/tpl/collections/collections.go
index <HASH>..<HASH> 100644
--- a/tpl/collections/collections.go
+++ b/tpl/collections/collections.go
@@ -298,8 +298,16 @@ func (ns *Namespace) Intersect(l1, l2 interface{}) (interface{}, error) {
case reflect.Array, reflect.Slice:
for i := 0; i < l1v.Len(); i++ {
l1vv := l1v.Index(i)
+ if !l1vv.Type().Comparable() {
+ return make([]interface{}, 0), errors.New("intersect does not support slices or arrays of uncomparable types")
+ }
+
for j := 0; j < l2v.Len(); j++ {
l2vv := l2v.Index(j)
+ if !l2vv.Type().Comparable() {
+ return make([]interface{}, 0), errors.New("intersect does not support slices or arrays of uncomparable types")
+ }
+
ins.handleValuePair(l1vv, l2vv)
}
}
@@ -609,6 +617,11 @@ func (ns *Namespace) Union(l1, l2 interface{}) (interface{}, error) {
for i := 0; i < l1v.Len(); i++ {
l1vv, isNil = indirectInterface(l1v.Index(i))
+
+ if !l1vv.Type().Comparable() {
+ return []interface{}{}, errors.New("union does not support slices or arrays of uncomparable types")
+ }
+
if !isNil {
ins.appendIfNotSeen(l1vv)
}
diff --git a/tpl/collections/collections_test.go b/tpl/collections/collections_test.go
index <HASH>..<HASH> 100644
--- a/tpl/collections/collections_test.go
+++ b/tpl/collections/collections_test.go
@@ -360,10 +360,6 @@ func TestIntersect(t *testing.T) {
{[]int{1, 2, 4}, []int{3, 6}, []int{}},
{[]float64{2.2, 4.4}, []float64{1.1, 2.2, 4.4}, []float64{2.2, 4.4}},
- // errors
- {"not array or slice", []string{"a"}, false},
- {[]string{"a"}, "not array or slice", false},
-
// []interface{} ∩ []interface{}
{[]interface{}{"a", "b", "c"}, []interface{}{"a", "b", "b"}, []interface{}{"a", "b"}},
{[]interface{}{1, 2, 3}, []interface{}{1, 2, 2}, []interface{}{1, 2}},
@@ -404,9 +400,18 @@ func TestIntersect(t *testing.T) {
{pagesVals{}, pagesVals{p1v, p3v, p3v}, pagesVals{}},
{[]interface{}{p1, p4, p2, p3}, []interface{}{}, []interface{}{}},
{[]interface{}{}, []interface{}{p1v, p3v, p3v}, []interface{}{}},
+
+ // errors
+ {"not array or slice", []string{"a"}, false},
+ {[]string{"a"}, "not array or slice", false},
+
+ // uncomparable types - #3820
+ {[]map[int]int{{1: 1}, {2: 2}}, []map[int]int{{2: 2}, {3: 3}}, false},
+ {[][]int{{1, 1}, {1, 2}}, [][]int{{1, 2}, {1, 2}, {1, 3}}, false},
+ {[]int{1, 1}, [][]int{{1, 2}, {1, 2}, {1, 3}}, false},
} {
- errMsg := fmt.Sprintf("[%d]", test)
+ errMsg := fmt.Sprintf("[%d] %v", i, test)
result, err := ns.Intersect(test.l1, test.l2)
@@ -759,6 +764,10 @@ func TestUnion(t *testing.T) {
// errors
{"not array or slice", []string{"a"}, false, true},
{[]string{"a"}, "not array or slice", false, true},
+
+ // uncomparable types - #3820
+ {[]map[string]int{{"K1": 1}}, []map[string]int{{"K2": 2}, {"K2": 2}}, false, true},
+ {[][]int{{1, 1}, {1, 2}}, [][]int{{2, 1}, {2, 2}}, false, true},
} {
errMsg := fmt.Sprintf("[%d] %v", i, test)
|
tpl: Show error on union or intersect of uncomparable types
Fixes #<I>
|
gohugoio_hugo
|
train
|
3a308548529b874b145955b70f6ecbaac330c30e
|
diff --git a/sql/upgrade/PodsUpgrade.php b/sql/upgrade/PodsUpgrade.php
index <HASH>..<HASH> 100644
--- a/sql/upgrade/PodsUpgrade.php
+++ b/sql/upgrade/PodsUpgrade.php
@@ -87,8 +87,9 @@ class PodsUpgrade {
// Auto activate component.
if ( empty( PodsInit::$components ) ) {
- $pods_init = pods_init();
- $pods_init->load_components();
+ if ( ! defined( 'PODS_LIGHT' ) || ! PODS_LIGHT ) {
+ PodsInit::$components = pods_components();
+ }
}
if ( ! empty( PodsInit::$components ) ) {
|
Setup PodsInit::$components in PodsUpgrade directly
|
pods-framework_pods
|
train
|
718d443d5219ad32eb9a4de32eb2b88348311571
|
diff --git a/system/src/Grav/Common/Grav.php b/system/src/Grav/Common/Grav.php
index <HASH>..<HASH> 100644
--- a/system/src/Grav/Common/Grav.php
+++ b/system/src/Grav/Common/Grav.php
@@ -101,7 +101,7 @@ class Grav extends Container
/** @var Uri $uri */
$uri = $c['uri'];
- $path = $uri->path();
+ $path = rtrim($uri->path(), '/');
$page = $pages->dispatch($path);
|
trim trailing slashes from path during page lookup [fixes #<I>]
|
getgrav_grav
|
train
|
94628c7549780115a9990e965cf2661b01bef70a
|
diff --git a/auth/jwt/middleware.go b/auth/jwt/middleware.go
index <HASH>..<HASH> 100644
--- a/auth/jwt/middleware.go
+++ b/auth/jwt/middleware.go
@@ -2,8 +2,6 @@ package jwt
import (
"errors"
- "fmt"
- "reflect"
"golang.org/x/net/context"
@@ -18,15 +16,35 @@ const (
JWTClaimsContextKey = "JWTClaims"
)
+var (
+ ErrTokenContextMissing = errors.New("Token up for parsing was not passed through the context")
+ ErrTokenInvalid = errors.New("JWT Token was invalid")
+ ErrUnexpectedSigningMethod = errors.New("Unexptected signing method")
+ ErrKIDNotFound = errors.New("Key ID was not found in key set")
+ ErrNoKIDHeader = errors.New("Token doesn't have 'kid' header")
+)
+
+type Claims map[string]interface{}
+
+type KeySet map[string]struct {
+ Method jwt.SigningMethod
+ Key []byte
+}
+
// Create a new JWT token generating middleware, specifying signing method and the claims
// you would like it to contain. Particularly useful for clients.
-func NewSigner(key string, method jwt.SigningMethod, claims jwt.Claims) endpoint.Middleware {
+func NewSigner(kid string, keys KeySet, claims Claims) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
- token := jwt.NewWithClaims(method, claims)
+ key, ok := keys[kid]
+ if !ok {
+ return nil, ErrKIDNotFound
+ }
+ token := jwt.NewWithClaims(key.Method, jwt.MapClaims(claims))
+ token.Header["kid"] = kid
// Sign and get the complete encoded token as a string using the secret
- tokenString, err := token.SignedString([]byte(key))
+ tokenString, err := token.SignedString(key.Key)
if err != nil {
return nil, err
}
@@ -40,13 +58,13 @@ func NewSigner(key string, method jwt.SigningMethod, claims jwt.Claims) endpoint
// Create a new JWT token parsing middleware, specifying a jwt.Keyfunc interface and the
// signing method. Adds the resulting claims to endpoint context or returns error on invalid
// token. Particularly useful for servers.
-func NewParser(keyFunc jwt.Keyfunc, method jwt.SigningMethod) endpoint.Middleware {
+func NewParser(keys KeySet) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
// tokenString is stored in the context from the transport handlers
tokenString, ok := ctx.Value(JWTTokenContextKey).(string)
if !ok {
- return nil, errors.New("Token up for parsing was not passed through the context")
+ return nil, ErrTokenContextMissing
}
// Parse takes the token string and a function for looking up the key. The latter is especially
@@ -54,22 +72,33 @@ func NewParser(keyFunc jwt.Keyfunc, method jwt.SigningMethod) endpoint.Middlewar
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
+ kid, ok := token.Header["kid"]
+ if !ok {
+ return nil, ErrNoKIDHeader
+ }
+
+ key, ok := keys[kid.(string)]
+ if !ok {
+ return nil, ErrKIDNotFound
+ }
+
// Don't forget to validate the alg is what you expect:
- if reflect.TypeOf(token.Method) != reflect.TypeOf(method) {
- return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
+ if token.Method != key.Method {
+ return nil, ErrUnexpectedSigningMethod
}
- return keyFunc(token)
+
+ return key.Key, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
- return nil, errors.New("Could not parse JWT Token")
+ return nil, ErrTokenInvalid
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
- ctx = context.WithValue(ctx, JWTClaimsContextKey, claims)
+ ctx = context.WithValue(ctx, JWTClaimsContextKey, Claims(claims))
}
return next(ctx, request)
|
Refactor away from passing a function to passing a struct with multiple options for signing keys
|
go-kit_kit
|
train
|
13eded734ef8bd913d393309ffb433bcec5b1616
|
diff --git a/lib/bumper_pusher/version.rb b/lib/bumper_pusher/version.rb
index <HASH>..<HASH> 100644
--- a/lib/bumper_pusher/version.rb
+++ b/lib/bumper_pusher/version.rb
@@ -1,3 +1,3 @@
module BumperPusher
- VERSION = "0.1.5"
+ VERSION = "0.1.6"
end
|
Update gemspec to version <I>
|
skywinder_bumper_pusher
|
train
|
c8e389309593d52296de814cbc53812e88c90ab4
|
diff --git a/kitchen-tests/cookbooks/base/recipes/default.rb b/kitchen-tests/cookbooks/base/recipes/default.rb
index <HASH>..<HASH> 100644
--- a/kitchen-tests/cookbooks/base/recipes/default.rb
+++ b/kitchen-tests/cookbooks/base/recipes/default.rb
@@ -7,12 +7,12 @@
hostname "chef-travis-ci.chef.io"
-if node["platform_family"] == "debian"
+if platform_family?("debian")
include_recipe "ubuntu"
apt_update "packages"
end
-if %w{rhel fedora}.include?(node["platform_family"])
+if platform_family?("rhel", "fedora", "amazon")
include_recipe "selinux::disabled"
end
@@ -23,7 +23,7 @@ yum_repository "epel" do
gpgkey "https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-#{node['platform_version'].to_i}"
gpgcheck true
mirrorlist "https://mirrors.fedoraproject.org/metalink?repo=epel-#{node['platform_version'].to_i}&arch=$basearch"
- only_if { node["platform_family"] == "rhel" && node["platform"] != "amazon" }
+ only_if { platform_family?("rhel") }
end
include_recipe "build-essential"
|
Chef <I> recipe updates and simplification
|
chef_chef
|
train
|
a9587e88d13ea32764920befcfc07487dc031ff6
|
diff --git a/src/BoomCMS/Contracts/Repositories/Page.php b/src/BoomCMS/Contracts/Repositories/Page.php
index <HASH>..<HASH> 100644
--- a/src/BoomCMS/Contracts/Repositories/Page.php
+++ b/src/BoomCMS/Contracts/Repositories/Page.php
@@ -66,6 +66,16 @@ interface Page
public function findBySiteAndUri(SiteInterface $site, $uri);
/**
+ * Recurse through a section of the page tree and apply a function.
+ *
+ * @param PageInterface $page
+ * @param callable $closure
+ *
+ * @return void
+ */
+ public function recurse(PageInterface $page, callable $closure);
+
+ /**
* @param PageInterface $page
*
* @return PageInterface
diff --git a/src/BoomCMS/Repositories/Page.php b/src/BoomCMS/Repositories/Page.php
index <HASH>..<HASH> 100644
--- a/src/BoomCMS/Repositories/Page.php
+++ b/src/BoomCMS/Repositories/Page.php
@@ -139,6 +139,26 @@ class Page implements PageRepositoryInterface
}
/**
+ *
+ * @param PageModelInterface $page
+ * @param callable $closure
+ *
+ * @return void
+ */
+ public function recurse(PageModelInterface $page, callable $closure)
+ {
+ $children = $this->findByParentId($page->getId());
+
+ if (!empty($children)) {
+ foreach ($children as $child) {
+ $this->recurse($child, $closure);
+ }
+ }
+
+ $closure($page);
+ }
+
+ /**
* Save a page.
*
* @param PageModelInterface $page
diff --git a/tests/Repositories/PageTest.php b/tests/Repositories/PageTest.php
index <HASH>..<HASH> 100644
--- a/tests/Repositories/PageTest.php
+++ b/tests/Repositories/PageTest.php
@@ -216,4 +216,46 @@ class PageTest extends AbstractTestCase
$this->assertEquals($exists, $this->repository->internalNameExists($name));
}
+
+ public function testRecurse()
+ {
+ $pageId = 1;
+ $children = [m::mock(Page::class), m::mock(Page::class)];
+
+ $this->repository
+ ->shouldReceive('findByParentId')
+ ->once()
+ ->with($pageId)
+ ->andReturn($children);
+
+ $this->model
+ ->shouldReceive('getId')
+ ->once()
+ ->andReturn($pageId);
+
+ $this->model
+ ->shouldReceive('save')
+ ->once();
+
+ foreach ($children as $i => $child) {
+ $child
+ ->shouldReceive('getId')
+ ->once()
+ ->andReturn($i);
+
+ $child
+ ->shouldReceive('save')
+ ->once();
+
+ $this->repository
+ ->shouldReceive('findByParentId')
+ ->once()
+ ->with($i)
+ ->andReturn(null);
+ }
+
+ $this->repository->recurse($this->model, function(Page $page) {
+ $page->save();
+ });
+ }
}
|
Page repository: Added recurse() method to apply a callable to every descendent page
|
boomcms_boom-core
|
train
|
142448b4c82a8ded42fe691e28468705bd7bdce6
|
diff --git a/plexapi/library.py b/plexapi/library.py
index <HASH>..<HASH> 100644
--- a/plexapi/library.py
+++ b/plexapi/library.py
@@ -350,7 +350,7 @@ class LibrarySection(PlexObject):
self.filters = data.attrib.get('filters')
self.key = data.attrib.get('key') # invalid key from plex
self.language = data.attrib.get('language')
- self.locations = self.findItems(data, etag='Location')
+ self.locations = self.listAttrs(data, 'path', etag='Location')
self.refreshing = utils.cast(bool, data.attrib.get('refreshing'))
self.scanner = data.attrib.get('scanner')
self.thumb = data.attrib.get('thumb')
|
return library.LibrarySection.locations to previous listAttrs that returns a str
|
pkkid_python-plexapi
|
train
|
7e88aa243ed3356655b3a86da42e4d5dffb2bf10
|
diff --git a/sqlparse/compat.py b/sqlparse/compat.py
index <HASH>..<HASH> 100644
--- a/sqlparse/compat.py
+++ b/sqlparse/compat.py
@@ -14,7 +14,7 @@ PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
- def u(s):
+ def u(s, encoding=None):
return str(s)
@@ -37,17 +37,3 @@ elif PY2:
text_type = unicode
string_types = (basestring,)
from StringIO import StringIO
-
-
-# Directly copied from six:
-def with_metaclass(meta, *bases):
- """Create a base class with a metaclass."""
-
- # This requires a bit of explanation: the basic idea is to make a dummy
- # metaclass for one level of class instantiation that replaces itself with
- # the actual metaclass.
- class metaclass(meta):
- def __new__(cls, name, this_bases, d):
- return meta(name, bases, d)
-
- return type.__new__(metaclass, 'temporary_class', (), {})
diff --git a/sqlparse/lexer.py b/sqlparse/lexer.py
index <HASH>..<HASH> 100644
--- a/sqlparse/lexer.py
+++ b/sqlparse/lexer.py
@@ -17,48 +17,29 @@ import sys
from sqlparse import tokens
from sqlparse.keywords import SQL_REGEX
-from sqlparse.compat import StringIO, string_types, with_metaclass, text_type
+from sqlparse.compat import StringIO, string_types, text_type
-class LexerMeta(type):
- """
- Metaclass for Lexer, creates the self._tokens attribute from
- self.tokens on the first instantiation.
- """
-
- def __call__(cls, *args):
- if not hasattr(cls, '_tokens'):
- cls._all_tokens = {}
- processed = cls._all_tokens[cls.__name__] = {}
-
- for state in SQL_REGEX:
- processed[state] = []
-
- for tdef in SQL_REGEX[state]:
- rex = re.compile(tdef[0], cls.flags).match
-
- if len(tdef) == 2:
- new_state = None
- else:
- # Only Multiline comments
- tdef2 = tdef[2]
- # an existing state
- if tdef2 == '#pop':
- new_state = -1
- elif tdef2 in SQL_REGEX:
- new_state = (tdef2,)
- processed[state].append((rex, tdef[1], new_state))
- cls._tokens = processed
- return type.__call__(cls, *args)
-
-
-class _Lexer(object):
-
+class Lexer(object):
encoding = 'utf-8'
flags = re.IGNORECASE | re.UNICODE
def __init__(self):
- self.filters = []
+ self._tokens = {}
+
+ for state in SQL_REGEX:
+ self._tokens[state] = []
+
+ for tdef in SQL_REGEX[state]:
+ rex = re.compile(tdef[0], self.flags).match
+ new_state = None
+ if len(tdef) > 2:
+ # Only Multiline comments
+ if tdef[2] == '#pop':
+ new_state = -1
+ elif tdef[2] in SQL_REGEX:
+ new_state = (tdef[2],)
+ self._tokens[state].append((rex, tdef[1], new_state))
def _decode(self, text):
if sys.version_info[0] == 3:
@@ -170,10 +151,6 @@ class _Lexer(object):
break
-class Lexer(with_metaclass(LexerMeta, _Lexer)):
- pass
-
-
def tokenize(sql, encoding=None):
"""Tokenize sql.
|
Bid Adieu to metaclass
The singleton pattern isn't applicable since only one language is being
implemented.
Simplify Lexer initialization.
Fix compat func `u` on Py3. Signature didn't match Py2.
Feature isn't used yet.
|
andialbrecht_sqlparse
|
train
|
3a2462cbeb5fee3cafcd885eeb10f2514f6d096b
|
diff --git a/core/src/main/java/org/testcontainers/images/ParsedDockerfile.java b/core/src/main/java/org/testcontainers/images/ParsedDockerfile.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/org/testcontainers/images/ParsedDockerfile.java
+++ b/core/src/main/java/org/testcontainers/images/ParsedDockerfile.java
@@ -21,7 +21,7 @@ import java.util.stream.Collectors;
@Slf4j
public class ParsedDockerfile {
- private static final Pattern FROM_LINE_PATTERN = Pattern.compile("FROM ([^\\s]+).*");
+ private static final Pattern FROM_LINE_PATTERN = Pattern.compile("FROM (?<arg>--[^\\s]+\\s)*(?<image>[^\\s]+).*", Pattern.CASE_INSENSITIVE);
private final Path dockerFilePath;
@@ -57,7 +57,7 @@ public class ParsedDockerfile {
dependencyImageNames = lines.stream()
.map(FROM_LINE_PATTERN::matcher)
.filter(Matcher::matches)
- .map(matcher -> matcher.group(1))
+ .map(matcher -> matcher.group("image"))
.collect(Collectors.toSet());
if (!dependencyImageNames.isEmpty()) {
diff --git a/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java b/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java
+++ b/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java
@@ -17,6 +17,12 @@ public class ParsedDockerfileTest {
}
@Test
+ public void isCaseInsensitive() {
+ final ParsedDockerfile parsedDockerfile = new ParsedDockerfile(asList("from someimage", "RUN something"));
+ assertEquals("extracts a single image name", Sets.newHashSet("someimage"), parsedDockerfile.getDependencyImageNames());
+ }
+
+ @Test
public void handlesTags() {
final ParsedDockerfile parsedDockerfile = new ParsedDockerfile(asList("FROM someimage:tag", "RUN something"));
assertEquals("retains tags in image names", Sets.newHashSet("someimage:tag"), parsedDockerfile.getDependencyImageNames());
@@ -41,6 +47,18 @@ public class ParsedDockerfileTest {
}
@Test
+ public void ignoringPlatformArgs() {
+ final ParsedDockerfile parsedDockerfile = new ParsedDockerfile(asList("FROM --platform=linux/amd64 someimage", "RUN something"));
+ assertEquals("ignores platform args", Sets.newHashSet("someimage"), parsedDockerfile.getDependencyImageNames());
+ }
+
+ @Test
+ public void ignoringExtraPlatformArgs() {
+ final ParsedDockerfile parsedDockerfile = new ParsedDockerfile(asList("FROM --platform=linux/amd64 --somethingelse=value someimage", "RUN something"));
+ assertEquals("ignores platform args", Sets.newHashSet("someimage"), parsedDockerfile.getDependencyImageNames());
+ }
+
+ @Test
public void handlesGracefullyIfNoFromLine() {
final ParsedDockerfile parsedDockerfile = new ParsedDockerfile(asList("RUN something", "# is this even a valid Dockerfile?"));
assertEquals("handles invalid Dockerfiles gracefully", Sets.newHashSet(), parsedDockerfile.getDependencyImageNames());
|
Ensure that ParsedDockerfile supports platform args (#<I>)
|
testcontainers_testcontainers-java
|
train
|
d4b3d5f09dfa8236ad879dc3f42a3493d0131f23
|
diff --git a/components/ngDroplet.js b/components/ngDroplet.js
index <HASH>..<HASH> 100644
--- a/components/ngDroplet.js
+++ b/components/ngDroplet.js
@@ -172,6 +172,14 @@
requestUrl: '',
/**
+ * Name of the file property in the request.
+ *
+ * @property fileProperty
+ * @type {String}
+ */
+ fileProperty: 'file',
+
+ /**
* Determines whether the X-File-Size header is appended to the request.
*
* @property disableXFileSize
@@ -594,7 +602,9 @@
var httpRequest = new $window.XMLHttpRequest(),
formData = new $window.FormData(),
queuedFiles = $scope.filterFiles($scope.FILE_TYPES.VALID),
- fileProperty = $scope.options.useArray ? 'file[]' : 'file',
+ fileProperty = $scope.options.useArray ?
+ $scope.options.fileProperty + '[]' :
+ $scope.options.fileProperty,
requestLength = $scope.getRequestLength(queuedFiles),
deferred = $q.defer();
@@ -837,6 +847,15 @@
},
/**
+ * @method setFileProperty
+ * @param name {String}
+ * @return {void}
+ */
+ setFileProperty: function setFileProperty(name) {
+ $scope.options.fileProperty = name;
+ },
+
+ /**
* @method setMaximumValidFiles
* @param value {Number}
* @return {void}
|
Custom property name
Let user assign other property name instead of 'file'
|
Wildhoney_ngDroplet
|
train
|
d01ec3d98fef40e322243babd8bf33083fecd1c4
|
diff --git a/examples/playSpotifyMusic.js b/examples/playSpotifyMusic.js
index <HASH>..<HASH> 100644
--- a/examples/playSpotifyMusic.js
+++ b/examples/playSpotifyMusic.js
@@ -23,11 +23,18 @@ sonos.setSpotifyRegion(Regions.EU)
// This assumes you have the Spotify music service connected to
// your Sonos system.
-var spotifyUri = 'spotify:artistTopTracks:72qVrKXRp9GeFQOesj0Pmv'
+// var spotifyUri = 'spotify:artistTopTracks:72qVrKXRp9GeFQOesj0Pmv'
+var spotifyUri = 'spotify:track:6sYJuVcEu4gFHmeTLdHzRz'
-sonos.play(spotifyUri).then(success => {
- console.log('Yeay')
-}).catch(err => { console.log('Error occurred %j', err) })
+sonos.play(spotifyUri)
+ .then(success => {
+ console.log('Yeay')
+ return sonos.currentTrack()
+ })
+ .then(track => {
+ console.log(JSON.stringify(track, null, 2))
+ })
+ .catch(err => { console.log('Error occurred %j', err) })
// This example plays curated artist radio on Spotify. The
// artistId is found in the same way as described above. The
|
chore: Updated Spotify sample
Fixes #<I> - You didn't specify the url correctly
|
bencevans_node-sonos
|
train
|
7eb18e5da14193c97d82d9d42c448fc319559736
|
diff --git a/src/pybel/manager/models.py b/src/pybel/manager/models.py
index <HASH>..<HASH> 100644
--- a/src/pybel/manager/models.py
+++ b/src/pybel/manager/models.py
@@ -857,9 +857,14 @@ class Edge(Base):
and edge data information.
:rtype: dict
"""
+ source_dict = self.source.to_json()
+ source_dict['sha512'] = source_dict.sha512
+ target_dict = self.target.to_json()
+ target_dict['sha512'] = target_dict.sha512
+
result = {
- 'source': self.source.to_json(),
- 'target': self.target.to_json(),
+ 'source': source_dict,
+ 'target': target_dict,
'key': self.sha512,
'data': json.loads(self.data),
}
|
Add sha<I> to json of edges' nodes
|
pybel_pybel
|
train
|
5ad4cd6b72782a6f7e6033e2f609515ef4bbbd8a
|
diff --git a/pkg/scheduler/algorithm/predicates/metadata.go b/pkg/scheduler/algorithm/predicates/metadata.go
index <HASH>..<HASH> 100644
--- a/pkg/scheduler/algorithm/predicates/metadata.go
+++ b/pkg/scheduler/algorithm/predicates/metadata.go
@@ -389,6 +389,8 @@ func getTPMapMatchingExistingAntiAffinity(pod *v1.Pod, nodeInfoMap map[string]*s
}
}
+ ctx, cancel := context.WithCancel(context.Background())
+
processNode := func(i int) {
nodeInfo := nodeInfoMap[allNodeNames[i]]
node := nodeInfo.Node()
@@ -400,12 +402,13 @@ func getTPMapMatchingExistingAntiAffinity(pod *v1.Pod, nodeInfoMap map[string]*s
existingPodTopologyMaps, err := getMatchingAntiAffinityTopologyPairsOfPod(pod, existingPod, node)
if err != nil {
catchError(err)
+ cancel()
return
}
appendTopologyPairsMaps(existingPodTopologyMaps)
}
}
- workqueue.ParallelizeUntil(context.TODO(), 16, len(allNodeNames), processNode)
+ workqueue.ParallelizeUntil(ctx, 16, len(allNodeNames), processNode)
return topologyMaps, firstError
}
@@ -454,6 +457,8 @@ func getTPMapMatchingIncomingAffinityAntiAffinity(pod *v1.Pod, nodeInfoMap map[s
}
antiAffinityTerms := GetPodAntiAffinityTerms(affinity.PodAntiAffinity)
+ ctx, cancel := context.WithCancel(context.Background())
+
processNode := func(i int) {
nodeInfo := nodeInfoMap[allNodeNames[i]]
node := nodeInfo.Node()
@@ -479,6 +484,7 @@ func getTPMapMatchingIncomingAffinityAntiAffinity(pod *v1.Pod, nodeInfoMap map[s
selector, err := metav1.LabelSelectorAsSelector(term.LabelSelector)
if err != nil {
catchError(err)
+ cancel()
return
}
if priorityutil.PodMatchesTermsNamespaceAndSelector(existingPod, namespaces, selector) {
@@ -493,7 +499,7 @@ func getTPMapMatchingIncomingAffinityAntiAffinity(pod *v1.Pod, nodeInfoMap map[s
appendResult(node.Name, nodeTopologyPairsAffinityPodsMaps, nodeTopologyPairsAntiAffinityPodsMaps)
}
}
- workqueue.ParallelizeUntil(context.TODO(), 16, len(allNodeNames), processNode)
+ workqueue.ParallelizeUntil(ctx, 16, len(allNodeNames), processNode)
return topologyPairsAffinityPodsMaps, topologyPairsAntiAffinityPodsMaps, firstError
}
|
Cancel processing node if error occurs when getting affinity and antiaffinity
|
kubernetes_kubernetes
|
train
|
371bb39c5c23bb766f391974ea024219a5941fe8
|
diff --git a/CHANGELOG.asciidoc b/CHANGELOG.asciidoc
index <HASH>..<HASH> 100644
--- a/CHANGELOG.asciidoc
+++ b/CHANGELOG.asciidoc
@@ -27,6 +27,7 @@ TinkerPop 3.1.5 (Release Date: NOT OFFICIALLY RELEASED YET)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Removed the `appveyor.yml` file as the AppVeyor build is no longer enabled by Apache Infrastructure.
+* Fixed TinkerGraph which was not saving on `close()` if the path only consisted of the file name.
* Fixed a bug in `RangeByIsCountStrategy` which didn't use the `NotStep` properly.
[[release-3-1-4]]
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
index <HASH>..<HASH> 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
@@ -299,7 +299,9 @@ public final class TinkerGraph implements Graph {
f.delete();
} else {
final File parent = f.getParentFile();
- if (!parent.exists()) {
+
+ // the parent would be null in the case of an relative path if the graphLocation was simply: "f.gryo"
+ if (parent != null && !parent.exists()) {
parent.mkdirs();
}
}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraphTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraphTest.java
index <HASH>..<HASH> 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraphTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraphTest.java
@@ -440,6 +440,28 @@ public class TinkerGraphTest {
}
@Test
+ public void shouldPersistWithRelativePath() {
+ final String graphLocation = "shouldPersistToGryoRelative.kryo";
+ final File f = new File(graphLocation);
+ if (f.exists() && f.isFile()) f.delete();
+
+ try {
+ final Configuration conf = new BaseConfiguration();
+ conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
+ conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, graphLocation);
+ final TinkerGraph graph = TinkerGraph.open(conf);
+ TinkerFactory.generateModern(graph);
+ graph.close();
+
+ final TinkerGraph reloadedGraph = TinkerGraph.open(conf);
+ IoTest.assertModernGraph(reloadedGraph, true, false);
+ reloadedGraph.close();
+ } catch (Exception ex) {
+ if (f.exists() && f.isFile()) f.delete();
+ }
+ }
+
+ @Test
public void shouldPersistToAnyGraphFormat() {
final String graphLocation = TestHelper.makeTestDataDirectory(TinkerGraphTest.class) + "shouldPersistToAnyGraphFormat.dat";
final File f = new File(graphLocation);
|
TinkerGraph's would not save on close()
if the path was just a file name. Tested "just a file name" manually and added a test for relative paths - didn't want to generate test data outside of our test directories. TINKERPOP-<I>
|
apache_tinkerpop
|
train
|
a3e0db39f83ffdb23e9b24f1bee21bf56680cac1
|
diff --git a/neuroanalysis/base.py b/neuroanalysis/base.py
index <HASH>..<HASH> 100644
--- a/neuroanalysis/base.py
+++ b/neuroanalysis/base.py
@@ -320,30 +320,8 @@ class AcquiredFile(BaseFile):
super(AcquiredFile, self).__init__(name, file_format)
self._filename = filename
- def map_filename(self, name_map):
- """
- Returns a copy of the AcquiredFile with the filename mapped
-
- Parameters
- ----------
- name_map : Dict[str, str]
- Mapping from AcquiredFile name (Note: different types of files are,
- assigned fixed names (e.g. dMRI acquisition -> 'diffusion')
- to the saved filename
- """
- if self.name not in name_map:
- raise NeuroAnalysisError(
- "File name '{}' was not in provided name map ({})"
- .format(self.name, name_map))
- cpy = copy(self)
- cpy._filename = name_map[self.name]
- return cpy
-
@property
- def filename(self): # @UnusedVariable
- if self._filename is None:
- raise NeuroAnalysisError(
- "Filename mapping has not been set. See 'map_filename' method")
+ def filename(self):
return self._filename
@property
@@ -362,7 +340,7 @@ class ProcessedFile(BaseFile):
return self._options
@property
- def filename(self): # @UnusedVariable
+ def filename(self):
return "{}{}.{}".format(
self._name, ''.join('__{}={}'.format(n, v)
for n, v in self._options.iteritems()),
|
more cleaning up of acquired file filenames
|
MonashBI_arcana
|
train
|
35238eb776b64abc2fb64df0acdb2a28a9abd92c
|
diff --git a/gubernator/main.py b/gubernator/main.py
index <HASH>..<HASH> 100644
--- a/gubernator/main.py
+++ b/gubernator/main.py
@@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import os
import yaml
import webapp2
@@ -39,7 +40,7 @@ config = {
'secret_key': None, # filled in on the first request
'cookie_args': {
# we don't have SSL For local development
- 'secure': hostname and 'appspot.com' in hostname,
+ 'secure': os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'),
'httponly': True,
},
},
|
gubernator: require secure session cookies on k8s.io too
|
kubernetes_test-infra
|
train
|
401b41eda2e1c18f1a6c3ec3bc01de89a4fce61f
|
diff --git a/lib/PostCollection.php b/lib/PostCollection.php
index <HASH>..<HASH> 100644
--- a/lib/PostCollection.php
+++ b/lib/PostCollection.php
@@ -93,3 +93,6 @@ class PostsIterator extends \ArrayIterator {
return $post;
}
}
+
+class_alias('Timber\PostCollection', 'Timber\PostsCollection');
+class_alias('Timber\PostCollection', 'TimberPostsCollection');
diff --git a/readme.txt b/readme.txt
index <HASH>..<HASH> 100644
--- a/readme.txt
+++ b/readme.txt
@@ -41,6 +41,9 @@ Timber is great for any WordPress developer who cares about writing good, mainta
== Changelog ==
+= 1.1.7.1 =
+* Quick fix for backwards compaiblity in some situations
+
= 1.1.7 =
* A new PostQuery object that comes _with_ pagination (thanks @lggorman).
* You can pass an array of post types to `post.children()` (thanks @njbarrett)
diff --git a/tests/test-timber-post-collection.php b/tests/test-timber-post-collection.php
index <HASH>..<HASH> 100644
--- a/tests/test-timber-post-collection.php
+++ b/tests/test-timber-post-collection.php
@@ -9,6 +9,11 @@ class TestTimberPostQuery extends Timber_UnitTestCase {
parent::setUp();
}
+ function testBackwards() {
+ $pc = new TimberPostsCollection();
+ $pc = new Timber\PostsCollection();
+ }
+
function testBasicCollection() {
$pids = $this->factory->post->create_many(10);
$pc = new Timber\PostQuery('post_type=post&numberposts=6');
|
Created aliases for renamed classes
|
timber_timber
|
train
|
dcc8496dbc94391e2d984f0182d1412a257a3e46
|
diff --git a/lib/getFiltersAndTargetContentTypeFromQueryString.js b/lib/getFiltersAndTargetContentTypeFromQueryString.js
index <HASH>..<HASH> 100644
--- a/lib/getFiltersAndTargetContentTypeFromQueryString.js
+++ b/lib/getFiltersAndTargetContentTypeFromQueryString.js
@@ -19,7 +19,7 @@ Object.keys(gm.prototype).forEach(function (propertyName) {
}
});
-module.exports = function getFiltersAndTargetContentTypeFromQueryString(queryString, sourceFilePath, rootPath) {
+module.exports = function getFiltersAndTargetContentTypeFromQueryString(queryString, rootPath, sourceFilePath) {
var filters = [],
gmOperations = [],
operationNames = [],
diff --git a/lib/processImage.js b/lib/processImage.js
index <HASH>..<HASH> 100644
--- a/lib/processImage.js
+++ b/lib/processImage.js
@@ -25,7 +25,7 @@ module.exports = function (options) {
res.hijack(function (err, res) {
var contentType = res.getHeader('Content-Type');
if (contentType && contentType.indexOf('image/') === 0) {
- var filtersAndTargetFormat = getFiltersAndTargetContentTypeFromQueryString(queryString, options.root, Path.resolve(options.root, req.url)),
+ var filtersAndTargetFormat = getFiltersAndTargetContentTypeFromQueryString(queryString, options.root, Path.resolve(options.root, req.url.substr(1))),
filters = filtersAndTargetFormat.filters,
targetContentType = filtersAndTargetFormat.targetContentType;
if (!filtersAndTargetFormat.filters.length > 0) {
|
Fixed the SvgFilter arguments (external --runScript was broken for files not residing at the root level).
|
papandreou_express-processimage
|
train
|
43cda7148cb37b4e5ff2ee3c37de031088ae9217
|
diff --git a/shared/chat/conversation/list/index.native.js b/shared/chat/conversation/list/index.native.js
index <HASH>..<HASH> 100644
--- a/shared/chat/conversation/list/index.native.js
+++ b/shared/chat/conversation/list/index.native.js
@@ -90,9 +90,8 @@ const verticallyInvertedStyle = {
}
// Reverse the order of messageKeys to compensate for vertically reversed display
-const withReversedMessageKeys = withPropsOnChange(['messageKeys'], ({messageKeys, ...rest}) => ({
+const withReversedMessageKeys = withPropsOnChange(['messageKeys'], ({messageKeys}) => ({
messageKeys: messageKeys.reverse(),
- ...rest,
}))
export default withReversedMessageKeys(ConversationList)
|
Fix HoC to not cache props other than messageKeys (#<I>)
|
keybase_client
|
train
|
7800353bf96c724cad33a35d759eeaff29b1e902
|
diff --git a/ravendb/tests/jvm_migrated_tests/client_tests/test_custom_entity_name.py b/ravendb/tests/jvm_migrated_tests/client_tests/test_custom_entity_name.py
index <HASH>..<HASH> 100644
--- a/ravendb/tests/jvm_migrated_tests/client_tests/test_custom_entity_name.py
+++ b/ravendb/tests/jvm_migrated_tests/client_tests/test_custom_entity_name.py
@@ -1,3 +1,4 @@
+import logging
from typing import List
from ravendb.documents.conventions.document_conventions import DocumentConventions
@@ -89,6 +90,7 @@ class TestCustomEntityName(TestBase):
return basic_chars + special_chars
def test_find_collection_name(self):
+ logging.getLogger("QueryOperation").disabled = True
for c in self.__get_characters_to_test_with_special():
self.__test_when_collection_and_id_contain_special_chars(c)
|
RDBC-<I> Mute annoying logger on find collection name test
|
ravendb_ravendb-python-client
|
train
|
e67ce2fd171bad4cec76a4d687903b202915b1d2
|
diff --git a/calendar-bundle/contao/dca/tl_calendar.php b/calendar-bundle/contao/dca/tl_calendar.php
index <HASH>..<HASH> 100644
--- a/calendar-bundle/contao/dca/tl_calendar.php
+++ b/calendar-bundle/contao/dca/tl_calendar.php
@@ -156,7 +156,7 @@ $GLOBALS['TL_DCA']['tl_calendar'] = array
'exclude' => true,
'inputType' => 'pageTree',
'foreignKey' => 'tl_page.title',
- 'eval' => array('fieldType'=>'radio'),
+ 'eval' => array('mandatory'=>true, 'fieldType'=>'radio'),
'sql' => "int(10) unsigned NOT NULL default '0'",
'relation' => array('type'=>'hasOne', 'load'=>'eager')
),
diff --git a/calendar-bundle/contao/dca/tl_calendar_events.php b/calendar-bundle/contao/dca/tl_calendar_events.php
index <HASH>..<HASH> 100644
--- a/calendar-bundle/contao/dca/tl_calendar_events.php
+++ b/calendar-bundle/contao/dca/tl_calendar_events.php
@@ -421,7 +421,7 @@ $GLOBALS['TL_DCA']['tl_calendar_events'] = array
'exclude' => true,
'inputType' => 'pageTree',
'foreignKey' => 'tl_page.title',
- 'eval' => array('fieldType'=>'radio'),
+ 'eval' => array('mandatory'=>true, 'fieldType'=>'radio'),
'sql' => "int(10) unsigned NOT NULL default '0'",
'relation' => array('type'=>'belongsTo', 'load'=>'lazy')
),
|
[Calendar] Make eagerly loaded "pageTree" fields mandatory again (see #<I>)
|
contao_contao
|
train
|
1503902275de6e39f31cd36c19e85224c9ff2e41
|
diff --git a/src/I18n.js b/src/I18n.js
index <HASH>..<HASH> 100644
--- a/src/I18n.js
+++ b/src/I18n.js
@@ -9,7 +9,7 @@ export default class I18n extends Component {
super(props, context);
this.i18n = props.i18n || context.i18n || getI18n();
- this.namespaces = this.props.ns || (this.i18n.options && this.i18n.options.defaultNS);
+ this.namespaces = props.ns || (this.i18n.options && this.i18n.options.defaultNS);
if (typeof this.namespaces === 'string') this.namespaces = [this.namespaces];
const i18nOptions = (this.i18n && this.i18n.options && this.i18n.options.react) || {};
|
Fix reference to props in constructor
In <=IE<I>, `this.props` is null, so when attempting to set the namespaces,
the reference to `this.props.ns` raises an exception. By updating the
reference to use the version passed into the constructor, we are
consistent with other usages of props on the constructor, and I've
confirmed this patch works in <=IE<I> as well.
|
i18next_react-i18next
|
train
|
ecc62210ea59422034081ef55509d45069e04959
|
diff --git a/src/templates/c3/CategoryChart.html.php b/src/templates/c3/CategoryChart.html.php
index <HASH>..<HASH> 100644
--- a/src/templates/c3/CategoryChart.html.php
+++ b/src/templates/c3/CategoryChart.html.php
@@ -80,7 +80,7 @@
data.groups.push(group);
<?php endforeach ?>
- c3.generate({
+ var chart = c3.generate({
bindto: '#<?php echo $chartId ?>',
grid: {
x: {
@@ -93,5 +93,6 @@
axis: axis,
data: data
});
+ $('#<?php echo $chartId ?>').data('c3-chart', chart);
})();
</script>
diff --git a/src/templates/c3/Chart.html.php b/src/templates/c3/Chart.html.php
index <HASH>..<HASH> 100644
--- a/src/templates/c3/Chart.html.php
+++ b/src/templates/c3/Chart.html.php
@@ -83,7 +83,7 @@
data.groups.push(group);
<?php endforeach ?>
- c3.generate({
+ var chart = c3.generate({
bindto: '#<?php echo $chartId ?>',
grid: {
x: {
@@ -96,5 +96,6 @@
axis: axis,
data: data
});
+ $('#<?php echo $chartId ?>').data('c3-chart', chart);
})();
</script>
diff --git a/src/templates/c3/DateChart.html.php b/src/templates/c3/DateChart.html.php
index <HASH>..<HASH> 100644
--- a/src/templates/c3/DateChart.html.php
+++ b/src/templates/c3/DateChart.html.php
@@ -99,7 +99,7 @@
data.groups.push(group);
<?php endforeach ?>
- c3.generate({
+ var chart = c3.generate({
bindto: '#<?php echo $chartId ?>',
grid: {
x: {
@@ -112,5 +112,6 @@
axis: axis,
data: data
});
+ $('#<?php echo $chartId ?>').data('c3-chart', chart);
})();
</script>
diff --git a/src/templates/c3/DonutChart.html.php b/src/templates/c3/DonutChart.html.php
index <HASH>..<HASH> 100644
--- a/src/templates/c3/DonutChart.html.php
+++ b/src/templates/c3/DonutChart.html.php
@@ -50,11 +50,12 @@
data.columns.push(column);
<?php endforeach ?>
- c3.generate({
+ var chart = c3.generate({
bindto: '#<?php echo $chartId ?>',
data: data,
donut: donut
});
+ $('#<?php echo $chartId ?>').data('c3-chart', chart);
})();
</script>
<?php endif ?>
diff --git a/src/templates/c3/PieChart.html.php b/src/templates/c3/PieChart.html.php
index <HASH>..<HASH> 100644
--- a/src/templates/c3/PieChart.html.php
+++ b/src/templates/c3/PieChart.html.php
@@ -48,11 +48,12 @@
data.columns.push(column);
<?php endforeach ?>
- c3.generate({
+ var chart = c3.generate({
bindto: '#<?php echo $chartId ?>',
data: data,
pie: pie
});
+ $('#<?php echo $chartId ?>').data('c3-chart', chart);
})();
</script>
<?php endif ?>
|
feature: save chart reference to DOM for future usage
|
tlapnet_chart
|
train
|
90581c607b7cbf4359fa1b5cadc5a7f31a9cfaf2
|
diff --git a/networkapiclient/ClientFactory.py b/networkapiclient/ClientFactory.py
index <HASH>..<HASH> 100755
--- a/networkapiclient/ClientFactory.py
+++ b/networkapiclient/ClientFactory.py
@@ -55,6 +55,8 @@ from networkapiclient.OptionPool import OptionPool
from networkapiclient.Healthcheck import Healthcheck
from networkapiclient.ApiVipRequest import ApiVipRequest
from networkapiclient.ApiInterface import ApiInterfaceRequest
+from networkapiclient.ApiNetworkIPv4 import ApiNetworkIPv4
+from networkapiclient.ApiNetworkIPv6 import ApiNetworkIPv6
from networkapiclient.Rack import Rack
from networkapiclient.RackServers import RackServers
@@ -409,6 +411,27 @@ class ClientFactory(object):
self.user_ldap
)
+ def create_api_network_ipv4(self):
+
+ """Get an instance of Api Networkv4 services facade."""
+
+ return ApiNetworkIPv4(
+ self.networkapi_url,
+ self.user,
+ self.password,
+ self.user_ldap
+ )
+
+ def create_api_network_ipv6(self):
+
+ """Get an instance of Api Networkv6 services facade."""
+
+ return ApiNetworkIPv6(
+ self.networkapi_url,
+ self.user,
+ self.password,
+ self.user_ldap
+ )
def create_rack(self):
"""Get an instance of rack services facade."""
diff --git a/networkapiclient/Network.py b/networkapiclient/Network.py
index <HASH>..<HASH> 100644
--- a/networkapiclient/Network.py
+++ b/networkapiclient/Network.py
@@ -626,9 +626,9 @@ class DHCPRelayIPv4(ApiGenericClient):
uri = "api/dhcprelayv4/?"
if networkipv4:
- uri += "networkipv4=%d&" % networkipv4
+ uri += "networkipv4=%s&" % networkipv4
if ipv4:
- uri += "ipv4=%d" % ipv4
+ uri += "ipv4=%s" % ipv4
return self.get(uri)
@@ -753,9 +753,9 @@ class DHCPRelayIPv6(ApiGenericClient):
uri = "api/dhcprelayv6/?"
if networkipv6:
- uri += "networkipv6=%d&" % networkipv6
+ uri += "networkipv6=%s&" % networkipv6
if ipv6:
- uri += "ipv6=%d" % ipv6
+ uri += "ipv6=%s" % ipv6
return self.get(uri)
diff --git a/networkapiclient/__init__.py b/networkapiclient/__init__.py
index <HASH>..<HASH> 100644
--- a/networkapiclient/__init__.py
+++ b/networkapiclient/__init__.py
@@ -16,6 +16,6 @@
MAJOR_VERSION = '0'
MINOR_VERSION = '6'
-PATCH_VERSION = '7'
+PATCH_VERSION = '8'
VERSION = '.'.join((MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION,))
diff --git a/networkapiclient/version_control.py b/networkapiclient/version_control.py
index <HASH>..<HASH> 100755
--- a/networkapiclient/version_control.py
+++ b/networkapiclient/version_control.py
@@ -1 +1 @@
-CLIENT_VERSION = '0.6.7'
+CLIENT_VERSION = '0.6.8'
|
create class/methods to list and [un]deploy IPv4 and IPv6 networks with for API requests
|
globocom_GloboNetworkAPI-client-python
|
train
|
b6fe51ab7dfc58677b6d40f5014b3bf920e2394e
|
diff --git a/lib/cinch/timer.rb b/lib/cinch/timer.rb
index <HASH>..<HASH> 100644
--- a/lib/cinch/timer.rb
+++ b/lib/cinch/timer.rb
@@ -23,6 +23,9 @@ module Cinch
alias_method :threaded?, :threaded
alias_method :started?, :started
+ # @api private
+ attr_reader :thread_group
+
# @param [Bot] bot The instance of {Bot} the timer is associated
# with
# @option options [Number] :interval The interval (in seconds) of
@@ -43,7 +46,7 @@ module Cinch
@block = block
@started = false
- @thread = nil
+ @thread_group = ThreadGroup.new
end
# @return [Boolean]
@@ -57,7 +60,7 @@ module Cinch
def start
@shots = @orig_shots
- @thread = Thread.new do
+ @thread_group.add Thread.new {
while @shots > 0 do
sleep @interval
if threaded?
@@ -74,7 +77,7 @@ module Cinch
@shots -= 1
end
- end
+ }
@started = true
end
@@ -83,7 +86,7 @@ module Cinch
#
# @return [void]
def stop
- @thread.kill
+ @thread_group.list.each { |thread| thread.kill }
@started = false
end
end
|
use a ThreadGroup in Timer
|
cinchrb_cinch
|
train
|
8da0ddadded61e5dcea6c957d9b0819db534a788
|
diff --git a/tests/test_oggflac.py b/tests/test_oggflac.py
index <HASH>..<HASH> 100644
--- a/tests/test_oggflac.py
+++ b/tests/test_oggflac.py
@@ -1,5 +1,6 @@
import os
import shutil
+import sys
from tempfile import mkstemp
@@ -27,16 +28,23 @@ class TOggFLAC(TOggVorbis):
def test_vorbiscomment(self):
self.audio.save()
- self.failIf(os.system("flac --ogg -t %s 2> /dev/null" % self.filename))
+ badval = os.system("tools/notarealprogram 2> /dev/null")
+ value = os.system("flac --ogg -t %s 2> /dev/null" % self.filename)
+ self.failIf(value and value != badval)
+ if value == badval:
+ sys.stdout.write("\bS")
+ return
self.test_really_big()
self.audio.save()
- self.failIf(os.system("flac --ogg -t %s 2> /dev/null" % self.filename))
+ value = os.system("flac --ogg -t %s 2> /dev/null" % self.filename)
+ self.failIf(value and value != badval)
self.audio.delete()
self.audio["foobar"] = "foobar" * 1000
self.audio.save()
- self.failIf(os.system("flac --ogg -t %s 2> /dev/null" % self.filename))
+ value = os.system("flac --ogg -t %s 2> /dev/null" % self.filename)
+ self.failIf(value and value != badval)
def test_huge_tag(self):
pass
diff --git a/tests/test_oggvorbis.py b/tests/test_oggvorbis.py
index <HASH>..<HASH> 100644
--- a/tests/test_oggvorbis.py
+++ b/tests/test_oggvorbis.py
@@ -1,5 +1,6 @@
import os
import shutil
+import sys
from mutagen.oggvorbis import OggVorbis
from tests import TestCase, registerCase
from tempfile import mkstemp
@@ -120,7 +121,6 @@ class TOggVorbis(TestCase):
try: import ogg.vorbis
except ImportError:
- print "WARNING: Disabling pyvorbis crosscheck."
- del(TOggVorbis.test_vorbiscomment)
+ TOggVorbis.test_vorbiscomment = lambda self: sys.stdout.write("\bS")
registerCase(TOggVorbis)
|
TOggFLAC, TOggVorbis: Skip more quietly when required tools are missing. (Closes: #<I>)
|
quodlibet_mutagen
|
train
|
891b09a1246878ff97c87f7bd6b968b5eaf05e23
|
diff --git a/lib/record_cache/base.rb b/lib/record_cache/base.rb
index <HASH>..<HASH> 100644
--- a/lib/record_cache/base.rb
+++ b/lib/record_cache/base.rb
@@ -121,6 +121,10 @@ module RecordCache
@rc_dispatcher = RecordCache::Dispatcher.new(self)
# Callback for Data Store specific initialization
record_cache_init
+
+ class << self
+ alias_method_chain :inherited, :record_cache
+ end
end
# parse the requested strategies from the given options
@rc_dispatcher.parse(options)
@@ -128,13 +132,22 @@ module RecordCache
# Returns true if record cache is defined and active for this class
def record_cache?
- record_cache && RecordCache::Base.status == RecordCache::ENABLED
+ record_cache && record_cache.instance_variable_get('@base') == self && RecordCache::Base.status == RecordCache::ENABLED
end
# Returns the RecordCache (class) instance
def record_cache
@rc_dispatcher
end
+
+ def inherited_with_record_cache(subclass)
+ class << subclass
+ def record_cache
+ self.superclass.record_cache
+ end
+ end
+ inherited_without_record_cache(subclass)
+ end
end
module InstanceMethods
diff --git a/lib/record_cache/strategy/unique_index_cache.rb b/lib/record_cache/strategy/unique_index_cache.rb
index <HASH>..<HASH> 100644
--- a/lib/record_cache/strategy/unique_index_cache.rb
+++ b/lib/record_cache/strategy/unique_index_cache.rb
@@ -87,6 +87,10 @@ module RecordCache
def from_cache(id_to_versioned_key_map)
records = record_store.read_multi(*(id_to_versioned_key_map.values)).values.compact
records.map{ |record| Util.deserialize(record) }
+ records.map do |record|
+ record = Util.deserialize(record)
+ record.becomes(self.instance_variable_get('@base'))
+ end
end
# retrieve the records with the given ids from the database
|
Expire subclassed models correctly
We have cached models that are subclassed.
If an update happens on the subclassed record,
we need to expire the parent's cache.
|
orslumen_record-cache
|
train
|
0475d65f9428705e461eca01779960210c690e63
|
diff --git a/lib/graph/index.js b/lib/graph/index.js
index <HASH>..<HASH> 100644
--- a/lib/graph/index.js
+++ b/lib/graph/index.js
@@ -474,7 +474,7 @@ NetworkGraph.prototype.apply2DOffsets = function(transitive) {
for(var axisId in axisBundles) {
var segments = axisBundles[axisId];
- var lw = 10;
+ var lw = 1.2;
var bundleWidth = lw * (segments.length - 1);
var sortedSegments = segments.concat().sort(bundleSorter);
diff --git a/lib/segment.js b/lib/segment.js
index <HASH>..<HASH> 100644
--- a/lib/segment.js
+++ b/lib/segment.js
@@ -177,14 +177,13 @@ Segment.prototype.draw = function(display, capExtension) {
.data([ this ]);
};
+
+
/**
* Refresh
*/
-Segment.prototype.refresh = function(display, styler) {
- // compute the line width
- var lw = styler.compute(styler.segments['stroke-width'], display, this);
- this.lineWidth = parseFloat(lw.substring(0, lw.length - 2), 10) - 2;
+Segment.prototype.refresh = function() {
// update the line
if(!this.renderData || this.renderData.length === 0) return;
@@ -192,11 +191,17 @@ Segment.prototype.refresh = function(display, styler) {
};
-Segment.prototype.refreshRenderData = function(updatePoints) {
+Segment.prototype.refreshRenderData = function(updatePoints, styler, display) {
this.renderData = [];
var pointIndex = 0;
+ if(styler && display) {
+ // compute the line width
+ var lw = styler.compute(styler.segments['stroke-width'], display, this);
+ this.lineWidth = parseFloat(lw.substring(0, lw.length - 2), 10) - 2;
+ }
+
this.graphEdges.forEach(function(edge, edgeIndex) {
var edgeRenderData = [];
@@ -206,13 +211,13 @@ Segment.prototype.refreshRenderData = function(updatePoints) {
var fromOffsetX = 0, fromOffsetY = 0, toOffsetX = 0, toOffsetY = 0;
if(edge in this.edgeFromOffsets) {
- var fromOffset = this.edgeFromOffsets[edge];
+ var fromOffset = this.edgeFromOffsets[edge] * this.lineWidth;
fromOffsetX = fromOffset * edge.fromRightVector.x;
fromOffsetY = fromOffset * edge.fromRightVector.y;
}
if(edge in this.edgeToOffsets) {
- var toOffset = this.edgeToOffsets[edge];
+ var toOffset = this.edgeToOffsets[edge] * this.lineWidth;
toOffsetX = toOffset * edge.toRightVector.x;
toOffsetY = toOffset * edge.toRightVector.y;
}
@@ -233,7 +238,7 @@ Segment.prototype.refreshRenderData = function(updatePoints) {
};
edgeRenderData.push(pointInfo);
-
+
if(updatePoints) edge.fromVertex.point.addRenderData(pointInfo);
diff --git a/lib/transitive.js b/lib/transitive.js
index <HASH>..<HASH> 100644
--- a/lib/transitive.js
+++ b/lib/transitive.js
@@ -292,7 +292,7 @@ Transitive.prototype.render = function() {
// draw the segments
for(var s = 0; s < this.renderSegments.length; s++) {
var segment = this.renderSegments[s];
- segment.refreshRenderData(true);
+ segment.refreshRenderData(true, this.style, this.display);
segment.draw(this.display, 0); // 10);
}
@@ -358,8 +358,8 @@ Transitive.prototype.refresh = function() {
// refresh the segments
for(var s = 0; s < this.renderSegments.length; s++) {
var segment = this.renderSegments[s];
- segment.refreshRenderData(true);
- segment.refresh(this.display, this.style);
+ segment.refreshRenderData(true, this.style, this.display);
+ segment.refresh();
this.style.renderSegment(this.display, segment.lineGraph);
}
|
base line offset on dynamic line widths
|
conveyal_transitive.js
|
train
|
e52fce20bdcad4afbbfc766f86c168c6654a4e06
|
diff --git a/validator/sawtooth_validator/scheduler/serial.py b/validator/sawtooth_validator/scheduler/serial.py
index <HASH>..<HASH> 100644
--- a/validator/sawtooth_validator/scheduler/serial.py
+++ b/validator/sawtooth_validator/scheduler/serial.py
@@ -71,7 +71,7 @@ class SerialScheduler(Scheduler):
if (self._in_progress_transaction is None or
self._in_progress_transaction != transaction_signature):
raise ValueError("transaction not in progress: {}",
- transaction_signature)
+ transaction_signature)
self._in_progress_transaction = None
def finalize(self):
diff --git a/validator/sawtooth_validator/server/journal.py b/validator/sawtooth_validator/server/journal.py
index <HASH>..<HASH> 100644
--- a/validator/sawtooth_validator/server/journal.py
+++ b/validator/sawtooth_validator/server/journal.py
@@ -35,4 +35,4 @@ class FauxJournal(object):
return _handler
def on_batch_received(self, batch):
- self._scheduler.add_batch(batch)
\ No newline at end of file
+ self._scheduler.add_batch(batch)
diff --git a/validator/tests/unit3/test_scheduler.py b/validator/tests/unit3/test_scheduler.py
index <HASH>..<HASH> 100644
--- a/validator/tests/unit3/test_scheduler.py
+++ b/validator/tests/unit3/test_scheduler.py
@@ -22,6 +22,7 @@ from sawtooth_validator.scheduler.serial import SerialScheduler
import sawtooth_validator.protobuf.batch_pb2 as batch_pb2
import sawtooth_validator.protobuf.transaction_pb2 as transaction_pb2
+
def create_transaction(name, private_key, public_key):
payload = name
addr = '000000' + hashlib.sha512(name.encode()).hexdigest()
|
Fix lint in scheduler and tests
|
hyperledger_sawtooth-core
|
train
|
379d3230ede7c8f77460174a3717b406110d2f33
|
diff --git a/abydos/corpus.py b/abydos/corpus.py
index <HASH>..<HASH> 100644
--- a/abydos/corpus.py
+++ b/abydos/corpus.py
@@ -30,22 +30,27 @@ class Corpus(object):
sentences; each sentence is an ordered list of words that make up the
sentence.
"""
- corpus = []
-
- def __init__(self, corpus_text='', filter_chars=''):
+ def __init__(self, corpus_text='', filter_chars='', stop_words=[]):
"""Corpus initializer
corpus_text -- The corpus text as a single string
filter_chars -- A list of characters (as a string, tuple, set, or list)
- to filter out of the corpus text.
+ to filter out of the corpus text
+ stop_words -- A list of words (as a tuple, set, or list) to filter out
+ of the corpus text
When importing a corpus, newlines divide sentences and other whitespace
divides words.
"""
- for char in set(filter_chars):
- if char in corpus_text:
- corpus_text = corpus_text.replace(char, '')
+ self.corpus = []
+
+ for sentence in [s.split() for s in corpus_text.splitlines()]:
+ for sw in set(stop_words):
+ if sw in sentence:
+ sentence.remove(sw)
+ for char in set(filter_chars):
+ sentence = [w.replace(char, '') for w in sentence]
+ self.corpus.append(sentence)
- self.corpus = [s.split() for s in corpus_text.splitlines()]
while [] in self.corpus:
self.corpus.remove([])
|
added stopword removal option; moved the corpus data into an instance variable
|
chrislit_abydos
|
train
|
27f1f5b792f60c7a8b31666cb3032624829e76f5
|
diff --git a/core/server/server.js b/core/server/server.js
index <HASH>..<HASH> 100644
--- a/core/server/server.js
+++ b/core/server/server.js
@@ -91,6 +91,7 @@ const privateConfigSchema = Joi.object({
azure_devops_token: Joi.string(),
bintray_user: Joi.string(),
bintray_apikey: Joi.string(),
+ drone_token: Joi.string(),
gh_client_id: Joi.string(),
gh_client_secret: Joi.string(),
gh_token: Joi.string(),
@@ -108,6 +109,8 @@ const privateConfigSchema = Joi.object({
sl_insight_userUuid: Joi.string(),
sl_insight_apiToken: Joi.string(),
sonarqube_token: Joi.string(),
+ teamcity_user: Joi.string(),
+ teamcity_pass: Joi.string(),
twitch_client_id: Joi.string(),
twitch_client_secret: Joi.string(),
wheelmap_token: Joi.string(),
|
fix: private config schema (#<I>)
|
badges_shields
|
train
|
32d0aad3875ea8ac1d080f8addc804760bf364fb
|
diff --git a/internal/handles.go b/internal/handles.go
index <HASH>..<HASH> 100644
--- a/internal/handles.go
+++ b/internal/handles.go
@@ -879,9 +879,7 @@ func (fh *FileHandle) flushSmallFile(fs *Goofys) (err error) {
_, err = fs.s3.PutObject(params)
if err != nil {
err = mapAwsError(err)
- fh.mu.Lock()
fh.lastWriteError = err
- fh.mu.Unlock()
}
return
}
|
fix deadlock when smallflush fails
happens if creating a file < 5MB fails
|
kahing_goofys
|
train
|
38ae3ecc2b769bccd5f4f837cdde1d0bf1420055
|
diff --git a/lib/y_support/core_ext/module/misc.rb b/lib/y_support/core_ext/module/misc.rb
index <HASH>..<HASH> 100644
--- a/lib/y_support/core_ext/module/misc.rb
+++ b/lib/y_support/core_ext/module/misc.rb
@@ -16,9 +16,10 @@ class Module
# Defines a set of methods by applying the block on the return value of
# another set of methods. Accepts a hash of pairs { mapped_method_symbol =>
- # original_method_symbol } and a block with which to perform mapping.
+ # original_method_symbol } and a block which to chain to the original
+ # method result.
#
- def map! **hash, &block
+ def chain **hash, &block
hash.each_pair { |mapped_method_symbol, original_method_symbol|
define_method mapped_method_symbol do |*args, &b|
block.( send original_method_symbol, *args, &b )
diff --git a/test/misc_test.rb b/test/misc_test.rb
index <HASH>..<HASH> 100644
--- a/test/misc_test.rb
+++ b/test/misc_test.rb
@@ -29,6 +29,11 @@ describe Module do
m::Foo.must_equal 42
m.const_reset! :Foo, 43
m::Foo.must_equal 43
+ m.module_exec do
+ def a; 42 end
+ chain b: :a, &:to_s
+ end
+ Class.new do include m end.new.b.must_equal "42"
end
end
|
renaming Module#map! to Module#chain
|
boris-s_y_support
|
train
|
4c470ac6d724d040130895a7b1791cdac2e360eb
|
diff --git a/blitzdb/backends/mongo/backend.py b/blitzdb/backends/mongo/backend.py
index <HASH>..<HASH> 100644
--- a/blitzdb/backends/mongo/backend.py
+++ b/blitzdb/backends/mongo/backend.py
@@ -70,7 +70,7 @@ class Backend(BaseBackend):
for collection,cache in self._update_cache.items():
for pk,attributes in cache.items():
- self.db[collection].update({'_id' : pk},{'$set' : attributes['set'],'$unset' : attributes['unset']})
+ self.db[collection].update({'_id' : pk},attributes)
self._save_cache = defaultdict(lambda : {})
self._delete_cache = defaultdict(lambda : {})
@@ -165,23 +165,35 @@ class Backend(BaseBackend):
else:
unset_attributes = []
+ update_dict = {}
+ if set_attributes:
+ update_dict['$set'] = set_attributes
+ if unset_attributes:
+ update_dict['$unset'] = dict([(key,'') for key in unset_attributes])
+
if self.autocommit:
- self.db[collection].update({'_id' : obj.pk},{'$set' : set_attributes,'$unset' : dict([(key,'') for key in unset_attributes])})
+ self.db[collection].update({'_id' : obj.pk},update_dict)
else:
if obj.pk in self._delete_cache[collection]:
raise obj.DoesNotExist("update() on document that is marked for deletion!")
if obj.pk in self._update_cache[collection]:
update_cache = self._update_cache[collection][obj.pk]
- for key,value in set_attributes.items():
- if key in update_cache['unset']:
- del update_cache['unset'][key]
- update_cache['set'][key] = value
- for key in unset_attributes:
- if key in update_cache['set']:
- del update_cache['set'][key]
- update_cache['unset'][key] = ''
+ if set_attributes:
+ if not '$set' in update_cache:
+ update_cache['$set'] = {}
+ for key,value in set_attributes.items():
+ if '$unset' in update_cache and key in update_cache['$unset']:
+ del update_cache['$unset'][key]
+ update_cache['$set'][key] = value
+ if unset_attributes:
+ if not '$unset' in update_cache:
+ update_cache['$unset'] = {}
+ for key in unset_attributes:
+ if '$set' in update_cache and key in update_cache['$set']:
+ del update_cache['$set'][key]
+ update_cache['$unset'][key] = ''
else:
- self._update_cache[collection][obj.pk] = {'set' : set_attributes, 'unset' : dict([(key,'') for key in unset_attributes]) }
+ self._update_cache[collection][obj.pk] = update_dict
def serialize(self,obj,convert_keys_to_str = True,embed_level = 0,encoders = None,autosave = True):
|
Fix for update operator in MongoDB backend.
|
adewes_blitzdb
|
train
|
8a359203aca87ff5a16b084a90b5307adf6fc9f8
|
diff --git a/src/files.js b/src/files.js
index <HASH>..<HASH> 100644
--- a/src/files.js
+++ b/src/files.js
@@ -12,6 +12,7 @@ function createFilesContext(apiClient) {
isFile: isFile,
saveFile: saveFile,
status: fileStatus,
+ setUrl: setUrl,
urlForFile: urlForFile,
nativeFile: getNativeFile,
createFile: createFile
@@ -141,4 +142,11 @@ function createFilesContext(apiClient) {
}
return getInternalFile(file).status;
}
+
+ function setUrl(file, url) {
+ var internal = getInternalFile(file);
+ if(internal) {
+ internal.url = url;
+ }
+ }
}
diff --git a/src/objects.js b/src/objects.js
index <HASH>..<HASH> 100644
--- a/src/objects.js
+++ b/src/objects.js
@@ -281,8 +281,12 @@ function createObjectsContext(apiClient, files, collections) {
}
function markFilesSaved(object) {
- getFiles(object).forEach(function(file) {
+ var fileProperties = getFileProperties(object);
+ return Object.keys(fileProperties).map(function(key) {
+ var file = fileProperties[key];
+ var url = files.urlForFile(object.collectionName, object.id, key, file.filename);
files.status(file, "saved");
+ files.setUrl(file, url);
});
}
@@ -564,13 +568,6 @@ function createObjectsContext(apiClient, files, collections) {
return fileProperties;
}
- function getFiles(object) {
- var fileProperties = getFileProperties(object);
- return Object.keys(fileProperties).map(function(key) {
- return fileProperties[key];
- });
- }
-
function createInternalId() {
var id = "internal-id-" + contextId + "-" + internalIds.length;
internalIds.push(id);
diff --git a/test-browser/files-test.js b/test-browser/files-test.js
index <HASH>..<HASH> 100644
--- a/test-browser/files-test.js
+++ b/test-browser/files-test.js
@@ -133,7 +133,22 @@ describe("Files", function() {
});
});
- it("should have readonly url property with token", function() {
+ it("should have readonly url property with token after saving new object", function() {
+ apiClient.urlToken("abc12345");
+ var object = appstax.object("myobjects");
+ object.picture = appstax.file(mockFile("me120x200.jpg"));
+
+ var promise = object.save();
+ requests[0].respond(200, {}, JSON.stringify({sysObjectId:"id1"}));
+
+ return promise.then(function(promisedObject) {
+ var url = "http://localhost:3000/files/myobjects/id1/picture/me120x200.jpg?token=abc12345";
+ expect(object.picture.url).to.equal(url);
+ expect(function() { object.picture.url = "foo" }).to.throw(Error);
+ });
+ });
+
+ it("should have readonly url property with token after updating object (PUT file request)", function() {
apiClient.urlToken("abc12345");
var object = appstax.object("myobjects", {sysObjectId:"1234"});
object.picture = appstax.file(mockFile("profile120x200.jpg"));
@@ -155,9 +170,6 @@ describe("Files", function() {
window.setTimeout(function() {
expect(object.picture.url).to.equal("") // during file save
- var promise = object.save();
- requests[0].respond(200, {});
- expect(object.picture.url).to.equal("") // during file save
done();
}, 100);
});
|
Files now have files after saving, also after multipart object+file upload.
|
Appstax_appstax-js
|
train
|
c59a7cedcf74357aed46d2b027a82a443d5b86fa
|
diff --git a/spec/unit/sugarable_spec.rb b/spec/unit/sugarable_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/sugarable_spec.rb
+++ b/spec/unit/sugarable_spec.rb
@@ -3,13 +3,13 @@ require 'spec_helper'
module Omnibus
describe Software do
it 'is a sugarable' do
- expect(subject).to be_a(Sugarable)
+ expect(described_class.ancestors).to include(Sugarable)
end
end
describe Project do
it 'is a sugarable' do
- expect(subject).to be_a(Sugarable)
+ expect(described_class.ancestors).to include(Sugarable)
end
end
|
Update sugarable spec to check ancestors instead
|
chef_omnibus
|
train
|
e9ea32f4b0a70c0b55ff8e42200749a629b615bd
|
diff --git a/xcs/__init__.py b/xcs/__init__.py
index <HASH>..<HASH> 100644
--- a/xcs/__init__.py
+++ b/xcs/__init__.py
@@ -69,11 +69,6 @@ from xcs.bitstrings import BitString, BitCondition
from xcs.problems import MUXProblem, ObservedOnLineProblem
-def version():
- """Return the version of xcs that was imoprted."""
- return __version__
-
-
class RuleMetadata:
"""Metadata used by the XCS algorithm to track the rules (classifiers) in a population."""
|
Removed version function
Removed the version() function, as this is apparently an unusual way to
do things.
|
hosford42_xcs
|
train
|
7b22789a4a8e3cd417d068d49624fb3728447d10
|
diff --git a/packages/lib/Callback.js b/packages/lib/Callback.js
index <HASH>..<HASH> 100644
--- a/packages/lib/Callback.js
+++ b/packages/lib/Callback.js
@@ -14,7 +14,7 @@ exports = Class(function() {
this.fired = function() { return this._fired; }
this.reset = function() { this._args = []; this._fired = false; }
this.clear = function() { this.reset(); this._run = []; }
- this.forward = function(arguments) { this.run.apply(this, arguments); }
+ this.forward = function(args) { this.run.apply(this, args); }
this.run = function(ctx, method) {
var f = method ? bind.apply(this, arguments) : ctx;
if (f) {
diff --git a/packages/math/util.js b/packages/math/util.js
index <HASH>..<HASH> 100644
--- a/packages/math/util.js
+++ b/packages/math/util.js
@@ -4,7 +4,8 @@ exports.interpolate = function(a, b, x) { return a * (1 - x) + b * x; }
exports.random = function(a, b, rand) { return a + ((rand || Math.random)() * (b - a) | 0); }
exports.rand = Math.random;
-exports.int = exports.truncate = function(a) { return a | 0; }
+//FIXME integer is a reserved word XXX
+exports.integer = exports.truncate = function(a) { return a | 0; }
exports.clip = function(num, min, max) { return Math.max(Math.min(num, max), min); }
@@ -15,29 +16,30 @@ var round = exports.round = function(a, precision, method) {
if(!precision) {
if (method == round.ROUND_HALF_UP) { Math.round(a); }
-
- var int = a | 0,
- frac = a - int,
+
+ //FIXME integer is a reserved word XXX
+ var integer = a | 0,
+ frac = a - integer
half = frac == 0.5 || frac == -0.5;
if (!half) { return Math.round(a); }
var sign = a < 0 ? -1 : 1;
switch(method) {
case round.ROUND_HALF_TO_EVEN:
- return int % 2 ? int + sign : int;
+ return integer % 2 ? integer + sign : integer
case round.ROUND_HALF_TO_ODD:
- return int % 2 ? int : int + sign;
+ return integer % 2 ? integer : integer + sign;
case round.ROUND_HALF_STOCHASTIC:
- return Math.random() < 0.5 ? int + sign : int;
+ return Math.random() < 0.5 ? integer + sign : integer
case round.ROUND_HALF_ALTERNATE:
- return (round.alt = !round.alt) ? int + sign : int;
+ return (round.alt = !round.alt) ? integer + sign : integer
}
}
- var int = a | 0,
- frac = a - int,
+ var integer = a | 0,
+ frac = a - integer
p = Math.pow(10, precision);
- return (int + round(frac * p, 0, method) / p).toFixed(precision);
+ return (integer + round(frac * p, 0, method) / p).toFixed(precision);
}
round.alt = true;
|
fixing some JS errors so that closure compiler works
|
gameclosure_js.io
|
train
|
9a8edd3874e6105f770e10b28a62f7f853515a0a
|
diff --git a/lib/rest-graph.rb b/lib/rest-graph.rb
index <HASH>..<HASH> 100644
--- a/lib/rest-graph.rb
+++ b/lib/rest-graph.rb
@@ -289,10 +289,10 @@ class RestGraph < RestGraphStruct
end
alias_method :previous_page, :prev_page
- def for_pages hash, pages=1, kind=:next_page, opts={}, &cb
+ def for_pages hash, pages=1, opts={}, kind=:next_page, &cb
return hash if pages <= 1
send(kind, hash, opts){ |result|
- for_pages(merge_data(result, hash), pages - 1, kind, opts, &cb)
+ for_pages(merge_data(result, hash), pages - 1, opts, kind, &cb)
} || hash
end
diff --git a/test/test_page.rb b/test/test_page.rb
index <HASH>..<HASH> 100644
--- a/test/test_page.rb
+++ b/test/test_page.rb
@@ -32,24 +32,24 @@ describe RestGraph do
# invalid pages or just the page itself
(-1..1).each{ |page|
- rg.for_pages(data, page, kind).should == data
+ rg.for_pages(data, page, {}, kind).should == data
}
(2..4).each{ |pages|
# merge data
stub_request(:get, 'zzz').to_return(:body => '{"data":["y"]}')
- rg.for_pages(data, pages, kind).should == {'data' => %w[z y]}
+ rg.for_pages(data, pages, {}, kind).should == {'data' => %w[z y]}
# this data cannot be merged
stub_request(:get, 'zzz').to_return(:body => '{"data":"y"}')
- rg.for_pages(data, pages, kind).should == {'data' => %w[z]}
+ rg.for_pages(data, pages, {}, kind).should == {'data' => %w[z]}
}
stub_request(:get, 'zzz').to_return(:body =>
'{"paging":{"'+type+'":"yyy"},"data":["y"]}')
stub_request(:get, 'yyy').to_return(:body => '{"data":["x"]}')
- rg.for_pages(data, 3, kind).should == {'data' => %w[z y x]}
+ rg.for_pages(data, 3, {}, kind).should == {'data' => %w[z y x]}
}
end
end
|
rest-graph.rb: kind goes last for for_pages, to ease passing :async
|
godfat_rest-core
|
train
|
40d3c40f7d1726b0305a06600a127bd9b41e5ec2
|
diff --git a/jbpm-services/jbpm-services-cdi/src/main/java/org/jbpm/services/cdi/impl/store/DeploymentSynchronizerCDInvoker.java b/jbpm-services/jbpm-services-cdi/src/main/java/org/jbpm/services/cdi/impl/store/DeploymentSynchronizerCDInvoker.java
index <HASH>..<HASH> 100644
--- a/jbpm-services/jbpm-services-cdi/src/main/java/org/jbpm/services/cdi/impl/store/DeploymentSynchronizerCDInvoker.java
+++ b/jbpm-services/jbpm-services-cdi/src/main/java/org/jbpm/services/cdi/impl/store/DeploymentSynchronizerCDInvoker.java
@@ -25,6 +25,7 @@ import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
+import javax.ejb.NoSuchObjectLocalException;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@@ -37,6 +38,8 @@ import javax.ejb.TransactionManagementType;
import javax.inject.Inject;
import org.jbpm.kie.services.impl.store.DeploymentSynchronizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
@Startup
@@ -45,6 +48,8 @@ import org.jbpm.kie.services.impl.store.DeploymentSynchronizer;
@TransactionManagement(TransactionManagementType.BEAN)
@AccessTimeout(value=1, unit=TimeUnit.MINUTES)
public class DeploymentSynchronizerCDInvoker {
+
+ private static final Logger logger = LoggerFactory.getLogger(DeploymentSynchronizerCDInvoker.class);
private Timer timer;
@Resource
@@ -68,7 +73,11 @@ public class DeploymentSynchronizerCDInvoker {
@PreDestroy
public void shutdown() {
if (timer != null) {
- timer.cancel();
+ try {
+ timer.cancel();
+ } catch (NoSuchObjectLocalException e) {
+ logger.debug("Timer {} is already canceled or expired", timer);
+ }
}
}
diff --git a/jbpm-services/jbpm-services-ejb/jbpm-services-ejb-impl/src/main/java/org/jbpm/services/ejb/impl/store/DeploymentSynchronizerEJBImpl.java b/jbpm-services/jbpm-services-ejb/jbpm-services-ejb-impl/src/main/java/org/jbpm/services/ejb/impl/store/DeploymentSynchronizerEJBImpl.java
index <HASH>..<HASH> 100644
--- a/jbpm-services/jbpm-services-ejb/jbpm-services-ejb-impl/src/main/java/org/jbpm/services/ejb/impl/store/DeploymentSynchronizerEJBImpl.java
+++ b/jbpm-services/jbpm-services-ejb/jbpm-services-ejb-impl/src/main/java/org/jbpm/services/ejb/impl/store/DeploymentSynchronizerEJBImpl.java
@@ -26,6 +26,7 @@ import javax.ejb.ConcurrencyManagementType;
import javax.ejb.EJB;
import javax.ejb.Lock;
import javax.ejb.LockType;
+import javax.ejb.NoSuchObjectLocalException;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@@ -40,6 +41,8 @@ import org.jbpm.services.api.DeploymentService;
import org.jbpm.services.ejb.api.DeploymentServiceEJBLocal;
import org.jbpm.services.ejb.impl.tx.TransactionalCommandServiceEJBImpl;
import org.jbpm.shared.services.impl.TransactionalCommandService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
@Startup
@@ -47,6 +50,8 @@ import org.jbpm.shared.services.impl.TransactionalCommandService;
@Lock(LockType.WRITE)
@AccessTimeout(value=1, unit=TimeUnit.MINUTES)
public class DeploymentSynchronizerEJBImpl extends DeploymentSynchronizer {
+
+ private static final Logger logger = LoggerFactory.getLogger(DeploymentSynchronizerEJBImpl.class);
@Resource
private TimerService timerService;
@@ -73,7 +78,11 @@ public class DeploymentSynchronizerEJBImpl extends DeploymentSynchronizer {
@PreDestroy
public void shutdown() {
if (timer != null) {
- timer.cancel();
+ try {
+ timer.cancel();
+ } catch (NoSuchObjectLocalException e) {
+ logger.debug("Timer {} is already canceled or expired", timer);
+ }
}
}
|
BZ-<I> - WAS: stopping Business Central from admin console results into an error in server log
closes #<I>
|
kiegroup_jbpm
|
train
|
118d3a874fb4e9cabb7d97536b2d30a1982e12b1
|
diff --git a/Demo/src/androidTest/java/com/braintreepayments/demo/test/VisaCheckoutTest.java b/Demo/src/androidTest/java/com/braintreepayments/demo/test/VisaCheckoutTest.java
index <HASH>..<HASH> 100644
--- a/Demo/src/androidTest/java/com/braintreepayments/demo/test/VisaCheckoutTest.java
+++ b/Demo/src/androidTest/java/com/braintreepayments/demo/test/VisaCheckoutTest.java
@@ -11,6 +11,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import static com.lukekorth.deviceautomator.AutomatorAction.clearTextField;
import static com.lukekorth.deviceautomator.AutomatorAction.click;
import static com.lukekorth.deviceautomator.DeviceAutomator.onDevice;
import static com.lukekorth.deviceautomator.UiObjectMatcher.withContentDescription;
@@ -50,10 +51,8 @@ public class VisaCheckoutTest extends TestHelper {
@Test(timeout = 60000)
public void tokenizesVisaCheckout() throws UiObjectNotFoundException {
onDevice(withContentDescription("Visa Checkout")).perform(click());
- onDevice(withContentDescription("Email or Mobile Number")).perform(click());
- for (int i=0; i<VISA_CHECKOUT_USERNAME.length(); i++) {
- onDevice(withContentDescription("Email or Mobile Number")).pressDelete();
- }
+ onDevice(withContentDescription("Email or Mobile Number")).perform(click(), clearTextField());
+
// TODO bug in DeviceAutomator does not print symbols.
new UiObject(new UiSelector().descriptionStartsWith("Email or Mobile Number"))
.setText(VISA_CHECKOUT_USERNAME);
|
Use clearTextField to empty the email field
|
braintree_braintree_android
|
train
|
3b29cb212d0646e088487afd4d67cd85e32b7e0a
|
diff --git a/src/Commands/Command.php b/src/Commands/Command.php
index <HASH>..<HASH> 100644
--- a/src/Commands/Command.php
+++ b/src/Commands/Command.php
@@ -191,7 +191,7 @@ abstract class Command implements CommandInterface
return call_user_func_array([$this->telegram, $methodName], [$params]);
}
-
+
return 'Method Not Found';
}
}
|
Line ending was set for windows. All others were unix. Changed to unix
|
exileed_telegram-bot-api
|
train
|
af98f88b2439a6064401a1bc8e3c39481e563073
|
diff --git a/inflect.py b/inflect.py
index <HASH>..<HASH> 100644
--- a/inflect.py
+++ b/inflect.py
@@ -54,9 +54,9 @@ from typing import Dict, Union
try:
- import importlib.metadata as importlib_metadata # type: ignore
+ from importlib import metadata # type: ignore
except ImportError:
- import importlib_metadata # type: ignore
+ import importlib_metadata as metadata # type: ignore
class UnknownClassicalModeError(Exception):
@@ -88,7 +88,7 @@ class BadGenderError(Exception):
try:
- __version__ = importlib_metadata.version("inflect")
+ __version__ = metadata.version("inflect") # type: ignore
except Exception:
__version__ = "unknown"
|
🧎♀️ Genuflect to the types.
|
jazzband_inflect
|
train
|
4da0e99d77e2e26fae259c439ddaac4b4d3164b3
|
diff --git a/siv/s2v.go b/siv/s2v.go
index <HASH>..<HASH> 100644
--- a/siv/s2v.go
+++ b/siv/s2v.go
@@ -16,7 +16,8 @@
package siv
// Run the S2V "string to vector" function of RFC 5297 using the input key and
-// associated data.
-func s2v(key []byte, associatedData [][]byte) []byte {
+// string vector, which must be non-empty. (RFC 5297 defines S2V to handle the
+// empty vector case, but it is never used that way by higher-level functions.)
+func s2v(key []byte, strings [][]byte) []byte {
panic("TODO")
}
|
Fixed s2v docs.
|
jacobsa_crypto
|
train
|
9127d602ae8874c322a6dcf5eef8735918ec60ed
|
diff --git a/src/sagemaker/transformer.py b/src/sagemaker/transformer.py
index <HASH>..<HASH> 100644
--- a/src/sagemaker/transformer.py
+++ b/src/sagemaker/transformer.py
@@ -172,7 +172,7 @@ class Transformer(object):
'ExperimentName', 'TrialName', and 'TrialComponentDisplayName'.
(default: ``None``).
wait (bool): Whether the call should wait until the job completes
- (default: True).
+ (default: False).
logs (bool): Whether to show the logs produced by the job.
Only meaningful when wait is True (default: False).
"""
|
doc: correct transform()'s wait default value to "False" (#<I>)
|
aws_sagemaker-python-sdk
|
train
|
1bc4cf1fc04a1e1624347aa0d4bba896add38997
|
diff --git a/netctl/netctl.go b/netctl/netctl.go
index <HASH>..<HASH> 100755
--- a/netctl/netctl.go
+++ b/netctl/netctl.go
@@ -16,7 +16,7 @@ import (
)
// DefaultMaster is the master to use when none is provided.
-const DefaultMaster = "http://localhost:9999"
+const DefaultMaster = "http://netmaster:9999"
func getClient(ctx *cli.Context) *contivClient.ContivClient {
cl, err := contivClient.NewContivClient(ctx.GlobalString("netmaster"))
diff --git a/netmaster/master/consts.go b/netmaster/master/consts.go
index <HASH>..<HASH> 100644
--- a/netmaster/master/consts.go
+++ b/netmaster/master/consts.go
@@ -16,9 +16,6 @@ limitations under the License.
package master
const (
- // DaemonURL is default url used by netmaster to listen for http requests
- DaemonURL = "localhost:9999"
-
//DesiredConfigRESTEndpoint is the REST endpoint to post desired configuration
DesiredConfigRESTEndpoint = "desired-config"
//AddConfigRESTEndpoint is the REST endpoint to post configuration additions
|
use netmaster service name as default for netctl
this allows netctl commands to run from any where in cluster setup
by contiv ansible.
Also removed one unused variable
|
contiv_netplugin
|
train
|
515ab16aa6dccb8ffe9b0265bdde5d4fa7227967
|
diff --git a/src/examples/excelExpr.py b/src/examples/excelExpr.py
index <HASH>..<HASH> 100644
--- a/src/examples/excelExpr.py
+++ b/src/examples/excelExpr.py
@@ -7,10 +7,10 @@
from pyparsing import (CaselessKeyword, Suppress, Word, alphas,
alphanums, nums, Optional, Group, oneOf, Forward, Regex,
infixNotation, opAssoc, dblQuotedString, delimitedList,
- Combine, Literal, QuotedString, ParserElement)
+ Combine, Literal, QuotedString, ParserElement, pyparsing_common)
ParserElement.enablePackrat()
-EQ,EXCL,LPAR,RPAR,COLON,COMMA = map(Suppress, '=!():,')
+EQ,LPAR,RPAR,COLON,COMMA = map(Suppress, '=():,')
EXCL, DOLLAR = map(Literal,"!$")
sheetRef = Word(alphas, alphanums) | QuotedString("'",escQuote="''")
colRef = Optional(DOLLAR) + Word(alphas,max=2)
@@ -26,7 +26,7 @@ expr = Forward()
COMPARISON_OP = oneOf("< = > >= <= != <>")
condExpr = expr + COMPARISON_OP + expr
-ifFunc = (CaselessKeyword("if") +
+ifFunc = (CaselessKeyword("if") -
LPAR +
Group(condExpr)("condition") +
COMMA + Group(expr)("if_true") +
@@ -41,7 +41,7 @@ funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc
multOp = oneOf("* /")
addOp = oneOf("+ -")
-numericLiteral = Regex(r"\-?\d+(\.\d+)?")
+numericLiteral = pyparsing_common.number
operand = numericLiteral | funcCall | cellRange | cellRef
arithExpr = infixNotation(operand,
[
@@ -65,4 +65,5 @@ expr << (arithExpr | textExpr)
=3*'O''Reilly''s sheet'!$A$7+5
=if(Sum(A1:A25)>42,Min(B1:B25),if(Sum(C1:C25)>3.14, (Min(C1:C25)+3)*18,Max(B1:B25)))
=sum(a1:a25,10,min(b1,c2,d3))
+ =if("T"&a2="TTime", "Ready", "Not ready")
""")
\ No newline at end of file
|
Upgrade to use pyparsing_common for numbers
|
pyparsing_pyparsing
|
train
|
7b47fe52a241fc1273b31fdd5120dcdb5bfb511e
|
diff --git a/src/helpers/gravatar/GravatarHelper.php b/src/helpers/gravatar/GravatarHelper.php
index <HASH>..<HASH> 100644
--- a/src/helpers/gravatar/GravatarHelper.php
+++ b/src/helpers/gravatar/GravatarHelper.php
@@ -2,10 +2,11 @@
namespace ntentan\extensions\social\helpers\gravatar;
use \ntentan\honam\Helper;
-class GravatarHelper extends Helper {
-
+class GravatarHelper extends Helper
+{
private $hash;
private $size = 48;
+ private $default = 'identicon';
public function help($email)
{
@@ -18,10 +19,15 @@ class GravatarHelper extends Helper {
$this->size = $size;
return $this;
}
+
+ public function setDefault($default)
+ {
+ $this->default = $default;
+ }
public function __toString()
{
- return "http://www.gravatar.com/avatar/{$this->hash}.jpg?s={$this->size}&d=mm";
+ return "http://www.gravatar.com/avatar/{$this->hash}.jpg?s={$this->size}&d={$this->default}";
}
}
|
Added a way to change default avatars in gravatar
|
ntentan_social-extension
|
train
|
0540beae39785978aad06886910952e56d220501
|
diff --git a/src/Slick/Mvc/Command/Utils/ControllerData.php b/src/Slick/Mvc/Command/Utils/ControllerData.php
index <HASH>..<HASH> 100644
--- a/src/Slick/Mvc/Command/Utils/ControllerData.php
+++ b/src/Slick/Mvc/Command/Utils/ControllerData.php
@@ -78,7 +78,7 @@ class ControllerData extends Base
public function setControllerName($modelName)
{
$name = end(explode('/', $modelName));
- $this->_controllerName = ucfirst(Text::plural($name));
+ $this->_controllerName = ucfirst(Text::plural(lcfirst($name)));
return $this;
}
|
Fixing the plural conversion of model name.
|
slickframework_slick
|
train
|
05ac434d01d0bd2ad46a4e690911df94e4979924
|
diff --git a/selendroid-server/src/main/java/io/selendroid/android/AndroidTouchScreen.java b/selendroid-server/src/main/java/io/selendroid/android/AndroidTouchScreen.java
index <HASH>..<HASH> 100644
--- a/selendroid-server/src/main/java/io/selendroid/android/AndroidTouchScreen.java
+++ b/selendroid-server/src/main/java/io/selendroid/android/AndroidTouchScreen.java
@@ -93,11 +93,11 @@ public class AndroidTouchScreen implements TouchScreen {
Scroll scroll = new Scroll(origin, destination, downTime);
// Initial acceleration from origin to reference point
motionEvents.addAll(getMoveEvents(downTime, downTime, origin, scroll.getDecelerationPoint(),
- scroll.INITIAL_STEPS, scroll.TIME_BETWEEN_EVENTS));
+ Scroll.INITIAL_STEPS, Scroll.TIME_BETWEEN_EVENTS));
// Deceleration phase from reference point to destination
motionEvents.addAll(getMoveEvents(downTime, scroll.getEventTimeForReferencePoint(),
- scroll.getDecelerationPoint(), destination, scroll.DECELERATION_STEPS,
- scroll.TIME_BETWEEN_EVENTS));
+ scroll.getDecelerationPoint(), destination, Scroll.DECELERATION_STEPS,
+ Scroll.TIME_BETWEEN_EVENTS));
motionEvents.add(getMotionEvent(downTime,
(downTime + scroll.getEventTimeForDestinationPoint()), MotionEvent.ACTION_UP, destination));
@@ -241,7 +241,7 @@ public class AndroidTouchScreen implements TouchScreen {
Point destination = new Point(origin.x + xOffset, origin.y + yOffset);
Flick flick = new Flick(speed);
motionEvents.add(getMotionEvent(downTime, downTime, MotionEvent.ACTION_DOWN, origin));
- motionEvents.addAll(getMoveEvents(downTime, downTime, origin, destination, flick.STEPS,
+ motionEvents.addAll(getMoveEvents(downTime, downTime, origin, destination, Flick.STEPS,
flick.getTimeBetweenEvents()));
motionEvents.add(getMotionEvent(downTime, flick.getTimeForDestinationPoint(downTime),
MotionEvent.ACTION_UP, destination));
@@ -255,7 +255,7 @@ public class AndroidTouchScreen implements TouchScreen {
private List<MotionEvent> getMoveEvents(long downTime, long startingEVentTime, Point origin,
Point destination, int steps, long timeBetweenEvents) {
List<MotionEvent> move = new ArrayList<MotionEvent>();
- MotionEvent event = null;
+ MotionEvent event;
float xStep = (destination.x - origin.x) / steps;
float yStep = (destination.y - origin.y) / steps;
@@ -345,7 +345,7 @@ public class AndroidTouchScreen implements TouchScreen {
final static int DECELERATION_STEPS = 5;
final int TOTAL_STEPS = INITIAL_STEPS + DECELERATION_STEPS;
// Time in milliseconds to provide a speed similar to scroll
- final long TIME_BETWEEN_EVENTS = 50;
+ final static long TIME_BETWEEN_EVENTS = 50;
public Scroll(Point origin, Point destination, long downTime) {
this.origin = origin;
diff --git a/selendroid-test-app/src/test/java/io/selendroid/nativetests/SendKeyAndNativeKeyTest.java b/selendroid-test-app/src/test/java/io/selendroid/nativetests/SendKeyAndNativeKeyTest.java
index <HASH>..<HASH> 100644
--- a/selendroid-test-app/src/test/java/io/selendroid/nativetests/SendKeyAndNativeKeyTest.java
+++ b/selendroid-test-app/src/test/java/io/selendroid/nativetests/SendKeyAndNativeKeyTest.java
@@ -13,15 +13,15 @@
*/
package io.selendroid.nativetests;
-import static io.selendroid.waiter.TestWaiter.waitFor;
import io.selendroid.SelendroidKeys;
import io.selendroid.support.BaseAndroidTest;
import io.selendroid.waiter.WaitingConditions;
-
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
+import static io.selendroid.waiter.TestWaiter.waitFor;
+
public class SendKeyAndNativeKeyTest extends BaseAndroidTest {
@Test
|
Code clean up. No logical changes.
|
selendroid_selendroid
|
train
|
f1807c9b9040f3f514c81aebeefb7f5892fedf3e
|
diff --git a/lib/fluent/plugin/in_tail.rb b/lib/fluent/plugin/in_tail.rb
index <HASH>..<HASH> 100644
--- a/lib/fluent/plugin/in_tail.rb
+++ b/lib/fluent/plugin/in_tail.rb
@@ -1002,7 +1002,7 @@ module Fluent::Plugin
with_io do |io|
begin
number_bytes_read = 0
- start_reading = Fluent::EventTime.now
+ start_reading = Fluent::Clock.now
read_more = false
if !io.nil? && @lines.empty?
|
in_tail: Use Fluent::Clock.new to obtain starting time
|
fluent_fluentd
|
train
|
de22fe33dffe8fad2dbc70917f59c6b0a1598393
|
diff --git a/lib/plugins/load-plugin.js b/lib/plugins/load-plugin.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/load-plugin.js
+++ b/lib/plugins/load-plugin.js
@@ -308,6 +308,7 @@ var initReq = function(req, res, isServer) {
var headers = extractHeaders(req, pluginKeyMap);
req[REQ_ID_KEY] = oReq.id = reqId;
oReq.headers = headers;
+ oReq.isFromPlugin = headers[pluginOpts.PLUGIN_REQUEST_HEADER] == '1';
oReq.ruleValue = getValue(req, pluginOpts.RULE_VALUE_HEADER);
oReq.pipeValue = getValue(req, pluginOpts.PIPE_VALUE_HEADER);
oReq.hostValue = getValue(req, pluginOpts.HOST_VALUE_HEADER);
|
feat: add plugin.req.originalReq.isFromPlugin to determine if the request comes from a plugin
|
avwo_whistle
|
train
|
ce5ebed9f66a9802d96c222d528935cf6894b97e
|
diff --git a/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveLogicalPlanner.java b/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveLogicalPlanner.java
index <HASH>..<HASH> 100644
--- a/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveLogicalPlanner.java
+++ b/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveLogicalPlanner.java
@@ -2717,6 +2717,26 @@ public class TestHiveLogicalPlanner
}
@Test
+ public void testMaterializedViewOrderBy()
+ {
+ QueryRunner queryRunner = getQueryRunner();
+ String table = "orders_partitioned";
+ String view = "test_orders_view";
+ try {
+ queryRunner.execute(format("CREATE TABLE %s WITH (partitioned_by = ARRAY['ds']) AS " +
+ "SELECT orderkey, orderpriority, '2020-01-01' as ds FROM orders WHERE orderkey < 1000 " +
+ "UNION ALL " +
+ "SELECT orderkey, orderpriority, '2019-01-02' as ds FROM orders WHERE orderkey > 1000", table));
+
+ assertQueryFails(format("CREATE MATERIALIZED VIEW %s WITH (partitioned_by = ARRAY['ds']) " +
+ "AS SELECT orderkey, orderpriority, ds FROM %s order by orderkey", view, table), ".*OrderBy are not supported for materialized view.*");
+ }
+ finally {
+ queryRunner.execute("DROP TABLE IF EXISTS " + table);
+ }
+ }
+
+ @Test
public void testMaterializedViewSubqueryShapes()
{
QueryRunner queryRunner = getQueryRunner();
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/MaterializedViewPlanValidator.java b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/MaterializedViewPlanValidator.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/MaterializedViewPlanValidator.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/MaterializedViewPlanValidator.java
@@ -20,6 +20,7 @@ import com.facebook.presto.sql.tree.Join;
import com.facebook.presto.sql.tree.JoinCriteria;
import com.facebook.presto.sql.tree.JoinOn;
import com.facebook.presto.sql.tree.LogicalBinaryExpression;
+import com.facebook.presto.sql.tree.OrderBy;
import com.facebook.presto.sql.tree.Query;
import com.facebook.presto.sql.tree.QuerySpecification;
import com.facebook.presto.sql.tree.SubqueryExpression;
@@ -184,6 +185,12 @@ public class MaterializedViewPlanValidator
throw new SemanticException(NOT_SUPPORTED, node, "Subqueries are not supported for materialized view.");
}
+ @Override
+ protected Void visitOrderBy(OrderBy node, MaterializedViewPlanValidatorContext context)
+ {
+ throw new SemanticException(NOT_SUPPORTED, node, "OrderBy are not supported for materialized view.");
+ }
+
public static final class MaterializedViewPlanValidatorContext
{
private boolean isWithinJoinOn;
|
Error order by in materialized view
OrderBy are not supported in the materialized view.
|
prestodb_presto
|
train
|
d78de1d321d2b00cb70a9fe787ba70a68be28c83
|
diff --git a/imgaug/augmentables/lines.py b/imgaug/augmentables/lines.py
index <HASH>..<HASH> 100644
--- a/imgaug/augmentables/lines.py
+++ b/imgaug/augmentables/lines.py
@@ -414,7 +414,7 @@ class LineString(object):
# when first clipping and then calling is_fully_within_image()
# returning false
height, width = normalize_shape(image)[0:2]
- eps = 1e-5
+ eps = 1e-3
edges = [
LineString([(0.0, 0.0), (width - eps, 0.0)]),
LineString([(width - eps, 0.0), (width - eps, height - eps)]),
@@ -476,8 +476,8 @@ class LineString(object):
dist_next = np.linalg.norm(
np.float32(coord) - np.float32(p_next))
- dist_prev_ok = (dist_prev is None or dist_prev > 1e-4)
- dist_next_ok = (dist_next is None or dist_next > 1e-4)
+ dist_prev_ok = (dist_prev is None or dist_prev > 1e-2)
+ dist_next_ok = (dist_next is None or dist_next > 1e-2)
if dist_prev_ok and dist_next_ok:
line.append(coord)
diff --git a/test/augmentables/test_lines.py b/test/augmentables/test_lines.py
index <HASH>..<HASH> 100644
--- a/test/augmentables/test_lines.py
+++ b/test/augmentables/test_lines.py
@@ -348,7 +348,7 @@ class TestLineString(unittest.TestCase):
def test_clip_out_of_image(self):
def _eq(ls, other):
- return ls.coords_almost_equals(other, max_distance=1e-3)
+ return ls.coords_almost_equals(other, max_distance=1e-2)
ls = LineString([(0, 0), (1, 0), (2, 1)])
@@ -610,18 +610,27 @@ class TestLineString(unittest.TestCase):
assert len(lss_clipped) == 0
# combine clip + is_fully_within_image
- h, w = 100, 200
- ls = LineString([(0, 10), (w, 10), (w, h), (w-10, h-10)])
- lss_clipped = ls.clip_out_of_image((h, w))
- assert len(lss_clipped) == 2
- assert lss_clipped[0].is_fully_within_image((h, w))
- assert lss_clipped[1].is_fully_within_image((h, w))
-
- ls = LineString([(0, 10), (w+10, 10), (w+10, h-10), (w-10, h-10)])
- lss_clipped = ls.clip_out_of_image((h, w))
- assert len(lss_clipped) == 2
- assert lss_clipped[0].is_fully_within_image((h, w))
- assert lss_clipped[1].is_fully_within_image((h, w))
+ sizes = [(200, 400), (400, 800), (800, 1600), (1600, 3200),
+ (3200, 6400)]
+ sizes = sizes + [(w, h) for h, w in sizes]
+ for h, w in sizes:
+ ls = LineString([(0, 10), (w, 10), (w, h), (w-10, h-10)])
+ lss_clipped = ls.clip_out_of_image((h, w))
+ assert len(lss_clipped) == 2
+ assert lss_clipped[0].is_fully_within_image((h, w))
+ assert lss_clipped[1].is_fully_within_image((h, w))
+
+ ls = LineString([(0, 10), (w+10, 10), (w+10, h-10), (w-10, h-10)])
+ lss_clipped = ls.clip_out_of_image((h, w))
+ assert len(lss_clipped) == 2
+ assert lss_clipped[0].is_fully_within_image((h, w))
+ assert lss_clipped[1].is_fully_within_image((h, w))
+
+ ls = LineString([(-10, 10), (w+10, 10), (w-10, h-10)])
+ lss_clipped = ls.clip_out_of_image((h, w))
+ assert len(lss_clipped) == 2
+ assert lss_clipped[0].is_fully_within_image((h, w))
+ assert lss_clipped[1].is_fully_within_image((h, w))
def test_shift(self):
ls = LineString([(0, 0), (1, 0), (2, 1)])
|
Increase tolerance for thresholds in LS.clip_out_of_image()
|
aleju_imgaug
|
train
|
9b5beaeb083f4c6b5ca3a8a39d239ec23b0f6eb6
|
diff --git a/test/system/jsdoc-config.test.js b/test/system/jsdoc-config.test.js
index <HASH>..<HASH> 100644
--- a/test/system/jsdoc-config.test.js
+++ b/test/system/jsdoc-config.test.js
@@ -3,10 +3,9 @@
* on the content of the file as well. Any change to .jsdoc-config.json must be accompanied by valid test case in this
* spec-sheet.
*/
-/* global describe, it, expect */
+
describe('JSDoc configuration', function () {
var fs = require('fs'),
- _ = require('lodash'),
json,
content,
@@ -17,16 +16,16 @@ describe('JSDoc configuration', function () {
});
it('should have readable content', function () {
- expect(content = fs.readFileSync(jsdocConfigPath).toString()).to.be.ok;
+ expect(content = fs.readFileSync(jsdocConfigPath).toString(), 'Should have readable content').to.be.ok;
});
it('should have valid JSON content', function () {
- expect(json = JSON.parse(content)).to.be.ok;
+ expect(json = JSON.parse(content), 'Should have valid JSON content').to.be.ok;
});
describe('tags', function () {
- it('should allow unkown tags', function () {
- expect(json.tags.allowUnknownTags).to.be.ok;
+ it('should allow unknown tags', function () {
+ expect(json.tags.allowUnknownTags, 'Should allow unknown tags').to.be.ok;
});
it('should have jsdoc and closure dictionaries', function () {
@@ -46,17 +45,17 @@ describe('JSDoc configuration', function () {
describe('plugins', function () {
it('should have the markdown plugin', function () {
- expect(_.includes(json.plugins, 'plugins/markdown')).to.be.ok;
+ expect(json.plugins, 'Should use the markdown plugin').to.include('plugins/markdown');
});
});
describe('templates', function () {
it('should not have clever links', function () {
- expect(json.templates.cleverLinks).to.not.be.ok;
+ expect(json.templates.cleverLinks).to.be.false;
});
it('should not have monospace links', function () {
- expect(json.templates.monospaceLinks).to.not.be.ok;
+ expect(json.templates.monospaceLinks).to.be.false;
});
it('should highlight tutorial code', function () {
@@ -82,17 +81,17 @@ describe('JSDoc configuration', function () {
});
it('should have a valid readme', function () {
- expect(json.opts.readme).to.equal('README.md');
+ expect(json.opts.readme, 'Should use a valid readme').to.equal('README.md');
});
});
describe('markdown', function () {
it('should have a gfm parser', function () {
- expect(json.markdown.parser).to.equal('gfm');
+ expect(json.markdown.parser, 'Should use the gfm markdown parser').to.equal('gfm');
});
it('should have jsdoc and closure dictionaries', function () {
- expect(json.markdown.hardwrap).to.not.be.ok;
+ expect(json.markdown.hardwrap).to.be.false;
});
});
});
|
Updated changes in jsdoc-config
|
postmanlabs_uvm
|
train
|
e4bd4e9d627ee1b3c5b4a160d6f95111afa10b98
|
diff --git a/bin/giternal b/bin/giternal
index <HASH>..<HASH> 100755
--- a/bin/giternal
+++ b/bin/giternal
@@ -12,5 +12,6 @@ unless available_actions.include?(action)
exit 1
end
+Giternal::Repository.verbose = true
app = Giternal::App.new(FileUtils.pwd)
app.run(action)
diff --git a/lib/giternal/repository.rb b/lib/giternal/repository.rb
index <HASH>..<HASH> 100644
--- a/lib/giternal/repository.rb
+++ b/lib/giternal/repository.rb
@@ -2,11 +2,17 @@ require 'fileutils'
module Giternal
class Repository
+ class << self
+ attr_accessor :verbose
+ end
+ attr_accessor :verbose
+
def initialize(base_dir, name, repo_url, rel_path)
@base_dir = base_dir
@name = name
@repo_url = repo_url
@rel_path = rel_path
+ @verbose = self.class.verbose
end
def update
@@ -68,10 +74,9 @@ module Giternal
end
def update_output(&block)
- puts "Updating #{@name}"
+ puts "Updating #{@name}" if verbose
block.call
- puts " ..updated"
- puts
+ puts " ..updated\n" if verbose
end
end
end
diff --git a/spec/giternal/repository_spec.rb b/spec/giternal/repository_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/giternal/repository_spec.rb
+++ b/spec/giternal/repository_spec.rb
@@ -17,6 +17,18 @@ module Giternal
should == 'foo'
end
+ it "should not show any output when verbose mode is off" do
+ @repository.verbose = false
+ @repository.should_not_receive(:puts)
+ @repository.update
+ end
+
+ it "should not show output when verbose mode is on" do
+ @repository.verbose = true
+ @repository.should_receive(:puts).any_number_of_times
+ @repository.update
+ end
+
it "should update the repo when it's already been checked out" do
@repository.update
GiternalHelper.add_content 'foo', 'newfile'
|
added some specs and a switch for verbosity
|
patmaddox_giternal
|
train
|
308f121a40499e14819b3680af780ac52500ef72
|
diff --git a/src/sagemaker/model.py b/src/sagemaker/model.py
index <HASH>..<HASH> 100644
--- a/src/sagemaker/model.py
+++ b/src/sagemaker/model.py
@@ -810,7 +810,10 @@ class FrameworkModel(Model):
"""Placeholder docstring"""
if self.uploaded_code:
script_name = self.uploaded_code.script_name
- dir_name = self.uploaded_code.s3_prefix
+ if self.enable_network_isolation():
+ dir_name = "/opt/ml/model/code"
+ else:
+ dir_name = self.uploaded_code.s3_prefix
else:
script_name = self.entry_point
dir_name = "file://" + self.source_dir
diff --git a/src/sagemaker/sklearn/model.py b/src/sagemaker/sklearn/model.py
index <HASH>..<HASH> 100644
--- a/src/sagemaker/sklearn/model.py
+++ b/src/sagemaker/sklearn/model.py
@@ -135,10 +135,13 @@ class SKLearnModel(FrameworkModel):
)
deploy_key_prefix = model_code_key_prefix(self.key_prefix, self.name, deploy_image)
- self._upload_code(deploy_key_prefix)
+ self._upload_code(key_prefix=deploy_key_prefix, repack=self.enable_network_isolation())
deploy_env = dict(self.env)
deploy_env.update(self._framework_env_vars())
if self.model_server_workers:
deploy_env[MODEL_SERVER_WORKERS_PARAM_NAME.upper()] = str(self.model_server_workers)
- return sagemaker.container_def(deploy_image, self.model_data, deploy_env)
+ model_data_uri = (
+ self.repacked_model_data if self.enable_network_isolation() else self.model_data
+ )
+ return sagemaker.container_def(deploy_image, model_data_uri, deploy_env)
diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_model.py
+++ b/tests/unit/test_model.py
@@ -156,6 +156,25 @@ def test_prepare_container_def(time, sagemaker_session):
@patch("shutil.rmtree", MagicMock())
@patch("tarfile.open", MagicMock())
+@patch("os.listdir", MagicMock(return_value=["blah.py"]))
+@patch("time.strftime", return_value=TIMESTAMP)
+def test_prepare_container_def_with_network_isolation(time, sagemaker_session):
+ model = DummyFrameworkModel(sagemaker_session, enable_network_isolation=True)
+ assert model.prepare_container_def(INSTANCE_TYPE) == {
+ "Environment": {
+ "SAGEMAKER_PROGRAM": ENTRY_POINT,
+ "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code",
+ "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
+ "SAGEMAKER_REGION": REGION,
+ "SAGEMAKER_ENABLE_CLOUDWATCH_METRICS": "false",
+ },
+ "Image": MODEL_IMAGE,
+ "ModelDataUrl": MODEL_DATA,
+ }
+
+
+@patch("shutil.rmtree", MagicMock())
+@patch("tarfile.open", MagicMock())
@patch("os.path.exists", MagicMock(return_value=True))
@patch("os.path.isdir", MagicMock(return_value=True))
@patch("os.listdir", MagicMock(return_value=["blah.py"]))
diff --git a/tests/unit/test_sklearn.py b/tests/unit/test_sklearn.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_sklearn.py
+++ b/tests/unit/test_sklearn.py
@@ -23,6 +23,7 @@ from mock import patch
from sagemaker.sklearn import defaults
from sagemaker.sklearn import SKLearn
from sagemaker.sklearn import SKLearnPredictor, SKLearnModel
+from sagemaker.fw_utils import UploadedCode
DATA_DIR = os.path.join(os.path.dirname(__file__), "..", "data")
SCRIPT_PATH = os.path.join(DATA_DIR, "dummy_script.py")
@@ -168,6 +169,25 @@ def test_create_model(sagemaker_session):
assert model_values["Image"] == default_image_uri
+@patch("sagemaker.model.FrameworkModel._upload_code")
+def test_create_model_with_network_isolation(upload, sagemaker_session):
+ source_dir = "s3://mybucket/source"
+ repacked_model_data = "s3://mybucket/prefix/model.tar.gz"
+
+ sklearn_model = SKLearnModel(
+ model_data=source_dir,
+ role=ROLE,
+ sagemaker_session=sagemaker_session,
+ entry_point=SCRIPT_PATH,
+ enable_network_isolation=True,
+ )
+ sklearn_model.uploaded_code = UploadedCode(s3_prefix=repacked_model_data, script_name="script")
+ sklearn_model.repacked_model_data = repacked_model_data
+ model_values = sklearn_model.prepare_container_def(CPU)
+ assert model_values["Environment"]["SAGEMAKER_SUBMIT_DIRECTORY"] == "/opt/ml/model/code"
+ assert model_values["ModelDataUrl"] == repacked_model_data
+
+
def test_create_model_from_estimator(sagemaker_session, sklearn_version):
container_log_level = '"logging.INFO"'
source_dir = "s3://mybucket/source"
|
feature: enable sklearn for network isolation mode (#<I>)
|
aws_sagemaker-python-sdk
|
train
|
32f0bf2ebdc1f09694d346dba96eafd32af2f29c
|
diff --git a/announce/views.py b/announce/views.py
index <HASH>..<HASH> 100644
--- a/announce/views.py
+++ b/announce/views.py
@@ -1,4 +1,4 @@
-from django.http import HttpResponse # JsonResponse
+from django.http import HttpResponse, HttpResponseBadRequest # JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from bellman import Bellman
@@ -27,11 +27,12 @@ def announce(request):
# check that POST has the correct form?
- bellman = Bellman(
+ app = Bellman(
text=request.POST['text'],
user_name=request.POST['user_name'],
user_id=request.POST['user_id'])
- bellman.execute()
+ app.execute()
- return HttpResponse(bellman.get_response())
+ return HttpResponse(app.get_response())
+ return HttpResponseBadRequest()
|
bellman is now a module name
|
praekeltfoundation_bellman
|
train
|
6329a32ddc48bf3fcd0452e927a40e68a1df56d3
|
diff --git a/lib/pulse-meter/sensor/timeline.rb b/lib/pulse-meter/sensor/timeline.rb
index <HASH>..<HASH> 100644
--- a/lib/pulse-meter/sensor/timeline.rb
+++ b/lib/pulse-meter/sensor/timeline.rb
@@ -49,6 +49,7 @@ module PulseMeter
end
# Processes event
+ # @param value event value
def event(value = nil)
multi do
current_key = current_raw_data_key
@@ -57,7 +58,18 @@ module PulseMeter
end
end
-
+ # Processes event from the past
+ # @param time [Time] event time
+ # @param value event value
+ def event_at(time, value = nil)
+ multi do
+ interval_id = get_interval_id(time)
+ key = raw_data_key(interval_id)
+ aggregate_event(key, value)
+ redis.expire(key, raw_data_ttl)
+ end
+ end
+
# Reduces data in given interval.
# @note Interval id is
# just unixtime of its lower bound. Ruduction is a process
diff --git a/spec/shared_examples/timeline_sensor.rb b/spec/shared_examples/timeline_sensor.rb
index <HASH>..<HASH> 100644
--- a/spec/shared_examples/timeline_sensor.rb
+++ b/spec/shared_examples/timeline_sensor.rb
@@ -19,9 +19,15 @@ shared_examples_for "timeline sensor" do |extra_init_values, default_event|
before(:each) do
@interval_id = (Time.now.to_i / interval) * interval
+ @prev_interval_id = (Time.now.to_i / interval) * interval - interval
+
@raw_data_key = sensor.raw_data_key(@interval_id)
+ @prev_raw_data_key = sensor.raw_data_key(@prev_interval_id)
+
@next_raw_data_key = sensor.raw_data_key(@interval_id + interval)
+
@start_of_interval = Time.at(@interval_id)
+ @start_of_prev_interval = Time.at(@prev_interval_id)
end
describe "#dump" do
@@ -66,12 +72,36 @@ shared_examples_for "timeline sensor" do |extra_init_values, default_event|
end
it "should write data to bucket indicated by truncated timestamp" do
- key = sensor.raw_data_key(@interval_id)
expect{
Timecop.freeze(@start_of_interval) do
sensor.event(sample_event)
end
- }.to change{ redis.ttl(key) }
+ }.to change{ redis.ttl(@raw_data_key) }
+ end
+ end
+
+ describe "#event_at" do
+ let(:now) {Time.now}
+ it "should write events to redis" do
+ expect{
+ sensor.event_at(now, sample_event)
+ }.to change{ redis.keys('*').count }.by(1)
+ end
+
+ it "should write data so that it totally expires after :raw_data_ttl" do
+ key_count = redis.keys('*').count
+ sensor.event_at(now, sample_event)
+ Timecop.freeze(Time.now + raw_data_ttl + 1) do
+ redis.keys('*').count.should == key_count
+ end
+ end
+
+ it "should write data to bucket indicated by passed time" do
+ expect{
+ Timecop.freeze(@start_of_interval) do
+ sensor.event_at(@start_of_prev_interval, sample_event)
+ end
+ }.to change{ redis.ttl(@prev_raw_data_key) }
end
end
|
event_at method added to timelined sensor
|
savonarola_pulse_meter_cli
|
train
|
aeb767119935b1dc77f87ae2dade515f70a8a91e
|
diff --git a/lib/account_identity.rb b/lib/account_identity.rb
index <HASH>..<HASH> 100644
--- a/lib/account_identity.rb
+++ b/lib/account_identity.rb
@@ -10,12 +10,12 @@ module DataSift
# @param master [Boolean] (Optional, Default: false) Whether this is the
# master Identity for your account
# @return [Object] API reponse object
- def create(label = '', status = 'active', master = false)
+ def create(label = '', status = 'active', master = '')
fail ArgumentError, 'label is missing' if label.empty?
params = { label: label }
params.merge!(status: status) unless status.empty?
- params.merge!(master: master) if [true, false].include?(master)
+ params.merge!(master: master) if [TrueClass, FalseClass].include?(master.class)
DataSift.request(:POST, 'account/identity', @config, params)
end
@@ -57,7 +57,7 @@ module DataSift
params = {}
params.merge!(label: label) unless label.empty?
params.merge!(status: status) unless status.empty?
- params.merge!(master: master) unless master.empty?
+ params.merge!(master: master) if [TrueClass, FalseClass].include?(master.class)
DataSift.request(:PUT, "account/identity/#{id}", @config, params)
end
|
Only pass /account/identity "master" param when it is a boolean value. Default to empty string
|
datasift_datasift-ruby
|
train
|
e157f7f317cb0f4dc1fa971f8d23e3a2c38e4c92
|
diff --git a/src/DeckValidator.js b/src/DeckValidator.js
index <HASH>..<HASH> 100644
--- a/src/DeckValidator.js
+++ b/src/DeckValidator.js
@@ -12,6 +12,14 @@ function getDeckCount(deck) {
return count;
}
+function hasKeyword(card, keywordRegex) {
+ let lines = card.text.split('\n');
+ let keywordLine = lines[0] || '';
+ let keywords = keywordLine.split('.').map(keyword => keyword.trim()).filter(keyword => keyword.length !== 0);
+
+ return keywords.some(keyword => keywordRegex.test(keyword));
+}
+
function hasTrait(card, trait) {
return card.traits.some(t => t.toLowerCase() === trait.toLowerCase());
}
@@ -161,6 +169,10 @@ const agendaRules = {
'11079': {
cannotInclude: card => card.faction !== 'neutral'
},
+ // Kingdom of Shadows
+ '13079': {
+ mayInclude: card => !card.loyal && hasKeyword(card, /Shadow \(\d+\)/)
+ },
// Draft Agendas
// The Power of Wealth
'00001': rulesForDraft({
|
Add validation rule for Kingdom of Shadows
|
throneteki_throneteki-deck-helper
|
train
|
660813f10f63447077dd43dc3757aac8e008491f
|
diff --git a/examples/simpleapp.js b/examples/simpleapp.js
index <HASH>..<HASH> 100644
--- a/examples/simpleapp.js
+++ b/examples/simpleapp.js
@@ -8,6 +8,13 @@ app.controller(
}
);
+app.controller(
+ 'weatherController',
+ function (weatherData, $scope) {
+ $scope.weather = weatherData;
+ }
+);
+
app.config(
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
@@ -22,9 +29,7 @@ app.config(
).then(function (resp) { return resp.data; });
}
},
- controller: function (weatherData, $scope) {
- $scope.weather = weatherData;
- }
+ controller: 'weatherController'
}
);
$routeProvider.otherwise(
|
Make the weather page use a named controller.
We have to use named controllers rather than inline controllers because
we want to be able to indicate to the client which controller to use to
render the page. We can send the client a string to look up, but we can't
reliably serialize the controller function and transmit it.
|
saymedia_angularjs-server
|
train
|
64c836f14518e91e0d22cd9b0f2212be48e6e1c2
|
diff --git a/src/Entities/CallbackQuery.php b/src/Entities/CallbackQuery.php
index <HASH>..<HASH> 100644
--- a/src/Entities/CallbackQuery.php
+++ b/src/Entities/CallbackQuery.php
@@ -44,7 +44,7 @@ class CallbackQuery implements \ArrayAccess
* \brief Get data parameter if it is set.
* @return string $data if set or empty string otherwise.
*/
- public function getData() : string
+ public function getData()
{
return isset($this->container['data']) ? $this->container['data'] : null;
}
diff --git a/src/Entities/ChosenInlineResult.php b/src/Entities/ChosenInlineResult.php
index <HASH>..<HASH> 100644
--- a/src/Entities/ChosenInlineResult.php
+++ b/src/Entities/ChosenInlineResult.php
@@ -37,7 +37,7 @@ class ChosenInlineResult implements \ArrayAccess
* \brief Get result's query.
* @return $query Null if it's empty.
*/
- public function getQuery() : string
+ public function getQuery()
{
return isset($this->container['query']) ? $this->container['query'] : null;
}
diff --git a/src/Entities/InlineQuery.php b/src/Entities/InlineQuery.php
index <HASH>..<HASH> 100644
--- a/src/Entities/InlineQuery.php
+++ b/src/Entities/InlineQuery.php
@@ -38,7 +38,7 @@ class InlineQuery implements \ArrayAccess
* \brief Get result's query.
* @return string $query If set or <code>null</code> if empty.
*/
- public function getQuery() : string
+ public function getQuery()
{
return isset($this->container['query']) ? $this->container['query'] : null;
}
diff --git a/src/Entities/Message.php b/src/Entities/Message.php
index <HASH>..<HASH> 100644
--- a/src/Entities/Message.php
+++ b/src/Entities/Message.php
@@ -36,7 +36,7 @@ class Message implements \ArrayAccess
* \brief Get text parameter if it is set.
* @return string If set or <code>null</code> otherwise.
*/
- public function getText() : string
+ public function getText()
{
return isset($this->container['text']) ? $this->container['text'] : null;
}
|
Fixed some crash on the return type inconsistent with their statement (bout entities)
|
DanySpin97_PhpBotFramework
|
train
|
a31f55456a18765f4f8b27daece156e1a4b10612
|
diff --git a/mnemosyned/health.go b/mnemosyned/health.go
index <HASH>..<HASH> 100644
--- a/mnemosyned/health.go
+++ b/mnemosyned/health.go
@@ -1,8 +1,10 @@
package mnemosyned
import (
+ "context"
"database/sql"
"net/http"
+ "time"
"github.com/go-kit/kit/log"
"github.com/piotrkowalczuk/sklog"
@@ -15,7 +17,10 @@ type healthHandler struct {
func (hh *healthHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if hh.postgres != nil {
- if err := hh.postgres.Ping(); err != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ if err := hh.postgres.PingContext(ctx); err != nil {
sklog.Debug(hh.logger, "health check failure due to postgres connection")
http.Error(rw, "postgres ping failure", http.StatusServiceUnavailable)
return
|
health check endpoint - <I>s timeout
|
piotrkowalczuk_mnemosyne
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.