hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
09ccc78db77dc23cd2bf1c47190570d0c018ece2
|
diff --git a/lib/Paymill/Request.php b/lib/Paymill/Request.php
index <HASH>..<HASH> 100755
--- a/lib/Paymill/Request.php
+++ b/lib/Paymill/Request.php
@@ -38,6 +38,12 @@ class Request
private $_version = "3.0.2";
/**
+ * @var string
+ */
+ private $_source;
+
+
+ /**
* Creates a Request object instance
* @param string|null $privateKey
*/
@@ -133,7 +139,7 @@ class Request
/**
* Returns the Version of this Lib
- *
+ *
* @return string
*/
public function getVersion(){
@@ -202,6 +208,8 @@ class Request
}
}
+ $source = empty($this->_source) ? "PhpLib" . $this->getVersion(): "PhpLib" . $this->getVersion() . "_" . $this->getSource();
+ $parameter['source'] = $source;
$serviceResource = $model->getServiceResource() . $model->getId();
try {
@@ -236,4 +244,27 @@ class Request
return $convertedResponse;
}
+
+ /**
+ * Sets the source for requests
+ *
+ * @param string $source
+ * @return \Paymill\Request
+ */
+ public function setSource($source){
+ if(is_string($source)){
+ $this->_source = $source;
+ }
+ return $this;
+ }
+
+ /**
+ * Returns the source for requests
+ *
+ * @return string
+ */
+ public function getSource(){
+ return $this->_source;
+ }
+
}
diff --git a/tests/unit/Paymill/Services/RequestTest.php b/tests/unit/Paymill/Services/RequestTest.php
index <HASH>..<HASH> 100755
--- a/tests/unit/Paymill/Services/RequestTest.php
+++ b/tests/unit/Paymill/Services/RequestTest.php
@@ -40,6 +40,7 @@ class RequestTest
$this->_request = new RequestService();
$this->_client = new Request\Client();
$this->_curlObjectMock = $this->getMock('Paymill\API\Curl', array('requestApi'), array("TestToken"));
+ $this->_request->setSource("UNITTEST");
}
/**
|
PMPW-<I> : added source
|
paymill_paymill-php
|
train
|
78630ec94fec5c4463a9e62d4be9c01238c2656d
|
diff --git a/build/src/main/resources/configuration/subsystems/ejb3.xml b/build/src/main/resources/configuration/subsystems/ejb3.xml
index <HASH>..<HASH> 100644
--- a/build/src/main/resources/configuration/subsystems/ejb3.xml
+++ b/build/src/main/resources/configuration/subsystems/ejb3.xml
@@ -4,15 +4,13 @@
<extension-module>org.jboss.as.ejb3</extension-module>
<subsystem xmlns="urn:jboss:domain:ejb3:2.0">
<session-bean>
- <stateless>
- <bean-instance-pool-ref pool-name="slsb-strict-max-pool"/>
- </stateless>
<?STATEFUL-BEAN?>
<singleton default-access-timeout="5000"/>
</session-bean>
<?MDB?>
<pools>
<bean-instance-pools>
+ <!-- A sample strict max pool configuration -->
<strict-max-pool name="slsb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
<strict-max-pool name="mdb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
</bean-instance-pools>
diff --git a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/ManagedStatelessBean.java b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/ManagedStatelessBean.java
index <HASH>..<HASH> 100644
--- a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/ManagedStatelessBean.java
+++ b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/ManagedStatelessBean.java
@@ -29,6 +29,7 @@ import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
+import org.jboss.ejb3.annotation.Pool;
import org.jboss.ejb3.annotation.SecurityDomain;
/**
@@ -40,6 +41,7 @@ import org.jboss.ejb3.annotation.SecurityDomain;
@SecurityDomain("other")
@DeclareRoles(value = {"Role1", "Role2", "Role3"})
@RunAs("Role3")
+@Pool("slsb-strict-max-pool")
public class ManagedStatelessBean extends AbstractManagedBean implements BusinessInterface {
@Timeout
@Schedule(second="15", persistent = false)
diff --git a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/NoTimerStatelessBean.java b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/NoTimerStatelessBean.java
index <HASH>..<HASH> 100644
--- a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/NoTimerStatelessBean.java
+++ b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/management/deployments/NoTimerStatelessBean.java
@@ -26,6 +26,7 @@ import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RunAs;
import javax.ejb.Stateless;
+import org.jboss.ejb3.annotation.Pool;
import org.jboss.ejb3.annotation.SecurityDomain;
/**
@@ -37,6 +38,7 @@ import org.jboss.ejb3.annotation.SecurityDomain;
@SecurityDomain("other")
@DeclareRoles(value = {"Role1", "Role2", "Role3"})
@RunAs("Role3")
+@Pool("slsb-strict-max-pool")
public class NoTimerStatelessBean implements BusinessInterface {
@Override
|
WFLY-<I> Disable pooling of stateless EJBs by default.
|
wildfly_wildfly
|
train
|
9528e04fde7cab4fc35b178c2ad0ad38ab45a34a
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -53,6 +53,7 @@ module.exports = function debounce( f, ms, ctx, immediate ) {
fn.cancel = function () {
clearTimeout( timeout );
+ timeout = null; // properly clear the timeout so the next call to fn works as expected
};
return fn;
|
FIX: Properly cancel the previous execution of a debounced call
|
royriojas_debouncy
|
train
|
d771f0d6b570ea46d8d35e8efe86ec70878649c2
|
diff --git a/cellpy/_version.py b/cellpy/_version.py
index <HASH>..<HASH> 100644
--- a/cellpy/_version.py
+++ b/cellpy/_version.py
@@ -1,2 +1,2 @@
-version_info = (0, 4, 1, "a2")
+version_info = (0, 4, 1, "a3")
__version__ = ".".join(map(str, version_info))
|
bump v to <I>.a3
|
jepegit_cellpy
|
train
|
da76baef9a148a7994577c30daac21532fa5e7bb
|
diff --git a/openquake/hazardlib/site.py b/openquake/hazardlib/site.py
index <HASH>..<HASH> 100644
--- a/openquake/hazardlib/site.py
+++ b/openquake/hazardlib/site.py
@@ -140,11 +140,16 @@ site_param_dt = {
class SiteCollection(object):
- """
+ __doc__ = """\
A collection of :class:`sites <Site>`.
Instances of this class are intended to represent a large collection
- of sites in a most efficient way in terms of memory usage.
+ of sites in a most efficient way in terms of memory usage. The most
+ common usage is to instantiate it as `SiteCollection.from_points`, by
+ passing the set of required parameters, which must be a subset of the
+ following parameters:
+
+%s
.. note::
@@ -156,7 +161,8 @@ class SiteCollection(object):
:param sites:
A list of instances of :class:`Site` class.
- """
+ """ % '\n'.join(' %s: %s' % item for item in site_param_dt.items())
+
@classmethod
def from_shakemap(cls, shakemap_array):
"""
|
Improved SiteCollection.__doc__ [skip CI]
|
gem_oq-engine
|
train
|
c26776fe48acc52304321d92a5dfcb3e60327c5b
|
diff --git a/gcs/gcsbench_test.go b/gcs/gcsbench_test.go
index <HASH>..<HASH> 100644
--- a/gcs/gcsbench_test.go
+++ b/gcs/gcsbench_test.go
@@ -55,6 +55,30 @@ func BenchmarkGCSFilterBuild50000(b *testing.B) {
generatedFilter = localFilter
}
+// BenchmarkGCSFilterBuild benchmarks building a filter.
+func BenchmarkGCSFilterBuild100000(b *testing.B) {
+ b.StopTimer()
+ var testKey [gcs.KeySize]byte
+ for i := 0; i < gcs.KeySize; i += 4 {
+ binary.BigEndian.PutUint32(testKey[i:], rand.Uint32())
+ }
+ randFilterElems, genErr := genRandFilterElements(100000)
+ if err != nil {
+ b.Fatalf("unable to generate random item: %v", genErr)
+ }
+ b.StartTimer()
+
+ var localFilter *gcs.Filter
+ for i := 0; i < b.N; i++ {
+ localFilter, err = gcs.BuildGCSFilter(P, key,
+ randFilterElems)
+ if err != nil {
+ b.Fatalf("unable to generate filter: %v", err)
+ }
+ }
+ generatedFilter = localFilter
+}
+
var (
match bool
)
|
gcs: add an extra benchmark for a filter with <I>k items
|
btcsuite_btcutil
|
train
|
7dcff6ccc7d844d2ed22362f354d7425a6dd1926
|
diff --git a/API.rdoc b/API.rdoc
index <HASH>..<HASH> 100644
--- a/API.rdoc
+++ b/API.rdoc
@@ -13,13 +13,11 @@ Public API minus the optional stuff like Pool, IdentityMap, Migrations etc.
# Abstract.
Adapter
.new #=> Adapter
- #all #=> Result
#begin #=> Adapter
#commit
#create #=> Scheme or Result
- #destroy #=> Scheme or Result
+ #delete #=> Scheme or Result
#execute #=> Result
- #first #=> Scheme
#get #=> Scheme
#prepare #=> Statement
#rollback
@@ -48,21 +46,21 @@ Public API minus the optional stuff like Pool, IdentityMap, Migrations etc.
#execute #=> Result
Scheme
- .all #=> Result
.attribute #=> Type
.create #=> Scheme or Result
- .first #=> Scheme
.get #=> Scheme
.header #=> Header
.load #=> Scheme
.new #=> Scheme
- .scheme #=> Alias for self.class
.store #=> Symbol
- #destroy #=> Scheme or Result
+ #execute #=> Result
+ #prepare #=> Statement
+ #scheme #=> Alias for self.class
#tuple #=> Hash
#update #=> Scheme or Result
- # Enumerable collection of Types for Scheme
+
+ # Enumerable collection of Types for Scheme.
Header
.new #=> Header
#all #=> [Type, ...]
@@ -83,7 +81,7 @@ Public API minus the optional stuff like Pool, IdentityMap, Migrations etc.
#default #=> Object
#define_scheme_methods
- # Concrete
+ # Concrete.
Type
BigDecimal < Attribute
Boolean < Attribute
diff --git a/lib/swift/scheme.rb b/lib/swift/scheme.rb
index <HASH>..<HASH> 100644
--- a/lib/swift/scheme.rb
+++ b/lib/swift/scheme.rb
@@ -46,8 +46,8 @@ module Swift
# email: 'apple@arthurton.local',
# updated_at: Time.now
# )
- # apple.destroy
- def destroy resources = self
+ # apple.delete
+ def delete resources = self
Swift.db.destroy(scheme, resources)
end
@@ -113,51 +113,16 @@ module Swift
Swift.db.get(self, keys)
end
- # Select one or more.
- #
- # @example All.
- # User.all
- # @example All with conditions and binds.
- # User.all(':name = ? and :age > ?', 'Apple Arthurton', 32)
- # @example Block form iterator.
- # User.all(':age > ?', 32) do |user|
- # puts user.name
- # end
- #
- # @param [String] statement Optional select statement.
- # @param [Object, ...] *binds Optional bind values that accompany the statement.
- # @param [Proc] &block Optional 'each' iterator block.
- # @return [Swift::Result]
#--
- # TODO: select/find_all ala Enumerable?
- # TODO: Binds must be an Array to stop the splat -> array -> splat stuff.
- def all statement = '', *binds, &block
- Swift.db.all(self, statement, *binds, &block)
+ # TODO: Document.
+ def prepare statement = ''
+ Swift.db.prepare(self, statement)
end
- # Select one.
- #
- # Sugar to shift the first result from a result set. Does not limit the size of the set so remember to do that
- # yourself.
- #
- # @example First.
- # User.first
- # @example First with conditions and binds.
- # User.first(':name = ? and :age > ?', 'Apple Arthurton', 32)
- # @example Block form iterator.
- # User.first(User, 'age > ?', 32) do |user|
- # puts user.name
- # end
- #
- # @param [String] statement Optional select statement.
- # @param [Object, ...] *binds Optional bind values that accompany conditions SQL fragment.
- # @param [Proc] &block Optional 'each' iterator block.
- # @return [Swift::Scheme, nil]
#--
- # TODO: find/detect ala Enumerable?
- # TODO: Binds must be an Array to stop the splat -> array -> splat stuff.
- def first statement = '', *binds, &block
- Swift.db.first(self, statement, *binds, &block)
+ # TODO: Document.
+ def execute statement = '', *binds, &block
+ Swift.db.execute(self, statement, *binds, &block)
end
end
end # Scheme
diff --git a/test/test_scheme.rb b/test/test_scheme.rb
index <HASH>..<HASH> 100644
--- a/test/test_scheme.rb
+++ b/test/test_scheme.rb
@@ -84,11 +84,11 @@ describe 'scheme' do
it 'adapter should delete only relevant rows given condition & scheme' do
Swift.db.create(@user, [{name: 'dave'}, {name: 'mike'}])
- assert_equal 2, @user.all.rows
+ assert_equal 2, @user.execute("select * from #{@user.store}").rows
Swift.db.delete @user, "delete from #{@user.store} where #{@user.name} = ?", 'dave'
- assert_nil @user.first "select * from #{@user.store} where #{@user.name} = ?", 'dave'
- assert @user.first "select * from #{@user.store} where #{@user.name} = ?", 'mike'
+ assert_nil @user.execute("select * from #{@user.store} where #{@user.name} = ?", 'dave').first
+ assert @user.execute("select * from #{@user.store} where #{@user.name} = ?", 'mike').first
end
it 'should not update without valid keys' do
@@ -99,7 +99,7 @@ describe 'scheme' do
it 'should update with valid keys' do
user = @user.create
assert user.update(name: 'dave')
- assert_equal 'dave', @user.first.name
+ assert_equal 'dave', @user.execute("select * from #{@user.store}").first.name
end
end
end
|
Removing all/first SQL generation.
|
shanna_swift
|
train
|
920cc9a7c2822d65c6fcbe268aa28d10efebaa2c
|
diff --git a/spec/unit/mongoid/criteria_spec.rb b/spec/unit/mongoid/criteria_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/mongoid/criteria_spec.rb
+++ b/spec/unit/mongoid/criteria_spec.rb
@@ -892,11 +892,11 @@ describe Mongoid::Criteria do
end
it "is false when asking about a private criteria instance method without including private methods" do
- criteria.respond_to?(:gsub).should be_false
+ criteria.respond_to?(:puts).should be_false
end
it "is true when asking about a private criteria instance method when including private methods" do
- criteria.respond_to?(:gsub, true).should be_true
+ criteria.respond_to?(:puts, true).should be_true
end
end
|
Fix build. Rubies have work to do on consistent method publicity.
|
mongodb_mongoid
|
train
|
d6b923adbdfc9a4df20132f741bbfb43db12113c
|
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -37,6 +37,9 @@ module ActiveRecord
[Base, DynamicFinderMatch, ConnectionAdapters::AbstractAdapter]
end
+ autoload :ActiveRecordError, 'active_record/base'
+ autoload :ConnectionNotEstablished, 'active_record/base'
+
autoload :Aggregations, 'active_record/aggregations'
autoload :AssociationPreload, 'active_record/association_preload'
autoload :Associations, 'active_record/associations'
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index <HASH>..<HASH> 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -2990,3 +2990,6 @@ module ActiveRecord #:nodoc:
include Aggregations, Transactions, Reflection, Calculations, Serialization
end
end
+
+# TODO: Remove this and make it work with LAZY flag
+require 'active_record/connection_adapters/abstract_adapter'
|
get activerecord tests passing with lazy loading
|
rails_rails
|
train
|
c4684c8b72de56c5b4c475443ec92eee72b0d57b
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -180,13 +180,11 @@ Tracker.prototype._requestUdp = function (requestUrl, opts) {
function error (message) {
self.client.emit('error', new Error(message + ' (connecting to tracker ' + requestUrl + ')'))
- socket.close()
+ try { socket.close() } catch (e) { }
clearTimeout(timeout)
}
- socket.on('error', function (err) {
- error(err)
- })
+ socket.on('error', error)
socket.on('message', function (message, rinfo) {
|
fixed issue where an erroneous tracker could cause webtorrent to crash because socket.close was already closed after an error state
|
ZeroNetJS_zeronet-tracker
|
train
|
151e3333937c468f2cdca5a3c77241409919e45f
|
diff --git a/nerdamer.core.js b/nerdamer.core.js
index <HASH>..<HASH> 100644
--- a/nerdamer.core.js
+++ b/nerdamer.core.js
@@ -4327,7 +4327,7 @@ var nerdamer = (function (imports) {
acsc: function (symbol) {
if (Settings.PARSE2NUMBER) {
if (symbol.isConstant())
- return new Symbol(Math.acos(symbol.invert().valueOf()));
+ return new Symbol(Math.asin(symbol.invert().valueOf()));
if (symbol.isImaginary())
return complex.evaluate(symbol, 'acsc');
}
|
Fixed a bug that was causing the acsc to return symbol acos(1/x) instead of asin(1/x)
|
jiggzson_nerdamer
|
train
|
039aaf5f37dbc7d57955556ed06b769d079ea699
|
diff --git a/src/Tenanti/Migrator.php b/src/Tenanti/Migrator.php
index <HASH>..<HASH> 100644
--- a/src/Tenanti/Migrator.php
+++ b/src/Tenanti/Migrator.php
@@ -43,7 +43,7 @@ class Migrator extends \Illuminate\Database\Migrations\Migrator
return $this->pretendToRun($migration, 'up');
}
- $migration->up($this->entity);
+ $migration->up($this->entity->getKey(), $this->entity);
// Once we have run a migrations class, we will log that it was run in this
// repository so that we don't try to run it next time we do a migration
@@ -73,7 +73,7 @@ class Migrator extends \Illuminate\Database\Migrations\Migrator
return $this->pretendToRun($instance, 'down');
}
- $instance->down($this->entity);
+ $instance->down($this->entity->getKey(), $this->entity);
// Once we have successfully run the migration "down" we will remove it from
// the migration repository so it will be considered to have not been run
|
Use id as first parameter.
|
orchestral_tenanti
|
train
|
e65b3f34ab84d3d5686b5c384598dd5317fc07f6
|
diff --git a/lib/clickatell/api.rb b/lib/clickatell/api.rb
index <HASH>..<HASH> 100644
--- a/lib/clickatell/api.rb
+++ b/lib/clickatell/api.rb
@@ -69,12 +69,13 @@ module Clickatell
# Additional options:
# :from - the from number/name
# :set_mobile_originated - mobile originated flag
- #
+ # :client_message_id - user specified message id that can be used in place of Clickatell issued API message ID for querying message
# Returns a new message ID if successful.
def send_message(recipient, message_text, opts={})
- valid_options = opts.only(:from, :mo, :callback)
+ valid_options = opts.only(:from, :mo, :callback, :climsgid)
valid_options.merge!(:req_feat => '48') if valid_options[:from]
valid_options.merge!(:mo => '1') if opts[:set_mobile_originated]
+ valid_options.merge!(:climsgid => opts[:client_message_id]) if opts[:client_message_id]
recipient = recipient.join(",")if recipient.is_a?(Array)
response = execute_command('sendmsg', 'http',
{:to => recipient, :text => message_text}.merge(valid_options)
diff --git a/spec/api_spec.rb b/spec/api_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/api_spec.rb
+++ b/spec/api_spec.rb
@@ -147,6 +147,12 @@ module Clickatell
Response.stubs(:parse).with(response).returns('ID' => 'message_id')
@api.send_message('4477791234567', 'hello world', :callback => 1)
end
+
+ it "should set the client message id to the number passed in the options hash" do
+ @executor.expects(:execute).with('sendmsg', 'http', has_entry(:climsgid => 12345678)).returns(response=mock('response'))
+ Response.stubs(:parse).with(response).returns('ID' => 'message_id')
+ @api.send_message('4477791234567', 'hello world', :client_message_id => 12345678)
+ end
it "should ignore any invalid parameters when sending a message" do
@executor.expects(:execute).with('sendmsg', 'http', Not(has_key(:any_old_param))).returns(response = stub('response'))
|
updated api to accept a client message id that can be used in place of the generated Clickatell API message id
|
lukeredpath_clickatell
|
train
|
123696e21f7daa581c89f6d4891653465cc7e2a8
|
diff --git a/openaps/uses/registry.py b/openaps/uses/registry.py
index <HASH>..<HASH> 100644
--- a/openaps/uses/registry.py
+++ b/openaps/uses/registry.py
@@ -1,13 +1,4 @@
-__USES__ = { }
-def use ( ):
- def decorator (cls):
- if cls.__name__ not in __USES__:
- __USES__[cls.__name__] = cls
- return cls
- return decorator
-
-
class Registry (object):
def __init__ (self):
self.__USES__ = { }
@@ -18,3 +9,4 @@ class Registry (object):
self.__USES__[cls.__name__] = cls
return cls
return decorator
+
|
clean up registry, rm older prototype code
|
openaps_openaps
|
train
|
a8ea9445aae5822a988356633cba3e8d3ba7e319
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -35,7 +35,7 @@ requirements = [
# Protocol and data packages
"pytmpdir >= 0.2.3", # A temporary directory, useful for extracting archives to
"txhttputil >= 0.2.7", # Utility class for http requests
- "vortexpy >= 1.0.1", # Data serialisation and transport layer, observable based
+ "vortexpy >= 1.0.2", # Data serialisation and transport layer, observable based
# SOAP interface packages
"SOAPpy-py3 >= 0.52.24", # See http://soappy.ooz.ie for tutorials
|
Updating PoF SQL sql now also updates data using that SQL
OR<I>-<I>
|
Synerty_peek-plugin-base
|
train
|
dd050a094c5159cd90e4f90d0e09f1a8206010da
|
diff --git a/src/Illuminate/Support/Arr.php b/src/Illuminate/Support/Arr.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Support/Arr.php
+++ b/src/Illuminate/Support/Arr.php
@@ -313,17 +313,9 @@ class Arr
*/
public static function has($array, $keys)
{
- if (is_null($keys)) {
- return false;
- }
-
$keys = (array) $keys;
- if (! $array) {
- return false;
- }
-
- if ($keys === []) {
+ if (! $array || $keys === []) {
return false;
}
diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php
index <HASH>..<HASH> 100644
--- a/tests/Support/SupportArrTest.php
+++ b/tests/Support/SupportArrTest.php
@@ -321,6 +321,12 @@ class SupportArrTest extends TestCase
$this->assertFalse(Arr::has([], [null]));
$this->assertFalse(Arr::has(null, [null]));
+
+ $this->assertTrue(Arr::has(['' => 'some'], ''));
+ $this->assertTrue(Arr::has(['' => 'some'], ['']));
+ $this->assertFalse(Arr::has([''], ''));
+ $this->assertFalse(Arr::has([], ''));
+ $this->assertFalse(Arr::has([], ['']));
}
public function testIsAssoc()
|
[<I>] Arr::has code clean up (#<I>)
* Null value are coerced to an empty array, we do not need this check.
* Combine the two if blocks.
* Added more tests for edge cases
|
laravel_framework
|
train
|
5d591dde0f5e067a8a0ebc343eda3c16febf2831
|
diff --git a/client/state/plugins/installed/reducer.js b/client/state/plugins/installed/reducer.js
index <HASH>..<HASH> 100644
--- a/client/state/plugins/installed/reducer.js
+++ b/client/state/plugins/installed/reducer.js
@@ -2,7 +2,6 @@
* External dependencies
*/
import {
- uniqBy,
omit,
findIndex,
} from 'lodash';
@@ -58,7 +57,7 @@ const updatePlugin = function( state, action ) {
*/
export const plugins = createReducer( {}, {
[ PLUGINS_REQUEST_SUCCESS ]: ( state, action ) => {
- return { ...state, [ action.siteId ]: uniqBy( action.data, 'slug' ) };
+ return { ...state, [ action.siteId ]: action.data };
},
[ PLUGINS_REQUEST_FAILURE ]: ( state, action ) => {
return { ...state, [ action.siteId ]: [] };
|
Installed Plugins: Don't reduce the list down to unique plugins by slug because then we can loose active plugins.
If a user has two copies of a plugin, say different versions for testing, in different folders then when we uniq the list we just pick the first one we find which may or may not be the active one.
Ideally we should display the same list of plugins as the wp-admin view does so they can switch between the two versions from Calypso.
|
Automattic_wp-calypso
|
train
|
385a9331ca2f4315d7b78dde87baaa87734cbd67
|
diff --git a/src/com/brein/time/timeseries/ContainerBucketTimeSeries.java b/src/com/brein/time/timeseries/ContainerBucketTimeSeries.java
index <HASH>..<HASH> 100644
--- a/src/com/brein/time/timeseries/ContainerBucketTimeSeries.java
+++ b/src/com/brein/time/timeseries/ContainerBucketTimeSeries.java
@@ -26,6 +26,23 @@ public class ContainerBucketTimeSeries<E extends Serializable & Collection<T>, T
this.supplier = supplier;
}
+ public long[] createByContent(final ContainerBucketTimeSeries<E, T> timeSeries, final BiFunction<E, E, Long> create) {
+ final ContainerBucketTimeSeries<E, T> syncedTs = sync(timeSeries, (ts) -> new ContainerBucketTimeSeries<>(ts.getSupplier(), ts.getConfig(), ts.timeSeries, ts.getNow()));
+
+ final long[] result = new long[config.getTimeSeriesSize()];
+ for (int i = 0; i < config.getTimeSeriesSize(); i++) {
+ final int idx = idx(currentNowIdx + i);
+
+ final E coll = get(idx);
+ final E syncedColl = syncedTs.get(syncedTs.idx(syncedTs.currentNowIdx + i));
+
+ final Long val = create.apply(coll, syncedColl);
+ result[i] = val == null ? -1L : val;
+ }
+
+ return result;
+ }
+
public void combineByContent(final ContainerBucketTimeSeries<E, T> timeSeries, final BiConsumer<E, E> combine) throws IllegalConfiguration {
combineByContent(timeSeries, (coll1, coll2) -> {
|
- added create by content for long series
|
Breinify_brein-time-utilities
|
train
|
742fe00007624c5eaad8b990f46ec8491107370b
|
diff --git a/src/main/java/com/lazerycode/selenium/download/DownloadHandler.java b/src/main/java/com/lazerycode/selenium/download/DownloadHandler.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/lazerycode/selenium/download/DownloadHandler.java
+++ b/src/main/java/com/lazerycode/selenium/download/DownloadHandler.java
@@ -50,13 +50,13 @@ public class DownloadHandler {
String currentFileAbsolutePath = this.downloadedZipFileDirectory + File.separator + FilenameUtils.getName(fileToDownload.getValue().getFileLocation().getFile());
File desiredFile = new File(currentFileAbsolutePath);
File fileToUnzip = downloadFile(fileToDownload.getValue());
- LOG.info("Checking to see if archive file '" + currentFileAbsolutePath + "' exists : " + desiredFile.exists());
+ LOG.info("Checking to see if archive file '" + desiredFile.getName() + "' exists : " + desiredFile.exists());
if (desiredFile.exists()) {
if (checkFileHash) {
FileHashChecker fileHashChecker = new FileHashChecker(desiredFile);
fileHashChecker.setExpectedHash(fileToDownload.getValue().getHash(), fileToDownload.getValue().getHashType());
boolean fileIsValid = fileHashChecker.fileIsValid();
- LOG.info("Checking to see if archive file '" + currentFileAbsolutePath + "' is valid: " + fileIsValid);
+ LOG.info("Checking to see if archive file '" + desiredFile.getName() + "' is valid : " + fileIsValid);
if (fileIsValid) {
fileToUnzip = new File(currentFileAbsolutePath);
}
|
Only display filename not entire path in logs.
|
Ardesco_selenium-standalone-server-plugin
|
train
|
b790f141d1ba746d1e0291e5a383a8e2ddad6388
|
diff --git a/Controller/Email/Accountcallback.php b/Controller/Email/Accountcallback.php
index <HASH>..<HASH> 100755
--- a/Controller/Email/Accountcallback.php
+++ b/Controller/Email/Accountcallback.php
@@ -125,7 +125,7 @@ class Accountcallback extends \Magento\Framework\App\Action\Action
<h2 class='center'>Congratulations your dotmailer account is now ready,
time to make your marketing awesome</h2>
<div class='center'>
- <input type='submit' class='center' value='Start making money' />
+ <input id='btnStartMakingMoney' type='submit' class='center' value='Start making money' />
</div>
</div>";
}
diff --git a/view/adminhtml/web/js/fancyBoxInit.js b/view/adminhtml/web/js/fancyBoxInit.js
index <HASH>..<HASH> 100644
--- a/view/adminhtml/web/js/fancyBoxInit.js
+++ b/view/adminhtml/web/js/fancyBoxInit.js
@@ -19,5 +19,15 @@ require(['jquery', 'fancybox', 'domReady!'], function ($) {
$(document).on('click', 'a.fancybox-close', function () {
location.reload();
});
+
+ window.addEventListener("message", function(event) {
+ if (event.origin != 'https://magentosignup.dotmailer.com') {
+ return;
+ }
+
+ if (event.data === "close") {
+ location.reload();
+ }
+ });
}
});
|
Merged PR <I>: Merge sl/bundle-<I> to testing
Add event listener to enable cross frame communication.
|
dotmailer_dotmailer-magento2-extension
|
train
|
b82bbb4fcb7a05b8b929fddfcff40bbd8b0edac4
|
diff --git a/code/png.py b/code/png.py
index <HASH>..<HASH> 100755
--- a/code/png.py
+++ b/code/png.py
@@ -725,36 +725,35 @@ class Writer:
def extend(sl):
oldextend(map(lambda x: int(round(factor*x)), sl))
- # A test mostly to see if numpy integer types cause our
- # definition of extend to fail. See
+ # Build the first row, testing mostly to see if we need to
+ # changed the extend function to cope with NumPy integer types
+ # (they cause our ordinary definition of extend to fail, so we
+ # wrap it). See
# http://code.google.com/p/pypng/issues/detail?id=44
- try:
- row = rows[0]
- except:
- row = rows.next()
+ enumrows = enumerate(rows)
+ del rows
+
+ # First row's filter type.
+ data.append(0)
+ # :todo: Certain exceptions in the call to ``.next()`` or the
+ # following try would indicate no row data supplied.
+ # Should catch.
+ i,row = enumrows.next()
try:
# If this fails...
extend(row)
except:
- # Try a version that converts the values to int first.
+ # ... try a version that converts the values to int first.
+ # Not only does this work for the (slightly broken) NumPy
+ # types, there are probably lots of other, unknown, "nearly"
+ # int types it works for.
def wrapmapint(f):
return lambda sl: f(map(int, sl))
extend = wrapmapint(extend)
del wrapmapint
- # Reset the data array, because we corrupted it with our test
- # row.
- del data[:]
- try:
- rows[0]
- except:
- # Might be more efficient to use itertools.tee, but that would
- # cause fail on Python 2.2.
- rows = itertools.chain([row], rows)
-
- # Hack to make the row count and the error message correct in the
- # case where caller supplies no data.
- i = -1
- for i,row in enumerate(rows):
+ extend(row)
+
+ for i,row in enumrows:
# Add "None" filter type. Currently, it's essential that
# this filter type be used for every scanline as we do not
# mark the first row of a reduced pass image; that means we
@@ -767,7 +766,7 @@ class Writer:
if len(compressed):
# print >> sys.stderr, len(data), len(compressed)
write_chunk(outfile, 'IDAT', compressed)
- # Because of our very writty definition of ``extend``,
+ # Because of our very witty definition of ``extend``,
# above, we must re-use the same ``data`` object. Hence
# we use ``del`` to empty this one, rather than create a
# fresh one (which would be my natural FP instinct).
|
write_passes now consumes each row exactly once. Fixes Issue <I>.
git-svn-id: <URL>
|
drj11_pypng
|
train
|
4c5a7830c78ac8e647e351cb65d9ef295fc4a9d7
|
diff --git a/arcgis/arcgis.py b/arcgis/arcgis.py
index <HASH>..<HASH> 100644
--- a/arcgis/arcgis.py
+++ b/arcgis/arcgis.py
@@ -143,6 +143,11 @@ class ArcGIS:
if count_only:
return jsobj.get('count')
+ # If there is no geometry, we default to assuming it's a Table type
+ # data format, and we dump a simple (non-geo) json of all of the data.
+ if not jsobj.get('geometryType', None):
+ return self.getTable(layer, where, fields, jsobj=jsobj)
+
# From what I can tell, the entire layer tends to be of the same type,
# so we only have to determine the parsing function once.
geom_parser = self._determine_geom_parser(jsobj.get('geometryType'))
@@ -167,6 +172,24 @@ class ArcGIS:
'features': features
}
+ def getTable(self, layer, where="1 = 1", fields=[], jsobj=None):
+ base_where = where
+ features = []
+ # We always want to run once, and then break out as soon as we stop
+ # getting exceededTransferLimit.
+ while True:
+ features += [feat.get('attributes') for feat in jsobj.get('features')]
+ if jsobj.get('exceededTransferLimit', False) == False:
+ break
+ # If we've hit the transfer limit we offset by the last OBJECTID
+ # returned and keep moving along.
+ where = "%s > %s" % (self.object_id_field, features[-1]['properties'].get(self.object_id_field))
+ if base_where != "1 = 1" :
+ # If we have another WHERE filter we needed to tack that back on.
+ where += " AND %s" % base_where
+ jsobj = self.get_json(layer, where, fields)
+ return features
+
def getMultiple(self, layers, where="1 = 1", fields=[], srid='4326', layer_name_field=None):
"""
Get a bunch of layers and concatenate them together into one. This is useful if you
|
Added a method to just grab non-geo, Table-type data from arcgis
|
Schwanksta_python-arcgis-rest-query
|
train
|
eb76b7b10418c41a43e79b3432b79adfe6b6c8f1
|
diff --git a/packages/request-maxdome/src/Asset.js b/packages/request-maxdome/src/Asset.js
index <HASH>..<HASH> 100644
--- a/packages/request-maxdome/src/Asset.js
+++ b/packages/request-maxdome/src/Asset.js
@@ -18,7 +18,7 @@ class Asset {
this.title += ` (Staffel ${data.number})`;
}
this.searchTitle = data.title.replace(' (Hot from the US)', '');
- this.hotFromUS = data.title.includes(' (Hot from the US)');
+ this.hotFromTheUS = data.title.includes(' (Hot from the US)');
this.episodeTitle = data.episodeTitle;
this.episodeNumber = data.episodeNumber;
this.seasonNumber = data.seasonNumber || data.number;
|
Fix attributename hotFromUS => hotFromTheUS
|
Sharaal_dnode
|
train
|
4d74848f5f31bf07052efc4e99c0e61bcafda068
|
diff --git a/app/Http/RequestHandlers/MergeFactsAction.php b/app/Http/RequestHandlers/MergeFactsAction.php
index <HASH>..<HASH> 100644
--- a/app/Http/RequestHandlers/MergeFactsAction.php
+++ b/app/Http/RequestHandlers/MergeFactsAction.php
@@ -127,6 +127,7 @@ class MergeFactsAction implements RequestHandlerInterface
DB::table('hit_counter')
->where('gedcom_id', '=', $tree->id())
->where('page_name', '=', $page_name)
+ ->where('page_parameter', '=', $xref1)
->update(['page_count' => $page_count]);
}
|
Fix: merging records breaks hit-counter
|
fisharebest_webtrees
|
train
|
c3dcc0ad37e06cdddf2da859bf5a5aaa4271a403
|
diff --git a/asn1crypto/core.py b/asn1crypto/core.py
index <HASH>..<HASH> 100644
--- a/asn1crypto/core.py
+++ b/asn1crypto/core.py
@@ -638,7 +638,7 @@ class Constructable(object):
"""
# Instance attribute indicating if an object was indefinite
- # length when parsed – affects parsing and dumping
+ # length when parsed - affects parsing and dumping
_indefinite = False
# Class attribute that indicates the offset into self.contents
@@ -2267,7 +2267,7 @@ class IntegerBitString(Constructable, Castable, Primitive):
Allows reconstructing indefinite length values
:return:
- A unicode string of bits – 1s and 0s
+ A unicode string of bits - 1s and 0s
"""
extra_bits = int_from_bytes(self.contents[0:1])
@@ -3471,7 +3471,7 @@ class Sequence(Asn1Value):
raise ValueError(unwrap(
'''
Can not set a native python value to %s, which has the
- choice type of %s – value must be an instance of Asn1Value
+ choice type of %s - value must be an instance of Asn1Value
''',
field_name,
type_name(value_spec)
@@ -3911,7 +3911,7 @@ class SequenceOf(Asn1Value):
raise ValueError(unwrap(
'''
Can not set a native python value to %s where the
- _child_spec is Any – value must be an instance of Asn1Value
+ _child_spec is Any - value must be an instance of Asn1Value
''',
type_name(self)
))
@@ -3921,7 +3921,7 @@ class SequenceOf(Asn1Value):
raise ValueError(unwrap(
'''
Can not set a native python value to %s where the
- _child_spec is the choice type %s – value must be an
+ _child_spec is the choice type %s - value must be an
instance of Asn1Value
''',
type_name(self),
|
Remove en dashes from various comments and exceptions to help users with unicode issues in terminals
|
wbond_asn1crypto
|
train
|
c1ca9409afab5cd27be4d998fc445023cad42a24
|
diff --git a/src/config/bot-agent-list.php b/src/config/bot-agent-list.php
index <HASH>..<HASH> 100644
--- a/src/config/bot-agent-list.php
+++ b/src/config/bot-agent-list.php
@@ -120,4 +120,5 @@ $botagents=array("trueknowledgebot" => "TrueKnowledgeBot",
"seobility" => "Seobility SEO-Check",
"seocheck" => "SeoCheck",
"teoma" => "Teoma",
-); ?>
\ No newline at end of file
+"uptimebot" => "Uptimebot",
+); ?>
|
Fixed #<I>, Add Uptimebot
|
BugBuster1701_botdetection
|
train
|
4e5ec1b16f9bb66062617a94a2775f12b156d6c2
|
diff --git a/src/pymp4/parser.py b/src/pymp4/parser.py
index <HASH>..<HASH> 100644
--- a/src/pymp4/parser.py
+++ b/src/pymp4/parser.py
@@ -626,7 +626,8 @@ SoundMediaHeaderBox = Struct(
"type" / Const(b"smhd"),
"version" / Const(Int8ub, 0),
"flags" / Const(Int24ub, 0),
- "balance" / Default(Int16sb, 0)
+ "balance" / Default(Int16sb, 0),
+ Const(Int16ub, 0),
)
diff --git a/tests/test_box.py b/tests/test_box.py
index <HASH>..<HASH> 100644
--- a/tests/test_box.py
+++ b/tests/test_box.py
@@ -103,3 +103,19 @@ class BoxTests(unittest.TestCase):
b'\x00\x00\x00\x20trex\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x20trex\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
)
+
+ def test_smhd_parse(self):
+ in_bytes = b'\x00\x00\x00\x10smhd\x00\x00\x00\x00\x00\x00\x00\x00'
+ self.assertEqual(
+ Box.parse(in_bytes + b'padding'),
+ Container(offset=0)
+ (type=b"smhd")(version=0)(flags=0)
+ (balance=0)(reserved=0)(end=len(in_bytes))
+ )
+
+ def test_smhd_build(self):
+ smhd_data = Box.build(dict(
+ type=b"smhd",
+ balance=0))
+ self.assertEqual(len(smhd_data), 16),
+ self.assertEqual(smhd_data, b'\x00\x00\x00\x10smhd\x00\x00\x00\x00\x00\x00\x00\x00')
|
Fix smhd - missing reserved field
Add padding bytes in test to verify only expected bytes read
|
beardypig_pymp4
|
train
|
4de1d28c4665ea8116f6941d90584393ecf4458c
|
diff --git a/plenum/server/consensus/ordering_service.py b/plenum/server/consensus/ordering_service.py
index <HASH>..<HASH> 100644
--- a/plenum/server/consensus/ordering_service.py
+++ b/plenum/server/consensus/ordering_service.py
@@ -2262,6 +2262,8 @@ class OrderingService:
self._logger.info("{} processing {}".format(self, msg))
+ self.primaries_batch_needed = True
+
# apply PrePrepares from NewView that we have
# request missing PrePrepares from NewView
missing_batches = []
|
INDY-<I>: Fix more tests
|
hyperledger_indy-plenum
|
train
|
c2ce0606900517e98f5dbfbd7d03f91424bc5867
|
diff --git a/secretservice/secretservice.go b/secretservice/secretservice.go
index <HASH>..<HASH> 100644
--- a/secretservice/secretservice.go
+++ b/secretservice/secretservice.go
@@ -73,6 +73,7 @@ func NewService() (*SecretService, error) {
}
signalCh := make(chan *dbus.Signal, 16)
conn.Signal(signalCh)
+ _ = conn.AddMatchSignal(dbus.WithMatchOption("org.freedesktop.Secret.Prompt", "Completed"))
return &SecretService{conn: conn, signalCh: signalCh, sessionOpenTimeout: DefaultSessionOpenTimeout}, nil
}
|
add signal match (#<I>)
|
keybase_go-keychain
|
train
|
6a6f6af36b7effbb9e188ff58887013a76173cfa
|
diff --git a/lib/html/proofer/check_runner/issue.rb b/lib/html/proofer/check_runner/issue.rb
index <HASH>..<HASH> 100644
--- a/lib/html/proofer/check_runner/issue.rb
+++ b/lib/html/proofer/check_runner/issue.rb
@@ -5,9 +5,9 @@ class HTML::Proofer::CheckRunner
attr_reader :path, :desc, :status, :line_number
def initialize(path, desc, line_number = nil, status = -1)
- @line_number = " (line #{line_number || 'not given'})"
+ @line_number = line_number.nil? ? '' : " (line #{line_number})"
@path = path
- @desc = desc << @line_number
+ @desc = desc
@status = status
end
@@ -52,9 +52,9 @@ class HTML::Proofer::CheckRunner
matcher = issue.send(first_report)
end
if first_report == :status
- @logger.log :error, :red, " * #{issue}"
+ @logger.log :error, :red, " * #{issue}#{issue.line_number}"
else
- @logger.log :error, :red, " * #{issue.send(second_report)}"
+ @logger.log :error, :red, " * #{issue.send(second_report)}#{issue.line_number}"
end
end
end
diff --git a/lib/html/proofer/checkable.rb b/lib/html/proofer/checkable.rb
index <HASH>..<HASH> 100644
--- a/lib/html/proofer/checkable.rb
+++ b/lib/html/proofer/checkable.rb
@@ -6,6 +6,7 @@ module HTML
# Represents the superclass from which all checks derive.
class Checkable
include HTML::Utils
+ attr_reader :line
def initialize(obj, check)
obj.attributes.each_pair do |attribute, value|
diff --git a/spec/html/proofer_spec.rb b/spec/html/proofer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/html/proofer_spec.rb
+++ b/spec/html/proofer_spec.rb
@@ -52,13 +52,13 @@ describe HTML::Proofer do
output = send_proofer_output("#{FIXTURES_DIR}/sorting/issue", :error_sort => :desc)
expect(output.strip).to eq('''
- image ./gpl.png does not have an alt attribute
- * spec/html/proofer/fixtures/sorting/issue/broken_image_one.html
- * spec/html/proofer/fixtures/sorting/issue/broken_image_two.html
+ * spec/html/proofer/fixtures/sorting/issue/broken_image_one.html (line 1)
+ * spec/html/proofer/fixtures/sorting/issue/broken_image_two.html (line 1)
- internal image ./gpl.png does not exist
- * spec/html/proofer/fixtures/sorting/issue/broken_image_one.html
- * spec/html/proofer/fixtures/sorting/issue/broken_image_two.html
+ * spec/html/proofer/fixtures/sorting/issue/broken_image_one.html (line 1)
+ * spec/html/proofer/fixtures/sorting/issue/broken_image_two.html (line 1)
- internal image NOT_AN_IMAGE does not exist
- * spec/html/proofer/fixtures/sorting/issue/broken_image_two.html
+ * spec/html/proofer/fixtures/sorting/issue/broken_image_two.html (line 4)
'''.strip)
end
@@ -67,7 +67,7 @@ describe HTML::Proofer do
output = send_proofer_output("#{FIXTURES_DIR}/sorting/status", :typhoeus => { :followlocation => false }, :error_sort => :status)
expect(output.strip).to eq('''
- -1
- * spec/html/proofer/fixtures/sorting/status/broken_link.html: internally linking to nowhere.fooof (line 3), which does not exist
+ * spec/html/proofer/fixtures/sorting/status/broken_link.html: internally linking to nowhere.fooof, which does not exist (line 3)
- 404
* spec/html/proofer/fixtures/sorting/status/a_404.html: External link http://upload.wikimedia.org/wikipedia/en/thumb/not_here.png failed: 404 No error
* spec/html/proofer/fixtures/sorting/status/broken_link.html: External link http://upload.wikimedia.org/wikipedia/en/thumb/fooooof.png failed: 404 No error
|
Clean up the line number concatenation
|
gjtorikian_html-proofer
|
train
|
21b3547d015982777023c7c2d7b1bb4f9af76eb6
|
diff --git a/cdm/src/main/java/ucar/nc2/Group.java b/cdm/src/main/java/ucar/nc2/Group.java
index <HASH>..<HASH> 100644
--- a/cdm/src/main/java/ucar/nc2/Group.java
+++ b/cdm/src/main/java/ucar/nc2/Group.java
@@ -1,5 +1,5 @@
/*
- * Copyright 1998-2014 University Corporation for Atmospheric Research/Unidata
+ * Copyright 1998-2017 University Corporation for Atmospheric Research/Unidata
*
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
@@ -379,6 +379,18 @@ public class Group extends CDMNode implements AttributeContainer {
return sbuff.toString();
}
+ /**
+ * CDL representation.
+ *
+ * @param strict if true, write in strict adherence to CDL definition.
+ * @return CDL representation.
+ */
+ public String writeCDL(boolean strict) {
+ Formatter buf = new Formatter();
+ writeCDL(buf, new Indent(2), strict);
+ return buf.toString();
+ }
+
protected void writeCDL(Formatter out, Indent indent, boolean strict) {
boolean hasE = (enumTypedefs.size() > 0);
boolean hasD = (dimensions.size() > 0);
@@ -672,7 +684,7 @@ public class Group extends CDMNode implements AttributeContainer {
@Override
public String toString() {
- return getShortName();
+ return writeCDL(false);
}
/**
|
Return CDL notation from Group.toString
The toString() method in ucar.nc2.FGroup returned only the group short name rather than the CDL description as do other dataset structure classes.
|
Unidata_thredds
|
train
|
c86c306220dae4fd2b45adc1828534e8e3f98347
|
diff --git a/README.rdoc b/README.rdoc
index <HASH>..<HASH> 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -81,15 +81,13 @@ The declaration accepts any number of default parameters a normal controller fil
=== Additional Javascript options
-Sometimes, when you need complex arrays of data for plugins or such, the plugin helpers aren't complex enough to do what you need. But you can always fall back to supplying your own options. You can this by passing a raw javascript (no <script> tags) to the second parameter of the methods that initialize the TinyMCE plugin. Consider the following example for the template plugin.
-
- tiny_mce_init_if_needed(@tiny_mce_options, "template_templates : [
- {
- title : "Editor Details",
- src : "editor_details.htm",
- description : "Adds Editors Name and Staff ID"
- }
- ]")
+Sometimes, when you need complex arrays of data for plugins or such, the plugin helpers aren't complex enough to do what you need. But you can always fall back to supplying your own options. You can this by passing a raw javascript (no <script> tags) to the uses_tiny_mce declaration. Consider the following example for the template plugin.
+
+ uses_tiny_mce :raw_options => "template_templates : [ {
+ title : 'Editor Details',
+ src : 'editor_details.htm',
+ description : 'Adds Editors Name and Staff ID'
+ } ]"
== Methods
diff --git a/lib/tiny_mce.rb b/lib/tiny_mce.rb
index <HASH>..<HASH> 100644
--- a/lib/tiny_mce.rb
+++ b/lib/tiny_mce.rb
@@ -7,6 +7,7 @@ module TinyMCE
module ClassMethods
def uses_tiny_mce(options = {})
tiny_mce_options = options.delete(:options) || {}
+ raw_tiny_mce_options = options.delete(:raw_options) || {}
if !tiny_mce_options[:plugins].blank? && tiny_mce_options[:plugins].include?('spellchecker')
tiny_mce_options.reverse_merge!(:spellchecker_rpc_url => "/" + self.controller_name + "/spellchecker")
self.class_eval do
@@ -15,6 +16,7 @@ module TinyMCE
end
proc = Proc.new do |c|
c.instance_variable_set(:@tiny_mce_options, tiny_mce_options)
+ c.instance_variable_set(:@raw_tiny_mce_options, raw_tiny_mce_options)
c.instance_variable_set(:@uses_tiny_mce, true)
end
before_filter(proc, options)
diff --git a/lib/tiny_mce_helper.rb b/lib/tiny_mce_helper.rb
index <HASH>..<HASH> 100644
--- a/lib/tiny_mce_helper.rb
+++ b/lib/tiny_mce_helper.rb
@@ -6,7 +6,7 @@ module TinyMCEHelper
!@uses_tiny_mce.nil?
end
- def raw_tiny_mce_init(options = @tiny_mce_options, additional_js = "")
+ def raw_tiny_mce_init(options = @tiny_mce_options, raw_options = @raw_tiny_mce_options)
options ||= {}
default_options = { :mode => 'textareas',
:editor_selector => 'mceEditor',
@@ -36,18 +36,18 @@ module TinyMCEHelper
tinymce_js += ",\n"
else
# no more options in this array. Finish it by adding the addition JS
- tinymce_js += ",\n#{additional_js}" unless additional_js.blank?
+ tinymce_js += ",\n#{raw_options}" unless raw_options.blank?
tinymce_js += "\n"
end
end
tinymce_js += "\n});"
end
- def tiny_mce_init(options = @tiny_mce_options, additional_js = "")
- javascript_tag raw_tiny_mce_init(options, additional_js)
+ def tiny_mce_init(options = @tiny_mce_options, raw_options = @raw_tiny_mce_options)
+ javascript_tag raw_tiny_mce_init(options, raw_options)
end
- def tiny_mce_init_if_needed(options = @tiny_mce_options, additional_js = "")
- tiny_mce_init(options, additional_js) if using_tiny_mce?
+ def tiny_mce_init_if_needed(options = @tiny_mce_options, raw_options = @raw_tiny_mce_options)
+ tiny_mce_init(options, raw_options) if using_tiny_mce?
end
def include_tiny_mce_js
@@ -57,9 +57,9 @@ module TinyMCEHelper
include_tiny_mce_js if using_tiny_mce?
end
- def include_tiny_mce_if_needed(options = @tiny_mce_options, additional_js = "")
+ def include_tiny_mce_if_needed(options = @tiny_mce_options, raw_options = @raw_tiny_mce_options)
if using_tiny_mce?
- include_tiny_mce_js + tiny_mce_init(options, additional_js)
+ include_tiny_mce_js + tiny_mce_init(options, raw_options)
end
end
end
|
refinement: minor change to previous commit that allows per controller additional JS.
|
kete_tiny_mce
|
train
|
dd488c339e82ffb9353e7725e0a78ed0d7e9e295
|
diff --git a/test/it/testbase.py b/test/it/testbase.py
index <HASH>..<HASH> 100644
--- a/test/it/testbase.py
+++ b/test/it/testbase.py
@@ -73,8 +73,8 @@ class TestBase(unittest.TestCase):
self.assertEqual(self.bintrayContext.get_service("FAKE_BINTRAY").status(), [])
def waitForCondition(self, f, expected, time_out_secs = default_time_out):
- dead_line = time.clock() + time_out_secs
- while (time.clock() < dead_line):
+ dead_line = time.time() + time_out_secs
+ while (time.time() < dead_line):
if f() == expected: return
time.sleep(0.1)
|
Fix the waitForCondition which was looping forever
|
hmrc_service-manager
|
train
|
2bc86d4c84e544373f9bb2171adfcb41c868911a
|
diff --git a/app/models/catarse_pagarme/bank_account_concern.rb b/app/models/catarse_pagarme/bank_account_concern.rb
index <HASH>..<HASH> 100644
--- a/app/models/catarse_pagarme/bank_account_concern.rb
+++ b/app/models/catarse_pagarme/bank_account_concern.rb
@@ -3,6 +3,8 @@ module CatarsePagarme::BankAccountConcern
included do
+ validate :must_be_valid_on_pagarme
+
def must_be_valid_on_pagarme
pagarme_errors.each do |p_error|
_attr = attributes_parsed_from_pagarme[p_error.parameter_name.to_sym]
diff --git a/lib/catarse_pagarme/engine.rb b/lib/catarse_pagarme/engine.rb
index <HASH>..<HASH> 100644
--- a/lib/catarse_pagarme/engine.rb
+++ b/lib/catarse_pagarme/engine.rb
@@ -5,7 +5,6 @@ module CatarsePagarme
config.to_prepare do
::Contribution.send(:include, CatarsePagarme::ContributionConcern)
::CreditCard.send(:include, CatarsePagarme::CreditCardConcern)
- ::BankAccount.send(:include, CatarsePagarme::BankAccountConcern)
end
end
end
diff --git a/spec/models/catarse_pagarme/bank_account_concern_spec.rb b/spec/models/catarse_pagarme/bank_account_concern_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/catarse_pagarme/bank_account_concern_spec.rb
+++ b/spec/models/catarse_pagarme/bank_account_concern_spec.rb
@@ -2,8 +2,6 @@ require 'spec_helper'
class FakeBankAccount < BankAccount
include CatarsePagarme::BankAccountConcern
-
- validate :must_be_valid_on_pagarme
end
describe FakeBankAccount do
|
we should use include manual on bank account validation
|
catarse_catarse_pagarme
|
train
|
9cd907c9b54d0466f8f395cfe1f2b31eded7005f
|
diff --git a/agent/server.go b/agent/server.go
index <HASH>..<HASH> 100644
--- a/agent/server.go
+++ b/agent/server.go
@@ -87,15 +87,16 @@ func (s *Agent) Subscribe(args *Args, stream rpcplus.Stream) error {
return nil
}
-func (s *Agent) Register(args *Args, ret *struct{}) (string, error) {
+func (s *Agent) Register(args *Args, ret *string) error {
addr := expandAddr(args.Addr)
err := s.Backend.Register(args.Name, addr, args.Attrs)
if err != nil {
log.Println("Register: error:", err)
- return nil, err
+ return err
}
+ ret = &addr
log.Println("Register:", args.Name, addr, args.Attrs)
- return addr, err
+ return nil
}
func (s *Agent) Unregister(args *Args, ret *struct{}) error {
|
discoverd: forgot how rpc works
|
flynn_flynn
|
train
|
412c8866baf2775e31801b9307dde711f551dee9
|
diff --git a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_model_output.py b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_model_output.py
index <HASH>..<HASH> 100644
--- a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_model_output.py
+++ b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_model_output.py
@@ -1,12 +1,17 @@
-library(h2o)
+import h2o
+from h2o.estimators.glm import H2OGeneralizedLinearEstimator
h2o.init()
-path = system.file("extdata", "prostate.csv", package = "h2o")
-h2o_df = h2o.importFile(path)
+h2o_df = h2o.import_file("http://h2o-public-test-data.s3.amazonaws.com/smalldata/prostate/prostate.csv")
+h2o_df['CAPSULE'] = h2o_df['CAPSULE'].asfactor()
+
+
h2o_df$CAPSULE = as.factor(h2o_df$CAPSULE)
rand_vec <- h2o.runif(h2o_df, seed = 1234)
train <- h2o_df[rand_vec <= 0.8,]
valid <- h2o_df[rand_vec > 0.8,]
-binomial.fit = h2o.glm(y = "CAPSULE", x = c("AGE", "RACE", "PSA", "GLEASON"), training_frame = train, validation_frame = valid, family = "binomial")
+
+binomial_fit = H2OGeneralizedLinearEstimator(family = "binomial")
+binomial_fit.train(y = "CAPSULE", x = ["AGE", "RACE", "PSA", "GLEASON"], training_frame = h2o_df)
print(binomial.fit)
binomial.fit@model$coefficients
diff --git a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_recalculate_predict.py b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_recalculate_predict.py
index <HASH>..<HASH> 100644
--- a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_recalculate_predict.py
+++ b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_recalculate_predict.py
@@ -1,3 +1,5 @@
-pred = binomial_fit.predict(h2o_df)
+#manually define our threshold for predictions to be 0.3
+import pandas as pd
+pred = binomial_fit.predict(h2o_df).as_data_frame(use_pandas=True)
+pred['predict'] = (pred.p1 > 0.3).astype(int)
-#redefine our threshold for predictions to be 0.3 rather than 0.5
diff --git a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.R b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.R
index <HASH>..<HASH> 100644
--- a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.R
+++ b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.R
@@ -1,8 +1,8 @@
library(h2o)
h2o.init()
h2o_df = h2o.importFile("http://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
+
+#stops the model when we reach 10 active predictors
+#Objective epsilon and gradient epsilon stopping criteria will be added in a future release.
model = h2o.glm(y = "IsDepDelayed", x = c("Year", "Origin"), training_frame = h2o_df, family = "binomial", lambda_search = TRUE, max_active_predictors = 10)
print(model)
-v1 = model@model$coefficients
-v2 = v1[v1 > 0]
-print(v2)
diff --git a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.py b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.py
index <HASH>..<HASH> 100644
--- a/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.py
+++ b/h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_stopping_criteria.py
@@ -1,8 +1,9 @@
import h2o
h2o.init()
h2o_df = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
+
+#stops the model when we reach 10 active predictors
+#Objective epsilon and gradient epsilon stopping criteria will be added in a future release.
model = h2o.glm(y = "IsDepDelayed", x = ["Year", "Origin"], training_frame = h2o_df, family = "binomial", lambda_search = True, max_active_predictors = 10)
print(model)
-#v1 = model@model$coefficients
-#v2 = v1[v1 > 0]
-#print(v2)
+
|
GLM partial merge- ky's push
|
h2oai_h2o-3
|
train
|
a932b1e171b147214f7b9020eac183e92714a6f6
|
diff --git a/src/meshio/ansys/_ansys.py b/src/meshio/ansys/_ansys.py
index <HASH>..<HASH> 100644
--- a/src/meshio/ansys/_ansys.py
+++ b/src/meshio/ansys/_ansys.py
@@ -18,7 +18,6 @@ def _skip_to(f, char):
c = None
while c != char:
c = f.read(1).decode()
- return
def _skip_close(f, num_open_brackets):
@@ -28,7 +27,6 @@ def _skip_close(f, num_open_brackets):
num_open_brackets += 1
elif char == ")":
num_open_brackets -= 1
- return
def _read_points(f, line, first_point_index_overall, last_point_index):
diff --git a/tests/helpers.py b/tests/helpers.py
index <HASH>..<HASH> 100644
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -668,7 +668,15 @@ def write_read(writer, reader, input_mesh, atol, extension=".dat"):
assert face.flags["WRITEABLE"]
# assert that the input mesh hasn't changed at all
+ assert in_mesh.points.dtype == input_mesh.points.dtype
assert np.allclose(in_mesh.points, input_mesh.points, atol=atol, rtol=0.0)
+ for c0, c1 in zip(in_mesh.cells, input_mesh.cells):
+ print(c0)
+ print(c1)
+ assert c0.type == c1.type
+ assert c0.data.shape == c1.data.shape
+ assert c0.data.dtype == c1.data.dtype
+ assert np.all(c0.data == c1.data)
# Numpy's array_equal is too strict here, cf.
# <https://mail.scipy.org/pipermail/numpy-discussion/2015-December/074410.html>.
|
test that input mesh is not changed at all
|
nschloe_meshio
|
train
|
764ffc95af41602b7ba216bad4be438330c3dc45
|
diff --git a/xarray/core/formatting.py b/xarray/core/formatting.py
index <HASH>..<HASH> 100644
--- a/xarray/core/formatting.py
+++ b/xarray/core/formatting.py
@@ -141,7 +141,7 @@ def format_item(x, timedelta_format=None, quote_strings=True):
return format_timedelta(x, timedelta_format=timedelta_format)
elif isinstance(x, (str, bytes)):
return repr(x) if quote_strings else x
- elif isinstance(x, (float, np.float_)):
+ elif np.issubdtype(type(x), np.floating):
return f"{x:.4}"
else:
return str(x)
diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py
index <HASH>..<HASH> 100644
--- a/xarray/tests/test_formatting.py
+++ b/xarray/tests/test_formatting.py
@@ -87,6 +87,9 @@ class TestFormatting:
(b"foo", "b'foo'"),
(1, "1"),
(1.0, "1.0"),
+ (np.float16(1.1234), "1.123"),
+ (np.float32(1.0111111), "1.011"),
+ (np.float64(22.222222), "22.22"),
]
for item, expected in cases:
actual = formatting.format_item(item)
|
Match all float types in formatitem (#<I>)
* Match all float types in formatitem
* Add formatting tests of other floating types
|
pydata_xarray
|
train
|
7802349c3a5c9d0a2f5d4e172fa4c518a07701a0
|
diff --git a/src/browsing.js b/src/browsing.js
index <HASH>..<HASH> 100644
--- a/src/browsing.js
+++ b/src/browsing.js
@@ -41,7 +41,7 @@ var minorHeading = chalk.bold;
var write = console.log.bind(console);
var prototypeOf = Object.getPrototypeOf;
var properties = Object.getOwnPropertyNames;
-
+var property = Object.getOwnPropertyDescriptor;
// -- Helpers ----------------------------------------------------------
function repeat(text, times) {
@@ -95,10 +95,25 @@ function toPairs(map) {
return [...map.entries()];
}
+function isFunction(a) {
+ return typeof a === 'function';
+}
+
+function describe(p, name) {
+ return [
+ p.value && isFunction(p.value)? name + '()'
+ : p.get && p.set? 'get/set ' + name
+ : p.get? 'get ' + name
+ : p.set? 'set ' + name
+ : /* otherwise */ name
+ , p];
+}
+
function prop(object) {
return (key) => {
try {
- return [key, object[key]];
+ var p = property(object, key);
+ return [describe(p, key), object[key]];
} catch(e) {
return null;
}
@@ -209,13 +224,9 @@ var Browser = Refinable.refine({
pairs.forEach(([category, methods]) => {
display.lineBreak();
display.minorHeading(category);
- methods.forEach(([name, method]) => {
+ methods.forEach(([[name, descriptor], method]) => {
var meta = getObjectMeta(method);
- if (!meta.signature && !meta.name) {
- display.line(` • ${name}`);
- } else {
- display.line(` • ${signature(meta)}`);
- }
+ display.line(` • ${name}`);
var doc = summary(meta);
if (doc) {
display.line(faded(` | ${summary(meta)}`));
|
fix: Use property name in the message list
JS doesn't have methods that *belong* only to a single object,
like Siren does, so properties work more like aliases than
anything else.
This new way of reporting shows the name of the property and
any modifiers it might have.
|
robotlolita_metamagical
|
train
|
ad2a9920f7a4e417560825e0d6c2e48fac054855
|
diff --git a/EpicsUtil/src/main/java/org/epics/util/array/ArrayDouble.java b/EpicsUtil/src/main/java/org/epics/util/array/ArrayDouble.java
index <HASH>..<HASH> 100644
--- a/EpicsUtil/src/main/java/org/epics/util/array/ArrayDouble.java
+++ b/EpicsUtil/src/main/java/org/epics/util/array/ArrayDouble.java
@@ -4,6 +4,7 @@
*/
package org.epics.util.array;
+import java.io.Serializable;
import java.util.Arrays;
/**
@@ -11,7 +12,9 @@ import java.util.Arrays;
*
* @author Gabriele Carcassi
*/
-public final class ArrayDouble extends ListDouble {
+public final class ArrayDouble extends ListDouble implements Serializable {
+
+ private static final long serialVersionUID = 7493025761455302917L;
private final double[] array;
private final boolean readOnly;
diff --git a/EpicsUtil/src/test/java/org/epics/util/array/ArrayDoubleTest.java b/EpicsUtil/src/test/java/org/epics/util/array/ArrayDoubleTest.java
index <HASH>..<HASH> 100644
--- a/EpicsUtil/src/test/java/org/epics/util/array/ArrayDoubleTest.java
+++ b/EpicsUtil/src/test/java/org/epics/util/array/ArrayDoubleTest.java
@@ -4,6 +4,10 @@
*/
package org.epics.util.array;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
@@ -62,4 +66,16 @@ public class ArrayDoubleTest {
ArrayDouble array2 = new ArrayDouble(new double[] {Double.MAX_VALUE}, false);
assertThat(array, not(equalTo(array2)));
}
+
+ @Test
+ public void serialization1() throws Exception {
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ ObjectOutputStream stream = new ObjectOutputStream(buffer);
+ ArrayDouble array = new ArrayDouble(new double[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+ stream.writeObject(array);
+ ObjectInputStream inStream = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
+ ArrayDouble read = (ArrayDouble) inStream.readObject();
+ assertThat(read, not(sameInstance(array)));
+ assertThat(read, equalTo(array));
+ }
}
|
Implementing serialization for ArrayDouble.
|
diirt_util
|
train
|
2931fa425438330f0a369a5e3939f69a48ee10d9
|
diff --git a/src/main/java/sklearn/preprocessing/PolynomialFeatures.java b/src/main/java/sklearn/preprocessing/PolynomialFeatures.java
index <HASH>..<HASH> 100644
--- a/src/main/java/sklearn/preprocessing/PolynomialFeatures.java
+++ b/src/main/java/sklearn/preprocessing/PolynomialFeatures.java
@@ -27,7 +27,6 @@ import com.google.common.collect.Lists;
import org.dmg.pmml.DataType;
import org.dmg.pmml.DerivedField;
import org.dmg.pmml.FieldName;
-import org.dmg.pmml.TypeDefinitionField;
import org.jpmml.converter.ContinuousFeature;
import org.jpmml.converter.Feature;
import org.jpmml.converter.InteractionFeature;
@@ -90,10 +89,10 @@ public class PolynomialFeatures extends Transformer {
features[0] = feature;
- TypeDefinitionField field = encoder.getField(feature.getName());
+ ContinuousFeature continuousFeature = feature.toContinuousFeature();
for(int i = 2; i <= degree; i++){
- features[i - 1] = new PowerFeature(encoder, field, i);
+ features[i - 1] = new PowerFeature(encoder, continuousFeature.getName(), continuousFeature.getDataType(), i);
}
return features;
|
Fixed the encoding of power features. Fixes #<I>
|
jpmml_jpmml-sklearn
|
train
|
d588430ae8e171a62072467977d27f894b0f543c
|
diff --git a/test/spambl_test.py b/test/spambl_test.py
index <HASH>..<HASH> 100644
--- a/test/spambl_test.py
+++ b/test/spambl_test.py
@@ -573,8 +573,7 @@ class GoogleSafeBrowsingTest(unittest.TestCase):
self.assertIn(item.value, self.spam_urls_classification)
self.assertEqual(item.source, self.google_safe_browsing)
self.assertEqual(item.classification, self.spam_urls_classification[item.value].split(','))
-
-
+
def testLookupForSpamUrls(self):
''' lookup should return a sequence of objects representing
all urls when called with sequence of spam urls as argument '''
@@ -600,7 +599,6 @@ class GoogleSafeBrowsingTest(unittest.TestCase):
def tearDownClass(cls):
cls.patcher.stop()
-
class HostCollectionTest(unittest.TestCase):
def setUp(self):
@@ -613,7 +611,7 @@ class HostCollectionTest(unittest.TestCase):
self.not_listed_hosts = self.not_listed_hostnames + self.not_listed_ips
self.host_collection_A = HostCollection(self.listed_hosts)
-
+
self.matching_A = HostCollection(self.listed_hosts+self.not_listed_hosts)
self.not_matching_a = HostCollection(self.not_listed_hosts)
self.empty = HostCollection()
@@ -841,7 +839,7 @@ class IsValidUrlTest(unittest.TestCase):
class BaseUrlTesterTest(unittest.TestCase):
http_urls = []
- ftp_urls = []
+ non_http_urls = []
invalid_urls = []
@classmethod
@@ -870,7 +868,7 @@ class BaseUrlTesterTest(unittest.TestCase):
@classmethod
def getRegisteredRedirectsToFtp(cls, *urls):
- return cls.getRegisteredRedirects(cls.ftp_urls, urls)
+ return cls.getRegisteredRedirects(cls.non_http_urls, urls)
@classmethod
def getRegisteredRedirectsToInvalidUrl(cls, *urls):
@@ -966,7 +964,7 @@ class BaseUrlTesterTest(unittest.TestCase):
if url_in(cls.missing_schema_urls):
raise MissingSchema
- elif url_in(cls.ftp_urls):
+ elif url_in(cls.non_http_urls):
raise InvalidSchema
elif url_in(cls.invalid_urls):
@@ -1029,7 +1027,7 @@ class BaseUrlTesterTest(unittest.TestCase):
return a sequence containing all url addresses of
redirects resolved for given urls '''
- for url in self.http_urls+self.ftp_urls:
+ for url in self.http_urls+self.non_http_urls:
expected = self.getExpectedRedirectUrls((url,))
actual = list(self.base_url_tester.resolve_redirects(url.value))
@@ -1064,7 +1062,7 @@ class BaseUrlTesterTest(unittest.TestCase):
Test is performed for resolve_redirects = False
'''
- url_values = [u.value for u in self.http_urls+self.ftp_urls]
+ url_values = [u.value for u in self.http_urls+self.non_http_urls]
actual = list(self.base_url_tester.urls_to_test(url_values))
self.assertItemsEqual(url_values, actual)
@@ -1081,7 +1079,7 @@ class BaseUrlTesterTest(unittest.TestCase):
method in the result
'''
- for u in self.http_urls+self.ftp_urls:
+ for u in self.http_urls+self.non_http_urls:
urls = u.value,
url_set = set(urls)
|
Rename ftp_urls to non_http_urls in BaseUrlTesterTest
|
piotr-rusin_spam-lists
|
train
|
c11922d4056edaca76f8606706a48b4279930c90
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -157,6 +157,26 @@ new FastClasspathScanner("com.xyz.widget")
.scan();
```
+**Mechanism 3:** Call `ScanResult#classNameToClassInfo()` after calling `FastClasspathScanner#scan()`, then query the class graph directly. Java 8 streams can be used for creating complex multi-criterion class filters using this mechanism.
+
+```
+// Manually query classNameToClassInfo
+ScanResult scanResult = new FastClasspathScanner().scan();
+Map<String, ClassInfo> classNameToClassInfo = scanResult.getClassNameToClassInfo();
+ClassInfo callableClassInfo = classNameToClassInfo.get(Callable.class.getName());
+List<String> callables = callableClassInfo == null ? Collections.emptyList()
+ : callableClassInfo.getNamesOfClassesImplementing();
+
+// Filter all ClassInfo using Java 8 stream filtering:
+List<String> runnableWidgets = new FastClasspathScanner().scan()
+ .getClassNameToClassInfo().values().stream()
+ .filter(c -> c.hasSuperinterface(Runnable.class.getName()))
+ .filter(c -> c.hasSuperclass(Widget.class.getName()))
+ .map(c -> c.getClassName())
+ .collect(Collectors.toList());
+```
+
+
### Classpath mechanisms handled by FastClasspathScanner
FastClasspathScanner handles a number of classpath specification mechanisms, including some non-standard ClassLoader implementations:
diff --git a/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassGraphBuilder.java b/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassGraphBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassGraphBuilder.java
+++ b/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassGraphBuilder.java
@@ -137,22 +137,13 @@ class ClassGraphBuilder {
}
}
- /** Return the sorted list of names of all classes implementing the named interface. */
+ /** Return the sorted list of names of all classes implementing the named interface, and their subclasses. */
List<String> getNamesOfClassesImplementing(final String interfaceName) {
- final ClassInfo interfaceClassInfo = classNameToClassInfo.get(interfaceName);
- if (interfaceClassInfo == null) {
+ final ClassInfo classInfo = classNameToClassInfo.get(interfaceName);
+ if (classInfo == null) {
return Collections.emptyList();
} else {
- final Set<ClassInfo> implementingClasses = ClassInfo.filterClassInfo(
- interfaceClassInfo.getReachableClasses(RelType.CLASSES_IMPLEMENTING),
- /* removeExternalClasses = */ true, ClassType.STANDARD_CLASS);
- // Subclasses of implementing classes also implement the interface
- final Set<ClassInfo> allImplementingClasses = new HashSet<>();
- for (final ClassInfo implementingClass : implementingClasses) {
- allImplementingClasses.add(implementingClass);
- allImplementingClasses.addAll(implementingClass.getReachableClasses(RelType.SUBCLASSES));
- }
- return ClassInfo.getClassNames(allImplementingClasses);
+ return classInfo.getNamesOfClassesImplementing();
}
}
diff --git a/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassInfo.java b/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassInfo.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassInfo.java
+++ b/src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassInfo.java
@@ -597,6 +597,55 @@ public class ClassInfo implements Comparable<ClassInfo> {
return getNamesOfDirectSuperinterfaces().contains(directSuperinterfaceName);
}
+ // -------------
+
+ /** Return the set of all class implementing this interface, and all their subclasses. */
+ public Set<ClassInfo> getClassesImplementing() {
+ if (!isImplementedInterface()) {
+ return Collections.emptySet();
+ } else {
+ final Set<ClassInfo> implementingClasses = ClassInfo.filterClassInfo(
+ getReachableClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClasses = */ true,
+ ClassType.STANDARD_CLASS);
+ // Subclasses of implementing classes also implement the interface
+ final Set<ClassInfo> allImplementingClasses = new HashSet<>();
+ for (final ClassInfo implementingClass : implementingClasses) {
+ allImplementingClasses.add(implementingClass);
+ allImplementingClasses.addAll(implementingClass.getReachableClasses(RelType.SUBCLASSES));
+ }
+ return allImplementingClasses;
+ }
+ }
+
+ /** Return the names of all classes implementing this interface, and all their subclasses. */
+ public List<String> getNamesOfClassesImplementing() {
+ return getClassNames(getClassesImplementing());
+ }
+
+ /** Returns true if this class is implemented by the named class, or by one of its superclasses. */
+ public boolean isImplementedByClass(final String className) {
+ return getNamesOfClassesImplementing().contains(className);
+ }
+
+ // -------------
+
+ /** Return the set of all class directly implementing this interface. */
+ public Set<ClassInfo> getClassesDirectlyImplementing() {
+ return !isImplementedInterface() ? Collections.emptySet()
+ : ClassInfo.filterClassInfo(getRelatedClasses(RelType.CLASSES_IMPLEMENTING),
+ /* removeExternalClasses = */ true, ClassType.STANDARD_CLASS);
+ }
+
+ /** Return the names of all classes directly implementing this interface. */
+ public List<String> getNamesOfClassesDirectlyImplementing() {
+ return getClassNames(getClassesDirectlyImplementing());
+ }
+
+ /** Returns true if this class is directly implemented by the named class. */
+ public boolean isDirectlyImplementedByClass(final String className) {
+ return getNamesOfClassesDirectlyImplementing().contains(className);
+ }
+
// -------------------------------------------------------------------------------------------------------------
// Annotations
|
Add methods for finding implementors of a given interface
|
classgraph_classgraph
|
train
|
88c48395471e686389bc2c672e29d61026de8d95
|
diff --git a/ceph_deploy/mon.py b/ceph_deploy/mon.py
index <HASH>..<HASH> 100644
--- a/ceph_deploy/mon.py
+++ b/ceph_deploy/mon.py
@@ -58,7 +58,7 @@ def catch_mon_errors(conn, logger, hostname, cfg, args):
and warn apropriately about it.
"""
monmap = mon_status_check(conn, logger, hostname, args).get('monmap', {})
- mon_initial_members = cfg.safe_get('global', 'mon_initial_members')
+ mon_initial_members = get_mon_initial_members(args, _cfg=cfg)
public_addr = cfg.safe_get('global', 'public_addr')
public_network = cfg.safe_get('global', 'public_network')
mon_in_monmap = [
@@ -235,11 +235,7 @@ def mon_create(args):
cfg = conf.ceph.load(args)
if not args.mon:
- mon_initial_members = cfg.safe_get('global', 'mon_initial_members')
- args.mon = re.split(r'[,\s]+', mon_initial_members)
-
- if not args.mon:
- raise exc.NeedHostError()
+ args.mon = get_mon_initial_members(args, error_on_empty=True, _cfg=cfg)
if args.keyrings:
monitor_keyring = concatenate_keyrings(args)
@@ -398,11 +394,7 @@ def mon_destroy(args):
def mon_create_initial(args):
- cfg = conf.ceph.load(args)
- cfg_initial_members = cfg.safe_get('global', 'mon_initial_members')
- if cfg_initial_members is None:
- raise RuntimeError('No `mon initial members` defined in config')
- mon_initial_members = re.split(r'[,\s]+', cfg_initial_members)
+ mon_initial_members = get_mon_initial_members(args, error_on_empty=True)
# create them normally through mon_create
mon_create(args)
@@ -536,6 +528,26 @@ def make(parser):
#
+def get_mon_initial_members(args, error_on_empty=False, _cfg=None):
+ """
+ Read the ceph config file and return the value of mon_initial_members
+ Optionally, a NeedHostError can be raised if the value is None.
+ """
+ if _cfg:
+ cfg = _cfg
+ else:
+ cfg = conf.ceph.load(args)
+ mon_initial_members = cfg.safe_get('global', 'mon_initial_members')
+ if not mon_initial_members:
+ if error_on_empty:
+ raise exc.NeedHostError(
+ 'could not find `mon initial members` defined in ceph.conf'
+ )
+ else:
+ mon_initial_members = re.split(r'[,\s]+', mon_initial_members)
+ return mon_initial_members
+
+
def is_running(conn, args):
"""
Run a command to check the status of a mon, return a boolean.
diff --git a/ceph_deploy/osd.py b/ceph_deploy/osd.py
index <HASH>..<HASH> 100644
--- a/ceph_deploy/osd.py
+++ b/ceph_deploy/osd.py
@@ -9,7 +9,7 @@ from textwrap import dedent
from cStringIO import StringIO
-from ceph_deploy import conf, exc, hosts
+from ceph_deploy import conf, exc, hosts, mon
from ceph_deploy.util import constants, system
from ceph_deploy.cliutil import priority
from ceph_deploy.lib import remoto
@@ -466,16 +466,7 @@ def disk_list(args, cfg):
def osd_list(args, cfg):
- # FIXME: this portion should probably be abstracted. We do the same in
- # mon.py
- cfg = conf.ceph.load(args)
- mon_initial_members = cfg.safe_get('global', 'mon_initial_members')
- monitors = re.split(r'[,\s]+', mon_initial_members)
-
- if not monitors:
- raise exc.NeedHostError(
- 'could not find `mon initial members` defined in ceph.conf'
- )
+ monitors = mon.get_mon_initial_members(args, error_on_empty=True, _cfg=cfg)
# get the osd tree from a monitor host
mon_host = monitors[0]
|
Add abstracted function about get monitor initial members.
To get monitor members feature will be reuse serval
times in mon.py and osd.py. Due to this reason, I
rewrite the helper function for this feature.
1. Add get_mon_initial_members that can handle
monitor member featching and configuration
input.
2. Let all works about monitor featching of
mon.py and osd.py to use this abstracted function.
If you have any questions, feel free to let me know.
Thanks!
|
ceph_ceph-deploy
|
train
|
31746519d0af3f0b182f4195ec13c7589180bc16
|
diff --git a/features/addressing/managing_zones/adding_zone.feature b/features/addressing/managing_zones/adding_zone.feature
index <HASH>..<HASH> 100644
--- a/features/addressing/managing_zones/adding_zone.feature
+++ b/features/addressing/managing_zones/adding_zone.feature
@@ -40,3 +40,15 @@ Feature: Adding a new zone with country type members
And I add it
Then I should be notified that it has been successfully created
And the zone named "America" with the "North America" zone member should appear in the registry
+
+ @ui @javascript
+ Scenario: Adding a zone with a country type member and a shipping scope
+ When I want to create a new zone consisting of country
+ And I name it "European Union"
+ And I specify its code as "EU"
+ And I add a country "France"
+ And I select its scope as "shipping"
+ And I add it
+ Then I should be notified that it has been successfully created
+ And the zone named "European Union" with the "France" country member should appear in the registry
+ And its scope should be "shipping"
diff --git a/src/Sylius/Behat/Context/Ui/Admin/ManagingZonesContext.php b/src/Sylius/Behat/Context/Ui/Admin/ManagingZonesContext.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Behat/Context/Ui/Admin/ManagingZonesContext.php
+++ b/src/Sylius/Behat/Context/Ui/Admin/ManagingZonesContext.php
@@ -172,6 +172,14 @@ final class ManagingZonesContext implements Context
}
/**
+ * @When I select its scope as :scope
+ */
+ public function iSelectItsScopeAs($scope)
+ {
+ $this->createPage->selectScope($scope);
+ }
+
+ /**
* @When I add it
* @When I try to add it
*/
@@ -197,6 +205,21 @@ final class ManagingZonesContext implements Context
}
/**
+ * @Given /^(its) scope should be ("[^"]+")$/
+ */
+ public function itsScopeShouldBe(ZoneInterface $zone, $scope)
+ {
+ $this->updatePage->open(['id' => $zone->getId()]);
+ $zoneScope = $this->updatePage->getScope();
+
+ Assert::same(
+ $scope,
+ $zoneScope,
+ sprintf('Zone should have scope "%s" but it has "%s".', $scope, $zoneScope)
+ );
+ }
+
+ /**
* @Then /^(this zone) should have only (the "([^"]*)" (?:country|province|zone) member)$/
*/
public function thisZoneShouldHaveOnlyTheProvinceMember(ZoneInterface $zone, ZoneMemberInterface $zoneMember)
diff --git a/src/Sylius/Behat/Page/Admin/Zone/CreatePage.php b/src/Sylius/Behat/Page/Admin/Zone/CreatePage.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Behat/Page/Admin/Zone/CreatePage.php
+++ b/src/Sylius/Behat/Page/Admin/Zone/CreatePage.php
@@ -63,6 +63,14 @@ class CreatePage extends BaseCreatePage implements CreatePageInterface
/**
* {@inheritdoc}
*/
+ public function selectScope($scope)
+ {
+ $this->getDocument()->selectFieldOption('Scope', $scope);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
public function hasType($type)
{
$typeField = $this->getElement('type');
diff --git a/src/Sylius/Behat/Page/Admin/Zone/CreatePageInterface.php b/src/Sylius/Behat/Page/Admin/Zone/CreatePageInterface.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Behat/Page/Admin/Zone/CreatePageInterface.php
+++ b/src/Sylius/Behat/Page/Admin/Zone/CreatePageInterface.php
@@ -26,11 +26,16 @@ interface CreatePageInterface extends BaseCreatePageInterface
public function checkValidationMessageForMembers($message);
/**
- * @param $name
+ * @param string $name
*/
public function chooseMember($name);
/**
+ * @param string $scope
+ */
+ public function selectScope($scope);
+
+ /**
* @param string $type
*
* @return bool
diff --git a/src/Sylius/Behat/Page/Admin/Zone/UpdatePage.php b/src/Sylius/Behat/Page/Admin/Zone/UpdatePage.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Behat/Page/Admin/Zone/UpdatePage.php
+++ b/src/Sylius/Behat/Page/Admin/Zone/UpdatePage.php
@@ -39,6 +39,14 @@ class UpdatePage extends BaseUpdatePage implements UpdatePageInterface
/**
* {@inheritdoc}
*/
+ public function getScope()
+ {
+ return $this->getElement('scope')->getValue();
+ }
+
+ /**
+ * {@inheritdoc}
+ */
public function hasMember(ZoneMemberInterface $zoneMember)
{
$selectedZoneMembers = $this->getSelectedZoneMembers();
@@ -95,6 +103,7 @@ class UpdatePage extends BaseUpdatePage implements UpdatePageInterface
'code' => '#sylius_zone_code',
'member' => '.one.field',
'name' => '#sylius_zone_name',
+ 'name' => '#sylius_zone_scope',
'type' => '#sylius_zone_type',
'zone_members' => '#sylius_zone_members',
]);
diff --git a/src/Sylius/Behat/Page/Admin/Zone/UpdatePageInterface.php b/src/Sylius/Behat/Page/Admin/Zone/UpdatePageInterface.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Behat/Page/Admin/Zone/UpdatePageInterface.php
+++ b/src/Sylius/Behat/Page/Admin/Zone/UpdatePageInterface.php
@@ -30,6 +30,11 @@ interface UpdatePageInterface extends BaseUpdatePageInterface
public function countMembers();
/**
+ * @return string
+ */
+ public function getScope();
+
+ /**
* @param ZoneMemberInterface $zoneMember
*
* @return bool
|
[Admin][Zone] Adding zone with scope scenario
|
Sylius_Sylius
|
train
|
7493a8f06bddd5d4794e4f891e3fbf1b217cc410
|
diff --git a/spec/dummy/config/initializers/monologue.rb b/spec/dummy/config/initializers/monologue.rb
index <HASH>..<HASH> 100644
--- a/spec/dummy/config/initializers/monologue.rb
+++ b/spec/dummy/config/initializers/monologue.rb
@@ -1,12 +1,13 @@
-Monologue.site_name = "@jipiboily / Jean-Philippe Boily"
-Monologue.site_subtitle = "my own place online"
-Monologue.site_url = "http://jipiboily.com"
-Monologue.disqus_shortname = "jipiboily"
-Monologue.meta_description = "This is my personal blog about Rails, Monologue, programming, etc..."
-Monologue.meta_keyword = "rails, programming, monologue, ruby"
-Monologue.twitter_username = "jipiboily"
-Monologue.twitter_locale = "en" # "fr"
-Monologue.facebook_like_locale = "en_US" # "fr_CA"
-Monologue.google_plusone_locale = "en"
-Monologue.admin_force_ssl = false
-Monologue.posts_per_page = 3
\ No newline at end of file
+ Monologue.site_name = "@jipiboily / Jean-Philippe Boily"
+ Monologue.site_subtitle = "my own place online"
+ Monologue.site_url = "http://jipiboily.com"
+ Monologue.disqus_shortname = "jipiboily"
+ Monologue.meta_description = "This is my personal blog about Rails, Monologue, programming, etc..."
+ Monologue.meta_keyword = "rails, programming, monologue, ruby"
+ Monologue.twitter_username = "jipiboily"
+ Monologue.twitter_locale = "en" # "fr"
+ Monologue.facebook_like_locale = "en_US" # "fr_CA"
+ Monologue.google_plusone_locale = "en"
+ Monologue.admin_force_ssl = false
+ Monologue.posts_per_page = 3
+ # Monologue.google_analytics_id = "YOUR GA CODE"
\ No newline at end of file
|
added a commented config for GA in dummy's initializer
|
jipiboily_monologue
|
train
|
75d597c411884f7b843e87ba19cc04241a72f1f5
|
diff --git a/mode/clojure/clojure.js b/mode/clojure/clojure.js
index <HASH>..<HASH> 100644
--- a/mode/clojure/clojure.js
+++ b/mode/clojure/clojure.js
@@ -59,7 +59,8 @@ CodeMirror.defineMode("clojure", function (options) {
sign: /[+-]/,
exponent: /e/i,
keyword_char: /[^\s\(\[\;\)\]]/,
- symbol: /[\w*+!\-\._?:<>\/\xa1-\uffff]/
+ symbol: /[\w*+!\-\._?:<>\/\xa1-\uffff]/,
+ block_indent: /^(?:def|with)[^\/]+$|\/(?:def|with)/
};
function stateStack(indent, type, prev) { // represents a state stack object
@@ -190,7 +191,7 @@ CodeMirror.defineMode("clojure", function (options) {
}
if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
- /^(?:def|with)/.test(keyWord))) { // indent-word
+ tests.block_indent.test(keyWord))) { // indent-word
pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
} else { // non-indent word
// we continue eating the spaces
|
[clojure mode] Allow namespaced forms to smartly indent
Fix from
<URL>
|
codemirror_CodeMirror
|
train
|
bc97ac197bd6fc652ea5fc3013c8744f55c391c3
|
diff --git a/modules/archi/includes/archiAdresse.class.php b/modules/archi/includes/archiAdresse.class.php
index <HASH>..<HASH> 100644
--- a/modules/archi/includes/archiAdresse.class.php
+++ b/modules/archi/includes/archiAdresse.class.php
@@ -20999,7 +20999,13 @@ class archiAdresse extends ArchiContenu
//Loop on each address infos
foreach ($addressesInfromations as $info){
- $illustration = $this->getUrlImageFromAdresse($info['idHistoriqueAdresse'], 'mini', array('idEvenementGroupeAdresse'=>$info['idEvenementGroupeAdresse']));
+ $illustration = $this->getUrlImageFromAdresse(
+ $info['idHistoriqueAdresse'],
+ 'mini',
+ array(
+ 'idEvenementGroupeAdresse'=>$info['idEvenementGroupeAdresse']
+
+ ));
$addressUrl = $this->creerUrl(
'',
'',
@@ -21012,11 +21018,10 @@ class archiAdresse extends ArchiContenu
//Processing name of the address
$nom = $info['nom'];
- if(empty($nom)){
- $nom = $this->getIntituleAdresseFrom($info['idHistoriqueAdresse'],$type='idAdresse');
+ if(empty($nom) || $nom == "" || $nom == ' '){
+ $nom = $this->getIntituleAdresseFrom($info['idEvenementGroupeAdresse'],$type='idEvenementGroupeAdresse');
}
-
$titreEvenements = implode(" - ", $info['titresEvenements']); // Getting all the events links on one line
$t->assign_block_vars(
'adresses',
@@ -21063,7 +21068,7 @@ class archiAdresse extends ArchiContenu
}
$req="
- SELECT ha.nom , ha.idHistoriqueAdresse , ha.idAdresse , ae.idEvenement
+ SELECT ha.nom , ha.idHistoriqueAdresse , ha.idAdresse , ae.idEvenement as idEvenementGroupeAdresse
FROM historiqueAdresse ha
LEFT JOIN _adresseEvenement ae on ae.idAdresse = ha.idHistoriqueAdresse
".$whereClause."
@@ -21073,7 +21078,7 @@ class archiAdresse extends ArchiContenu
$res = $this->connexionBdd->requete($req);
//Processing all the adresses get from the request : getting address title and link to the events linked
- while($fetch = mysql_fetch_assoc($res)){
+ while($fetch = mysql_fetch_assoc($res)){
$reqTitresEvenements ="
SELECT distinct he1.titre
FROM historiqueEvenement he1
@@ -21114,7 +21119,6 @@ class archiAdresse extends ArchiContenu
$positionAncre++;
}
}
- debug($addressesInformations);
return $addressesInformations;
}
diff --git a/modules/archi/includes/archiRecherche.class.php b/modules/archi/includes/archiRecherche.class.php
index <HASH>..<HASH> 100644
--- a/modules/archi/includes/archiRecherche.class.php
+++ b/modules/archi/includes/archiRecherche.class.php
@@ -2084,7 +2084,6 @@ class archiRecherche extends config {
* *************************************************************************
*/
private function buildWhereClause($criterias ){
- debug($criterias);
$sqlWhere = '';
$sqlWhereTab = array();
$motcle="";
@@ -2174,12 +2173,10 @@ class archiRecherche extends config {
;";
}
else{
- $request = "SELECT idHistoriqueAdresse, idEvenementGA, nomRue,nomSousQuartier,nomQuartier,nomVille,nomPays,prefixeRue,description,titre,nomPersonne, prenomPersonne, numeroAdresse,concat1,concat2,concat3 ,
- 1 as relevance
-
+ $request = "SELECT idHistoriqueAdresse, idEvenementGA, nomRue,nomSousQuartier,nomQuartier,nomVille,nomPays,prefixeRue,description,titre,nomPersonne, prenomPersonne, numeroAdresse,concat1,concat2,concat3 , 1 as relevance
FROM recherchetmp "
- .$sqlWhere.
- "ORDER BY relevance DESC
+ .$sqlWhere.
+ "ORDER BY relevance DESC
;";
}
|
Fixed bug for address title generation in list display
|
Archi-Strasbourg_archi-wiki
|
train
|
bdcae60f8a3e6bc460ad0fd270b0f17371944372
|
diff --git a/app/models/setting.rb b/app/models/setting.rb
index <HASH>..<HASH> 100644
--- a/app/models/setting.rb
+++ b/app/models/setting.rb
@@ -6,16 +6,18 @@ class Setting < ActiveRecord::Base
cattr_accessor :cache
@@cache = Rails.cache
+ after_commit :expire_cache
+
class << self
def []=(name, value)
- cache.write(name, value)
- setting = where(name: name).first_or_initialize
- setting.value = value
- setting.save
+ write(name, value)
+ find_or_create_by!(name: name) do |setting|
+ setting.value = value
+ end
end
def [](name)
- unless (value = cache.read(name)).nil?
+ unless (value = read(name)).nil?
return value
end
@@ -25,22 +27,22 @@ class Setting < ActiveRecord::Base
value = yield # default value passed as block
end
- cache.write(name, value)
+ write(name, value)
value.presence
end
def has_key?(name)
- cache.exist? name
+ cache.exist? cache_key(name)
end
def expire(name)
- cache.delete(name)
+ cache.delete cache_key(name)
end
def apply_all(settings = {})
settings.each do |name, value|
- find_or_create_by!(name: name.to_s) do |setting|
+ find_or_create_by!(name: name) do |setting|
if value.is_a? Array
setting.value, setting.unit = value
else
@@ -52,9 +54,29 @@ class Setting < ActiveRecord::Base
def remove_all(*settings)
settings.each do |name|
- find_by(name: name.to_s).try(:destroy!)
+ find_by(name: name).try(:destroy!)
expire(name)
end
end
+
+ private
+
+ def read(name)
+ cache.read cache_key(name)
+ end
+
+ def write(name, value)
+ cache.write cache_key(name), value
+ end
+
+ def cache_key(name)
+ "setting/#{name}"
+ end
+ end
+
+ private
+
+ def expire_cache
+ self.class.expire(name)
end
end
|
Setting model improved and now clear cache key after commit
|
o2web_rails_admin_cms
|
train
|
e51915030c9a47207fbc97b38cce366f3f46d573
|
diff --git a/public/js/editors/panel.js b/public/js/editors/panel.js
index <HASH>..<HASH> 100644
--- a/public/js/editors/panel.js
+++ b/public/js/editors/panel.js
@@ -103,7 +103,7 @@ var Panel = function (name, settings) {
}
// Add Zen Coding to html pane
- if (name === 'html') {
+ if (name === 'html' && jsbin.settings.editor.zen === true) {
$.extend(cmSettings, {
syntax: 'html', /* define Zen Coding syntax */
profile: 'html', /* define Zen Coding output profile */
|
Selectively apply Zen Coding — no lazy loading
Zen Coding is now only on if jsbin.settings.editor.zen === true.
It's not lazy loaded, but I'm not sure if this is possible as Zen
might have to be applied when the Panel is set up? Currently it
requires a refresh to work.
|
jsbin_jsbin
|
train
|
1dfa752ec39b047d3b6d28a99eb73c214b3f3ba6
|
diff --git a/lib/ice_cube/rule_occurrence.rb b/lib/ice_cube/rule_occurrence.rb
index <HASH>..<HASH> 100644
--- a/lib/ice_cube/rule_occurrence.rb
+++ b/lib/ice_cube/rule_occurrence.rb
@@ -22,10 +22,6 @@ module IceCube
find_occurrences { |roc| roc > end_time }.select { |d| d >= begin_time }
end
- def occurring_at?(time)
-
- end
-
def upto(end_date)
find_occurrences { |roc| roc > end_date }
end
@@ -47,6 +43,7 @@ module IceCube
end
#walk through all of the successive dates, looking for the next occurrence (interval-valid), then return it.
begin
+ return nil if yield(date)
return nil if @end_time && date > @end_time
return nil if @rule.until_date && date > @rule.until_date # until check
return RuleOccurrence.new(@rule, @start_date, @end_time, date, @index + 1) if @rule.in_interval?(date, @start_date)
@@ -57,15 +54,14 @@ module IceCube
private
- def find_occurrences
+ def find_occurrences(&block)
include_dates = []
roc = self
begin
break if roc.nil? #go until we run out of dates
next if roc.to_time.nil? #handle the case where start_date is not a valid occurrence
- break if yield(roc) #recurrence condition
include_dates << roc.to_time
- end while roc = roc.succ
+ end while roc = roc.succ(&block)
include_dates
end
diff --git a/spec/examples/ice_cube_spec.rb b/spec/examples/ice_cube_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/examples/ice_cube_spec.rb
+++ b/spec/examples/ice_cube_spec.rb
@@ -501,4 +501,10 @@ describe Schedule, 'occurs_on?' do
schedule.occurring_at?((DAY + 4*ONE_DAY + 10).to_date).should be(false) # out of range
end
+ it 'should not create an infinite loop crossing over february - github issue 6' do
+ schedule = Schedule.new(Time.parse('2010-08-30'))
+ schedule.add_recurrence_rule Rule.monthly(6)
+ schedule.occurrences_between(Time.parse('2010-07-01'), Time.parse('2010-09-01'))
+ end
+
end
|
Resolve github issue 6
|
seejohnrun_ice_cube
|
train
|
077f9a8760346e5f30a54820a438c7daa59f6955
|
diff --git a/test/models/authorization/activation_key_authorization_test.rb b/test/models/authorization/activation_key_authorization_test.rb
index <HASH>..<HASH> 100644
--- a/test/models/authorization/activation_key_authorization_test.rb
+++ b/test/models/authorization/activation_key_authorization_test.rb
@@ -38,11 +38,10 @@ end
class ActivationKeyAuthorizationNoPermsTest < MiniTest::Rails::ActiveSupport::TestCase
include RepositoryTestBase
- include ::TestUserBase
def setup
super
- User.current = @no_perms_user
+ User.current = User.find(users('no_perms_user'))
end
def test_readable
|
removing UserBaseTest requirement
|
Katello_katello
|
train
|
8709d5e4015761d985c6d4d29e4a9333ef6780c8
|
diff --git a/Filter/BooleanFilter.php b/Filter/BooleanFilter.php
index <HASH>..<HASH> 100644
--- a/Filter/BooleanFilter.php
+++ b/Filter/BooleanFilter.php
@@ -11,8 +11,8 @@
namespace Sonata\DoctrineORMAdminBundle\Filter;
-use Sonata\AdminBundle\Form\Type\BooleanType;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
+use Sonata\CoreBundle\Form\Type\BooleanType;
class BooleanFilter extends Filter
{
diff --git a/Tests/Filter/BooleanFilterTest.php b/Tests/Filter/BooleanFilterTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Filter/BooleanFilterTest.php
+++ b/Tests/Filter/BooleanFilterTest.php
@@ -12,7 +12,7 @@
namespace Sonata\DoctrineORMAdminBundle\Tests\Filter;
use Sonata\DoctrineORMAdminBundle\Filter\BooleanFilter;
-use Sonata\AdminBundle\Form\Type\BooleanType;
+use Sonata\CoreBundle\Form\Type\BooleanType;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
class BooleanFilterTest extends \PHPUnit_Framework_TestCase
|
Migrate to CoreBundle
|
sonata-project_SonataDoctrineORMAdminBundle
|
train
|
8ceb3e67d56934c47eb09904120eab24b0f330d1
|
diff --git a/lib/weblib.php b/lib/weblib.php
index <HASH>..<HASH> 100644
--- a/lib/weblib.php
+++ b/lib/weblib.php
@@ -2515,7 +2515,7 @@ function print_simple_box($message, $align='', $width='', $color='', $padding=5,
/**
* Print the top portion of a standard themed box.
*
- * @param string $align string, alignment of the box, not the text (not used, box is always centred).
+ * @param string $align string, alignment of the box, not the text (default left, center, right).
* @param string $width string, width of the box, including units, for example '100%'.
* @param string $color string, background colour of the box, for example '#eee'.
* @param int $padding integer, padding in pixels, specified without units.
@@ -2534,22 +2534,30 @@ function print_simple_box_start($align='', $width='', $color='', $padding=5, $cl
if ($color) {
$style_out .= 'background-color:'. $color .'; ';
}
- //Note, $align not used - box is always centred.
+ if ($align && 'center' == $align) {
+ $style_out .= 'margin-left:auto; margin-right:auto; ';
+ }
+ elseif (!align || 'left' == $align) {
+ $style_out .= 'float:left; ';
+ }
+ else {
+ $style_out .= 'float:right; ';
+ }
if ($width) {
//Note, width units provided.
- $style_out .= 'width:'. $width .'; margin-left:auto; margin-right:auto;';
+ $style_out .= 'width:'. $width .'; ';
}
if ($id) {
$id = 'id="'. $id .'"';
}
- echo "<div $id class=\"$class\" style=\"$style_out\"><div class=\"$class"."content\" style=\"$style_in\">\n";
+ echo "<div $id class=\"$class\" style=\"$style_out\"><div class=\"$class"."content\" style=\"$style_in\">\n";
}
/**
* Print the end portion of a standard themed box.
*/
function print_simple_box_end() {
- echo "</div></div>\n";
+ echo "</div></div><div class=\"clearer\"></div>\n";
}
/**
|
Part fix, bug <I>: print_simple_box behaviour changed. Now aligns box, and shrinks to fit for left/right-alignment.
|
moodle_moodle
|
train
|
f2afb57a276042d7110a2a938965d41196fcfb9f
|
diff --git a/test/matrix.test.js b/test/matrix.test.js
index <HASH>..<HASH> 100644
--- a/test/matrix.test.js
+++ b/test/matrix.test.js
@@ -122,7 +122,7 @@ suite('numbers', function() {
];
var res0 = matrix.determinant(m0);
- assert.equal(1,m0);
+ assert.equal(1, res0);
var m1 = [
[2, 3],
|
Fix Bug in Test
(Will, rightly, break the build until the determinant function is updated.)
|
numbers_numbers.js
|
train
|
c8541a9933db4af6e157c3f587b2e5d88d4005b7
|
diff --git a/spec/how_is/contributions_spec.rb b/spec/how_is/contributions_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/how_is/contributions_spec.rb
+++ b/spec/how_is/contributions_spec.rb
@@ -130,7 +130,7 @@ describe HowIs::Contributions do
context "#pretty_date" do
it "formats the date correctly" do
- date = Date.new(2017, 01, 02)
+ date = Date.new(2017, 1, 2)
expect(contributions.send(:pretty_date, date)).to eq("Jan 02, 2017")
end
end
|
no unintentional octal literals
|
duckinator_inq
|
train
|
743c4fa8cb0494bb7015d9c03a6e7672d794b191
|
diff --git a/lib/core/config.js b/lib/core/config.js
index <HASH>..<HASH> 100644
--- a/lib/core/config.js
+++ b/lib/core/config.js
@@ -24,6 +24,7 @@ var Config = function(options) {
this.events = options.events;
this.embarkConfig = {};
this.context = options.context || [constants.contexts.any];
+ this.shownNoAccountConfigMsg = false; // flag to ensure "no account config" message is only displayed once to the user
self.events.setCommandHandler("config:contractsConfig", (cb) => {
cb(self.contractsConfig);
@@ -183,13 +184,30 @@ Config.prototype.loadBlockchainConfigFile = function() {
if (!configFilePath) {
this.blockchainConfig.default = true;
}
- if (!this.blockchainConfig.account && !this.blockchainConfig.isDev &&
+ if (
+ !this.shownNoAccountConfigMsg &&
+ (/rinkeby|testnet|livenet/).test(this.blockchainConfig.networkType) &&
+ !(this.blockchainConfig.account && this.blockchainConfig.account.address && this.blockchainConfig.account.password) &&
+ !this.blockchainConfig.isDev &&
this.env !== 'development' && this.env !== 'test') {
- this.logger.warn(
- __('Account settings are needed for this chain.' +
- ' Please put a valid address and possibly a password in your blockchain config or use a dev chain.')
- );
- }
+ this.logger.warn((
+ '\n=== ' + __('Cannot unlock account - account config missing').bold + ' ===\n' +
+ __('Geth is configured to sync to a testnet/livenet and needs to unlock an account ' +
+ 'to allow your dApp to interact with geth, however, the address and password must ' +
+ 'be specified in your blockchain config. Please update your blockchain config with ' +
+ 'a valid address and password: \n') +
+ ` - config/blockchain.js > ${this.env} > account\n\n`.italic +
+ __('Please also make sure the keystore file for the account is located at: ') +
+ '\n - Mac: ' + `~/Library/Ethereum/${this.env}/keystore`.italic +
+ '\n - Linux: ' + `~/.ethereum/${this.env}/keystore`.italic +
+ '\n - Windows: ' + `%APPDATA%\Ethereum/${this.env}/keystore`.italic) +
+ __('\n\nAlternatively, you could change ' +
+ `config/blockchain.js > ${this.env} > networkType`.italic +
+ __(' to ') +
+ '"custom"\n'.italic).yellow
+ );
+ this.shownNoAccountConfigMsg = true;
+ }
};
Config.prototype.loadContractsConfigFile = function() {
|
Update “no account” message and hide for infura
The “no account” message was appearing when using infura as the contract deploy target. This has been changed so that this message will only show when the user has configured their environment to have a `networkType` of `testnet`, `rinkeby`, or `mainnet` and a missing `account` address and/or password.
Additionally, the warning message has been updated to help the user resolve the issue.
A flag has also been added to prevent the message from appearing multiple times.
|
embark-framework_embark
|
train
|
aa46425080e8ce45cbfe387487be20181bdec5bc
|
diff --git a/adventure/game.py b/adventure/game.py
index <HASH>..<HASH> 100644
--- a/adventure/game.py
+++ b/adventure/game.py
@@ -113,6 +113,16 @@ class Game(Data):
def start(self):
"""Start the game."""
+
+ # For old-fashioned players, accept five-letter truncations like
+ # "inven" instead of insisting on full words like "inventory".
+
+ for key, value in list(self.vocabulary.items()):
+ if isinstance(key, str) and len(key) > 5:
+ self.vocabulary[key[:5]] = value
+
+ # Set things going.
+
self.chest_room = self.rooms[114]
self.bottle.contents = self.water
self.yesno(self.messages[65], self.start2) # want instructions?
|
Adjusted game vocabulary to accept the old 5-letter command abbreviations.
|
brandon-rhodes_python-adventure
|
train
|
58197f75c8cfc69e3e2734a60db89533bf9fc731
|
diff --git a/gcs/gcstesting/register_bucket_tests.go b/gcs/gcstesting/register_bucket_tests.go
index <HASH>..<HASH> 100644
--- a/gcs/gcstesting/register_bucket_tests.go
+++ b/gcs/gcstesting/register_bucket_tests.go
@@ -18,25 +18,38 @@ type bucketTestSetUpInterface interface {
}
func getSuiteName(suiteType reflect.Type) string {
- return strings.Title(suiteType.Elem().Name())
+ return strings.Title(suiteType.Name())
}
-func getTestMethods(suiteType reflect.Type) []reflect.Method {
- return srcutil.GetMethodsInSourceOrder(suiteType)
+func isExported(name string) bool {
+ return len(name) > 0 && name[0] >= 'A' && name[0] <= 'Z'
+}
+
+func getTestMethods(suitePointerType reflect.Type) []reflect.Method {
+ var exportedMethods []reflect.Method
+ for _, m := range srcutil.GetMethodsInSourceOrder(suitePointerType) {
+ if isExported(m.Name) {
+ exportedMethods = append(exportedMethods, m)
+ }
+ }
+
+ return exportedMethods
}
func registerTestSuite(
makeBucket func() gcs.Bucket,
prototype bucketTestSetUpInterface) {
- suiteType := reflect.TypeOf(prototype)
+ suitePointerType := reflect.TypeOf(prototype)
+ suiteType := suitePointerType.Elem()
// We don't need anything fancy at the suite level.
var ts ogletest.TestSuite
ts.Name = getSuiteName(suiteType)
// For each method, we create a test function.
- for _, method := range getTestMethods(suiteType) {
+ for _, method := range getTestMethods(suitePointerType) {
var tf ogletest.TestFunction
+ tf.Name = method.Name
// Create an instance to be shared among SetUp and the test function itself.
var instance reflect.Value = reflect.New(suiteType)
|
Filter out unexported methods.
|
jacobsa_gcloud
|
train
|
9b7482afc5f5618e2cfc8c983ec556fff7a28094
|
diff --git a/controllers/ThemeController.php b/controllers/ThemeController.php
index <HASH>..<HASH> 100644
--- a/controllers/ThemeController.php
+++ b/controllers/ThemeController.php
@@ -74,7 +74,7 @@ class ThemeController extends ApiController
if ($return)
return false;
- throw new CHttpException(404, Yii::t('Api.Theme', 'Theme is not installed'));
+ return $this->returnError(200, Yii::t('Api.main', 'Theme is not installed'), false);
}
/**
|
Themes isInstalled now returns <I> instead of <I> when a theme is not installed
|
ciims_ciims-modules-api
|
train
|
fc862a3edd010e65b9b3fe586855fe81807ee4e8
|
diff --git a/airflow/executors/celery_executor.py b/airflow/executors/celery_executor.py
index <HASH>..<HASH> 100644
--- a/airflow/executors/celery_executor.py
+++ b/airflow/executors/celery_executor.py
@@ -170,11 +170,11 @@ class CeleryExecutor(BaseExecutor):
task_tuples_to_send.append((key, simple_ti, command, queue, execute_command))
if task_tuples_to_send:
- tasks = [t[4] for t in task_tuples_to_send]
+ first_task = next(t[4] for t in task_tuples_to_send)
# Celery state queries will stuck if we do not use one same backend
# for all tasks.
- cached_celery_backend = tasks[0].backend
+ cached_celery_backend = first_task.backend
key_and_async_results = self._send_tasks_to_celery(task_tuples_to_send)
self.log.debug('Sent all tasks.')
@@ -194,6 +194,11 @@ class CeleryExecutor(BaseExecutor):
self.last_state[key] = celery_states.PENDING
def _send_tasks_to_celery(self, task_tuples_to_send):
+ if len(task_tuples_to_send) == 1:
+ # One tuple, so send it in the main thread.
+ return [
+ send_task_to_executor(task_tuples_to_send[0])
+ ]
# Use chunks instead of a work queue to reduce context switching
# since tasks are roughly uniform in size
chunksize = self._num_tasks_per_send_process(len(task_tuples_to_send))
|
Do not create a separate process for one task in CeleryExecutor (#<I>)
|
apache_airflow
|
train
|
2a489d3eeac4d4909862aac1b43ea891e427f416
|
diff --git a/core/src/main/java/hudson/security/SecurityRealm.java b/core/src/main/java/hudson/security/SecurityRealm.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/security/SecurityRealm.java
+++ b/core/src/main/java/hudson/security/SecurityRealm.java
@@ -48,6 +48,7 @@ import static org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.ACEGI
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
+import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
@@ -488,7 +489,8 @@ public abstract class SecurityRealm extends AbstractDescribableImpl<SecurityReal
/**
* Perform a calculation where we should go back after sucessfull login
*
- * @return Encoded URI where we should go back after sucessfull login or "/" if no way back
+ * @return Encoded URI where we should go back after sucessfull login
+ * or "/" if no way back or an issue occurred
*
* @since TODO
*/
@@ -496,31 +498,39 @@ public abstract class SecurityRealm extends AbstractDescribableImpl<SecurityReal
String from = null;
final StaplerRequest request = Stapler.getCurrentRequest();
- if (request.getSession(false) != null) {
+ if (from == null
+ && request != null
+ && request.getSession(false) != null) {
from = (String) request.getSession().getAttribute("from");
}
- if (from == null) {
+ if (from == null
+ && request != null) {
from = request.getParameter("from");
}
- final String requestURI = request.getRequestURI();
- if (from == null && requestURI != null
- && requestURI.compareTo("/loginError") != 0 && requestURI.compareTo("/login") != 0) {
- from = requestURI;
+ if (from == null
+ && request != null) {
+ final String requestURI = request.getRequestURI();
+ if (requestURI != null
+ && requestURI.compareTo("/loginError") != 0
+ && requestURI.compareTo("/login") != 0) {
+ from = requestURI;
+ }
}
- if (from == null || from.trim().isEmpty()) {
+ if (StringUtils.isBlank(from)) {
from = "/";
}
+ from.trim();
try {
- from = java.net.URLEncoder.encode(from, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- from = "/";
- }
+ final String oldFrom = from;
+ from = null;
+ from = java.net.URLEncoder.encode(oldFrom, "UTF-8");
+ } catch (UnsupportedEncodingException e) { }
- return from;
+ return StringUtils.isBlank(from) ? "/" : from;
}
private static class None extends SecurityRealm {
|
Better handled or fixed identified problematic parts of the code.
|
jenkinsci_jenkins
|
train
|
3677c0aa05f9eda116407c61570a3dfcd7828893
|
diff --git a/bin/blt-robo.php b/bin/blt-robo.php
index <HASH>..<HASH> 100755
--- a/bin/blt-robo.php
+++ b/bin/blt-robo.php
@@ -17,6 +17,11 @@ require_once __DIR__ . '/blt-robo-run.php';
/**
* Finds the root directory for the repository.
*
+ * Ordinarily this function is robust, but it can fail if you've symlinked BLT
+ * into your vendor directory (as with a Composer path repository) and are not
+ * running commands from the project root. In this state, BLT has no possible
+ * way to identify the root directory.
+ *
* @return bool|string
* Root.
*/
@@ -35,6 +40,8 @@ function find_repo_root() {
return $repo_root;
}
}
+ print "Unable to determine the BLT root directory.\n";
+ exit(1);
}
/**
|
More informative error when BLT can't locate repo root. (#<I>)
|
acquia_blt
|
train
|
6c067bd343349af1238a7d99cf1f4bcd8ab07d49
|
diff --git a/test/test_cli.py b/test/test_cli.py
index <HASH>..<HASH> 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -7,6 +7,7 @@ import subprocess
from importlib import import_module
from pathlib import Path
from git import Repo
+from pyontutils.utils import TermColors as tc
from pyontutils.config import devconfig
p1 = Path(__file__).resolve().absolute().parent.parent.parent
@@ -123,7 +124,9 @@ class TestScripts(Folders):
'neuron_models/basic_neurons',
'neuron_models/huang2017',)
print('checkout ok:', checkout_ok)
- if not checkout_ok:
+
+ ont_branch = Repo(devconfig.ontology_local_repo).active_branch.name
+ if not checkout_ok and ont_branch != 'neurons':
skip += tuple(n.split('/')[-1] for n in neurons) # FIXME don't use stem below
else:
lasts += tuple(f'pyontutils/{s}.py' for s in neurons)
@@ -187,7 +190,7 @@ class TestScripts(Folders):
module_path = ppath.relative_to(repo.working_dir).as_posix()[:-3].replace('/', '.')
#print('MPATH: ', module_path)
if stem not in skip:
- #print('TESTING:', module_path)
+ print(tc.ltyellow('TESTING:'), module_path)
module = import_module(module_path) # this returns the submod
#submod = getattr(module, stem)
if hasattr(module, '_CHECKOUT_OK'):
|
test cli fixed logic that prevented neurons tests from running locally, still issues with LocalNameManager collisions
|
tgbugs_pyontutils
|
train
|
7bad040ea715b7a9ca1767076edc35fb2822f762
|
diff --git a/lib/Doctrine/Common/Cache/CacheProvider.php b/lib/Doctrine/Common/Cache/CacheProvider.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Common/Cache/CacheProvider.php
+++ b/lib/Doctrine/Common/Cache/CacheProvider.php
@@ -40,6 +40,11 @@ abstract class CacheProvider implements Cache
private $namespace = '';
/**
+ * @var string The namespace version
+ */
+ private $namespaceVersion = NULL;
+
+ /**
* Set the namespace to prefix all cache ids with.
*
* @param string $namespace
@@ -117,10 +122,11 @@ abstract class CacheProvider implements Cache
*/
public function deleteAll()
{
- $namespaceCacheKey = sprintf(self::DOCTRINE_NAMESPACE_CACHEKEY, $this->namespace);
- $namespaceVersion = ($this->doContains($namespaceCacheKey)) ? $this->doFetch($namespaceCacheKey) : 1;
+ $namespaceCacheKey = $this->getNamespaceCacheKey();
+ $namespaceVersion = $this->getNamespaceVersion() + 1;
+ $this->namespaceVersion = $namespaceVersion;
- return $this->doSave($namespaceCacheKey, $namespaceVersion + 1);
+ return $this->doSave($namespaceCacheKey, $namespaceVersion);
}
/**
@@ -131,13 +137,38 @@ abstract class CacheProvider implements Cache
*/
private function getNamespacedId($id)
{
- $namespaceCacheKey = sprintf(self::DOCTRINE_NAMESPACE_CACHEKEY, $this->namespace);
- $namespaceVersion = ($this->doContains($namespaceCacheKey)) ? $this->doFetch($namespaceCacheKey) : 1;
+ $namespaceVersion = $this->getNamespaceVersion();
return sprintf('%s[%s][%s]', $this->namespace, $id, $namespaceVersion);
}
/**
+ * Namespace cache key
+ *
+ * @return string $namespaceCacheKey
+ */
+ private function getNamespaceCacheKey()
+ {
+ return sprintf(self::DOCTRINE_NAMESPACE_CACHEKEY, $this->namespace);
+ }
+
+ /**
+ * Namespace version
+ *
+ * @return string $namespaceVersion
+ */
+ private function getNamespaceVersion()
+ {
+ if (NULL === $this->namespaceVersion)
+ {
+ $namespaceCacheKey = $this->getNamespaceCacheKey();
+ $this->namespaceVersion = ($this->doContains($namespaceCacheKey)) ? $this->doFetch($namespaceCacheKey) : 1;
+ }
+
+ return $this->namespaceVersion;
+ }
+
+ /**
* Fetches an entry from the cache.
*
* @param string $id cache id The id of the cache entry to fetch.
|
CacheProvider: memoize namespace version value.
Prior implementation for CacheProvider was seriously flawed
from performance point of view as each fetch() call results
in 2 additional cache storage calls due to $this->getNamespaceId(),
which always checks for $namespaceCacheKey (and fetches it if
exists, which will be the case for 2nd and next calls).
|
doctrine_common
|
train
|
475a5509f6d491618461a6c5c5681540020fadb4
|
diff --git a/src/Http/RedirectBinding.php b/src/Http/RedirectBinding.php
index <HASH>..<HASH> 100644
--- a/src/Http/RedirectBinding.php
+++ b/src/Http/RedirectBinding.php
@@ -51,32 +51,21 @@ class RedirectBinding
*/
private $entityRepository;
- /**
- * @var bool
- */
- private $mustBeSigned;
-
public function __construct(
LoggerInterface $logger,
SignatureVerifier $signatureVerifier,
- ServiceProviderRepository $repository = null,
- $mustBeSigned = TRUE
+ ServiceProviderRepository $repository = null
) {
$this->logger = $logger;
$this->signatureVerifier = $signatureVerifier;
$this->entityRepository = $repository;
- $this->mustBeSigned = $mustBeSigned;
}
/**
* @param Request $request
* @return AuthnRequest
- * @throws \Exception
- *
- * @SuppressWarnings(PHPMD.CyclomaticComplexity)
- * @SuppressWarnings(PHPMD.NPathComplexity)
*/
- public function processRequest(Request $request)
+ public function processUnsignedRequest(Request $request)
{
if (!$this->entityRepository) {
throw new LogicException(
@@ -93,24 +82,54 @@ class RedirectBinding
));
}
- if ($request->get(AuthnRequest::PARAMETER_SIGNATURE) && !$request->get(AuthnRequest::PARAMETER_SIGNATURE_ALGORITHM)) {
+ $authnRequest = AuthnRequestFactory::createUnsignedFromHttpRequest($request);
+
+ $currentUri = $this->getFullRequestUri($request);
+ if (!$authnRequest->getDestination() === $currentUri) {
throw new BadRequestHttpException(sprintf(
- 'The request includes a signature "%s", but does not include the signature algorithm (SigAlg) parameter',
- $request->get('Signature')
+ 'Actual Destination "%s" does no match the AuthnRequest Destination "%s"',
+ $currentUri,
+ $authnRequest->getDestination()
));
}
- if ($this->mustBeSigned) {
- $authnRequest = AuthnRequestFactory::createSignedFromHttpRequest(
- $request
- );
+ if (!$this->entityRepository->hasServiceProvider($authnRequest->getServiceProvider())) {
+ throw new UnknownServiceProviderException($authnRequest->getServiceProvider());
}
- else {
- $authnRequest = AuthnRequestFactory::createUnsignedFromHttpRequest(
- $request
+
+ return $authnRequest;
+ }
+
+ /**
+ * @param Request $request
+ * @return AuthnRequest
+ */
+ public function processSignedRequest(Request $request)
+ {
+ if (!$this->entityRepository) {
+ throw new LogicException(
+ 'RedirectBinding::processRequest requires a ServiceProviderRepository to be configured'
);
}
+ $rawSamlRequest = $request->get(AuthnRequest::PARAMETER_REQUEST);
+
+ if (!$rawSamlRequest) {
+ throw new BadRequestHttpException(sprintf(
+ 'Required GET parameter "%s" is missing',
+ AuthnRequest::PARAMETER_REQUEST
+ ));
+ }
+
+ if ($request->get(AuthnRequest::PARAMETER_SIGNATURE) && !$request->get(AuthnRequest::PARAMETER_SIGNATURE_ALGORITHM)) {
+ throw new BadRequestHttpException(sprintf(
+ 'The request includes a signature "%s", but does not include the signature algorithm (SigAlg) parameter',
+ $request->get('Signature')
+ ));
+ }
+
+ $authnRequest = AuthnRequestFactory::createSignedFromHttpRequest($request);
+
$currentUri = $this->getFullRequestUri($request);
if (!$authnRequest->getDestination() === $currentUri) {
throw new BadRequestHttpException(sprintf(
@@ -124,9 +143,7 @@ class RedirectBinding
throw new UnknownServiceProviderException($authnRequest->getServiceProvider());
}
- if ($this->mustBeSigned) {
- $this->verifySignature($authnRequest);
- }
+ $this->verifySignature($authnRequest);
return $authnRequest;
}
@@ -138,33 +155,47 @@ class RedirectBinding
{
if (!$authnRequest->isSigned()) {
throw new BadRequestHttpException(
- 'The SAMLRequest has to be signed'
+ 'The SAMLRequest has to be signed'
);
}
if (!$authnRequest->getSignatureAlgorithm()) {
throw new BadRequestHttpException(
- sprintf(
- 'The SAMLRequest has to be signed with SHA256 algorithm: "%s"',
- XMLSecurityKey::RSA_SHA256
- )
+ sprintf(
+ 'The SAMLRequest has to be signed with SHA256 algorithm: "%s"',
+ XMLSecurityKey::RSA_SHA256
+ )
);
}
$serviceProvider = $this->entityRepository->getServiceProvider(
- $authnRequest->getServiceProvider()
+ $authnRequest->getServiceProvider()
);
if (!$this->signatureVerifier->hasValidSignature(
- $authnRequest,
- $serviceProvider
+ $authnRequest,
+ $serviceProvider
)
) {
throw new BadRequestHttpException(
- 'The SAMLRequest has been signed, but the signature could not be validated'
+ 'The SAMLRequest has been signed, but the signature could not be validated'
);
}
}
+ /**
+ * @param Request $request
+ * @return AuthnRequest
+ * @throws \Exception
+ *
+ * @deprecated Use processSignedRequest or processUnsignedRequest
+ * @SuppressWarnings(PHPMD.CyclomaticComplexity)
+ * @SuppressWarnings(PHPMD.NPathComplexity)
+ */
+ public function processRequest(Request $request)
+ {
+ return $this->processSignedRequest($request);
+ }
+
public function createRedirectResponseFor(AuthnRequest $request)
{
return new RedirectResponse($request->getDestination() . '?' . $request->buildRequestQuery());
|
Remove boolean in favor of new method.
|
OpenConext_Stepup-saml-bundle
|
train
|
09a12d89dce9c602fe14433b4bc9ed45f2acae25
|
diff --git a/lib/dat-tcp.rb b/lib/dat-tcp.rb
index <HASH>..<HASH> 100644
--- a/lib/dat-tcp.rb
+++ b/lib/dat-tcp.rb
@@ -134,9 +134,10 @@ module DatTCP
def work_loop(client_file_descriptors = nil)
logger.info "Starting work loop..."
- pool_args = [ @min_workers, @max_workers, @debug ]
- @worker_pool = DatWorkerPool.new(*pool_args){ |socket| serve(socket) }
- enqueue_file_descriptors(client_file_descriptors || [])
+ @worker_pool = DatWorkerPool.new(@min_workers, @max_workers) do |socket|
+ serve(socket)
+ end
+ add_client_sockets_from_fds client_file_descriptors
while @signal.start?
@worker_pool.add_work accept_connection
end
@@ -155,19 +156,14 @@ module DatTCP
logger.info "Stopped work loop"
end
- def enqueue_file_descriptors(file_descriptors)
- file_descriptors.each do |file_descriptor|
+ def add_client_sockets_from_fds(file_descriptors)
+ (file_descriptors || []).each do |file_descriptor|
@worker_pool.add_work TCPSocket.for_fd(file_descriptor)
end
end
- # An accept-loop waiting for new connections. Will wait for a connection
- # (up to `ready_timeout`) and accept it. `IO.select` with the timeout
- # allows the server to be responsive to shutdowns.
def accept_connection
- while @signal.start?
- return @tcp_server.accept if connection_ready?
- end
+ @tcp_server.accept if connection_ready?
end
def connection_ready?
diff --git a/test/unit/dat-tcp_tests.rb b/test/unit/dat-tcp_tests.rb
index <HASH>..<HASH> 100644
--- a/test/unit/dat-tcp_tests.rb
+++ b/test/unit/dat-tcp_tests.rb
@@ -217,7 +217,7 @@ module DatTCP
@thread.join(0.5) # give the server a chance to queue the connection
end
teardown do
- @client_socket.close
+ @client_socket.close rescue false
@server.stop true
@thread.join
end
|
Remove `accept_connection` loop, not needed
This removes the while loop in the `accept_connection` method.
This is ultimately not-needed and just creates extra overhead.
I'm not sure why I originally thought this was needed, but it's
a loop within a loop that both have the same conditions. This
might have been due to legacy concerns. This is a simpler
implementation that achieves the same functionality.
|
redding_dat-tcp
|
train
|
42f95e82551e350eb8f1a2ddd24987e3fa38e5bc
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,3 +22,4 @@ _testmain.go
*.exe
*.test
*.prof
+coverage.out
diff --git a/auth_test.go b/auth_test.go
index <HASH>..<HASH> 100644
--- a/auth_test.go
+++ b/auth_test.go
@@ -9,7 +9,7 @@ import (
var _ = Describe("Authentication", func() {
Describe("InitAuth", func() {
- var m *ClassicMartini
+ var m *martini.ClassicMartini
BeforeEach(func() {
m = martini.Classic()
})
diff --git a/controller.go b/controller.go
index <HASH>..<HASH> 100644
--- a/controller.go
+++ b/controller.go
@@ -1 +1,5 @@
package pezdispenser
+
+func RandomController(x interface{}) {
+
+}
diff --git a/routes_test.go b/routes_test.go
index <HASH>..<HASH> 100644
--- a/routes_test.go
+++ b/routes_test.go
@@ -9,7 +9,7 @@ import (
var _ = Describe("Routes", func() {
Describe("InitRoutes", func() {
- var m *ClassicMartini
+ var m *martini.ClassicMartini
BeforeEach(func() {
m = martini.Classic()
})
|
[#<I>] fixing tests
|
pivotal-pez_pezdispenser
|
train
|
ab186deb1a4d221f54f439bf9f2006a56d2a055e
|
diff --git a/package.php b/package.php
index <HASH>..<HASH> 100644
--- a/package.php
+++ b/package.php
@@ -4,7 +4,7 @@
require_once 'PEAR/PackageFileManager2.php';
-$version = '1.4.63';
+$version = '1.4.64';
$notes = <<<EOT
No release notes for you!
EOT;
|
prepare for release of <I>
svn commit r<I>
|
silverorange_swat
|
train
|
ebc71bb6b1a4351333fb4578ed9bbfc9b7eff2f0
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index <HASH>..<HASH> 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,10 @@
Changelog
=========
+next
+----
+#. New content type `Search` allows tweets to be retrieved by term or hashtag.
+
0.3.2
-----
#. Increase cache time so we can survive Twitter outages better.
diff --git a/jmbo_twitter/tests.py b/jmbo_twitter/tests.py
index <HASH>..<HASH> 100644
--- a/jmbo_twitter/tests.py
+++ b/jmbo_twitter/tests.py
@@ -60,3 +60,11 @@ class TestCase(BaseTestCase):
def test_search_get_statuses(self):
statuses = self.search.get_statuses(self.fakeapi)
self.assertEqual(len(statuses), 1)
+
+ def test_feed_detail_view(self):
+ response = self.client.get(self.feed.get_absolute_url())
+ self.assertEqual(response.status_code, 200)
+
+ def test_search_detail_view(self):
+ response = self.client.get(self.search.get_absolute_url())
+ self.assertEqual(response.status_code, 200)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,3 +1,4 @@
+import multiprocessing
from setuptools import setup, find_packages
setup(
diff --git a/test_settings.py b/test_settings.py
index <HASH>..<HASH> 100644
--- a/test_settings.py
+++ b/test_settings.py
@@ -1,32 +1,13 @@
+from foundry.settings import *
+
+
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.spatialite',
- 'NAME': 'jmbo-twitter.db',
+ 'NAME': 'test_jmbo_twitter.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
-
-INSTALLED_APPS = [
- 'jmbo_twitter',
- 'foundry',
- 'jmbo',
- 'photologue',
- 'category',
- 'secretballot',
- 'publisher',
- 'preferences',
- 'atlas',
- 'south',
- 'django.contrib.auth',
- 'django.contrib.comments',
- 'django.contrib.contenttypes',
- 'django.contrib.sites',
- 'django.contrib.gis',
-]
-
-SITE_ID = 1
-STATIC_URL = '/'
-SOUTH_TESTS_MIGRATE = False
|
Simplify test setup and add more tests
|
praekelt_jmbo-twitter
|
train
|
3511da62611bbd41b9fc72b296adca47a3d7e05e
|
diff --git a/pkg/synthetictests/duplicated_events.go b/pkg/synthetictests/duplicated_events.go
index <HASH>..<HASH> 100644
--- a/pkg/synthetictests/duplicated_events.go
+++ b/pkg/synthetictests/duplicated_events.go
@@ -78,7 +78,7 @@ var allowedRepeatedEventPatterns = []*regexp.Regexp{
// currently UPI install defaults to HW 13 which causes events in 4.10 CI
// since 4.10 still supports vSphere 6.5, we can't default to HW 15 in RHCOS image but such clusters are unupgradable to 4.11 and hence
// events are still valid.
- regexp.MustCompile(`ns/openshift-cluster-storage-operator\s+deployment/vsphere-problem-detector-operator - reason/VSphereOlderVersionDetected.+vmx-13`),
+ regexp.MustCompile(`ns/openshift-cluster-csi-drivers\s+deployment/vmware-vsphere-csi-driver-operator - reason/check_deprecated_hw_version.+vmx-13`),
}
var allowedRepeatedEventFns = []isRepeatedEventOKFunc{
diff --git a/pkg/synthetictests/duplicated_events_test.go b/pkg/synthetictests/duplicated_events_test.go
index <HASH>..<HASH> 100644
--- a/pkg/synthetictests/duplicated_events_test.go
+++ b/pkg/synthetictests/duplicated_events_test.go
@@ -86,7 +86,7 @@ func TestEventRegexExcluder(t *testing.T) {
},
{
name: "vsphere-hw-13-default-upi-install",
- message: `ns/openshift-cluster-storage-operator deployment/vsphere-problem-detector-operator - reason/VSphereOlderVersionDetected Marking cluster un-upgradeable because one or more VMs are on hardware version vmx-13`,
+ message: `ns/openshift-cluster-csi-drivers deployment/vmware-vsphere-csi-driver-operator - reason/check_deprecated_hw_version Marking cluster un-upgradeable because node control-plane-1 has hardware version vmx-13, which is below the minimum required version 15`,
},
}
diff --git a/test/extended/operators/operators.go b/test/extended/operators/operators.go
index <HASH>..<HASH> 100644
--- a/test/extended/operators/operators.go
+++ b/test/extended/operators/operators.go
@@ -27,7 +27,7 @@ import (
)
var (
- vmxPattern = regexp.MustCompile(`VSphereProblemDetectorControllerUpgradeable.+vmx-13`)
+ vmxPattern = regexp.MustCompile(`VMwareVSphereControllerUpgradeable.+vmx-13`)
)
var _ = g.Describe("[sig-arch][Early] Managed cluster should", func() {
|
Fix vsphere testing workarounds
|
openshift_origin
|
train
|
066eb23e4a415f3992169398c22749632af1e1f1
|
diff --git a/Algebra.js b/Algebra.js
index <HASH>..<HASH> 100644
--- a/Algebra.js
+++ b/Algebra.js
@@ -4163,7 +4163,7 @@ if((typeof module) !== 'undefined') {
return [symbol, patterns];
},
- simplify: function(symbol) {
+ simplify: function(symbol) {
//remove the multiplier to make calculation easier;
var sym_array = __.Simplify.strip(symbol);
symbol = sym_array.pop();
@@ -4354,4 +4354,5 @@ if((typeof module) !== 'undefined') {
}
]);
nerdamer.api();
-})();
\ No newline at end of file
+})();
+
diff --git a/Solve.js b/Solve.js
index <HASH>..<HASH> 100644
--- a/Solve.js
+++ b/Solve.js
@@ -200,6 +200,20 @@ if ((typeof module) !== 'undefined') {
return new Equation(a, b);
};
+ // Extend simplify
+ (function() {
+ var simplify = _.functions.simplify[0];
+ _.functions.simplify[0] = function(symbol) {
+ if(symbol instanceof Equation) {
+ symbol.LHS = simplify(symbol.LHS);
+ symbol.RHS = simplify(symbol.RHS);
+ return symbol;
+ }
+ // Just call the original simplify
+ return simplify(symbol);
+ };
+ })();
+
/**
* Sets two expressions equal
* @param {Symbol} symbol
diff --git a/nerdamer.core.js b/nerdamer.core.js
index <HASH>..<HASH> 100644
--- a/nerdamer.core.js
+++ b/nerdamer.core.js
@@ -1253,9 +1253,11 @@ var nerdamer = (function (imports) {
var Big = {
cos: function (x) {
return new Symbol(bigDec.cos(x.multiplier.toDecimal()));
+// return bigDec.cos(x.multiplier.toDecimal());
},
sin: function (x) {
return new Symbol(bigDec.sin(x.multiplier.toDecimal()));
+// return bigDec.sin(x.multiplier.toDecimal());
}
};
//Math2 ========================================================================
|
Extend simplify to `Equation` class as per #<I>
|
jiggzson_nerdamer
|
train
|
94ef3d88b9054372ff9442695f1dd6c2c6b112bc
|
diff --git a/cmd/minikube/cmd/start.go b/cmd/minikube/cmd/start.go
index <HASH>..<HASH> 100644
--- a/cmd/minikube/cmd/start.go
+++ b/cmd/minikube/cmd/start.go
@@ -46,6 +46,7 @@ const (
cpus = "cpus"
humanReadableDiskSize = "disk-size"
vmDriver = "vm-driver"
+ xhyveDiskDriver = "xhyve-disk-driver"
kubernetesVersion = "kubernetes-version"
hostOnlyCIDR = "host-only-cidr"
containerRuntime = "container-runtime"
@@ -99,6 +100,7 @@ func runStart(cmd *cobra.Command, args []string) {
CPUs: viper.GetInt(cpus),
DiskSize: diskSizeMB,
VMDriver: viper.GetString(vmDriver),
+ XhyveDiskDriver: viper.GetString(xhyveDiskDriver),
DockerEnv: dockerEnv,
DockerOpt: dockerOpt,
InsecureRegistry: insecureRegistry,
@@ -217,6 +219,7 @@ func init() {
startCmd.Flags().String(hostOnlyCIDR, "192.168.99.1/24", "The CIDR to be used for the minikube VM (only supported with Virtualbox driver)")
startCmd.Flags().String(hypervVirtualSwitch, "", "The hyperv virtual switch name. Defaults to first found. (only supported with HyperV driver)")
startCmd.Flags().String(kvmNetwork, "default", "The KVM network name. (only supported with KVM driver)")
+ startCmd.Flags().String(xhyveDiskDriver, "ahci-hd", "The disk driver to use [ahci-hd|virtio-blk] (only supported with xhyve driver)")
startCmd.Flags().StringArrayVar(&dockerEnv, "docker-env", nil, "Environment variables to pass to the Docker daemon. (format: key=value)")
startCmd.Flags().StringArrayVar(&dockerOpt, "docker-opt", nil, "Specify arbitrary flags to pass to the Docker daemon. (format: key=value)")
startCmd.Flags().String(apiServerName, constants.APIServerName, "The apiserver name which is used in the generated certificate for localkube/kubernetes. This can be used if you want to make the apiserver available from outside the machine")
diff --git a/pkg/minikube/cluster/cluster_darwin.go b/pkg/minikube/cluster/cluster_darwin.go
index <HASH>..<HASH> 100644
--- a/pkg/minikube/cluster/cluster_darwin.go
+++ b/pkg/minikube/cluster/cluster_darwin.go
@@ -51,6 +51,8 @@ type xhyveDriver struct {
DiskNumber int
Virtio9p bool
Virtio9pFolder string
+ QCow2 bool
+ RawDisk bool
}
func createXhyveHost(config MachineConfig) *xhyveDriver {
@@ -66,5 +68,7 @@ func createXhyveHost(config MachineConfig) *xhyveDriver {
DiskSize: int64(config.DiskSize),
Virtio9p: true,
Virtio9pFolder: "/Users",
+ QCow2: false,
+ RawDisk: config.XhyveDiskDriver == "virtio-blk",
}
}
diff --git a/pkg/minikube/cluster/types.go b/pkg/minikube/cluster/types.go
index <HASH>..<HASH> 100644
--- a/pkg/minikube/cluster/types.go
+++ b/pkg/minikube/cluster/types.go
@@ -25,6 +25,7 @@ type MachineConfig struct {
CPUs int
DiskSize int
VMDriver string
+ XhyveDiskDriver string // Only used by the xhyve driver
DockerEnv []string // Each entry is formatted as KEY=VALUE.
InsecureRegistry []string
RegistryMirror []string
|
Add support for using raw disks with xhyve (#<I>)
* Add support for using raw disks with xhyve, default it to true
* Fix formatting issue
* Prefix disk-driver with xhyve to make it clear it is only for xhyve
* Add missing config
|
kubernetes_minikube
|
train
|
0c724baed8d24c0bd82845674b592a949e0e8dec
|
diff --git a/Resources/public/js/views/ez-contenteditview.js b/Resources/public/js/views/ez-contenteditview.js
index <HASH>..<HASH> 100644
--- a/Resources/public/js/views/ez-contenteditview.js
+++ b/Resources/public/js/views/ez-contenteditview.js
@@ -7,9 +7,7 @@ YUI.add('ez-contenteditview', function (Y) {
Y.namespace('eZ');
- var DETAILS_SEL = '.ez-technical-infos',
- doc = Y.config.doc,
- IS_TOUCH = !!(doc && doc.createTouch);
+ var DETAILS_SEL = '.ez-technical-infos';
/**
* The content edit view
@@ -102,7 +100,7 @@ YUI.add('ez-contenteditview', function (Y) {
* @return {Boolean}
*/
_isTouch: function () {
- return IS_TOUCH;
+ return Y.UA.touchEnabled;
}
}, {
ATTRS: {
|
Changed the touch device detection to use Y.UA
|
ezsystems_PlatformUIBundle
|
train
|
94aea9af02c5f9da8f6b28e7a491af335c4f12d7
|
diff --git a/dataclass.py b/dataclass.py
index <HASH>..<HASH> 100644
--- a/dataclass.py
+++ b/dataclass.py
@@ -295,7 +295,7 @@ def dataclass(_cls=None, *, repr=True, cmp=True, hash=None, init=True,
return wrap(_cls)
-def make_class(cls_name, fields, bases=None, repr=True, cmp=True,
+def make_class(cls_name, fields, *, bases=None, repr=True, cmp=True,
hash=None, init=True, slots=False, frozen=False):
# fields is a list of (name, type, field)
if bases is None:
diff --git a/tst.py b/tst.py
index <HASH>..<HASH> 100755
--- a/tst.py
+++ b/tst.py
@@ -313,6 +313,15 @@ class TestCase(unittest.TestCase):
C = make_class('C', 'a b')
self.assertEqual(repr(C(1, 2)), 'C(a=1,b=2)')
+ def test_make_derived(self):
+ @dataclass
+ class Base:
+ x: int
+ y: int
+
+ C = make_class('C', 'z x', bases=(Base,))
+ self.assertEqual(repr(C(4,5,6)), 'C(x=4,y=5,z=6)')
+
def main():
unittest.main()
|
Make most params to make_class keyword-only.
Add a test for derived classes in make_class.
|
ericvsmith_dataclasses
|
train
|
0dd046b7deaa7962f68c4439ad71a963db2645d5
|
diff --git a/demo/component/TextDemo.js b/demo/component/TextDemo.js
index <HASH>..<HASH> 100644
--- a/demo/component/TextDemo.js
+++ b/demo/component/TextDemo.js
@@ -81,9 +81,9 @@ class TextDemo extends Component {
onChange={e => this.setState({ width: Number(e.target.value) })}
/> {this.state.width}
</div>
-
+
<div>
- textAnchor:
+ textAnchor:
<label>
<input
type="radio"
diff --git a/src/util/CartesianUtils.js b/src/util/CartesianUtils.js
index <HASH>..<HASH> 100644
--- a/src/util/CartesianUtils.js
+++ b/src/util/CartesianUtils.js
@@ -102,7 +102,9 @@ export const getStackGroupsByAxisId = (data, items, numericAxisId, cateAxisId, o
const parentGroup = result[axisId] || { hasStack: false, stackGroups: {} };
if (isNumOrStr(stackId)) {
- const childGroup = parentGroup.stackGroups[stackId] || { items: [] };
+ const childGroup = parentGroup.stackGroups[stackId] || {
+ numericAxisId, cateAxisId, items: [],
+ };
childGroup.items = [item].concat(childGroup.items);
diff --git a/test/specs/chart/BarChartSpec.js b/test/specs/chart/BarChartSpec.js
index <HASH>..<HASH> 100644
--- a/test/specs/chart/BarChartSpec.js
+++ b/test/specs/chart/BarChartSpec.js
@@ -97,6 +97,17 @@ describe('<BarChart />', () => {
expect(wrapper.find('.recharts-rectangle').length).to.equal(8);
});
+ it('Renders 4 bars in a stacked BarChart which only have one Bar', () => {
+ const wrapper = render(
+ <BarChart width={100} height={50} data={data}>
+ <YAxis />
+ <Bar dataKey="uv" stackId="test" fill="#ff7300"/>
+ </BarChart>
+ );
+
+ expect(wrapper.find('.recharts-rectangle').length).to.equal(4);
+ });
+
// it('Renders tooltip when Tooltip item is added', () => {
// const wrapper = mount(
// <BarChart width={100} height={50} data={data}>
diff --git a/test/specs/component/TextSpec.js b/test/specs/component/TextSpec.js
index <HASH>..<HASH> 100644
--- a/test/specs/component/TextSpec.js
+++ b/test/specs/component/TextSpec.js
@@ -62,19 +62,11 @@ describe('<Text />', () => {
expect(wrapper.text()).to.contain('anything');
});
- it("Don't Render text when x or y is NaN, null, or undefined ", () => {
+ it("Don't Render text when x or y is NaN ", () => {
const wrapperNan = render(
<Text x={NaN} y={10}>anything</Text>
);
- const wrapperNull = render(
- <Text x={5} y={null}>anything</Text>
- );
- const wrapperUndefined = render(
- <Text x={5} y={undefined}>anything</Text>
- );
expect(wrapperNan.text()).to.not.contain('anything');
- expect(wrapperNull.text()).to.not.contain('anything');
- expect(wrapperUndefined.text()).to.not.contain('anything');
});
});
|
fix: fix bug of BarChart when add stackId in only one Bar and update test cases, fix #<I>
|
recharts_recharts
|
train
|
6071120890347fd2c04bcfb4e8387d4b1dd839ba
|
diff --git a/lib/usmu/page.rb b/lib/usmu/page.rb
index <HASH>..<HASH> 100644
--- a/lib/usmu/page.rb
+++ b/lib/usmu/page.rb
@@ -1,3 +1,4 @@
+require 'usmu/layout'
module Usmu
# Represents a page in the source directory of the website.
diff --git a/lib/usmu/site_generator.rb b/lib/usmu/site_generator.rb
index <HASH>..<HASH> 100644
--- a/lib/usmu/site_generator.rb
+++ b/lib/usmu/site_generator.rb
@@ -1,4 +1,7 @@
require 'fileutils'
+require 'usmu/configuration'
+require 'usmu/page'
+require 'usmu/static_file'
module Usmu
# This is the class that brings everything together to generate a new website.
diff --git a/lib/usmu/static_file.rb b/lib/usmu/static_file.rb
index <HASH>..<HASH> 100644
--- a/lib/usmu/static_file.rb
+++ b/lib/usmu/static_file.rb
@@ -1,3 +1,4 @@
+require 'usmu/configuration'
module Usmu
# Represents a static file which should be transferred to the destination unchanged. This also acts as the base
diff --git a/test/spec/static_file_spec.rb b/test/spec/static_file_spec.rb
index <HASH>..<HASH> 100644
--- a/test/spec/static_file_spec.rb
+++ b/test/spec/static_file_spec.rb
@@ -24,4 +24,3 @@ RSpec.describe Usmu::StaticFile do
expect(file.output_filename).to eq('robots.txt')
end
end
-
|
Updates so specs can be run individually
|
usmu_usmu
|
train
|
78a16853a1c9ec37377860cea3ecf604cdedf260
|
diff --git a/examples/async-effects-example/src/store.test.js b/examples/async-effects-example/src/store.test.js
index <HASH>..<HASH> 100644
--- a/examples/async-effects-example/src/store.test.js
+++ b/examples/async-effects-example/src/store.test.js
@@ -3,17 +3,19 @@ const { configureStore } = require("./store");
const storeForTest = () => configureStore([storeSpy]);
-const effect = async dispatch => {
+const effect = dispatch => {
dispatch({ type: "REQUEST_STARTED" });
- const result = await fetch("/api/count");
-
- if (result.ok) {
- dispatch({
- type: "REQUEST_SUCCESS",
- payload: (await result.json()).count
- });
- }
+ return fetch("/api/count").then(result => {
+ if (result.ok) {
+ return result.json().then(jsonBody => {
+ dispatch({
+ type: "REQUEST_SUCCESS",
+ payload: jsonBody.count
+ });
+ });
+ }
+ });
};
describe("service", () => {
|
Remove async/await from example to comply with lts/boron lang support
|
rradczewski_expect-redux
|
train
|
687bcf0461f8251e60caa508c898b87046fbbe1c
|
diff --git a/blueprints/glimmer-component/index.js b/blueprints/glimmer-component/index.js
index <HASH>..<HASH> 100644
--- a/blueprints/glimmer-component/index.js
+++ b/blueprints/glimmer-component/index.js
@@ -20,7 +20,7 @@ module.exports = {
},
locals(options) {
- let className = stringUtils.classify(options.entity.name);
+ let className = `${stringUtils.classify(options.entity.name)}Component`;
return { className };
},
};
|
blueprints: Add "Component" suffix to generated class name
|
glimmerjs_glimmer-application-pipeline
|
train
|
4082dbfbb342163ab1ba58d9e0a55fbe0a5b10a4
|
diff --git a/symphony/content/content.publish.php b/symphony/content/content.publish.php
index <HASH>..<HASH> 100644
--- a/symphony/content/content.publish.php
+++ b/symphony/content/content.publish.php
@@ -17,6 +17,12 @@ class contentPublish extends AdministrationPage
public function sort(&$sort, &$order, $params)
{
$section = $params['current-section'];
+ $filters = '';
+ // Format the filter query string
+ if (isset($params['filters']) && !empty($params['filters'])) {
+ $filters = preg_replace('/^&/i', '', $params['filters'], 1);
+ $filters = '?' . trim($filters);
+ }
// If `?unsort` is appended to the URL, then sorting is reverted
// to 'none', aka. by 'entry-id'.
@@ -24,11 +30,11 @@ class contentPublish extends AdministrationPage
$section->setSortingField('id', false);
$section->setSortingOrder('desc');
- redirect(Administration::instance()->getCurrentPageURL());
+ redirect(Administration::instance()->getCurrentPageURL() . $filters);
}
// By default, sorting information are retrieved from
- // the filesystem and stored inside the `Configuration` object
+ // the file system and stored inside the `Configuration` object
if (is_null($sort) && is_null($order)) {
$sort = $section->getSortingField();
$order = $section->getSortingOrder();
@@ -37,7 +43,6 @@ class contentPublish extends AdministrationPage
EntryManager::setFetchSorting($sort, $order);
} else {
$sort = General::sanitize($sort);
- $filters = '';
// Ensure that this field is infact sortable, otherwise
// fallback to IDs
@@ -45,12 +50,6 @@ class contentPublish extends AdministrationPage
$sort = $section->getDefaultSortingField();
}
- // Format the filter query string
- if ($params['filters']) {
- $filters = preg_replace('/^&/i', '', $params['filters'], 1);
- $filters = '?' . trim($filters);
- }
-
// If the sort order or direction differs from what is saved,
// update the config file and reload the page
if ($sort != $section->getSortingField() || $order != $section->getSortingOrder()) {
|
Preserve filters when doing a 'unsort' operation
Re: #<I>
Re: #<I>
Picked from b5de<I>ed<I>
Picked from d1c1bb<I>d
|
symphonycms_symphony-2
|
train
|
d2553f08f7144ea412be91046af9a7ced21a37c5
|
diff --git a/__tests__/index.spec.js b/__tests__/index.spec.js
index <HASH>..<HASH> 100644
--- a/__tests__/index.spec.js
+++ b/__tests__/index.spec.js
@@ -43,5 +43,6 @@ describe('core', () => {
it('export intent', () => {
expect(core.REGEX).toBeDefined();
expect(core.recognizers).toBeDefined();
+ expect(core.createRecognizer).toBeDefined();
});
});
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -7,7 +7,7 @@ export { default as FBGraphAPIClient } from './api/FBGraphAPIClient';
export { default as LINEBotAPIClient } from './api/LINEBotAPIClient';
export { default as REGEX } from './intent/REGEX';
-export { default as recognizers } from './intent/recognizers';
+export { default as recognizers, createRecognizer } from './intent/recognizers';
export {
default as verifyMessengerWebhook,
|
export createRecognizer from core
|
Yoctol_bottender
|
train
|
55e244efceb6d0b3b4bbbdfbb362f202c1d9dbbf
|
diff --git a/lenses/optics/traversals.py b/lenses/optics/traversals.py
index <HASH>..<HASH> 100644
--- a/lenses/optics/traversals.py
+++ b/lenses/optics/traversals.py
@@ -112,7 +112,7 @@ class RecurTraversal(Traversal):
>>> data = [[1, 2, 100.0], [3, 'hello', [{}, 4], 5]]
>>> RecurTraversal(int).to_list_of(data)
[1, 2, 3, 4, 5]
- >>> class Container():
+ >>> class Container(object):
... def __init__(self, contents):
... self.contents = contents
... def __repr__(self):
@@ -143,34 +143,44 @@ class RecurTraversal(Traversal):
yield focus
def builder(self, state, values):
- state, leftovers = self.build_object(state, values)
- assert list(leftovers) == [], 'Did not consume all the values'
- return state
+ return self.build_object(state, values)
def build_object(self, state, values):
if isinstance(state, self.cls):
- return values[0], values[1:]
+ assert len(values) == 1
+ return values[0]
elif self.can_iter(state):
return self.build_from_iter(state, values)
elif hasattr(state, '__dict__'):
return self.build_dunder_dict(state, values)
- return state, values
+ else:
+ return state
def build_from_iter(self, state, values):
new_substates = []
for substate in hooks.to_iter(state):
- new_substate, values = self.build_object(substate, values)
+ count = len(list(self.folder(substate)))
+ new_substate = substate
+ if count:
+ subvalues, values = values[:count], values[count:]
+ new_substate = self.build_object(substate, subvalues)
new_substates.append(new_substate)
+
+ assert len(values) == 0
new_state = hooks.from_iter(state, new_substates)
- return new_state, values
+ return new_state
def build_dunder_dict(self, state, values):
- state = copy.copy(state)
+ new_state = state
for attr in sorted(state.__dict__):
substate = getattr(state, attr)
- new_substate, values = self.build_object(substate, values)
- setattr(state, attr, new_substate)
- return state, values
+ count = len(list(self.folder(substate)))
+ if count:
+ subvalues, values = values[:count], values[count:]
+ new_substate = self.build_object(substate, subvalues)
+ new_state = hooks.setattr(new_state, attr, new_substate)
+ assert len(values) == 0
+ return new_state
@staticmethod
def can_iter(state):
diff --git a/lenses/ui/base.py b/lenses/ui/base.py
index <HASH>..<HASH> 100644
--- a/lenses/ui/base.py
+++ b/lenses/ui/base.py
@@ -745,7 +745,7 @@ class BaseUiLens(Generic[S, T, A, B]):
It also works on custom classes:
- >>> class Container():
+ >>> class Container(object):
... def __init__(self, contents):
... self.contents = contents
... def __repr__(self):
diff --git a/tests/test_optics.py b/tests/test_optics.py
index <HASH>..<HASH> 100644
--- a/tests/test_optics.py
+++ b/tests/test_optics.py
@@ -396,6 +396,23 @@ def test_RecurTraversal_over_with_frozenset():
assert lens.over(data, lambda n: n + 10) == result
+def test_RecurTraversal_no_change():
+ data = [
+ 1,
+ [],
+ [2],
+ Pair(3, 4),
+ Pair('one', 'two'),
+ Pair([Pair(5, [6, 7]), 256.0], 8),
+ Pair(['three', Pair(9, 'four')], 'five'),
+ ]
+ lens = b.RecurTraversal(float)
+ result = lens.over(data, lambda a: 512.0)
+ assert data is not result
+ for n in (0, 1, 2, 3, 4, 6):
+ assert data[n] is result[n]
+
+
def test_TrivialIso_view():
obj = object()
assert b.TrivialIso().view(obj) is obj
|
refactored RecurTraversal to stop consuming values list
|
ingolemo_python-lenses
|
train
|
5f0574496b53a557564c9480c3e490c39d1ace56
|
diff --git a/eli5/keras/explain_prediction.py b/eli5/keras/explain_prediction.py
index <HASH>..<HASH> 100644
--- a/eli5/keras/explain_prediction.py
+++ b/eli5/keras/explain_prediction.py
@@ -116,7 +116,7 @@ def explain_prediction_keras(estimator, # type: Model
weights, activations, grads, predicted_idx, predicted_val = values
heatmap = gradcam(weights, activations)
- doc = doc[0] # rank 4 batch -> rank 3 single image
+ doc, = doc # rank 4 batch -> rank 3 single image
image = keras.preprocessing.image.array_to_img(doc) # -> RGB Pillow image
image = image.convert(mode='RGBA')
|
Use tuple unpacking to get image from batch
|
TeamHG-Memex_eli5
|
train
|
31aebc480315d94b91570db999a3e35107d56d59
|
diff --git a/cmsplugin_cascade/bootstrap4/grid.py b/cmsplugin_cascade/bootstrap4/grid.py
index <HASH>..<HASH> 100644
--- a/cmsplugin_cascade/bootstrap4/grid.py
+++ b/cmsplugin_cascade/bootstrap4/grid.py
@@ -225,7 +225,8 @@ class Bootstrap4Row(list):
def compute_column_bounds(self):
assert isinstance(self.bounds, dict)
for bp in [Breakpoint.xs, Breakpoint.sm, Breakpoint.md, Breakpoint.lg, Breakpoint.xl]:
- remaining_width = copy(self.bounds[bp])
+ if bp in self.bounds:
+ remaining_width = copy(self.bounds[bp])
# first compute the bounds of columns with a fixed width
for column in self:
|
Fix: KeyError if a Breakpoint is not checked in container plugin
If a Breakpoint is not checked in container plugin and if there is a image / picture in a columns.
This is not necessary for the jumbotron apparently.
|
jrief_djangocms-cascade
|
train
|
29f48465cd5c16a087a24508a23f4066c97a63bc
|
diff --git a/kie-api/src/main/java/org/kie/api/definition/process/Process.java b/kie-api/src/main/java/org/kie/api/definition/process/Process.java
index <HASH>..<HASH> 100644
--- a/kie-api/src/main/java/org/kie/api/definition/process/Process.java
+++ b/kie-api/src/main/java/org/kie/api/definition/process/Process.java
@@ -17,6 +17,7 @@
package org.kie.api.definition.process;
import org.kie.api.definition.KieDefinition;
+import org.kie.api.io.Resource;
import java.util.Map;
@@ -73,4 +74,7 @@ public interface Process
*/
Map<String, Object> getMetaData();
+ Resource getResource();
+
+ void setResource( Resource res );
}
|
[DROOLS-<I>] PKGs downloaded from guvor contain void references to the internal resources
|
kiegroup_droolsjbpm-knowledge
|
train
|
16579a96338af6c1d8c7b33bef149a88ccb9ee4f
|
diff --git a/lib/ace/document.js b/lib/ace/document.js
index <HASH>..<HASH> 100644
--- a/lib/ace/document.js
+++ b/lib/ace/document.js
@@ -40,7 +40,7 @@ define(function(require, exports, module) {
var oop = require("ace/lib/oop").oop;
var lang = require("ace/lib/lang").lang;
var MEventEmitter = require("ace/event_emitter").MEventEmitter;
-var Selection = require("ace/selection");
+var Selection = require("ace/selection").Selection;
var TextMode = require("ace/mode/text").Text;
var Range = require("ace/range").Range;
diff --git a/lib/ace/editor.js b/lib/ace/editor.js
index <HASH>..<HASH> 100644
--- a/lib/ace/editor.js
+++ b/lib/ace/editor.js
@@ -40,10 +40,10 @@ define(function(require, exports, module) {
var oop = require("ace/lib/oop").oop;
var event = require("ace/lib/event").event;
var lang = require("ace/lib/lang").lang;
-var TextInput = require("ace/textinput");
+var TextInput = require("ace/textinput").TextInput;
var KeyBinding = require("ace/keybinding").KeyBinding;
var Document = require("ace/document").Document;
-var Search = require("ace/search");
+var Search = require("ace/search").Search;
var BackgroundTokenizer = require("ace/background_tokenizer").BackgroundTokenizer;
var Range = require("ace/range").Range;
var MEventEmitter = require("ace/event_emitter").MEventEmitter;
diff --git a/lib/ace/search.js b/lib/ace/search.js
index <HASH>..<HASH> 100644
--- a/lib/ace/search.js
+++ b/lib/ace/search.js
@@ -317,5 +317,5 @@ Search.SELECTION = 2;
}).call(Search.prototype);
-return Search;
+exports.Search = Search;
});
diff --git a/lib/ace/selection.js b/lib/ace/selection.js
index <HASH>..<HASH> 100644
--- a/lib/ace/selection.js
+++ b/lib/ace/selection.js
@@ -417,5 +417,5 @@ var Selection = function(doc) {
}).call(Selection.prototype);
-return Selection;
+exports.Selection = Selection;
});
diff --git a/lib/ace/textinput.js b/lib/ace/textinput.js
index <HASH>..<HASH> 100644
--- a/lib/ace/textinput.js
+++ b/lib/ace/textinput.js
@@ -146,5 +146,5 @@ var TextInput = function(parentNode, host) {
};
};
-return TextInput;
-});
\ No newline at end of file
+exports.TextInput = TextInput;
+});
|
convert Search, Selection and TextInput to exports style
|
joewalker_gcli
|
train
|
b19802e6fc8a0655c257b89ffe39ce39fa2ad79d
|
diff --git a/fontaine/builder.py b/fontaine/builder.py
index <HASH>..<HASH> 100644
--- a/fontaine/builder.py
+++ b/fontaine/builder.py
@@ -66,9 +66,9 @@ class Director(object):
if self.charmaps:
cn = getattr(cmap, 'common_name', False)
nn = getattr(cmap, 'native_name', False)
- if cn and cn not in self._charmaps:
+ if cn and cn not in self.charmaps:
continue
- if nn and nn not in self._charmaps:
+ if nn and nn not in self.charmaps:
continue
if cmap.key not in font._unicodeValues:
|
rename accessed variable `_charmaps` to `charmaps`
|
davelab6_pyfontaine
|
train
|
bc854dcc7031df5040ef8a58d0f9b82fdcb08a69
|
diff --git a/spyder/plugins/plots/widgets/figurebrowser.py b/spyder/plugins/plots/widgets/figurebrowser.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/plots/widgets/figurebrowser.py
+++ b/spyder/plugins/plots/widgets/figurebrowser.py
@@ -481,8 +481,8 @@ class FigureViewer(QScrollArea):
def scale_image(self):
"""Scale the image size."""
- fwidth = self.figcanvas.fwidth
- fheight = self.figcanvas.fheight
+ fwidth = self.figcanvas.fwidth * 1.0
+ fheight = self.figcanvas.fheight * 1.0
# Don't auto fit plotting
if not self.auto_fit_plotting:
@@ -494,14 +494,14 @@ class FigureViewer(QScrollArea):
else:
size = self.size()
scrollbar_width = self.verticalScrollBar().sizeHint().width()
- width = size.width() - scrollbar_width
+ width = (size.width() - scrollbar_width) * 1.0
scrollbar_height = self.horizontalScrollBar().sizeHint().height()
- height = size.height() - scrollbar_height
+ height = (size.height() - scrollbar_height) * 1.0
if (fwidth / fheight) > (width / height):
- new_width = width
+ new_width = int(width)
new_height = int(width / fwidth * fheight)
else:
- new_height = height
+ new_height = int(height)
new_width = int(height / fheight * fwidth)
self.figcanvas.setFixedSize(new_width, new_height)
diff --git a/spyder/plugins/plots/widgets/tests/test_plots_widgets.py b/spyder/plugins/plots/widgets/tests/test_plots_widgets.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/plots/widgets/tests/test_plots_widgets.py
+++ b/spyder/plugins/plots/widgets/tests/test_plots_widgets.py
@@ -373,7 +373,7 @@ def test_autofit_figure_viewer(figbrowser, tmpdir, fmt):
# Calculate original figure size in pixels.
qpix = QPixmap()
qpix.loadFromData(fig, fmt.upper())
- fwidth, fheight = qpix.width(), qpix.height()
+ fwidth, fheight = qpix.width() * 1.0, qpix.height() * 1.0
# Test when `Fit plots to window` is set to True.
# Otherwise, test should fall into `test_zoom_figure_viewer`
@@ -381,14 +381,14 @@ def test_autofit_figure_viewer(figbrowser, tmpdir, fmt):
size = figviewer.size()
scrollbar_width = figviewer.verticalScrollBar().sizeHint().width()
- width = size.width() - scrollbar_width
+ width = (size.width() - scrollbar_width) * 1.0
scrollbar_height = figviewer.horizontalScrollBar().sizeHint().height()
- height = size.height() - scrollbar_height
+ height = (size.height() - scrollbar_height) * 1.0
if (fwidth / fheight) > (width / height):
- new_width = width
+ new_width = int(width)
new_height = int(width / fwidth * fheight)
else:
- new_height = height
+ new_height = int(height)
new_width = int(height / fheight * fwidth)
assert figcanvas.width() == new_width
|
Fix int devide to see if test pass in py2
|
spyder-ide_spyder
|
train
|
b4664630952fdef5445da38f1e20867cba8b45aa
|
diff --git a/lib/jitsu/commands/env.js b/lib/jitsu/commands/env.js
index <HASH>..<HASH> 100644
--- a/lib/jitsu/commands/env.js
+++ b/lib/jitsu/commands/env.js
@@ -194,7 +194,16 @@ env.clear = function (appName, callback) {
//
function viewApp(callback, success) {
jitsu.package.tryRead(process.cwd(), callback, function (pkg) {
+ jitsu.log.info('Attempting to set env variables for app ' + (process.cwd()+ '/package.json').grey);
jitsu.apps.view(pkg.name, function (err, app) {
+ //
+ // TODO: replace this error handling with errs library
+ //
+ if (err && err.result && err.result.error === "not_found") {
+ jitsu.log.error('app ' + pkg.name.magenta + ' doesn\'t exist!');
+ jitsu.log.help('Try running ' + 'jitsu deploy'.magenta);
+ return callback({});
+ }
return err ? callback(err) : success(null, app);
});
});
|
[ux] Better messaging on attempting to set env vars for local-only app. Closes #<I>
|
nodejitsu_jitsu
|
train
|
5ae847a0761318375a714334e7cafcb55e1274f8
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -78,25 +78,25 @@ module.exports = class Multispinner {
// iterate over spinners to check state and build current strings
Object.keys(this.spinners).map(spinner => {
+ let color
+ let symbol
switch (this.spinners[spinner].state) {
case states.incomplete:
- this.spinners[spinner].current = chalk[this.incompleteColor](
- `${this.indentStr}${animation} ${this.spinners[spinner].base}`
- )
+ color = this.incompleteColor
+ symbol = animation
break
case states.success:
- this.spinners[spinner].current = chalk[this.successColor](
- `${this.indentStr}${this.successIndicator} ` +
- `${this.spinners[spinner].base}`
- )
+ color = this.successColor
+ symbol = this.successIndicator
break
case states.error:
- this.spinners[spinner].current = chalk[this.errorColor](
- `${this.indentStr}${this.errorIndicator} ` +
- `${this.spinners[spinner].base}`
- )
+ color = this.errorColor
+ symbol = this.errorIndicator
break
}
+ this.spinners[spinner].current = this._spinnerStrBuilder(
+ color, symbol, spinner
+ )
})
// call update method to apply current strings to terminal
@@ -108,6 +108,17 @@ module.exports = class Multispinner {
}
/**
+ * @method _spinnerStrBuilder
+ * @desc Helper method to build spinner strings for _loop.
+ * @param {}
+ */
+ _spinnerStrBuilder(color, symbol, spinner) {
+ return chalk[color](
+ `${this.indentStr}${symbol} ${this.spinners[spinner].base}`
+ )
+ }
+
+ /**
* @method _update
* @desc Call to log-update made by _loop. Iterates over spinners.
* @returns {undefined}
diff --git a/opts.js b/opts.js
index <HASH>..<HASH> 100644
--- a/opts.js
+++ b/opts.js
@@ -79,6 +79,11 @@ module.exports = function(opts) {
// check for errs
if (opts) {
+ if (!opts instanceof Object) {
+ throw new Error(
+ 'node-multispinner: opts parameter must be a valid JS object'
+ )
+ }
Object.keys(opts).map(opt => {
// ensure each opt passed is a configurable opt
if (!defaults.hasOwnProperty(opt)) {
diff --git a/test/_allCompleted.js b/test/_allCompleted.js
index <HASH>..<HASH> 100644
--- a/test/_allCompleted.js
+++ b/test/_allCompleted.js
@@ -0,0 +1,4 @@
+describe('_allCompleted method', () => {
+ it('Return false if not all spinners are complete')
+ it('Return true if all spinners are complete')
+})
diff --git a/test/_clearState.js b/test/_clearState.js
index <HASH>..<HASH> 100644
--- a/test/_clearState.js
+++ b/test/_clearState.js
@@ -0,0 +1,3 @@
+describe('_clearState method', () => {
+ it('Clear interval bound to this.state')
+})
diff --git a/test/_complete.js b/test/_complete.js
index <HASH>..<HASH> 100644
--- a/test/_complete.js
+++ b/test/_complete.js
@@ -0,0 +1,5 @@
+describe('_complete method', () => {
+ it('Call _clearState method')
+ it('Update spinner with state')
+ it('Call _loop method')
+})
diff --git a/test/error.js b/test/error.js
index <HASH>..<HASH> 100644
--- a/test/error.js
+++ b/test/error.js
@@ -0,0 +1,3 @@
+describe('error method', () => {
+ it('Complete spinner and change state to error')
+})
diff --git a/test/opts.js b/test/opts.js
index <HASH>..<HASH> 100644
--- a/test/opts.js
+++ b/test/opts.js
@@ -0,0 +1,25 @@
+describe('parse opts', () => {
+ it('Bind defaults to this when no opts are passed')
+ it('Override defaults with passed opts')
+ it('Throw if opts is not an object')
+
+ //----------------------------------------------------------
+ // Typecheck opts -- numbers
+ //----------------------------------------------------------
+ it('Throw if delay option is not a number')
+ it('Throw if indent option is not a number')
+
+ //----------------------------------------------------------
+ // Typecheck opts -- strings
+ //----------------------------------------------------------
+ it('Throw if errorColor option is not a string')
+ it('Throw if errorIndicator option is not a string')
+ it('Throw if incompleteColor option is not a string')
+ it('Throw if successColor option is not a string')
+ it('Throw if succesIndicator option is not a string')
+
+ //----------------------------------------------------------
+ // Typecheck opts -- array of strings
+ //----------------------------------------------------------
+ it('Throw if frames option is not an array of strings')
+})
diff --git a/test/start.js b/test/start.js
index <HASH>..<HASH> 100644
--- a/test/start.js
+++ b/test/start.js
@@ -0,0 +1,3 @@
+describe('start method', () => {
+ it('Call _loop method')
+})
diff --git a/test/success.js b/test/success.js
index <HASH>..<HASH> 100644
--- a/test/success.js
+++ b/test/success.js
@@ -0,0 +1,3 @@
+describe('success method', () => {
+ it('Complete spinner and change state to success')
+})
|
stub out remaining tests; simplify spinner string logic
|
codekirei_node-multispinner
|
train
|
2d00c417bbf69b62da84e313cec1630fe9f0456d
|
diff --git a/flask_user/views.py b/flask_user/views.py
index <HASH>..<HASH> 100644
--- a/flask_user/views.py
+++ b/flask_user/views.py
@@ -433,7 +433,7 @@ def register():
# delete new User object if send fails
db_adapter.delete_object(user)
db_adapter.commit()
- raise e
+ raise
# Send user_registered signal
signals.user_registered.send(current_app._get_current_object(),
@@ -507,7 +507,7 @@ def invite():
# delete new User object if send fails
db_adapter.delete_object(user_invite)
db_adapter.commit()
- raise e
+ raise
signals \
.user_sent_invitation \
|
rethrow exception, instead of catching and throwing
|
lingthio_Flask-User
|
train
|
c0aec09693cd2366c950e436732a86d76057a177
|
diff --git a/src/org/opencms/search/CmsSearchManager.java b/src/org/opencms/search/CmsSearchManager.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/search/CmsSearchManager.java
+++ b/src/org/opencms/search/CmsSearchManager.java
@@ -525,6 +525,9 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
/** Configured analyzers for languages using <analyzer>. */
private HashMap<Locale, CmsSearchAnalyzer> m_analyzers;
+ /** The Solr core container. */
+ private CoreContainer m_coreContainer;
+
/** A map of document factory configurations. */
private List<CmsSearchDocumentType> m_documentTypeConfigs;
@@ -576,8 +579,6 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
/** Timeout for abandoning indexing thread. */
private long m_timeout;
- private CoreContainer m_coreContainer;
-
/**
* Default constructor when called as cron job.<p>
*/
@@ -880,6 +881,23 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
}
/**
+ * Returns all Solr index.<p>
+ *
+ * @return all Solr indexes
+ */
+ public List<CmsSolrIndex> getAllSolrIndexes() {
+
+ List<CmsSolrIndex> result = new ArrayList<CmsSolrIndex>();
+ for (String indexName : getIndexNames()) {
+ CmsSolrIndex index = getIndexSolr(indexName);
+ if (index != null) {
+ result.add(index);
+ }
+ }
+ return result;
+ }
+
+ /**
* Returns an analyzer for the given language.<p>
*
* The analyzer is selected according to the analyzer configuration.<p>
@@ -1511,7 +1529,7 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
}
// get the core container that contains one core for each configured index
- if (m_coreContainer == null) {
+ if (m_coreContainer == null) {
m_coreContainer = createCoreContainer();
}
@@ -1531,22 +1549,26 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
index.getPath()));
}
}
-
+
CoreDescriptor descriptor = new CoreDescriptor(m_coreContainer, "descriptor", m_solrConfig.getHome());
descriptor.setDataDir(dataDir.getAbsolutePath());
try {
- core = m_coreContainer.create(descriptor);
- core.setName(index.getName());
+ core = m_coreContainer.create(descriptor);
+ core.setName(index.getName());
// Register the newly created core
m_coreContainer.register(core, false);
- } catch (Exception e) {
- throw new CmsConfigurationException(Messages.get().container(Messages.ERR_SOLR_SERVER_NOT_CREATED_3, index.getName(), index.getPath(), m_solrConfig.getSolrConfigFile().getAbsolutePath()));
- }
+ } catch (Exception e) {
+ throw new CmsConfigurationException(Messages.get().container(
+ Messages.ERR_SOLR_SERVER_NOT_CREATED_3,
+ index.getName(),
+ index.getPath(),
+ m_solrConfig.getSolrConfigFile().getAbsolutePath()));
+ }
}
SolrServer server = new EmbeddedSolrServer(m_coreContainer, index.getName());
LOG.info(Messages.get().getBundle().key(
- Messages.LOG_SOLR_CREATED_EMBEDDED_SERVER_1,
- OpenCms.getSearchManager().getSolrServerConfiguration().getSolrFile().getAbsolutePath()));
+ Messages.LOG_SOLR_CREATED_EMBEDDED_SERVER_1,
+ OpenCms.getSearchManager().getSolrServerConfiguration().getSolrFile().getAbsolutePath()));
return server;
}
@@ -1968,11 +1990,11 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
index.shutDown();
}
- if (m_coreContainer != null && m_coreContainer.getCores() != null) {
- for (SolrCore core : m_coreContainer.getCores()) {
+ if ((m_coreContainer != null) && (m_coreContainer.getCores() != null)) {
+ for (SolrCore core : m_coreContainer.getCores()) {
core.closeSearcher();
core.close();
- }
+ }
}
m_coreContainer.shutdown();
|
Added a method to get all Solr indexes.
|
alkacon_opencms-core
|
train
|
a541b585b11c96e08ac8c385e6b3c4262141d9ed
|
diff --git a/addon/components/file-browser/component.js b/addon/components/file-browser/component.js
index <HASH>..<HASH> 100644
--- a/addon/components/file-browser/component.js
+++ b/addon/components/file-browser/component.js
@@ -218,6 +218,7 @@ export default Ember.Component.extend(Analytics, {
item.set('links', response.data.links); //Push doesnt pass it links
this.get('_items').unshiftObject(item);
this.notifyPropertyChange('_items');
+ item.getGuid();
Ember.run.next(() => {
this.flash(item, 'This file has been added.');
this.get('toast').success('A file has been added');
|
Always attempt to create a file's guid on upload
|
CenterForOpenScience_ember-osf
|
train
|
020889efee28216215a1589da6153d786ff66b0f
|
diff --git a/lib/field.js b/lib/field.js
index <HASH>..<HASH> 100644
--- a/lib/field.js
+++ b/lib/field.js
@@ -167,6 +167,18 @@ MarcControlField.clone = function(field) {
}
/*
+ * Replaces content of the field.
+ */
+MarcControlField.prototype.assign = function(field) {
+ if (!(field instanceof MarcControlField)) {
+ return false;
+ }
+ this.tag = field.tag;
+ this.data = field.data;
+ return true;
+}
+
+/*
* Returns copy of the field.
*/
MarcControlField.prototype.clone = function() {
@@ -295,6 +307,20 @@ MarcDataField.prototype.clone = function() {
}
/*
+ * Replaces content of the field.
+ */
+MarcDataField.prototype.assign = function(field) {
+ if (!(field instanceof MarcDataField)) {
+ return false;
+ }
+ this.tag = field.tag;
+ this.ind1 = field.ind1;
+ this.ind2 = field.ind2;
+ this.subfields = field.subfields;
+ return true;
+}
+
+/*
* Always returns true.
*/
MarcDataField.prototype.isDataField = function() {
diff --git a/lib/record.js b/lib/record.js
index <HASH>..<HASH> 100644
--- a/lib/record.js
+++ b/lib/record.js
@@ -112,6 +112,14 @@ MarcRecord.prototype.clone = function() {
}
/*
+ * Replaces content of the record.
+ */
+MarcRecord.prototype.assign = function(record) {
+ this.leader = record.leader;
+ this.fields = record.fields;
+}
+
+/*
* Returns true if the records are equal.
*/
MarcRecord.equals = function(record1, record2, opts) {
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "marcrecord",
"description": "MARC record library (inspired by marc4j)",
- "version": "1.0.2",
+ "version": "1.0.3",
"author": "Alexander Fronkin <alexander.fronkin@afronkin.net>",
"repository": {
"type": "git",
diff --git a/test/field.js b/test/field.js
index <HASH>..<HASH> 100644
--- a/test/field.js
+++ b/test/field.js
@@ -175,6 +175,14 @@ var fieldClone = field.clone();
assert(fieldClone !== field && fieldClone.equals(field));
/*
+ * MarcControlField.assign()
+ */
+var field1 = MarcVariableField.parse('001 ID1');
+var field2 = MarcVariableField.parse('001 ID2');
+field1.assign(field2);
+assert(field1 !== field2 && field1.equals(field2));
+
+/*
* MarcControlField.equals()
*/
var field1 = MarcVariableField.parse('001 ID1');
@@ -259,6 +267,14 @@ var fieldClone = MarcDataField.clone({});
assert(fieldClone === null);
/*
+ * MarcDataField.assign()
+ */
+var field1 = MarcVariableField.parse('111 23$aAAA$bBBB');
+var field2 = MarcVariableField.parse('111 23$aAAA$bBBBC');
+field1.assign(field2);
+assert(field1 !== field2 && field1.equals(field2));
+
+/*
* MarcDataField.equals()
*/
var field1 = MarcVariableField.parse('111 23$aAAA$bBBB');
diff --git a/test/record.js b/test/record.js
index <HASH>..<HASH> 100644
--- a/test/record.js
+++ b/test/record.js
@@ -74,6 +74,14 @@ assert(recordClone !== record && recordClone.equals(record));
assert(MarcRecord.clone({}) === null);
/*
+ * MarcRecord.assign()
+ */
+var record1 = MarcRecord.parse('001 ID1\n111 23$aAAA$bBBB');
+var record2 = MarcRecord.parse('111 23$bBBB$aAAA\n001 ID1');
+record1.assign(record2);
+assert(record1 !== record2 && record1.equals(record2));
+
+/*
* MarcRecord.equals()
*/
var record1 = MarcRecord.parse('001 ID1\n111 23$aAAA$bBBB');
|
Added method assign() to record and fields.
|
afronkin_node-marcrecord
|
train
|
1a6f5e78335f114da347109a4da8c5f4d9c7846d
|
diff --git a/test/last/last.test.js b/test/last/last.test.js
index <HASH>..<HASH> 100644
--- a/test/last/last.test.js
+++ b/test/last/last.test.js
@@ -5,10 +5,17 @@ test('Testing last', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof last === 'function', 'last is a Function');
- t.equal(last([1, 2, 3]), 3, "Returns the last element in an array");
- //t.deepEqual(last(args..), 'Expected');
- //t.equal(last(args..), 'Expected');
- //t.false(last(args..), 'Expected');
- //t.throws(last(args..), 'Expected');
+ t.true(last({ a: 1234}) === undefined, 'last({ a: 1234}) returns undefined');
+ t.equal(last([1, 2, 3]), 3, "last([1, 2, 3]) returns 3");
+ t.equal(last({ 0: false}), undefined, 'last({ 0: false}) returns undefined');
+ t.equal(last('String'), 'g', 'last(String) returns g');
+ t.throws(() => last(null), 'last(null) throws an Error');
+ t.throws(() => last(undefined), 'last(undefined) throws an Error');
+ t.throws(() => last(), 'last() throws an Error');
+
+ let start = new Date().getTime();
+ last([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]);
+ let end = new Date().getTime();
+ t.true((end - start) < 2000, 'last([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run');
t.end();
});
\ No newline at end of file
|
update last test, type, throw err, time, and omit args
|
30-seconds_30-seconds-of-code
|
train
|
3208e8c458a53b817a2f40562f2528670bb1a0d7
|
diff --git a/modules/core/src/main/java/org/projectodd/wunderboss/ec/ConcreteDaemonContext.java b/modules/core/src/main/java/org/projectodd/wunderboss/ec/ConcreteDaemonContext.java
index <HASH>..<HASH> 100644
--- a/modules/core/src/main/java/org/projectodd/wunderboss/ec/ConcreteDaemonContext.java
+++ b/modules/core/src/main/java/org/projectodd/wunderboss/ec/ConcreteDaemonContext.java
@@ -103,11 +103,12 @@ public class ConcreteDaemonContext extends ConcreteExecutionContext implements D
@Override
public synchronized void stop() throws TimeoutException, InterruptedException {
+ if (this.stopCallback != null) {
+ this.stopCallback.notify(this.name);
+ }
+
if (isRunning()) {
this.isRunning = false;
- if (this.stopCallback != null) {
- this.stopCallback.notify(this.name);
- }
this.thread.join(threadTimeout);
if (this.thread.isAlive()) {
|
Notify stop callback whenever stop is called
even if the daemon is no longer running.
|
projectodd_wunderboss-release
|
train
|
34b10830c21dac777f90ddb381b74be6a339efa9
|
diff --git a/packages/webpack/lib/middleware/render.js b/packages/webpack/lib/middleware/render.js
index <HASH>..<HASH> 100644
--- a/packages/webpack/lib/middleware/render.js
+++ b/packages/webpack/lib/middleware/render.js
@@ -29,7 +29,8 @@ module.exports = function createRenderMiddleware(webpackConfig) {
fs.readFile(filePath, 'utf8', (readError, fileContents) => {
if (readError) return reject(readError);
try {
- resolve(requireFromString(fileContents, filePath));
+ const middleware = requireFromString(fileContents, filePath);
+ resolve(middleware.default);
} catch (moduleError) {
reject(moduleError);
}
diff --git a/packages/webpack/lib/shims/node.js b/packages/webpack/lib/shims/node.js
index <HASH>..<HASH> 100644
--- a/packages/webpack/lib/shims/node.js
+++ b/packages/webpack/lib/shims/node.js
@@ -1,14 +1,7 @@
-'use strict';
-
-require('source-map-support/register');
-
-const { getConfigAndMixins } = require('./loader');
-
-let entryPoint = require('@untool/entrypoint');
-if (typeof entryPoint.default === 'function') {
- entryPoint = entryPoint.default;
-}
+import 'source-map-support/register';
+import { getConfigAndMixins } from './loader';
+import entryPoint from '@untool/entrypoint';
const { config, mixins } = getConfigAndMixins();
-module.exports = entryPoint(config, mixins);
+export default entryPoint(config, mixins);
diff --git a/packages/webpack/mixin.core.js b/packages/webpack/mixin.core.js
index <HASH>..<HASH> 100644
--- a/packages/webpack/mixin.core.js
+++ b/packages/webpack/mixin.core.js
@@ -24,7 +24,7 @@ class WebpackMixin extends Mixin {
const statsFilePath = join(serverDir, statsFile);
this.stats.resolve(exists(statsFilePath) ? require(statsFilePath) : {});
if (exists(serverFilePath)) {
- return require(serverFilePath);
+ return require(serverFilePath).default;
} else {
return (req, res, next) => next();
}
|
feat(webpack): use esm in node entry to enable possible tree shaking
|
untool_untool
|
train
|
4f1caaa03a931c764ad25c569e15af4e05cee8ed
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -13,37 +13,45 @@ blockRenderer.urltransform = function (url) {
var hasSigil = (c == '@' || c == '&' || c == '%')
if (this.options.sanitize && !hasSigil) {
+ // sanitize - only allow ssb refs or http/s links
try {
- var prot = decodeURIComponent(unescape(url))
- .replace(/[^\w:]/g, '')
- .toLowerCase();
+ var prot = decodeURIComponent(unescape(url.replace(/[^\w:]/g, ''))).toLowerCase();
} catch (e) {
return false;
}
- if (prot.indexOf('javascript:') === 0) {
+ if (prot.indexOf('http:') !== 0 && prot.indexOf('https:') !== 0 && prot.indexOf('data:') !== 0) {
return false;
}
}
- var islink = ssbref.isLink(url)
- if (hasSigil && !islink && this.options.mentionNames) {
- // do a name lookup
+ // is this an ssb ref, or perhaps a ref within an HTTP url?
+ var isSsbRef = ssbref.isLink(url)
+ if (!isSsbRef) {
+ // check if there's a ref inside somewhere
+ var ref = ssbref.extract(url)
+ if (ref) {
+ url = ref
+ isSsbRef = true
+ }
+ }
+
+ // is this an @username mention?
+ if (hasSigil && !isSsbRef && this.options.mentionNames) {
+ // try a name lookup
url = this.options.mentionNames[url.slice(1)]
if (!url)
return false
- islink = true
+ isSsbRef = true
}
- if (islink) {
+ // use our own link if this is an ssb ref
+ if (isSsbRef) {
if (ssbref.isFeedId(url))
return '#/profile/'+encodeURIComponent(url)
else if (ssbref.isMsgId(url))
return '#/msg/'+encodeURIComponent(url)
else if (ssbref.isBlobId(url))
- return '#/webview/'+encodeURIComponent(url)
- }
- else if (url.indexOf('http') !== 0) {
- return false;
+ return '/'+encodeURIComponent(url)
}
return url
}
@@ -53,7 +61,7 @@ blockRenderer.link = function(href, title, text) {
href = this.urltransform(href)
var out
if (href !== false) {
- if (href.indexOf('#/webview/') === 0 && (title || text)) // add ?name param if this is a link to a blob
+ if ((href.indexOf('/%26') === 0 || href.indexOf('/&') === 0) && (title || text)) // add ?name param if this is a link to a blob
href += '?name='+encodeURIComponent(title || text)
out = '<a href="' + href + '"';
} else
@@ -73,11 +81,11 @@ blockRenderer.link = function(href, title, text) {
blockRenderer.image = function (href, title, text) {
href = href.replace(/^&/, '&')
if (ssbref.isLink(href)) {
- var out = '<a href="#/webview/' + encodeURIComponent(href) + '"><img src="http://localhost:7777/' + href + '?fallback=img" alt="' + text + '"'
+ var out = '<img src="http://localhost:7777/' + href + '?fallback=img" alt="' + text + '"'
if (title) {
out += ' title="' + title + '"'
}
- out += '></a>'
+ out += '>'
return out
}
return text
@@ -87,7 +95,7 @@ blockRenderer.image = function (href, title, text) {
inlineRenderer.urltransform = function (url) { return false }
inlineRenderer.link = function (href, title, text) { return unquote(text) }
inlineRenderer.image = function (href, title, text) { return unquote(text) }
-inlineRenderer.code = function(code, lang, escaped) { return escaped ? code : quote(code) }
+inlineRenderer.code = function(code, lang, escaped) { return escaped ? code : escape(code) }
inlineRenderer.blockquote = function(quote) { return unquote(quote) }
inlineRenderer.html = function(html) { return false }
inlineRenderer.heading = function(text, level, raw) { return '<strong>'+unquote(text)+'</strong> ' }
@@ -107,7 +115,7 @@ inlineRenderer.mention = function(preceding, id) { return unquote((preceding||''
function unquote (text) {
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, '\'')
}
-function quote (text) {
+function escape (text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
|
extract refs from http urls when found in markdown content
|
ssbc_ssb-markdown
|
train
|
322e0ac624c7b83c1ea5f31e6118cba3f2ffbbcc
|
diff --git a/jsonapi/resource.py b/jsonapi/resource.py
index <HASH>..<HASH> 100644
--- a/jsonapi/resource.py
+++ b/jsonapi/resource.py
@@ -38,6 +38,27 @@ class ResourceManager(object):
ResourceManager.get_concrete_model(resource.Meta))
@staticmethod
+ def get_concrete_model_by_name(model_name):
+ """ Get model by its name.
+
+ :param str model_name: name of model.
+ :return django.db.models.Model:
+
+ Example:
+ get_concrete_model_by_name('auth.User')
+ django.contrib.auth.models.User
+
+ """
+ if isinstance(model_name, six.string_types) and \
+ len(model_name.split('.')) == 2:
+ app_name, model_name = model_name.split('.')
+ model = models.get_model(app_name, model_name)
+ else:
+ raise ValueError("{0} is not a Django model".format(model_name))
+
+ return model
+
+ @staticmethod
def get_concrete_model(meta):
""" Get model defined in Meta.
@@ -52,13 +73,8 @@ class ResourceManager(object):
if model is None:
return None
- if isinstance(model, six.string_types) and len(model.split('.')) == 2:
- app_name, model_name = model.split('.')
- model = models.get_model(app_name, model_name)
- elif inspect.isclass(model) and issubclass(model, models.Model):
- pass
- else:
- raise ValueError("{0} is not a Django model".format(model))
+ if not (inspect.isclass(model) and issubclass(model, models.Model)):
+ model = ResourceManager.get_concrete_model_by_name(model)
if model._meta.abstract:
raise ValueError(
|
split get_concrete_model into two: get model by name and by meta
|
pavlov99_jsonapi
|
train
|
1d296c03c9b2fd415e434066f1b0e51728f0095a
|
diff --git a/backtrader/indicator.py b/backtrader/indicator.py
index <HASH>..<HASH> 100644
--- a/backtrader/indicator.py
+++ b/backtrader/indicator.py
@@ -26,6 +26,7 @@ import six
from six.moves import xrange
from .lineiterator import LineIterator, IndicatorBase
+from .lineseries import LineSeriesMaker
class MetaIndicator(IndicatorBase.__class__):
@@ -61,6 +62,23 @@ class MetaIndicator(IndicatorBase.__class__):
_obj, args, kwargs = super(MetaIndicator, cls).donew(*args, **kwargs)
+ # If only 1 data was passed and it's multiline, put the 2nd
+ # and later lines in the datas array. This allows things like
+ # passing a "Stochastic" to a crossover indicator and it will
+ # automatically calculate the crossover of %k and %d
+ if len(_obj.datas) == 1:
+ if _obj.data.size():
+ r = range(1, _obj.data.size())
+ else:
+ r = range(0, _obj.data.lines.extrasize())
+
+ # print('init object', _obj)
+ # print('with datas', _obj.datas)
+
+ for l in r:
+ newdata = LineSeriesMaker(_obj.data.lines[l])
+ _obj.datas.append(newdata)
+
# return the values
return _obj, args, kwargs
|
Indicators receiving only 1 data get the 2nd and later lines as extras (use case: a crossover uses line 0 and 1 automatically)
|
backtrader_backtrader
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.