hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
af7b548bff54ea5557a28ec04e88cc004ce28315
|
diff --git a/librosa/display.py b/librosa/display.py
index <HASH>..<HASH> 100644
--- a/librosa/display.py
+++ b/librosa/display.py
@@ -633,7 +633,7 @@ def __log_scale(n):
y = n * (1 - np.logspace(-logn, 0, n, base=2, endpoint=True))[::-1]
y = y.astype(int)
- y_inv = np.arange(len(y)+1)
+ y_inv = np.arange(len(y))
for i in range(len(y)-1):
y_inv[y[i]:y[i+1]] = i
|
removed an unnecessary <I> in __log_scale
|
librosa_librosa
|
train
|
4b39013ef43bd22791bbab870d731e26e7c9b6aa
|
diff --git a/tests/testlib.py b/tests/testlib.py
index <HASH>..<HASH> 100644
--- a/tests/testlib.py
+++ b/tests/testlib.py
@@ -103,6 +103,18 @@ if hasattr(subprocess.Popen, 'terminate'):
Popen__terminate = subprocess.Popen.terminate
+def threading__thread_is_alive(thread):
+ """Return whether the thread is alive (Python version compatibility shim).
+
+ On Python >= 3.8 thread.isAlive() is deprecated (removed in Python 3.9).
+ On Python <= 2.5 thread.is_alive() isn't present (added in Python 2.6).
+ """
+ try:
+ return thread.is_alive()
+ except AttributeError:
+ return thread.isAlive()
+
+
def wait_for_port(
host,
port,
@@ -334,7 +346,9 @@ class TestCase(unittest2.TestCase):
for thread in threading.enumerate():
name = thread.getName()
# Python 2.4: enumerate() may return stopped threads.
- assert (not thread.isAlive()) or name in self.ALLOWED_THREADS, \
+ assert \
+ not threading__thread_is_alive(thread) \
+ or name in self.ALLOWED_THREADS, \
'Found thread %r still running after tests.' % (name,)
counts[name] = counts.get(name, 0) + 1
diff --git a/tests/utils_test.py b/tests/utils_test.py
index <HASH>..<HASH> 100644
--- a/tests/utils_test.py
+++ b/tests/utils_test.py
@@ -31,14 +31,14 @@ class RunWithRouterTest(testlib.TestCase):
def test_run_with_broker(self):
router = mitogen.utils.run_with_router(func0)
self.assertIsInstance(router, mitogen.master.Router)
- self.assertFalse(router.broker._thread.isAlive())
+ self.assertFalse(testlib.threading__thread_is_alive(router.broker._thread))
class WithRouterTest(testlib.TestCase):
def test_with_broker(self):
router = func()
self.assertIsInstance(router, mitogen.master.Router)
- self.assertFalse(router.broker._thread.isAlive())
+ self.assertFalse(testlib.threading__thread_is_alive(router.broker._thread))
class Dict(dict): pass
|
tests: Compatiblity shim for threading.Thread.is_alive()
On Python >= <I> thread.isAlive() is deprecated (removed in Python <I>.
On Python <= <I> thread.is_alive() isn't present (added in Python <I>).
|
dw_mitogen
|
train
|
6dfff8023d0f1aa974d14e2baf7e7aca5358ed20
|
diff --git a/examples/long-short.py b/examples/long-short.py
index <HASH>..<HASH> 100644
--- a/examples/long-short.py
+++ b/examples/long-short.py
@@ -4,8 +4,8 @@ import time
import datetime
import queue
-API_KEY = "PKI0VRI38E9RGWCO98DN"
-API_SECRET = "tlQyYESkpkrbKdccfRJZNQ2AU6jk/7g/6yaHV45v"
+API_KEY = "API_KEY"
+API_SECRET = "API_SECRET"
APCA_API_BASE_URL = "https://paper-api.alpaca.markets"
class LongShort:
|
Removed defunct keys for pseudo-keys
|
alpacahq_alpaca-trade-api-python
|
train
|
fd0df3d19beed2b65647c49bc929dc00f504a658
|
diff --git a/plugins/Admin/templates/Manufacturers/index.php b/plugins/Admin/templates/Manufacturers/index.php
index <HASH>..<HASH> 100644
--- a/plugins/Admin/templates/Manufacturers/index.php
+++ b/plugins/Admin/templates/Manufacturers/index.php
@@ -275,7 +275,7 @@ echo '<td colspan="2"><b>' . $i . '</b> '.__d('admin', '{0,plural,=1{record} oth
echo '<td><b>' . $sumProductCount . '</b></td>';
$colspan = 8;
echo '<td>';
- if ($sumDeposit > 0) {
+ if ($sumDeposit <> 0) {
echo '<b class="' . ($sumDeposit < 0 ? 'negative' : '') . '">'.$this->Number->formatAsCurrency($sumDeposit) . '</b>';
}
echo '</td>';
|
sum of deposit was not shown if negative
|
foodcoopshop_foodcoopshop
|
train
|
3ce39bc784e6ebc85d9d669a7c379c362a40cf4a
|
diff --git a/lib/remote-debugger-message-handler.js b/lib/remote-debugger-message-handler.js
index <HASH>..<HASH> 100644
--- a/lib/remote-debugger-message-handler.js
+++ b/lib/remote-debugger-message-handler.js
@@ -84,7 +84,9 @@ export default class RpcMessageHandler {
// we can get an error, or we can get a response that is an error
if (result && result.wasThrown) {
- let message = result.result.value || result.result.description;
+ let message = (result.result && (result.result.value || result.result.description)) ?
+ (result.result.value || result.result.description) :
+ 'Error occurred in handling data message';
error = new Error(message);
}
|
putting null and undefined check for error message
Addressing comment
better handing of result.result
addressing comment
|
appium_appium-remote-debugger
|
train
|
a0a63678a934d30580afaa19f471bd4f9236795b
|
diff --git a/version.php b/version.php
index <HASH>..<HASH> 100644
--- a/version.php
+++ b/version.php
@@ -29,11 +29,11 @@
defined('MOODLE_INTERNAL') || die();
-$version = 2016052300.02; // YYYYMMDD = weekly release date of this DEV branch.
+$version = 2016052300.03; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
-$release = '3.2dev (Build: 20160603)'; // Human-friendly version name
+$release = '3.2dev (Build: 20160609)'; // Human-friendly version name
$branch = '32'; // This version's branch.
$maturity = MATURITY_ALPHA; // This version's maturity level.
|
weekly on-sync release <I>dev
|
moodle_moodle
|
train
|
3924c13fa38388320fa6005be8445c62e65d3e60
|
diff --git a/dev_tools/src/d1_dev/src-format.py b/dev_tools/src/d1_dev/src-format.py
index <HASH>..<HASH> 100755
--- a/dev_tools/src/d1_dev/src-format.py
+++ b/dev_tools/src/d1_dev/src-format.py
@@ -70,6 +70,7 @@ def main():
)
parser.add_argument(
"--include-untracked",
+ "-u",
action="store_true",
help="Also process files not tracked by git",
)
@@ -152,6 +153,9 @@ def format_single(_args, format_path):
def run_cmd(*cmd_list):
print("Running command: {}".format(" ".join(cmd_list)))
+ py_bin_dir_path = os.path.split(sys.executable)[0]
+ cmd_list = list(cmd_list)
+ cmd_list[0] = os.path.join(py_bin_dir_path, cmd_list[0])
try:
subprocess.check_call(cmd_list)
except subprocess.CalledProcessError as e:
|
Add support for running outside of venv to src-format.py
|
DataONEorg_d1_python
|
train
|
d9658876a94c6636674bfa5db5650c54cdb6bccf
|
diff --git a/skyfield/tests/test_strs_and_reprs.py b/skyfield/tests/test_strs_and_reprs.py
index <HASH>..<HASH> 100644
--- a/skyfield/tests/test_strs_and_reprs.py
+++ b/skyfield/tests/test_strs_and_reprs.py
@@ -19,7 +19,7 @@ def test_jpl_segment(eph):
""")
assert repr(e) == expected
-def test_satellite(eph):
+def test_satellite_with_name(eph):
lines = [
'ISS (ZARYA) ',
'1 25544U 98067A 13330.58127943 .00000814 00000-0 21834-4 0 1064',
@@ -35,6 +35,21 @@ def test_satellite(eph):
""")
assert repr(s) == expected
+def test_satellite_without_name(eph):
+ lines = [
+ '1 25544U 98067A 13330.58127943 .00000814 00000-0 21834-4 0 1064',
+ '2 25544 51.6484 23.7537 0001246 74.1647 18.7420 15.50540527859894',
+ ]
+ s = EarthSatellite(lines, None)
+ expected = dedent("""\
+ EarthSatellite number=25544 epoch=2013-11-26T13:57:03Z
+ """)
+ assert str(s) == expected
+ expected = dedent("""\
+ <EarthSatellite number=25544 epoch=2013-11-26T13:57:03Z>
+ """)
+ assert repr(s) == expected
+
def test_topos(eph):
t = Topos(latitude_degrees=42.2, longitude_degrees=-88.1)
expected = dedent("""\
|
Add test of str/repr for satellite without a name
|
skyfielders_python-skyfield
|
train
|
fa0ca29c9c79061c6f6b72f7c1ffefccd67bd5f3
|
diff --git a/example/models/tests.js b/example/models/tests.js
index <HASH>..<HASH> 100644
--- a/example/models/tests.js
+++ b/example/models/tests.js
@@ -17,6 +17,7 @@ var s = new Schema({
// second_ref: { type: ObjectId, ref: 'users', limit: 500, query: '/__value__/i.test(this.email)', required: true },
string: { type: String, required: true },
date: { type: Date, required: true },
+ time: { type: Schema.Types.Time },
enum: { type: String, enum: ['1', '2', '3'], required: true },
rich_text: { type: Schema.Types.Html, required: true },
text: { type: Schema.Types.Text, required: true },
diff --git a/forms/fields.js b/forms/fields.js
index <HASH>..<HASH> 100644
--- a/forms/fields.js
+++ b/forms/fields.js
@@ -291,6 +291,20 @@ var DateField = exports.DateField = BaseField.extend({
}
});
+var TimeField = exports.TimeField = BaseField.extend({
+ init: function (options) {
+ options = options || {};
+ options.widget = options.widget || widgets.TimeWidget;
+ this._super(options);
+ },
+
+ to_schema: function () {
+ var schema = this._super();
+ schema['type'] = String;
+ return schema;
+ }
+});
+
function extractSubFieldKeyAndName(field_name, prefix) {
var pre_len = prefix.length;
diff --git a/forms/forms.js b/forms/forms.js
index <HASH>..<HASH> 100644
--- a/forms/forms.js
+++ b/forms/forms.js
@@ -84,15 +84,15 @@ var BaseForm = exports.BaseForm = Class.extend({
},
get_static: function () {
var self = this;
+ self.static = self.static || {js:[], css:[]};
_.each(this.fields, function (field) {
- var _static = field.get_static();
- if (_static.js.length) {
- self.static.js = _.union(self.static.js, _static.js);
- }
- if (_static.css.length) {
- self.static.css = _.union(self.static.css, _static.css);
- }
+ var _static = ('fields' in field) ? self.get_static.call(field) : field.get_static();
+ self.static.js = self.static.js.concat(_static.js || []);
+ self.static.css = self.static.css.concat(_static.css || []);
});
+ self.static.js = _(self.static.js).unique();
+ self.static.css = _(self.static.css).unique();
+ return self.static;
},
render_head: function () {
var self = this;
@@ -442,6 +442,9 @@ var MongooseForm = exports.MongooseForm = BaseForm.extend({
if (mongoose_field.options.type === Date) {
return new fields.DateField(options);
}
+ if (mongoose_field.options.type.name === 'Time') {
+ return new fields.TimeField(options);
+ }
if (mongoose_field.options.type.name === 'Html') {
options.widget = widgets.RichTextAreaWidget;
return new fields.StringField(options);
diff --git a/forms/mongoose-types.js b/forms/mongoose-types.js
index <HASH>..<HASH> 100644
--- a/forms/mongoose-types.js
+++ b/forms/mongoose-types.js
@@ -42,6 +42,20 @@ var init = function () {
exports.Picture = Picture;
+ var Time = function Time (path, options) {
+ Time.super_.call(this, path, options);
+ };
+ util.inherits(Time, mongoose.Schema.Types.String);
+ Time.prototype.cast = function (value, doc, init) {
+ return Picture.super_.prototype.cast.call(this, value, doc, init);
+ };
+
+ mongoose.Types.Time = Object;
+ mongoose.Schema.Types.Time = Time;
+
+ exports.Time = Time;
+
+
var Integer = function Integer (path, options) {
Integer.super_.call(this, path, options);
};
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "formage-admin",
"description": "Admin gui app for mongoose and non mongoose projects",
- "version": "1.3.4",
+ "version": "1.3.5",
"author": {
"name": "Ishai Jaffe",
"email": "ishai@empeeric.com"
|
add Time field
recursively add all js and css resources to main head
|
node4good_formage
|
train
|
de1d74051a80a700bf3f0cd876796088b9831894
|
diff --git a/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocbookBuilder.java b/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocbookBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocbookBuilder.java
+++ b/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocbookBuilder.java
@@ -2463,7 +2463,8 @@ public class DocbookBuilder implements ShutdownAbleApp {
if (authorTags.size() > 0) {
for (final TagWrapper author : authorTags) {
if (!authorIDtoAuthor.containsKey(author.getId())) {
- final AuthorInformation authorInfo = EntityUtilities.getAuthorInformation(providerFactory, author.getId());
+ final AuthorInformation authorInfo = EntityUtilities.getAuthorInformation(providerFactory, author.getId(),
+ author.getRevision());
if (authorInfo != null) {
authorIDtoAuthor.put(author.getId(), authorInfo);
}
@@ -2691,7 +2692,7 @@ public class DocbookBuilder implements ShutdownAbleApp {
// An assigned writer tag exists for the User so check if there is an AuthorInformation tuple for that writer
if (author != null) {
- AuthorInformation authorInfo = EntityUtilities.getAuthorInformation(providerFactory, author.getId());
+ AuthorInformation authorInfo = EntityUtilities.getAuthorInformation(providerFactory, author.getId(), author.getRevision());
if (authorInfo != null) {
final Element revision = generateRevision(buildData, revHistoryDoc, authorInfo);
|
Fixed a bug that was causing builds to fail when author tags no longer existed.
|
pressgang-ccms_PressGangCCMSBuilder
|
train
|
e579538f64ea2e748eeabed59d5b1af6ae61b38e
|
diff --git a/lib/algoliasearch/utilities.rb b/lib/algoliasearch/utilities.rb
index <HASH>..<HASH> 100644
--- a/lib/algoliasearch/utilities.rb
+++ b/lib/algoliasearch/utilities.rb
@@ -2,7 +2,11 @@ module AlgoliaSearch
module Utilities
class << self
def get_model_classes
- Rails.application.eager_load! if Rails.application # Ensure all models are loaded (not necessary in production when cache_classes is true).
+ if defined?(Rails.autoloaders) && Rails.autoloaders.zeitwerk_enabled?
+ Zeitwerk::Loader.eager_load_all
+ elsif Rails.application
+ Rails.application.eager_load!
+ end
AlgoliaSearch.instance_variable_get :@included_in
end
|
Use Zeitwerk for loading models in Rails 6
In Rails 6, model loading is no longer working. This is because Zeitwerk has
replaced the original code loading. We now use Zeitwerk if it's available.
|
algolia_algoliasearch-rails
|
train
|
81e7cb60fff3d5bdaba38e2cd766b016fbfb9562
|
diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go
index <HASH>..<HASH> 100644
--- a/pkg/api/dashboard.go
+++ b/pkg/api/dashboard.go
@@ -338,7 +338,7 @@ func (hs *HTTPServer) PostDashboard(c *models.ReqContext, cmd models.SaveDashboa
dashboard = dash // the original request
}
- // This will broadcast all save requets only if a `gitops` observer exists.
+ // This will broadcast all save requests only if a `gitops` observer exists.
// gitops is useful when trying to save dashboards in an environment where the user can not save
channel := hs.Live.GrafanaScope.Dashboards
liveerr := channel.DashboardSaved(c.SignedInUser.OrgId, c.SignedInUser.ToUserDisplayDTO(), cmd.Message, dashboard, err)
|
Chore: Fix typo in dashboard.go (#<I>)
requets -> requests
|
grafana_grafana
|
train
|
7cc006b42e34074b2094318737f5b58b1ae0694a
|
diff --git a/command_list.go b/command_list.go
index <HASH>..<HASH> 100644
--- a/command_list.go
+++ b/command_list.go
@@ -1,12 +1,12 @@
package imap
-const LIST_ARG_SELECTOR int = 1
+const listArgSelector int = 1
func cmdList(args commandArgs, c *Conn) {
- if args.Arg(LIST_ARG_SELECTOR) == "" {
+ if args.Arg(listArgSelector) == "" {
// Blank selector means request directory separator
c.writeResponse("", "LIST (\\Noselect) \"/\" \"\"")
- } else if args.Arg(LIST_ARG_SELECTOR) == "*" {
+ } else if args.Arg(listArgSelector) == "*" {
// List all mailboxes requested
for _, mailbox := range c.user.Mailboxes() {
c.writeResponse("", "LIST () \"/\" \""+mailbox.Name()+"\"")
|
Use correct casing for (and de-export) constant #8
|
jordwest_imap-server
|
train
|
978325ec5fa9076a0d428e95ba4ed31cd49d56b4
|
diff --git a/spec/pg_search/document_spec.rb b/spec/pg_search/document_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/pg_search/document_spec.rb
+++ b/spec/pg_search/document_spec.rb
@@ -7,7 +7,7 @@ describe PgSearch::Document do
table
model do
include PgSearch
- multisearchable({})
+ multisearchable
end
end
|
multisearchable doesn't require an argument
|
Casecommons_pg_search
|
train
|
0448c8321de413eb5a93c56c66194beca3153b79
|
diff --git a/lib/bumper_pusher/version.rb b/lib/bumper_pusher/version.rb
index <HASH>..<HASH> 100644
--- a/lib/bumper_pusher/version.rb
+++ b/lib/bumper_pusher/version.rb
@@ -1,3 +1,3 @@
module BumperPusher
- VERSION = "0.1.2"
+ VERSION = "0.1.3"
end
|
Update gemspec to version <I>
|
skywinder_bumper_pusher
|
train
|
5f8e54c5502ba35873f563216c426a91b556e29e
|
diff --git a/salt/modules/mysql.py b/salt/modules/mysql.py
index <HASH>..<HASH> 100644
--- a/salt/modules/mysql.py
+++ b/salt/modules/mysql.py
@@ -93,6 +93,16 @@ __grants__ = [
'USAGE'
]
+__ssl_options_parameterized__ = [
+ 'CIPHER',
+ 'ISSUER',
+ 'SUBJECT'
+]
+__ssl_options__ = __ssl_options_parameterized__ + [
+ 'SSL',
+ 'X509'
+]
+
################################################################################
# DEVELOPPER NOTE: ABOUT arguments management, escapes, formats, arguments and
# security of SQL.
@@ -1434,12 +1444,39 @@ def __grant_normalize(grant):
return grant
+def __ssl_option_sanitize(ssl_option):
+ new_ssl_option = []
+
+ # Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
+ for opt in ssl_option:
+ key = opt.keys()[0]
+ value = opt[key]
+
+ normal_key = key.strip().upper()
+
+ if not normal_key in __ssl_options__:
+ raise Exception('Invalid SSL option : {0!r}'.format(
+ key
+ ))
+
+ if normal_key in __ssl_options_parameterized__:
+ # SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
+ # we need to sanitize for single quotes...
+ new_ssl_option.append("%s '%s'" % (normal_key, opt[key].replace("'", '')))
+ # omit if falsey
+ elif opt[key]:
+ new_ssl_option.append(normal_key)
+
+ return ' REQUIRE ' + ' AND '.join(new_ssl_option)
+
+
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
- escape=True):
+ escape=True,
+ ssl_option=False):
'''
Validate grants and build the query that could set the given grants
@@ -1468,6 +1505,8 @@ def __grant_generate(grant,
args = {}
args['user'] = user
args['host'] = host
+ if isinstance(ssl_option, type([])) and len(ssl_option):
+ qry += __ssl_option_sanitize(ssl_option)
if salt.utils.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: {0} args {1}'.format(qry, repr(args)))
@@ -1576,6 +1615,7 @@ def grant_add(grant,
host='localhost',
grant_option=False,
escape=True,
+ ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
@@ -1596,7 +1636,7 @@ def grant_add(grant,
# Avoid spaces problems
grant = grant.strip()
- qry = __grant_generate(grant, database, user, host, grant_option, escape)
+ qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
diff --git a/salt/states/mysql_grants.py b/salt/states/mysql_grants.py
index <HASH>..<HASH> 100644
--- a/salt/states/mysql_grants.py
+++ b/salt/states/mysql_grants.py
@@ -70,6 +70,7 @@ def present(name,
grant_option=False,
escape=True,
revoke_first=False,
+ ssl_option=False,
**connection_args):
'''
Ensure that the grant is present with the specified properties
@@ -111,6 +112,25 @@ def present(name,
Use with caution!
default: False
+
+ ssl_option
+ Adds the specified ssl options for the connecting user as requirements for
+ this grant. Value is a list of single-element dicts corresponding to the
+ list of ssl options to use.
+
+ Possible key/value pairings for the dicts in the value:
+
+ - SSL: True
+ - X509: True
+ - SUBJECT: <subject>
+ - ISSUER: <issuer>
+ - CIPHER: <cipher>
+
+ The non-boolean ssl options take a string as their values, which should
+ be an appropriate value as specified by the MySQL documentation for these
+ options.
+
+ default: False (no ssl options will be used)
'''
comment = 'Grant {0} on {1} to {2}@{3} is already present'
ret = {'name': name,
@@ -161,7 +181,7 @@ def present(name,
ret['comment'] = ('MySQL grant {0} is set to be created').format(name)
return ret
if __salt__['mysql.grant_add'](
- grant, database, user, host, grant_option, escape, **connection_args
+ grant, database, user, host, grant_option, escape, ssl_option, **connection_args
):
ret['comment'] = 'Grant {0} on {1} to {2}@{3} has been added'
ret['comment'] = ret['comment'].format(grant, database, user, host)
|
Adds support for REQUIRE <SSL, etc> to mysql_grants state - Satisfies request (issue) #<I>.
|
saltstack_salt
|
train
|
19dd19753eeea90d5b76649291ff69f0ad1b9f67
|
diff --git a/lib/semantic_logger/base.rb b/lib/semantic_logger/base.rb
index <HASH>..<HASH> 100644
--- a/lib/semantic_logger/base.rb
+++ b/lib/semantic_logger/base.rb
@@ -341,7 +341,12 @@ module SemanticLogger
log = Log.new(name, level, index)
should_log =
if payload.nil? && exception.nil? && message.is_a?(Hash)
- log.assign(message)
+ # Check if someone just logged a hash payload instead of meaning to call semantic logger
+ if message.has_key?(:message) || message.has_key?(:payload) || message.has_key?(:exception) || message.has_key?(:metric)
+ log.assign(message)
+ else
+ log.assign_positional(nil, message, nil, &block)
+ end
else
log.assign_positional(message, payload, exception, &block)
end
|
Fixes #<I> Check if a hash without specific keys is being logged instead of a string and handle it as a payload.
|
rocketjob_semantic_logger
|
train
|
1123cf46f9df671d9dfbeb76bc9bc342cb3234d9
|
diff --git a/image.go b/image.go
index <HASH>..<HASH> 100644
--- a/image.go
+++ b/image.go
@@ -211,8 +211,6 @@ func (i *Image) DrawImage(img *Image, options *DrawImageOptions) error {
}
// Vertex represents a vertex passed to DrawTriangles.
-//
-// Note that this API is experimental.
type Vertex struct {
// DstX and DstY represents a point on a destination image.
DstX float32
@@ -248,8 +246,6 @@ const (
)
// DrawTrianglesOptions represents options to render triangles on an image.
-//
-// Note that this API is experimental.
type DrawTrianglesOptions struct {
// ColorM is a color matrix to draw.
// The default (zero) value is identity, which doesn't change any color.
@@ -281,8 +277,6 @@ const MaxIndicesNum = graphics.IndicesNum
// The rule in which DrawTriangles works effectively is same as DrawImage's.
//
// When the image i is disposed, DrawTriangles does nothing.
-//
-// Note that this API is experimental.
func (i *Image) DrawTriangles(vertices []Vertex, indices []uint16, img *Image, options *DrawTrianglesOptions) {
i.copyCheck()
|
ebiten: DrawTriangles is no longer experimental
|
hajimehoshi_ebiten
|
train
|
2c9657b1d447aaa92f77c7558a3389d918f57aaf
|
diff --git a/lib/carrierwave-meta/meta.rb b/lib/carrierwave-meta/meta.rb
index <HASH>..<HASH> 100644
--- a/lib/carrierwave-meta/meta.rb
+++ b/lib/carrierwave-meta/meta.rb
@@ -20,51 +20,49 @@ module CarrierWave
model_delegate_attribute :height, 0
end
- module InstanceMethods
- def store_meta
- if self.file.present?
- dimensions = get_dimensions
- width, height = dimensions
- self.content_type = self.file.content_type
- self.file_size = self.file.size
- self.image_size = dimensions
- self.width = width
- self.height = height
- end
- end
-
- def set_content_type(file = nil)
- set_content_type(true)
- end
-
- def image_size_s
- image_size.join('x')
- end
-
- private
- def call_store_meta(file = nil)
- # Re-retrieve metadata for a file only if model is not present OR model is not saved.
- store_meta if self.model.nil? || (self.model.respond_to?(:new_record?) && self.model.new_record?)
+ def store_meta
+ if self.file.present?
+ dimensions = get_dimensions
+ width, height = dimensions
+ self.content_type = self.file.content_type
+ self.file_size = self.file.size
+ self.image_size = dimensions
+ self.width = width
+ self.height = height
end
-
- def get_dimensions
- [].tap do |size|
- if self.file.content_type =~ /image/
- manipulate! do |img|
- if defined?(::Magick::Image) && img.is_a?(::Magick::Image)
- size << img.columns
- size << img.rows
- elsif defined?(::MiniMagick::Image) && img.is_a?(::MiniMagick::Image)
- size << img["width"]
- size << img["height"]
- else
- raise "Only RMagick is supported yet. Fork and update it."
- end
- img
- end
+ end
+
+ def set_content_type(file = nil)
+ set_content_type(true)
+ end
+
+ def image_size_s
+ image_size.join('x')
+ end
+
+ private
+ def call_store_meta(file = nil)
+ # Re-retrieve metadata for a file only if model is not present OR model is not saved.
+ store_meta if self.model.nil? || (self.model.respond_to?(:new_record?) && self.model.new_record?)
+ end
+
+ def get_dimensions
+ [].tap do |size|
+ if self.file.content_type =~ /image/
+ manipulate! do |img|
+ if defined?(::Magick::Image) && img.is_a?(::Magick::Image)
+ size << img.columns
+ size << img.rows
+ elsif defined?(::MiniMagick::Image) && img.is_a?(::MiniMagick::Image)
+ size << img["width"]
+ size << img["height"]
+ else
+ raise "Only RMagick is supported yet. Fork and update it."
+ end
+ img
end
end
- end
- end
+ end
+ end
end
end
\ No newline at end of file
diff --git a/lib/carrierwave-meta/model_delegate_attribute.rb b/lib/carrierwave-meta/model_delegate_attribute.rb
index <HASH>..<HASH> 100644
--- a/lib/carrierwave-meta/model_delegate_attribute.rb
+++ b/lib/carrierwave-meta/model_delegate_attribute.rb
@@ -33,15 +33,13 @@ module CarrierWave
end
end
- module InstanceMethods
- private
- def model_getter_name(attribute)
- name = []
- name << mounted_as if mounted_as.present?
- name << version_name if version_name.present?
- name << attribute
- name.join('_')
- end
+ private
+ def model_getter_name(attribute)
+ name = []
+ name << mounted_as if mounted_as.present?
+ name << version_name if version_name.present?
+ name << attribute
+ name.join('_')
end
end
end
|
Move methods out of InstanceMethods module to prevent deprecation warnings in Rails
|
gzigzigzeo_carrierwave-meta
|
train
|
93e10f9911fb2a096681ee0a0bc82487a9a06c44
|
diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/named_scope.rb
+++ b/activerecord/lib/active_record/named_scope.rb
@@ -103,7 +103,7 @@ module ActiveRecord
attr_reader :proxy_scope, :proxy_options
[].methods.each do |m|
- unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?)/
+ unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?|any?)/
delegate m, :to => :proxy_found
end
end
@@ -140,6 +140,14 @@ module ActiveRecord
@found ? @found.empty? : count.zero?
end
+ def any?
+ if block_given?
+ proxy_found.any? { |*block_args| yield(*block_args) }
+ else
+ !empty?
+ end
+ end
+
protected
def proxy_found
@found || load_found
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -184,6 +184,28 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
+ def test_any_should_not_load_results
+ topics = Topic.base
+ assert_queries(1) do
+ topics.expects(:empty?).returns(true)
+ assert !topics.any?
+ end
+ end
+
+ def test_any_should_call_proxy_found_if_using_a_block
+ topics = Topic.base
+ assert_queries(1) do
+ topics.expects(:empty?).never
+ topics.any? { true }
+ end
+ end
+
+ def test_any_should_not_fire_query_if_named_scope_loaded
+ topics = Topic.base
+ topics.collect # force load
+ assert_no_queries { assert topics.any? }
+ end
+
def test_should_build_with_proxy_options
topic = Topic.approved.build({})
assert topic.approved
|
Ensure NamedScope#any? uses COUNT query wherever possible. [#<I> state:resolved]
|
rails_rails
|
train
|
56c28d71b90ee24fdb28cad793b6e5d6a41add48
|
diff --git a/lib/app/js/directives/design.js b/lib/app/js/directives/design.js
index <HASH>..<HASH> 100644
--- a/lib/app/js/directives/design.js
+++ b/lib/app/js/directives/design.js
@@ -7,10 +7,20 @@ angular.module('sgApp')
restrict: 'A',
templateUrl: 'views/partials/design.html',
link: function(scope) {
+
+ var parentRef;
+
scope.showRelated = true;
- scope.$watch('currentReference.section', function(newVal, oldVal) {
- scope.relatedVariables = scope.currentReference.section.variables
+ scope.$watch('currentReference.section', function() {
+ var relatedVariables = scope.currentReference.section.variables || [];
+ if (scope.showRelated && relatedVariables.length === 0 && scope.sections.data) {
+ parentRef = scope.currentReference.section.reference;
+ scope.relatedChildVariableNames = scope.sections.data.filter(isSubSection)
+ .map(getVariables)
+ .reduce(concat, [])
+ .filter(unique);
+ }
});
scope.saveVariables = function() {
@@ -19,7 +29,26 @@ angular.module('sgApp')
scope.resetLocal = function() {
Variables.resetLocal();
+ };
+
+ function isSubSection(section) {
+ var ref = section.parentReference;
+ return (typeof ref === 'string') &&
+ (ref === parentRef || ref.substring(0, ref.indexOf('.')) === parentRef);
+ }
+
+ function getVariables(section) {
+ return section.variables;
}
+
+ function concat(a, b) {
+ return a.concat(b);
+ }
+
+ function unique(a, idx, arr) {
+ return arr.indexOf(a) === idx && a !== undefined;
+ }
+
}
};
});
diff --git a/lib/app/js/directives/section.js b/lib/app/js/directives/section.js
index <HASH>..<HASH> 100644
--- a/lib/app/js/directives/section.js
+++ b/lib/app/js/directives/section.js
@@ -10,7 +10,7 @@ angular.module('sgApp')
function updateCurrentReference() {
var topOffset = element[0].offsetTop,
bottomOffset = element[0].offsetTop + element[0].offsetHeight,
- buffer = 100;
+ buffer = 50;
if (this.pageYOffset > topOffset - buffer && this.pageYOffset < bottomOffset - buffer) {
if ($rootScope.currentReference.section.reference !== scope.section.reference) {
diff --git a/lib/app/views/partials/design.html b/lib/app/views/partials/design.html
index <HASH>..<HASH> 100644
--- a/lib/app/views/partials/design.html
+++ b/lib/app/views/partials/design.html
@@ -14,14 +14,22 @@
<a class="sg" ng-click="showRelated = false" ng-show="showRelated">Show all variables</a>
<h3 class="sg" ng-show="showRelated">{{currentReference.section.reference}} {{currentReference.section.header}}</h3>
<h3 class="sg" ng-hide="showRelated">All variables</h3>
- <ul>
+ <ul class="sg">
<li ng-hide="showRelated" ng-repeat="variable in variables">
<div sg-variable></div>
</li>
<li ng-if="showRelated" ng-repeat="variable in filteredItems = (variables | filterRelated: currentReference.section.variables)">
<div sg-variable></div>
</li>
- <li ng-if="showRelated" ng-show="!filteredItems.length">This section does not contain related variables.</li>
+
+ <li ng-if="showRelated" ng-show="filteredItems.length === 0"><b>This section does not contain any related variables.</b></li>
+ <li ng-if="showRelated" ng-show="relatedChildVariableNames.length > 0">
+ <p>Sub sections use the following variables:</p>
+ </li>
+ <li ng-if="showRelated && filteredItems.length === 0" ng-repeat="variable in childVariables = (variables | filterRelated: relatedChildVariableNames)">
+ <div sg-variable></div>
+ </li>
+
</ul>
<div class="sg action-footer" ng-if="socketService.isAvailable()">
<button class="sg button primary" ng-click="saveVariables()">Save changes</button>
|
Feature: if section does not use variables, list variables from sub-sections
|
SC5_sc5-styleguide
|
train
|
6b8d9d363e790ef8556172c763b7145baa93ae17
|
diff --git a/src/js/index.js b/src/js/index.js
index <HASH>..<HASH> 100644
--- a/src/js/index.js
+++ b/src/js/index.js
@@ -28,6 +28,7 @@ var Grommet = {
Map: require('./components/Map'),
Menu: require('./components/Menu'),
Meter: require('./components/Meter'),
+ Notification: require('./components/Notification'),
NumberInput: require('./components/NumberInput'),
RadioButton: require('./components/RadioButton'),
Search: require('./components/Search'),
|
Added Notification to index.js
|
grommet_grommet
|
train
|
d19bc9b0eaa6b81dcd9767aad71395546321f929
|
diff --git a/scapy.py b/scapy.py
index <HASH>..<HASH> 100755
--- a/scapy.py
+++ b/scapy.py
@@ -13267,31 +13267,34 @@ def autorun_commands(cmds,my_globals=None,verb=0):
sv = conf.verb
import __builtin__
try:
- if my_globals is None:
- my_globals = globals()
- conf.verb = verb
- interp = ScapyAutorunInterpreter(my_globals)
- cmd = ""
- cmds = cmds.splitlines()
- cmds.append("") # ensure we finish multiline commands
- cmds.reverse()
- __builtin__.__dict__["_"] = None
- while 1:
- if cmd:
- sys.stderr.write(sys.__dict__.get("ps2","... "))
- else:
- sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt())))
-
- l = cmds.pop()
- print l
- cmd += "\n"+l
- if interp.runsource(cmd):
- continue
- if interp.error:
- return 0
+ try:
+ if my_globals is None:
+ my_globals = globals()
+ conf.verb = verb
+ interp = ScapyAutorunInterpreter(my_globals)
cmd = ""
- if len(cmds) <= 1:
- break
+ cmds = cmds.splitlines()
+ cmds.append("") # ensure we finish multiline commands
+ cmds.reverse()
+ __builtin__.__dict__["_"] = None
+ while 1:
+ if cmd:
+ sys.stderr.write(sys.__dict__.get("ps2","... "))
+ else:
+ sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt())))
+
+ l = cmds.pop()
+ print l
+ cmd += "\n"+l
+ if interp.runsource(cmd):
+ continue
+ if interp.error:
+ return 0
+ cmd = ""
+ if len(cmds) <= 1:
+ break
+ except SystemExit:
+ pass
finally:
conf.verb = sv
return _
|
Catch SystemExit exception in autorun commands
|
secdev_scapy
|
train
|
b585d19de26632dafc7d482a6d0c303a6c4aeab6
|
diff --git a/src/Symfony/Component/Security/Http/Authenticator/AuthenticatorInterface.php b/src/Symfony/Component/Security/Http/Authenticator/AuthenticatorInterface.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Security/Http/Authenticator/AuthenticatorInterface.php
+++ b/src/Symfony/Component/Security/Http/Authenticator/AuthenticatorInterface.php
@@ -34,7 +34,7 @@ interface AuthenticatorInterface
/**
* Does the authenticator support the given Request?
*
- * If this returns false, the authenticator will be skipped.
+ * If this returns true, authenticate() will be called. If false, the authenticator will be skipped.
*
* Returning null means authenticate() can be called lazily when accessing the token storage.
*/
|
[Security] Add a little explanations in supports() description
|
symfony_symfony
|
train
|
5a83bb8a96fb7f25726cbf5bd5a0b78259f56fff
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "stackerjs-db-mysql-adapter",
- "version": "0.9.3",
+ "version": "0.9.4",
"author": {
"name": "Vinicius Guedes",
"email": "viniciusgued@gmail.com",
diff --git a/src/QueryBuilder/QueryBuilderInsert.js b/src/QueryBuilder/QueryBuilderInsert.js
index <HASH>..<HASH> 100644
--- a/src/QueryBuilder/QueryBuilderInsert.js
+++ b/src/QueryBuilder/QueryBuilderInsert.js
@@ -1,5 +1,4 @@
import { QueryBuilderQueries } from './QueryBuilderQueries';
-import { treatValue } from '../Utils';
export class QueryBuilderInsert extends QueryBuilderQueries
@@ -11,7 +10,7 @@ export class QueryBuilderInsert extends QueryBuilderQueries
Object.keys(this.fields).map(field => field).join(', ') +
') VALUES (' +
Object.keys(this.fields)
- .map(field => treatValue(this.fields[field])).join(', ') +
+ .map(field => this.fields[field]).join(', ') +
');';
}
diff --git a/src/QueryBuilder/QueryBuilderQueries.js b/src/QueryBuilder/QueryBuilderQueries.js
index <HASH>..<HASH> 100644
--- a/src/QueryBuilder/QueryBuilderQueries.js
+++ b/src/QueryBuilder/QueryBuilderQueries.js
@@ -1,4 +1,4 @@
-import { parseFilters, parseFieldAndTable } from "../Utils";
+import { parseFilters, parseFieldAndTable, treatValue } from "../Utils";
export class QueryBuilderQueries
@@ -29,7 +29,7 @@ export class QueryBuilderQueries
.map((field) => this.set(field, fields[field]));
if (typeof fields === 'string')
- this.fields[parseFieldAndTable(fields)] = value;
+ this.fields[parseFieldAndTable(fields)] = treatValue(value);
return this;
}
diff --git a/src/QueryBuilder/QueryBuilderUpdate.js b/src/QueryBuilder/QueryBuilderUpdate.js
index <HASH>..<HASH> 100644
--- a/src/QueryBuilder/QueryBuilderUpdate.js
+++ b/src/QueryBuilder/QueryBuilderUpdate.js
@@ -1,5 +1,4 @@
import { QueryBuilderQueries } from "./QueryBuilderQueries";
-import { treatValue } from "../Utils";
export class QueryBuilderUpdate extends QueryBuilderQueries
@@ -9,7 +8,7 @@ export class QueryBuilderUpdate extends QueryBuilderQueries
{
return `UPDATE ${this.tableName} SET ` +
Object.keys(this.fields)
- .map(field => `${field} = ${treatValue(this.fields[field])}`)
+ .map(field => `${field} = ${this.fields[field]}`)
.join(', ') +
(this._where ? ` WHERE ${this._where}` : '') +
';';
diff --git a/src/QueryCriteria.js b/src/QueryCriteria.js
index <HASH>..<HASH> 100644
--- a/src/QueryCriteria.js
+++ b/src/QueryCriteria.js
@@ -7,44 +7,38 @@ export class QueryCriteria
like(field, value)
{
- value = treatValue(value.indexOf('%') >= 0 ? value : `%${value}%`);
- return `${parseFieldAndTable(field)} LIKE ${value}`;
+ value = value.indexOf('%') >= 0 ? value : `%${treatValue(value)}%`;
+ return `${parseFieldAndTable(field)} LIKE ${treatValue(value)}`;
}
eq(field, value)
{
- value = treatValue(value);
- return `${parseFieldAndTable(field)} = ${value}`;
+ return `${parseFieldAndTable(field)} = ${treatValue(value)}`;
}
neq(field, value)
{
- value = treatValue(value);
- return `${parseFieldAndTable(field)} <> ${value}`;
+ return `${parseFieldAndTable(field)} <> ${treatValue(value)}`;
}
lt(field, value)
{
- value = treatValue(value);
- return `${parseFieldAndTable(field)} < ${value}`;
+ return `${parseFieldAndTable(field)} < ${treatValue(value)}`;
}
lte(field, value)
{
- value = treatValue(value);
- return `${parseFieldAndTable(field)} <= ${value}`;
+ return `${parseFieldAndTable(field)} <= ${treatValue(value)}`;
}
gt(field, value)
{
- value = treatValue(value);
- return `${parseFieldAndTable(field)} > ${value}`;
+ return `${parseFieldAndTable(field)} > ${treatValue(value)}`;
}
gte(field, value)
{
- value = treatValue(value);
- return `${parseFieldAndTable(field)} >= ${value}`;
+ return `${parseFieldAndTable(field)} >= ${treatValue(value)}`;
}
andX()
|
fix(parsing): defines single point for parsing values'
|
parpeoficial_stackerjs-db-mysql-adapter
|
train
|
80dc1644aaa89dabfe69484ab927f0aca6f2b634
|
diff --git a/gesso/command.js b/gesso/command.js
index <HASH>..<HASH> 100644
--- a/gesso/command.js
+++ b/gesso/command.js
@@ -27,6 +27,8 @@ function globalMain() {
}).launch({}, function(env) {
// Check for local installation
if (!env.modulePath) {
+ // TODO: Check for package.json and either warn that there's no project or show help instead
+
// Show --help or --version and exit
docopt(doc, {version: version});
// Show local installation message and exit
|
TODO: Check for package.json and either warn that there's no project or show help instead
|
joeyespo_gesso.js
|
train
|
7e378399e6d683cc6fc1e35601143504b27a608e
|
diff --git a/src/Models/Tag.php b/src/Models/Tag.php
index <HASH>..<HASH> 100644
--- a/src/Models/Tag.php
+++ b/src/Models/Tag.php
@@ -104,8 +104,6 @@ class Tag extends BaseTag
$this->mergeCasts(['style' => 'string', 'icon' => 'string']);
$this->mergeRules(['style' => 'nullable|string|strip_tags|max:150', 'icon' => 'nullable|string|strip_tags|max:150']);
-
- $this->setTable(config('rinvex.tags.tables.tags'));
}
/**
|
Remove duplicate `setTable` method call override as it's already called in parent class
|
rinvex_cortex-tags
|
train
|
015fc2540556c3fe5cfff32be03238468163fa9f
|
diff --git a/packages/perspective-viewer-d3fc/src/js/d3fcChart.js b/packages/perspective-viewer-d3fc/src/js/d3fcChart.js
index <HASH>..<HASH> 100644
--- a/packages/perspective-viewer-d3fc/src/js/d3fcChart.js
+++ b/packages/perspective-viewer-d3fc/src/js/d3fcChart.js
@@ -56,6 +56,8 @@ function renderBar(config, container, horizontal) {
.yOrient('left')
.plotArea(multi);
+ horizontal ? chart.xLabel(labels.mainLabel) : chart.yLabel(labels.mainLabel);
+
styleDark(chart);
d3.select(container)
@@ -226,7 +228,7 @@ function interpretLabels(config) {
splitLabel: null
};
- labels.mainLabel = config.series[0].stack;
+ labels.mainLabel = config.series.map(s => s.stack).join(",");
labels.crossLabel = config.row_pivots[0];
labels.splitLabel = config.col_pivots[0];
|
Add field name(s) to x/y axis
|
finos_perspective
|
train
|
54e9332ca1c98bf8a231849d300f3893d209ac4d
|
diff --git a/src/org/jgroups/protocols/SSL_KEY_EXCHANGE.java b/src/org/jgroups/protocols/SSL_KEY_EXCHANGE.java
index <HASH>..<HASH> 100644
--- a/src/org/jgroups/protocols/SSL_KEY_EXCHANGE.java
+++ b/src/org/jgroups/protocols/SSL_KEY_EXCHANGE.java
@@ -67,7 +67,7 @@ public class SSL_KEY_EXCHANGE extends KeyExchange {
"Types are listed in http://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html")
protected String keystore_type="JKS";
- @Property(description="Password to access the keystore")
+ @Property(description="Password to access the keystore",exposeAsManagedAttribute=false)
protected String keystore_password="changeit";
@Property(description="The type of secret key to be sent up the stack (converted from DH). " +
|
SSL_KEY_EXCHANGE: hide keystore_password from JMX/probe
|
belaban_JGroups
|
train
|
f58484b9ccdcadca26f7f6b499ed83e8a8a2f586
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -48,7 +48,7 @@ except (IOError, ImportError):
long_description = f.read()
-version = '0.2.0'
+version = '0.2.1'
class TestCommand(Command):
|
Increase version package to <I>
|
chaoss_grimoirelab-perceval-mozilla
|
train
|
2b4de5cb932eb457ba26b2fc921d9e9e75e29ca3
|
diff --git a/parser.go b/parser.go
index <HASH>..<HASH> 100644
--- a/parser.go
+++ b/parser.go
@@ -30,7 +30,8 @@ func (parser *StandardResultParser) ParseError(response *SelectResponse, sr *Sol
}
}
-
+// ParseResponse will assign result and build sr.docs if there is a response
+// if there is no response property in response it will panic
func (parser *StandardResultParser) ParseResponse(response *SelectResponse, sr *SolrResult) {
if resp, ok := response.response["response"].(map[string]interface{}); ok {
sr.results.numFound = int(resp["numFound"].(float64))
@@ -47,12 +48,16 @@ func (parser *StandardResultParser) ParseResponse(response *SelectResponse, sr *
}
}
+// ParseFacetCounts will assign facet_counts to sr if there is one
+// no modification done here
func (parser *StandardResultParser) ParseFacetCounts(response *SelectResponse, sr *SolrResult) {
if facetCounts, ok := response.response["facet_counts"]; ok {
sr.facet_counts = facetCounts.(map[string]interface{})
}
}
+// ParseHighlighting will assign highlighting to sr if there is one
+// no modification done here
func (parser *StandardResultParser) ParseHighlighting(response *SelectResponse, sr *SolrResult) {
if highlighting, ok := response.response["highlighting"]; ok {
sr.highlighting = highlighting.(map[string]interface{})
diff --git a/search.go b/search.go
index <HASH>..<HASH> 100644
--- a/search.go
+++ b/search.go
@@ -37,6 +37,7 @@ type Search struct {
debug string
}
+// NewSearch takes c and q as optional
func NewSearch(c *Connection, q *Query) * Search {
s := new(Search)
if q != nil {
@@ -59,6 +60,8 @@ func (s *Search) AddQuery(q *Query) {
s.queries = append(s.queries, q)
}
+// QueryString return a query string of all queries, including start, rows debug and wt=json
+// wt is always json
func (s *Search) QueryString() string {
query := []string{"wt=json"}
@@ -84,6 +87,8 @@ func (s *Search) QueryString() string {
return strings.Join(query, "&")
}
+// Result will create a StandardResultParser if no parser specified
+// parser must be an implement ResultParser interface
func (s *Search) Result(parser ResultParser) (*SolrResult, error) {
if s.conn == nil {
return nil, fmt.Errorf("No connection found for making request to solr")
|
#2 some more docs for select related code
|
vanng822_go-solr
|
train
|
ef596c6b6b58ebebf621749bfebed00ecc959067
|
diff --git a/cmd/influxd/backup/backup.go b/cmd/influxd/backup/backup.go
index <HASH>..<HASH> 100644
--- a/cmd/influxd/backup/backup.go
+++ b/cmd/influxd/backup/backup.go
@@ -281,6 +281,14 @@ func (cmd *Command) downloadAndVerify(req *snapshotter.Request, path string, val
// download downloads a snapshot of either the metastore or a shard from a host to a given path.
func (cmd *Command) download(req *snapshotter.Request, path string) error {
+ // FIXME This needs to use the meta client now to download the snapshot
+ // Create local file to write to.
+ f, err := os.Create(path)
+ if err != nil {
+ return fmt.Errorf("open temp file: %s", err)
+ }
+ defer f.Close()
+
// Connect to snapshotter service.
conn, err := tcp.Dial("tcp", cmd.host, snapshotter.MuxHeader)
if err != nil {
diff --git a/cmd/influxd/run/backup_restore_test.go b/cmd/influxd/run/backup_restore_test.go
index <HASH>..<HASH> 100644
--- a/cmd/influxd/run/backup_restore_test.go
+++ b/cmd/influxd/run/backup_restore_test.go
@@ -12,6 +12,7 @@ import (
)
func TestServer_BackupAndRestore(t *testing.T) {
+ t.Skip("The backup package needs to use the meta client now to download the snapshot")
config := NewConfig()
config.Data.Engine = "tsm1"
config.Data.Dir, _ = ioutil.TempDir("", "data_backup")
|
skip backup/restore test until we update the code
|
influxdata_influxdb
|
train
|
b6c0754ed946eaa8becd1a68f7f3f56533c2c42d
|
diff --git a/atomic_reactor/plugins/post_koji_upload.py b/atomic_reactor/plugins/post_koji_upload.py
index <HASH>..<HASH> 100644
--- a/atomic_reactor/plugins/post_koji_upload.py
+++ b/atomic_reactor/plugins/post_koji_upload.py
@@ -8,13 +8,12 @@ of the BSD license. See the LICENSE file for details.
from collections import namedtuple
import os
-from tempfile import NamedTemporaryFile
from atomic_reactor.plugin import PostBuildPlugin
from atomic_reactor.constants import PLUGIN_KOJI_UPLOAD_PLUGIN_KEY
from atomic_reactor.config import get_koji_session, get_openshift_session
from atomic_reactor.util import is_scratch_build, map_to_user_params
-from atomic_reactor.utils.koji import get_buildroot, get_output, get_output_metadata
+from atomic_reactor.utils.koji import get_buildroot, get_output
# An output file and its metadata
Output = namedtuple('Output', ['file', 'metadata'])
@@ -88,22 +87,6 @@ class KojiUploadPlugin(PostBuildPlugin):
self.pullspec_image = None
self.platform = platform
- def get_logs(self):
- """
- Build the logs entry for the metadata 'output' section
-
- :return: list, Output instances
- """
-
- build_logs = NamedTemporaryFile(prefix="buildstep-%s" % self.build_id,
- suffix=".log",
- mode='wb')
- build_logs.write("\n".join(self.workflow.data.build_result.logs).encode('utf-8'))
- build_logs.flush()
- filename = "{platform}-build.log".format(platform=self.platform)
- return [Output(file=build_logs,
- metadata=get_output_metadata(build_logs.name, filename))]
-
def get_metadata(self):
"""
Build the metadata needed for importing the build
@@ -136,7 +119,7 @@ class KojiUploadPlugin(PostBuildPlugin):
buildroot = get_buildroot()
output_files, _ = get_output(workflow=self.workflow, buildroot_id=buildroot['id'],
pullspec=self.pullspec_image, platform=self.platform,
- source_build=False, logs=self.get_logs())
+ source_build=False)
output = [output.metadata for output in output_files]
koji_metadata = {
|
koji_upload does not rely on build_result.logs
* CLOUDBLD-<I>
This is part of removing BuildResult from codebase. koji_upload will be
merged into koji_import and the build logs will be handled in the
solution of CLOUDBLD-<I>.
|
projectatomic_atomic-reactor
|
train
|
3dc361b248fcf57c9559d985575b01512794c352
|
diff --git a/packages/sagas/src/calculations.js b/packages/sagas/src/calculations.js
index <HASH>..<HASH> 100644
--- a/packages/sagas/src/calculations.js
+++ b/packages/sagas/src/calculations.js
@@ -11,6 +11,7 @@ import { selectors } from '@openchemistry/redux';
import girderClient from '@openchemistry/girder-client';
import { setPaginationDefaults } from './index'
+import { fetchOcFolder } from './app'
function fetchCalculations(options={}, creatorId) {
// Let's modify a clone of the options instead of the original options
@@ -26,6 +27,15 @@ function fetchCalculations(options={}, creatorId) {
.then(response => response.data )
}
+function createNewCalculation(parameters) {
+ return girderClient().post('calculations', parameters)
+ .then(response => response.data);
+}
+
+function ingestCalculation(id, params, json) {
+ return girderClient().put(`calculations/${id}`, json, {params:{...params}});
+}
+
export function* loadCalculationNotebooks(action) {
try {
const { calculationId } = action.payload;
@@ -82,3 +92,36 @@ function* loadCalculations(action) {
export function* watchLoadCalculations() {
yield takeEvery(calculationsRedux.LOAD_CALCULATIONS, loadCalculations);
}
+
+function* createCalculationFile(payload) {
+ const { body, name, size, moleculeId } = payload;
+ const parent = yield call(fetchOcFolder);
+ const createFile = yield call(file.create, parent._id, parent._modelType, name, 0);
+ const createUpload = yield call(file.update, createFile._id, size, body);
+ yield call(file.chunk, createUpload._id, 0, body, {});
+ return createFile;
+}
+
+function* uploadCalculation(body) {
+ const calc = yield call(createNewCalculation, body);
+ const params = {'detectBonds': true};
+ yield call(ingestCalculation, calc._id, params, body);
+ yield put(calculationsRedux.receiveNewCalculation(calc));
+}
+
+function* createCalculation(action) {
+ try {
+ const createdFile = yield call(createCalculationFile, action.payload);
+ var body = JSON.parse(action.payload.body);
+ body['fileId'] = createdFile._id;
+ body['format'] = 'cjson';
+ body['public'] = true;
+ yield call(uploadCalculation, body);
+ } catch (error) {
+ yield put(calculationsRedux.createCalculation(error));
+ }
+}
+
+export function* watchCreateCalculation() {
+ yield takeEvery(calculationsRedux.CREATE_CALCULATION, createCalculation);
+}
diff --git a/packages/sagas/src/index.js b/packages/sagas/src/index.js
index <HASH>..<HASH> 100644
--- a/packages/sagas/src/index.js
+++ b/packages/sagas/src/index.js
@@ -17,8 +17,8 @@ import { watchRedirectToJupyterHub, watchInvalidateSession, watchInvalidateToken
export { watchRedirectToJupyterHub, watchInvalidateSession, watchInvalidateToken}
import girderClient from '@openchemistry/girder-client';
-import { watchLoadCalculationNotebooks, watchLoadCalculations } from './calculations'
-export { watchLoadCalculationNotebooks, watchLoadCalculations }
+import { watchLoadCalculationNotebooks, watchLoadCalculations, watchCreateCalculation } from './calculations'
+export { watchLoadCalculationNotebooks, watchLoadCalculations, watchCreateCalculation }
import { watchLoadConfiguration } from './configuration'
export { watchLoadConfiguration }
|
Upload the calculation to Girder and ingest it
Create a file for the calculation in Girder, then create the calculation and
ingest it.
|
OpenChemistry_oc-web-components
|
train
|
14f9d9a55b409f15b66b558de6c7d216122a6ea9
|
diff --git a/src/Core/LTIX.php b/src/Core/LTIX.php
index <HASH>..<HASH> 100644
--- a/src/Core/LTIX.php
+++ b/src/Core/LTIX.php
@@ -459,7 +459,15 @@ class LTIX {
}
} else { // LTI 1.3
- // echo("<pre>\n"); var_dump($row); die('This is still broken');
+ $key_id = $row['key_id'];
+ $issuer_key = $post['issuer_key'];
+ $issuer_client = $post['issuer_client'];
+ $deployment_id = $post['deployment_id'];
+
+ if ( $key_id < 1 ) {
+ self::abort_with_error_log("Could not find tenant/key for $issuer_key / clientid=$issuer_client deployment_id=$deployment_id");
+ }
+
$raw_jwt = LTI13::raw_jwt($request_data);
$jwt = LTI13::parse_jwt($raw_jwt);
@@ -472,11 +480,11 @@ class LTIX {
$private_key = $row['lti13_privkey'];
$token_url = $row['lti13_token_url'];
- $consumer_sha256 = $post['issuer_sha256'];
+ $issuer_sha256 = $post['issuer_sha256'];
// Sanity check
- if ( strlen($public_key) < 1 && strlen($our_keyset_url) < 1 ) {
- self::abort_with_error_log("For LTI 1.3, $consumer_pk either must have a public_key or keyset_url\n$consumer_sha256");
+ if ( strlen($our_keyset_url) < 1 ) {
+ self::abort_with_error_log("Could not find keyset and $issuer_key");
}
// Make sure we have or update to the latest keyset if we have a keyset_url
diff --git a/src/UI/CrudForm.php b/src/UI/CrudForm.php
index <HASH>..<HASH> 100644
--- a/src/UI/CrudForm.php
+++ b/src/UI/CrudForm.php
@@ -199,13 +199,13 @@ class CrudForm {
if ( ! $do_edit ) {
echo('<p><strong>'.self::fieldToTitle($field, $titles)."</strong></p>\n");
if ( strpos($field, "secret") !== false || strpos($field, "privkey") !== false ) {
- echo("<p>\n");
+ echo('<p id="'.$field.'">'."\n");
echo("<span style=\"display: none;\" id=\"text_{$i}\">".htmlent_utf8($value).'</span>');
echo("<span id=\"show_{$i}\" onclick=\"$('#text_{$i}').show();$('#show_{$i}').hide();$('#hide_{$i}').show();\";>(Click to show)</span>\n");
echo("<span id=\"hide_{$i}\" onclick=\"$('#text_{$i}').hide();$('#hide_{$i}').hide();$('#show_{$i}').show();\" style=\"display:none\";>(Click to hide)</span>\n");
echo("\n</p>\n");
} else {
- echo("<p>".htmlent_utf8($value)."</p>\n");
+ echo('<p id="'.$field.'">'.htmlent_utf8($value)."</p>\n");
}
continue;
}
diff --git a/src/Util/LTI13.php b/src/Util/LTI13.php
index <HASH>..<HASH> 100644
--- a/src/Util/LTI13.php
+++ b/src/Util/LTI13.php
@@ -30,17 +30,6 @@ class LTI13 {
const RESULTS_TYPE = 'application/vnd.ims.lis.v2.resultcontainer+json';
/**
- * Pull out the effective oauth_consumer key from a JWT
- *
- * @param string $jwt The parsed JWT
- */
- // TODO: Remove this after the issuer refactor
- public static function extract_consumer_key($jwt) {
- die('DONT CALL LTI13::extract_consumer_key()');
- return 'lti13_' . $jwt->body->iss;
- }
-
- /**
* Pull out the issuer_key from a JWT
*
* @param string $jwt The parsed JWT
@@ -926,6 +915,28 @@ class LTI13 {
return $html;
}
+ /**
+ * Generate a PKCS8 Ppublic / private key pair
+ *
+ * @param string $publicKey Returned public key
+ * @param string $privateKey Returned private key
+ */
+ // https://stackoverflow.com/questions/6648337/generate-ssh-keypair-form-php
+ public static function generatePKCS8Pair(&$publicKey, &$privateKey) {
+ $privKey = openssl_pkey_new(
+ array('digest_alg' => 'sha256',
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA));
+
+ // Private Key
+ $privKey = openssl_pkey_get_private($privKey);
+ openssl_pkey_export($privKey, $privateKey);
+
+ // Public Key
+ $pubKey = openssl_pkey_get_details($privKey);
+ $publicKey = $pubKey['key'];
+ }
+
/** Cleanup common mess-ups in PKCS8 strings
*
* Often when public/private keys are pasted, stuff is added or
|
Make public key generation happen and be pastable
|
tsugiproject_tsugi-php
|
train
|
3e35922651d8d2d9cc7862663e458d76c51a8818
|
diff --git a/src/ascender/ascender_script.js b/src/ascender/ascender_script.js
index <HASH>..<HASH> 100644
--- a/src/ascender/ascender_script.js
+++ b/src/ascender/ascender_script.js
@@ -54,12 +54,12 @@ goog.scope(function () {
* @return {Array.<webfont.Font>}
*/
AscenderScript.prototype.parseFamiliesAndVariations = function (providedFamilies) {
- var families = [];
+ var fonts = [];
for (var i = 0, len = providedFamilies.length; i < len; i++) {
- families.push.apply(families, this.parseFamilyAndVariations(providedFamilies[i]));
+ fonts.push.apply(fonts, this.parseFamilyAndVariations(providedFamilies[i]));
}
- return families;
+ return fonts;
};
/**
diff --git a/src/custom/customcss.js b/src/custom/customcss.js
index <HASH>..<HASH> 100644
--- a/src/custom/customcss.js
+++ b/src/custom/customcss.js
@@ -35,7 +35,7 @@ goog.scope(function () {
this.domHelper_.insertInto('head', this.domHelper_.createCssLink(url));
}
- var families = [];
+ var fonts = [];
for (i = 0, len = familiesConfiguration.length; i < len; i++) {
var components = familiesConfiguration[i].split(":");
@@ -44,14 +44,14 @@ goog.scope(function () {
var variations = components[1].split(",");
for (var j = 0; j < variations.length; j += 1) {
- families.push(new Font(components[0], variations[j]));
+ fonts.push(new Font(components[0], variations[j]));
}
} else {
- families.push(new Font(components[0]));
+ fonts.push(new Font(components[0]));
}
}
- onReady(families);
+ onReady(fonts);
};
CustomCss.prototype.supportUserAgent = function(userAgent, support) {
diff --git a/src/typekit/typekit_script.js b/src/typekit/typekit_script.js
index <HASH>..<HASH> 100644
--- a/src/typekit/typekit_script.js
+++ b/src/typekit/typekit_script.js
@@ -9,7 +9,7 @@ goog.require('webfont.Font');
webfont.TypekitScript = function(domHelper, configuration) {
this.domHelper_ = domHelper;
this.configuration_ = configuration;
- this.fontFamilies_ = [];
+ this.fonts_ = [];
};
webfont.TypekitScript.NAME = 'typekit';
@@ -46,10 +46,10 @@ goog.scope(function () {
if (variations) {
for(var j = 0; j < variations.length; j += 1) {
- self.fontFamilies_.push(new Font(fontFamilies[i], variations[j]));
+ self.fonts_.push(new Font(fontFamilies[i], variations[j]));
}
} else {
- self.fontFamilies_.push(new Font(fontFamilies[i]));
+ self.fonts_.push(new Font(fontFamilies[i]));
}
}
support(typekitSupports);
@@ -66,7 +66,7 @@ goog.scope(function () {
};
TypekitScript.prototype.load = function(onReady) {
- onReady(this.fontFamilies_);
+ onReady(this.fonts_);
};
});
|
More renaming of families to fonts.
|
typekit_webfontloader
|
train
|
fe8142232c7e7fb626fb9ab714a49430ea5b48a0
|
diff --git a/lib/volt/data_stores/data_store.rb b/lib/volt/data_stores/data_store.rb
index <HASH>..<HASH> 100644
--- a/lib/volt/data_stores/data_store.rb
+++ b/lib/volt/data_stores/data_store.rb
@@ -9,10 +9,11 @@ module Volt
database_name = Volt.config.db_driver
driver_name = database_name.camelize + 'Driver'
- begin
- driver = const_get(driver_name)
- @driver = MongoDriver.new
- rescue NameError => e
+ root = Volt::DataStore
+ if root.const_defined?(driver_name)
+ driver = root.const_get(driver_name)
+ @driver = driver.new
+ else
raise "#{database_name} is not a supported database"
end
end
diff --git a/lib/volt/data_stores/mongo_driver.rb b/lib/volt/data_stores/mongo_driver.rb
index <HASH>..<HASH> 100644
--- a/lib/volt/data_stores/mongo_driver.rb
+++ b/lib/volt/data_stores/mongo_driver.rb
@@ -1,5 +1,5 @@
-require 'volt/data_stores/base'
require 'mongo'
+require 'volt/data_stores/base'
module Volt
class DataStore
@@ -8,10 +8,11 @@ module Volt
def initialize
if Volt.config.db_uri.present?
- @mongo_db ||= Mongo::MongoClient.from_uri(Volt.config.db_uri)
+ puts "DB URI"
+ @mongo_db ||= ::Mongo::MongoClient.from_uri(Volt.config.db_uri)
@db ||= @mongo_db.db(Volt.config.db_uri.split('/').last || Volt.config.db_name)
else
- @mongo_db ||= Mongo::MongoClient.new(Volt.config.db_host, Volt.config.db_path)
+ @mongo_db ||= ::Mongo::MongoClient.new(Volt.config.db_host, Volt.config.db_port)
@db ||= @mongo_db.db(Volt.config.db_name)
end
end
diff --git a/lib/volt/server.rb b/lib/volt/server.rb
index <HASH>..<HASH> 100644
--- a/lib/volt/server.rb
+++ b/lib/volt/server.rb
@@ -50,7 +50,7 @@ module Volt
attr_reader :listener, :app_path
# You can also optionally pass in a prebooted app
- def initialize(root_path = nil, app = false)
+ def initialize(root_path = nil, app = nil)
@root_path = root_path || Dir.pwd
@volt_app = app
diff --git a/lib/volt/server/forking_server.rb b/lib/volt/server/forking_server.rb
index <HASH>..<HASH> 100644
--- a/lib/volt/server/forking_server.rb
+++ b/lib/volt/server/forking_server.rb
@@ -79,6 +79,22 @@ module Volt
end
end
+
+ def stop_child
+ # clear the drb object and kill the child process.
+ if @drb_object
+ begin
+ @drb_object = nil
+ DRb.stop_service
+ @reader.close
+ stop_change_listener
+ Process.kill(9, @child_id)
+ rescue => e
+ puts "Stop Child Error: #{e.inspect}"
+ end
+ end
+ end
+
# In the even the parent gets killed without at_exit running,
# we watch the pipe and close if the pipe gets closed.
def watch_for_parent_exit
@@ -129,20 +145,6 @@ module Volt
end
end
- def stop_child
- # clear the drb object and kill the child process.
- if @drb_object
- begin
- @drb_object = nil
- DRb.stop_service
- @reader.close
- stop_change_listener
- Process.kill(9, @child_id)
- rescue => e
- puts "Stop Child Error: #{e.inspect}"
- end
- end
- end
def reload(changed_files)
# only reload the server code if a non-view file was changed
diff --git a/lib/volt/server/socket_connection_handler.rb b/lib/volt/server/socket_connection_handler.rb
index <HASH>..<HASH> 100644
--- a/lib/volt/server/socket_connection_handler.rb
+++ b/lib/volt/server/socket_connection_handler.rb
@@ -53,7 +53,7 @@ module Volt
# Remove ourself from the available channels
@@channels.delete(self)
- QueryTasks.new(self).close!
+ @@dispatcher.close_channel(self)
else
Volt.logger.error("Socket Error: Connection already closed\n#{inspect}")
end
diff --git a/lib/volt/tasks/dispatcher.rb b/lib/volt/tasks/dispatcher.rb
index <HASH>..<HASH> 100644
--- a/lib/volt/tasks/dispatcher.rb
+++ b/lib/volt/tasks/dispatcher.rb
@@ -89,5 +89,9 @@ module Volt
false
end
+
+ def close_channel(channel)
+ QueryTasks.new(channel).close!
+ end
end
end
|
- Fix mongo loading, port issue.
- Fix socket close issue.
|
voltrb_volt
|
train
|
2dcf98c65013ba390332e1528801bbe98b3b0c1d
|
diff --git a/src/collide.js b/src/collide.js
index <HASH>..<HASH> 100644
--- a/src/collide.js
+++ b/src/collide.js
@@ -6,7 +6,8 @@ export default function() {
var nodes,
radius = constant(1),
radii,
- radiusMax;
+ radiusMax,
+ strength = 0.7;
function force() {
var i, n = nodes.length,
@@ -25,7 +26,7 @@ export default function() {
nx0 = node.x - nr, ny0 = node.y - nr;
nx1 = node.x + nr, ny1 = node.y + nr;
tree.remove(node).visit(apply);
- node.x += vx, node.y += vy;
+ node.x += vx * strength, node.y += vy * strength;
tree.add(node);
}
@@ -37,7 +38,7 @@ export default function() {
l = x * x + y * y,
r = radii[i] + radii[quad.data.index];
if (l < r * r) {
- l = Math.sqrt(l), l = (r - l) / l;
+ l = (r - (l = Math.sqrt(l))) / l;
vx += x * l, vy += y * l;
}
}
@@ -54,6 +55,10 @@ export default function() {
}
};
+ force.strength = function(_) {
+ return arguments.length ? (strength = +_, force) : strength;
+ };
+
force.radius = function(_) {
return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), force) : radius;
};
|
Add a tiny bit of blending to collision.
This greatly improves stability.
|
d3_d3-force
|
train
|
8e27ec93f3fb7a4f59cf5e73d9b1c0d993a5fbc3
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@ from distutils.core import setup
setup(name = "amqplib",
description = "AMQP Client Library",
- version = "0.1",
+ version = "0.2",
license = "LGPL",
author = "Barry Pederson",
author_email = "bp@barryp.org",
|
Bump the version number in setup.py, oops.
|
barryp_py-amqplib
|
train
|
1c9f0617d73845fe8f111e34755001138b5cc4b9
|
diff --git a/dingo/config/config_db_interfaces.py b/dingo/config/config_db_interfaces.py
index <HASH>..<HASH> 100644
--- a/dingo/config/config_db_interfaces.py
+++ b/dingo/config/config_db_interfaces.py
@@ -23,3 +23,38 @@ class sqla_mv_grid_viz(Base):
geom_lv_stations = sa.Column('geom_lv_stations', Geometry(geometry_type='MULTIPOINT', srid=4326))
geom_mv_generators = sa.Column('geom_mv_generators', Geometry(geometry_type='MULTIPOINT', srid=4326))
geom_mv_lines = sa.Column('geom_mv_lines', Geometry(geometry_type='MULTILINESTRING', srid=4326))
+
+
+class sqla_mv_grid_viz_branches(Base):
+ """ SQLAlchemy table definition for the export of MV grids' branches for visualization purposes
+ """
+
+ __tablename__ = 'ego_deu_mv_grids_vis_branches'
+ __table_args__ = {'schema': 'calc_ego_grid'}
+
+ branch_id = sa.Column(sa.String(25), primary_key=True)
+ grid_id = sa.Column('grid_id', sa.Integer)
+ type_name = sa.Column('type_name', sa.String(25))
+ type_kind = sa.Column('type_kind', sa.String(5))
+ type_v_nom = sa.Column('type_v_nom', sa.Integer)
+ type_s_nom = sa.Column('type_s_nom', sa.Float(53))
+ length = sa.Column('length', sa.Float(53))
+ geom = sa.Column('geom', Geometry(geometry_type='LINESTRING', srid=4326))
+ s_res0 = sa.Column('s_res0', sa.Float(53))
+ s_res1 = sa.Column('s_res1', sa.Float(53))
+
+
+class sqla_mv_grid_viz_buses(Base):
+ """ SQLAlchemy table definition for the export of MV grids' branches for visualization purposes
+ """
+
+ __tablename__ = 'ego_deu_mv_grids_vis_buses'
+ __table_args__ = {'schema': 'calc_ego_grid'}
+
+
+ bus_id = sa.Column(sa.String(25), primary_key=True)
+ grid_id = sa.Column('grid_id', sa.Integer)
+ type_v_nom = sa.Column('type_v_nom', sa.Integer)
+ geom = sa.Column('geom', Geometry(geometry_type='POINT', srid=4326))
+ v_res0 = sa.Column('v_res0', sa.Float(53))
+ v_res1 = sa.Column('v_res1', sa.Float(53))
|
add sqla bus and branch obj to db interfaces
|
openego_ding0
|
train
|
4e2a3f490d142cb042f177158aa7d16465edbb03
|
diff --git a/source/php/Search.php b/source/php/Search.php
index <HASH>..<HASH> 100644
--- a/source/php/Search.php
+++ b/source/php/Search.php
@@ -120,7 +120,7 @@ class Search
$attributes['modules'] = substr(
$rendered,
0,
- (10000 - $contentBytes)
+ (9000 - $contentBytes)
);
}
|
Update to <I> to leave space for various other attributes
|
helsingborg-stad_Modularity
|
train
|
7b48908936ddcca75374918a45ed9c30bf69e654
|
diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/description/annotation/AnnotationValue.java b/byte-buddy-dep/src/main/java/net/bytebuddy/description/annotation/AnnotationValue.java
index <HASH>..<HASH> 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/description/annotation/AnnotationValue.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/description/annotation/AnnotationValue.java
@@ -17,6 +17,7 @@ package net.bytebuddy.description.annotation;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.build.CachedReturnPlugin;
+import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.description.enumeration.EnumerationDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDefinition;
@@ -2720,6 +2721,7 @@ public interface AnnotationValue<T, S> {
* @param <U> The type of the annotation's value when it is not loaded.
* @param <V> The type of the annotation's value when it is loaded.
*/
+ @HashCodeAndEqualsPlugin.Enhance
class ForMissingValue<U, V> extends AnnotationValue.AbstractBase<U, V> {
/**
@@ -2786,13 +2788,12 @@ public interface AnnotationValue<T, S> {
throw new IllegalStateException(typeDescription + " does not define " + property);
}
- /* does not implement hashCode and equals method to mimic OpenJDK behavior. */
-
/**
* Describes an annotation value for a property that is not assignable to it.
*
* @param <W> The type of the annotation's expected value.
*/
+ @HashCodeAndEqualsPlugin.Enhance
public static class Loaded<W> extends AnnotationValue.Loaded.AbstractBase<W> {
/**
@@ -2836,8 +2837,6 @@ public interface AnnotationValue<T, S> {
public boolean represents(Object value) {
return false;
}
-
- /* does not implement hashCode and equals method to mimic OpenJDK behavior. */
}
}
|
Treat missing value as equalizable object.
|
raphw_byte-buddy
|
train
|
99b498a62f398faac614c5e90e39920d31f8ff19
|
diff --git a/firebase/firebase_token_generator.py b/firebase/firebase_token_generator.py
index <HASH>..<HASH> 100644
--- a/firebase/firebase_token_generator.py
+++ b/firebase/firebase_token_generator.py
@@ -97,7 +97,7 @@ class FirebaseTokenGenerator(object):
return encoded.decode('utf-8').replace('=', '')
def _encode_json(self, obj):
- return self._encode(bytearray(json.dumps(obj), 'utf-8'))
+ return self._encode(json.dumps(obj).encode("utf-8"))
def _sign(self, secret, to_sign):
def portable_bytes(s):
diff --git a/firebase/jsonutil.py b/firebase/jsonutil.py
index <HASH>..<HASH> 100644
--- a/firebase/jsonutil.py
+++ b/firebase/jsonutil.py
@@ -2,13 +2,18 @@ import datetime
import json
import decimal
+try:
+ total_seconds = datetime.timedelta.total_seconds
+except AttributeError:
+ total_seconds = lambda self: ((self.days * 86400 + self.seconds) * 10 ** 6 + self.microseconds) / 10 ** 6.0
+
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
- return int(obj.total_seconds())
+ return total_seconds(obj)
elif isinstance(obj, decimal.Decimal):
return float(obj)
else:
diff --git a/tests/jsonutil_test.py b/tests/jsonutil_test.py
index <HASH>..<HASH> 100644
--- a/tests/jsonutil_test.py
+++ b/tests/jsonutil_test.py
@@ -15,9 +15,21 @@ class JSONTestCase(unittest.TestCase):
def test_conversion(self):
serialized = json.dumps(self.data, cls=JSONEncoder)
deserialized = json.loads(serialized)
- self.assertEqual(deserialized['oneday'],
- int(self.data['oneday'].total_seconds()))
+ self.assertEqual(deserialized['oneday'], 86400)
self.assertTrue(type(deserialized['five']) == float)
self.assertEqual(deserialized['five'], float(5))
self.assertEqual(deserialized['now'], str(self.data['now'].isoformat()))
+ def test_total_seconds(self):
+ from firebase.jsonutil import total_seconds
+
+ delta = datetime.timedelta(days=1,
+ seconds=3,
+ microseconds=440000,
+ milliseconds=3300,
+ minutes=5,
+ hours=2,
+ weeks=2)
+
+ self.assertEqual(total_seconds(delta), 1303506.74)
+
|
python<I> compatibility related.
in py<I> datetime.timedelta doesnt have total_seconds method.
base<I>.urlsafe_b<I>encode doesnt work with bytearray
|
ozgur_python-firebase
|
train
|
8a69c679454f645e659debf9c4d77ff34de1a5e1
|
diff --git a/matplotlib2tikz/legend.py b/matplotlib2tikz/legend.py
index <HASH>..<HASH> 100644
--- a/matplotlib2tikz/legend.py
+++ b/matplotlib2tikz/legend.py
@@ -200,7 +200,6 @@ def draw_legend(data, obj):
)
# Set color of lines in legend
- data['legend colors'] = []
for handle in obj.legendHandles:
try:
data, legend_color, _ = mycol.mpl_color2xcolor(data,
@@ -208,7 +207,7 @@ def draw_legend(data, obj):
data['legend colors'].append('\\addlegendimage{no markers, %s}\n'
% legend_color)
except AttributeError:
- data['legend colors'] = []
+ pass
# Write styles to data
if legend_style:
diff --git a/matplotlib2tikz/save.py b/matplotlib2tikz/save.py
index <HASH>..<HASH> 100644
--- a/matplotlib2tikz/save.py
+++ b/matplotlib2tikz/save.py
@@ -124,6 +124,7 @@ def get_tikz_code(
data['pgfplots libs'] = set()
data['font size'] = textsize
data['custom colors'] = {}
+ data['legend colors'] = []
data['extra tikzpicture parameters'] = extra_tikzpicture_parameters
# rectangle_legends is used to keep track of which rectangles have already
# had \addlegendimage added. There should be only one \addlegenimage per
|
legend colors initialization moved to save.py
|
nschloe_matplotlib2tikz
|
train
|
41874f85f2789da9f5a9f41c29aed5d0b4a33a70
|
diff --git a/lib/html_mockup/rack/html_mockup.rb b/lib/html_mockup/rack/html_mockup.rb
index <HASH>..<HASH> 100644
--- a/lib/html_mockup/rack/html_mockup.rb
+++ b/lib/html_mockup/rack/html_mockup.rb
@@ -8,7 +8,13 @@ module HtmlMockup
module Rack
class HtmlMockup
- def initialize(root,partial_path)
+
+ attr_reader :project
+
+ def initialize(project)
+ @project = project
+ root,partial_path = project.html_path, project.partial_path
+
@docroot = root
@partial_path = partial_path
@file_server = ::Rack::File.new(@docroot)
diff --git a/lib/html_mockup/server.rb b/lib/html_mockup/server.rb
index <HASH>..<HASH> 100644
--- a/lib/html_mockup/server.rb
+++ b/lib/html_mockup/server.rb
@@ -65,7 +65,7 @@ module HtmlMockup
return @app if @app
@stack.use Rack::HtmlValidator if self.options[:validate]
- @stack.run Rack::HtmlMockup.new(self.project.html_path, self.project.partial_path)
+ @stack.run Rack::HtmlMockup.new(self.project)
@app = @stack
end
|
Refactor the HtmlMockup Rack adapter to use project object instead of paths
|
DigitPaint_html_mockup
|
train
|
2103f890eafa5aa7d4dba155066f66a5b0998a82
|
diff --git a/includes/class-kirki-config.php b/includes/class-kirki-config.php
index <HASH>..<HASH> 100644
--- a/includes/class-kirki-config.php
+++ b/includes/class-kirki-config.php
@@ -2,8 +2,49 @@
class Kirki_Config extends Kirki_Customizer {
- public function __construct( $args = array() ) {
+ public $default_args = array();
+
+ public function __construct( $id, $args = array() ) {
+
parent::__construct();
+
+ $this->default_args = array(
+ 'capability' => 'edit_theme_options',
+ 'option_type' => 'theme_mod',
+ 'option_name' => '',
+ 'compiler' => array(),
+ );
+
+ $this->add_config( $id, $args );
+
+ }
+
+ public function add_config( $id, $args ) {
+
+ /**
+ * Allow empty value as the config ID by setting the id to global.
+ */
+ $config_id = ( '' == $config_id ) ? 'global' : $config_id;
+ /**
+ * Set the config
+ */
+ Kirki::$config[ $config_id ] = array_merge( $this->default_args, $args );
+
+ }
+
+
+ public function config_from_filters() {
+
+ $args = apply_filters( 'kirki/config', $this->default_args );
+
+ $valid_args = array();
+ $valid_args['capability'] = $args['capability'];
+ $valid_args['option_type'] = $args['option_type'];
+ $valid_args['option_name'] = $args['option_name'];
+ $valid_args['compiler'] = $args['compiler'];
+
+ return $valid_args;
+
}
}
diff --git a/includes/class-kirki.php b/includes/class-kirki.php
index <HASH>..<HASH> 100644
--- a/includes/class-kirki.php
+++ b/includes/class-kirki.php
@@ -243,24 +243,7 @@ class Kirki {
* @param string $config_id
*/
public static function add_config( $config_id, $args = array() ) {
-
- $default_args = array(
- 'capability' => 'edit_theme_options',
- 'option_type' => 'theme_mod',
- 'option_name' => '',
- 'compiler' => array(),
- );
- $args = array_merge( $default_args, $args );
-
- /**
- * Allow empty value as the config ID by setting the id to global.
- */
- $config_id = ( '' == $config_id ) ? 'global' : $config_id;
- /**
- * Set the config
- */
- self::$config[ $config_id ] = $args;
-
+ $config = new Kirki_Config( $config_id, $args );
}
/**
|
move code to the Kirki_Config class
|
aristath_kirki
|
train
|
769ac5e11bd4683653b3338e4a5b7cef336db9c6
|
diff --git a/src/Session.php b/src/Session.php
index <HASH>..<HASH> 100644
--- a/src/Session.php
+++ b/src/Session.php
@@ -51,7 +51,7 @@ class Session
protected $wsBaseURL = null;
// Webservice login validity
- private $serviceServerTime = null;
+ # private $serviceServerTime = null;
private $serviceExpireTime = null;
private $serviceToken = null;
@@ -186,7 +186,7 @@ class Session
return false;
}
- $this->serviceServerTime = $result['serverTime'];
+ # $this->serviceServerTime = $result['serverTime'];
$this->serviceExpireTime = $result['expireTime'];
$this->serviceToken = $result['token'];
|
commenting out serviceServerTime since it's not used
|
salaros_vtwsclib-php
|
train
|
ebbe5473dcf9be1f8591094d3a6d1976afc6d07b
|
diff --git a/packages/openneuro-server/datalad/dataset.js b/packages/openneuro-server/datalad/dataset.js
index <HASH>..<HASH> 100644
--- a/packages/openneuro-server/datalad/dataset.js
+++ b/packages/openneuro-server/datalad/dataset.js
@@ -17,15 +17,6 @@ const c = mongo.collections
const uri = config.datalad.uri
/**
- * Set commit info on a superagent request
- */
-const setCommitInfo = (req, name, email) => {
- if (name && email) {
- req.set('From', `"${name}" <${email}>`)
- }
-}
-
-/**
* Create a new dataset
*
* Internally we setup metadata and access
@@ -34,7 +25,7 @@ const setCommitInfo = (req, name, email) => {
* @param {String} label - descriptive label for this dataset
* @returns {Promise} - resolves to dataset id of the new dataset
*/
-export const createDataset = (label, uploader, userInfo) => {
+export const createDataset = (label, uploader) => {
return new Promise(async (resolve, reject) => {
const datasetId = await getAccessionNumber()
const dsObj = await createDatasetModel(datasetId, label, uploader)
@@ -42,8 +33,10 @@ export const createDataset = (label, uploader, userInfo) => {
// If successful, create the repo
const url = `${uri}/datasets/${datasetId}`
if (dsObj) {
- const req = request.post(url).set('Accept', 'application/json')
- if (userInfo) setCommitInfo(req, userInfo.name, userInfo.email)
+ const req = request
+ .post(url)
+ .set('Accept', 'application/json')
+ .set('Cookie', generateDataladCookie(config)(uploader))
await req
pubsub.publish('datasetAdded', { id: datasetId })
subscriptions
@@ -231,7 +224,6 @@ export const commitFiles = (datasetId, user) => {
return res.body.ref
})
.then(updateDatasetRevision(datasetId))
- setCommitInfo(req, user.name, user.email)
return req
}
diff --git a/packages/openneuro-server/graphql/resolvers/__tests__/dataset.spec.js b/packages/openneuro-server/graphql/resolvers/__tests__/dataset.spec.js
index <HASH>..<HASH> 100644
--- a/packages/openneuro-server/graphql/resolvers/__tests__/dataset.spec.js
+++ b/packages/openneuro-server/graphql/resolvers/__tests__/dataset.spec.js
@@ -1,6 +1,8 @@
import mongo from '../../../libs/mongo'
import * as ds from '../dataset'
+jest.mock('../../../config.js')
+
beforeAll(async () => {
await mongo.connect()
await mongo.collections.crn.counters.insertMany([
@@ -16,7 +18,7 @@ describe('dataset resolvers', () => {
{
label: 'testing dataset',
},
- { user: {}, userInfo: { name: 'test' } },
+ { user: { accessToken: '123456' } },
)
expect(dsId).toEqual(expect.stringMatching(/^ds[0-9]{6}$/))
done()
diff --git a/packages/openneuro-server/graphql/resolvers/dataset.js b/packages/openneuro-server/graphql/resolvers/dataset.js
index <HASH>..<HASH> 100644
--- a/packages/openneuro-server/graphql/resolvers/dataset.js
+++ b/packages/openneuro-server/graphql/resolvers/dataset.js
@@ -14,8 +14,8 @@ export const datasets = () => {
/**
* Create an empty dataset (new repo, new accession number)
*/
-export const createDataset = (obj, { label }, { user, userInfo }) => {
- return datalad.createDataset(label, user, userInfo).then(dataset => {
+export const createDataset = (obj, { label }, { user }) => {
+ return datalad.createDataset(label, user).then(dataset => {
return dataset
})
}
|
Update createDataset mutation to give credit (using cookies).
|
OpenNeuroOrg_openneuro
|
train
|
0d830e5a2436d55112755080d1084ed1ff13c1eb
|
diff --git a/server/http/http.go b/server/http/http.go
index <HASH>..<HASH> 100644
--- a/server/http/http.go
+++ b/server/http/http.go
@@ -103,6 +103,16 @@ func (i *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
req := cmds.NewRequest(path, opts, nil, nil)
res := commands.Root.Call(req)
+ // set the Content-Type based on res output
+ if _, ok := res.Value().(io.Reader); ok {
+ // TODO: set based on actual Content-Type of file
+ w.Header().Set("Content-Type", "application/octet-stream")
+ } else {
+ // TODO: get proper MIME type for encoding from multicodec lib
+ enc, _ := req.Option(cmds.EncShort)
+ w.Header().Set("Content-Type", "application/"+enc.(string))
+ }
+
// if response contains an error, write an HTTP error status code
if e := res.Error(); e != nil {
if e.Code == cmds.ErrClient {
@@ -115,6 +125,7 @@ func (i *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, err = io.Copy(w, res)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
+ w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(err.Error()))
}
}
|
server/http: Set Content-Type header based on command output
|
ipfs_go-ipfs
|
train
|
477517d8ea455d02e3492c06021eda79c5b7134b
|
diff --git a/lxd/devlxd.go b/lxd/devlxd.go
index <HASH>..<HASH> 100644
--- a/lxd/devlxd.go
+++ b/lxd/devlxd.go
@@ -85,7 +85,7 @@ var devlxdConfigKeyGet = devLxdHandler{"/1.0/config/{key}", func(d *Daemon, c in
}}
var devlxdImageExport = devLxdHandler{"/1.0/images/{fingerprint}/export", func(d *Daemon, c instance.Instance, w http.ResponseWriter, r *http.Request) *devLxdResponse {
- if !shared.IsTrue(c.ExpandedConfig()["security.devlxd.images"]) {
+ if shared.IsFalseOrEmpty(c.ExpandedConfig()["security.devlxd.images"]) {
return &devLxdResponse{"not authorized", http.StatusForbidden, "raw"}
}
|
lxd/devlxd: Replace !shared.IsTrue with shared.IsFalseOrEmpty for security.devlxd.images
|
lxc_lxd
|
train
|
68abfe211e0fff1188c744afba593259723322e8
|
diff --git a/plugins/scss/index.js b/plugins/scss/index.js
index <HASH>..<HASH> 100644
--- a/plugins/scss/index.js
+++ b/plugins/scss/index.js
@@ -192,6 +192,10 @@ const writer = function(thisPackage, outputDir) {
promises.push(fs.readFileAsync(path.resolve(outputDir, 'combined.scss'), 'utf8')
.then(function(fileContents) {
console.log('Creating combined.scss for ' + theme + ' theme');
+
+ // Add the theme name to a class for stylesheet load detection.
+ fileContents = '.u-loaded-theme { content: "' + theme + '"; }\n' + fileContents;
+
// Prepend and Append our theme around the bootstrap entry
var bootstrapEntry = '@import \'bootstrap\';';
if (theme != 'default') {
diff --git a/test/plugins/scss/index.test.js b/test/plugins/scss/index.test.js
index <HASH>..<HASH> 100644
--- a/test/plugins/scss/index.test.js
+++ b/test/plugins/scss/index.test.js
@@ -56,6 +56,21 @@ describe('scss resolver', () => {
expect(args).to.equal(expectedArgs);
expect(requireAll).to.equal(expectedRequireAll);
}
+
+ if (pack && pack.build && pack.build.themes) {
+ pack.build.themes.forEach((theme) => {
+ var themeCombinedFile = path.join(outputDir, 'themes', theme + '.combined.scss');
+ var themeArgsFile = path.join(outputDir, 'themes', theme + '.node-sass-args');
+
+ // theme files were written
+ expect(fs.existsSync(themeCombinedFile)).to.be.true;
+ expect(fs.existsSync(themeArgsFile)).to.be.true;
+
+ // theme detection class was added
+ var themeCombined = fs.readFileSync(themeCombinedFile, 'utf-8');
+ expect(themeCombined.startsWith('.u-loaded-theme { content: "' + theme + '"; }')).to.be.true;
+ });
+ }
});
});
}
|
feat(themes): Add detection class to theme stylesheets.
|
ngageoint_opensphere-build-resolver
|
train
|
a380ebabd520e850807ed8bc722ffe018bfa5379
|
diff --git a/select2.js b/select2.js
index <HASH>..<HASH> 100644
--- a/select2.js
+++ b/select2.js
@@ -2842,9 +2842,7 @@ the specific language governing permissions and limitations under the Apache Lic
return;
}
- index = indexOf(this.id(data), val);
-
- if (index >= 0) {
+ while((index = indexOf(this.id(data), val)) >= 0) {
val.splice(index, 1);
this.setVal(val);
if (this.select) this.postprocessResults();
|
Remove duplicated options from multi-valued select boxes.
|
select2_select2
|
train
|
72f61c85c7fc51711132fe2fab890630a1aa80e9
|
diff --git a/BlockBuilderInterface.php b/BlockBuilderInterface.php
index <HASH>..<HASH> 100644
--- a/BlockBuilderInterface.php
+++ b/BlockBuilderInterface.php
@@ -4,10 +4,4 @@ namespace Oro\Component\Layout;
interface BlockBuilderInterface
{
- /**
- * Creates the block.
- *
- * @return BlockInterface
- */
- public function getBlock();
}
diff --git a/LayoutBlockBuilder.php b/LayoutBlockBuilder.php
index <HASH>..<HASH> 100644
--- a/LayoutBlockBuilder.php
+++ b/LayoutBlockBuilder.php
@@ -2,15 +2,21 @@
namespace Oro\Component\Layout;
-class LayoutBlockBuilder extends LayoutBlock implements BlockBuilderInterface
+class LayoutBlockBuilder implements BlockBuilderInterface
{
+ /** @var string */
+ protected $blockId;
+
+ /** @var LayoutData */
+ protected $layoutData;
+
/**
- * Creates the block.
- *
- * @return BlockInterface
+ * @param LayoutData $layoutData
+ * @param string $blockId
*/
- public function getBlock()
+ public function __construct(LayoutData $layoutData, $blockId)
{
- return $this;
+ $this->layoutData = $layoutData;
+ $this->blockId = $blockId;
}
}
|
BAP-<I>: Base container block type class implementation. Decouple BlockBuilderInterface and BlockInterface
|
oroinc_OroLayoutComponent
|
train
|
8543da374847b28833b782f2cdbf70d2e4df4438
|
diff --git a/src/Zenaton/Common/Services/Jsonizer.php b/src/Zenaton/Common/Services/Jsonizer.php
index <HASH>..<HASH> 100644
--- a/src/Zenaton/Common/Services/Jsonizer.php
+++ b/src/Zenaton/Common/Services/Jsonizer.php
@@ -34,7 +34,7 @@ class Jsonizer
public function getObjectFromNameAndEncodedProperties($name, $encodedProperties, $class = null)
{
- $o = (new ReflectionClass($name))->newInstanceWithoutConstructor();
+ $o = $this->getNewObject($name);
// object must be of $class type
if ( ! is_null($class) && ( ! is_object($o) || ! $o instanceof $class)) {
@@ -48,6 +48,25 @@ class Jsonizer
return $this->setPropertiesToObject($o, $properties);
}
+ protected function getNewObject($name)
+ {
+ // this is a crazy hack necessary to be able to decode Carbon\Carbon object
+ // Datetime has a date property created by its constructor
+ // but Carbon forbid to access it if not yet set
+ $params = (new ReflectionClass($name))->getConstructor()->getParameters();
+ $useConstructor = count($params)===0 || array_unique(array_map(function($p) { return $p->isOptional(); }, $params)) === [true];
+
+ if ($useConstructor) {
+ $o = new $name;
+ // this is necessary - I do not known why really
+ var_export($o, true);
+
+ return $o;
+ }
+
+ return (new ReflectionClass($name))->newInstanceWithoutConstructor();
+ }
+
public function setPropertiesToObject($o, $properties)
{
$r = new ReflectionClass($o);
@@ -196,7 +215,8 @@ class Jsonizer
}
// build object
- $object = (new ReflectionClass($encodedObject[self::KEY_OBJECT_NAME]))->newInstanceWithoutConstructor();
+ $object = $this->getNewObject($encodedObject[self::KEY_OBJECT_NAME]);
+
$this->decoded[$id] = $object;
// transpile properties
|
crazy hack to be able to decode Carbon object
|
zenaton_zenaton-php
|
train
|
6c1aa3e3b2e9c54772584093dcf862b98e4b1419
|
diff --git a/logbook-core/src/main/java/org/zalando/logbook/CurlHttpLogFormatter.java b/logbook-core/src/main/java/org/zalando/logbook/CurlHttpLogFormatter.java
index <HASH>..<HASH> 100644
--- a/logbook-core/src/main/java/org/zalando/logbook/CurlHttpLogFormatter.java
+++ b/logbook-core/src/main/java/org/zalando/logbook/CurlHttpLogFormatter.java
@@ -26,6 +26,7 @@ public final class CurlHttpLogFormatter implements HttpLogFormatter {
final HttpRequest request = precorrelation.getRequest();
final List<String> command = new ArrayList<>();
+ command.add(precorrelation.getId());
command.add("curl");
command.add("-v"); // TODO optional?
diff --git a/logbook-core/src/test/java/org/zalando/logbook/CurlHttpLogFormatterTest.java b/logbook-core/src/test/java/org/zalando/logbook/CurlHttpLogFormatterTest.java
index <HASH>..<HASH> 100644
--- a/logbook-core/src/test/java/org/zalando/logbook/CurlHttpLogFormatterTest.java
+++ b/logbook-core/src/test/java/org/zalando/logbook/CurlHttpLogFormatterTest.java
@@ -30,7 +30,8 @@ public final class CurlHttpLogFormatterTest {
final HttpLogFormatter unit = new CurlHttpLogFormatter();
final String curl = unit.format(new SimplePrecorrelation<>(correlationId, request));
- assertThat(curl, is("curl -v -X GET 'http://localhost/test?limit=1' -H 'Accept: application/json' -H 'Content-Type: text/plain' --data-binary 'Hello, world!'"));
+ assertThat(curl, is("c9408eaa-677d-11e5-9457-10ddb1ee7671 " +
+ "curl -v -X GET 'http://localhost/test?limit=1' -H 'Accept: application/json' -H 'Content-Type: text/plain' --data-binary 'Hello, world!'"));
}
@Test
@@ -43,7 +44,8 @@ public final class CurlHttpLogFormatterTest {
final HttpLogFormatter unit = new CurlHttpLogFormatter();
final String curl = unit.format(new SimplePrecorrelation<>(correlationId, request));
- assertThat(curl, is("curl -v -X GET 'http://localhost/test' -H 'Accept: application/json'"));
+ assertThat(curl, is("0eae9f6c-6824-11e5-8b0a-10ddb1ee7671 " +
+ "curl -v -X GET 'http://localhost/test' -H 'Accept: application/json'"));
}
@Test
@@ -62,7 +64,8 @@ public final class CurlHttpLogFormatterTest {
final HttpLogFormatter unit = new CurlHttpLogFormatter();
final String curl = unit.format(new SimplePrecorrelation<>(correlationId, request));
- assertThat(curl, is("curl -v -X GET 'http://localhost/test?char=\\'' -H 'Foo\\'Bar: Baz' --data-binary '{\"message\":\"Hello, \\'world\\'!\"}'"));
+ assertThat(curl, is("c9408eaa-677d-11e5-9457-10ddb1ee7671 " +
+ "curl -v -X GET 'http://localhost/test?char=\\'' -H 'Foo\\'Bar: Baz' --data-binary '{\"message\":\"Hello, \\'world\\'!\"}'"));
}
@Test
diff --git a/logbook-spring-boot-starter/src/test/java/org/zalando/logbook/spring/FormatStyleCurlTest.java b/logbook-spring-boot-starter/src/test/java/org/zalando/logbook/spring/FormatStyleCurlTest.java
index <HASH>..<HASH> 100644
--- a/logbook-spring-boot-starter/src/test/java/org/zalando/logbook/spring/FormatStyleCurlTest.java
+++ b/logbook-spring-boot-starter/src/test/java/org/zalando/logbook/spring/FormatStyleCurlTest.java
@@ -55,7 +55,7 @@ public final class FormatStyleCurlTest extends AbstractTest {
private Matcher<Precorrelation<String>> isCurlFormatter() {
final Function<Precorrelation<String>, String> getRequest = Precorrelation::getRequest;
- return hasFeature("request", getRequest, is("curl -v -X GET 'http://localhost/'"));
+ return hasFeature("request", getRequest, containsString("curl -v -X GET 'http://localhost/'"));
}
}
\ No newline at end of file
|
Added correlation id to curl log
Fixes #<I>
|
zalando_logbook
|
train
|
c39211df29f94251895d38192bb53e17d621ac1d
|
diff --git a/samplify/test/imperial.py b/samplify/test/imperial.py
index <HASH>..<HASH> 100644
--- a/samplify/test/imperial.py
+++ b/samplify/test/imperial.py
@@ -1,8 +1,8 @@
import sys
import unittest
-from measurements import si
-from measurements import imperial
+from samplify import si
+from samplify import imperial
class ImperialTest(unittest.TestCase):
def setUp(self):
diff --git a/samplify/test/si.py b/samplify/test/si.py
index <HASH>..<HASH> 100644
--- a/samplify/test/si.py
+++ b/samplify/test/si.py
@@ -1,9 +1,9 @@
import unittest
-from measurements import *
-from measurements import si
-from measurements import imperial
-from measurements import energy
+from samplify import *
+from samplify import si
+from samplify import imperial
+from samplify import energy
class SITest(unittest.TestCase):
def setUp(self):
|
Point tests at samplify
|
BennettRand_Samplify
|
train
|
904d7dfd43188556b4d928d3f51400c7222807e9
|
diff --git a/lib/patron/request.rb b/lib/patron/request.rb
index <HASH>..<HASH> 100644
--- a/lib/patron/request.rb
+++ b/lib/patron/request.rb
@@ -23,6 +23,8 @@
##
## -------------------------------------------------------------------
+require 'cgi'
+
module Patron
# Represents the information necessary for an HTTP request.
@@ -144,6 +146,7 @@ module Patron
recursive = Proc.new do |h, prefix|
h.each_pair do |k,v|
key = prefix == '' ? k : "#{prefix}[#{k}]"
+ @action == :post ? v = CGI::escape(v.to_s) : v
v.is_a?(Hash) ? recursive.call(v, key) : pairs << "#{key}=#{v}"
end
end
|
Added URL encoding when an action is a POST
|
toland_patron
|
train
|
6a65bf6b30b61f7d85876e3954f4b2063f725dd0
|
diff --git a/src/Console.php b/src/Console.php
index <HASH>..<HASH> 100644
--- a/src/Console.php
+++ b/src/Console.php
@@ -7,10 +7,11 @@ namespace IrfanTOOR;
*/
class Console
{
+ protected static $is_terminal;
protected static $supported = false;
/** @var array */
- public static $styles = array(
+ protected static $styles = array(
'none' => null,
'bold' => '1',
'dark' => '2',
@@ -60,7 +61,7 @@ class Console
);
/** @var array */
- public static $theme = [
+ protected static $theme = [
'info' => ['cyan'],
'error' => ['bg_red', 'bold'],
'warning' => ['bg_light_yellow', 'red', 'bold'],
@@ -74,8 +75,9 @@ class Console
/**
* Constructs a console
*/
- public function __construct($theme = [])
+ function __construct($theme = [])
{
+ self::$is_terminal = PHP_SAPI === 'cli';
self::$supported = stream_isatty(STDOUT);
self::$theme = array_merge(
@@ -94,7 +96,7 @@ class Console
*/
function applyStyle($text, $styles = []): string
{
- if (!self::$supported)
+ if (!self::$is_terminal || !self::$supported)
return $text;
if (is_string($styles))
@@ -103,13 +105,14 @@ class Console
}
$output = $text;
+
foreach ($styles as $style) {
if (isset(self::$theme[$style])) {
$output = $this->applyStyle($output, self::$theme[$style]);
} else {
if (isset(self::$styles[$style])) {
- $pre = $this->escSequence(self::$styles[$style]);
- $post = $this->escSequence(0);
+ $pre = $this->_escSequence(self::$styles[$style]);
+ $post = $this->_escSequence(0);
} else {
$pre = $post = '';
}
@@ -127,7 +130,7 @@ class Console
* @param string|int $value
* @return string
*/
- private function escSequence($value): string
+ private function _escSequence($value): string
{
return "\033[{$value}m";
}
@@ -140,9 +143,12 @@ class Console
*
* @return the line read from console
*/
- public function read($prompt, $style = ''): string
+ function read($prompt, $style = ''): string
{
- $this->write($prompt . ' ', $style);
+ $this->write($prompt, $style);
+
+ if (!self::$is_terminal) return "";
+
$stdin = fopen('php://stdin', 'r');
$str = fgets($stdin, 4096);
fclose($stdin);
@@ -155,7 +161,7 @@ class Console
* @param mixed $text can be string or an array of strings
* @param mixed $style can be null, a style code as string or an array of strings.
*/
- public function write($text = '', $style = 'none'): void
+ function write($text = '', $style = 'none'): void
{
if (is_array($text)) {
$max = 0;
@@ -187,7 +193,7 @@ class Console
* @param mixed $text can be string or an array of strings
* @param mixed $style can be null, a style code as string or an array of strings.
*/
- public function writeln($text = '', $style = 'none'): void
+ function writeln($text = '', $style = 'none'): void
{
echo $this->write($text, $style);
echo PHP_EOL;
diff --git a/tests/ConsoleTest.php b/tests/ConsoleTest.php
index <HASH>..<HASH> 100644
--- a/tests/ConsoleTest.php
+++ b/tests/ConsoleTest.php
@@ -3,22 +3,39 @@
use IrfanTOOR\Console;
use IrfanTOOR\Test;
-class ConsoleTest extends Test
+class MockConsole extends Console
{
+ static function getStyles()
+ {
+ return self::$styles;
+ }
+}
+class ConsoleTest extends Test
+{
protected $console;
- public function setup(): void
+ function setup()
{
$this->console = new Console;
}
- public function testConsoleClassExists(): void
+ function testConsoleClassExists()
{
- $this->assertInstanceOf('IrfanTOOR\Console', $this->console);
+ $this->assertInstanceOf(Console::class, $this->console);
}
- public function testConsoleWrite(): void
+ function testConsoleCanRead()
+ {
+ $this->assertTrue(method_exists($this->console, 'read'));
+ ob_start();
+ $input = $this->console->read("Hello World!");
+ $output = ob_get_clean();
+ $this->assertEquals("Hello World!", $output);
+ $this->assertEquals("", $input);
+ }
+
+ function testConsoleCanWrite()
{
$c = $this->console;
@@ -35,12 +52,12 @@ class ConsoleTest extends Test
$this->assertEquals('Hello World!' . PHP_EOL, $output);
}
- public function testConsoleWriteWithStyle(): void
+ function testConsoleCanWriteWithStyle()
{
- $c = $this->console;
+ $c = new MockConsole();
$supported = stream_isatty(STDOUT);
- foreach ($c::$styles as $k => $v) {
+ foreach ($c::getStyles() as $k => $v) {
$txt = 'Hello World!';
if ($v && $supported) {
|
style is not applied if it is not a terminal
|
irfantoor_console
|
train
|
4d48a17138ebf8c65bf8dd88116e861b2f4f2184
|
diff --git a/go/vt/wrangler/testlib/reparent_external_test.go b/go/vt/wrangler/testlib/reparent_external_test.go
index <HASH>..<HASH> 100644
--- a/go/vt/wrangler/testlib/reparent_external_test.go
+++ b/go/vt/wrangler/testlib/reparent_external_test.go
@@ -54,6 +54,12 @@ func TestTabletExternallyReparented(t *testing.T) {
goodSlave2 := NewFakeTablet(t, wr, "cell2", 3, topodatapb.TabletType_REPLICA, nil)
badSlave := NewFakeTablet(t, wr, "cell1", 4, topodatapb.TabletType_REPLICA, nil)
+ // Build keyspace graph
+ err := topotools.RebuildKeyspace(context.Background(), logutil.NewConsoleLogger(), ts, oldMaster.Tablet.Keyspace, []string{"cell1", "cell2"})
+ if err != nil {
+ t.Fatalf("RebuildKeyspaceLocked failed: %v", err)
+ }
+
// Slightly unrelated test: make sure we can find the tablets
// even with a datacenter being down.
tabletMap, err := ts.GetTabletMapForShardByCell(ctx, "test_keyspace", "0", []string{"cell1"})
@@ -80,9 +86,11 @@ func TestTabletExternallyReparented(t *testing.T) {
t.Fatalf("FindTabletByHostAndPort(master) worked in cell2: %v %v", err, master)
}
+ // Get tablet map for all cells. If there were to be failures talking to local cells, this will return the tablet map
+ // and forward a partial result error
tabletMap, err = ts.GetTabletMapForShard(ctx, "test_keyspace", "0")
- if !topo.IsErrType(err, topo.PartialResult) {
- t.Fatalf("GetTabletMapForShard should have returned ErrPartialResult but got: %v", err)
+ if err != nil {
+ t.Fatalf("GetTabletMapForShard should nil but got: %v", err)
}
master, err = topotools.FindTabletByHostAndPort(tabletMap, oldMaster.Tablet.Hostname, "vt", oldMaster.Tablet.PortMap["vt"])
if err != nil || !topoproto.TabletAliasEqual(master, oldMaster.Tablet.Alias) {
diff --git a/go/vt/wrangler/testlib/shard_test.go b/go/vt/wrangler/testlib/shard_test.go
index <HASH>..<HASH> 100644
--- a/go/vt/wrangler/testlib/shard_test.go
+++ b/go/vt/wrangler/testlib/shard_test.go
@@ -25,6 +25,7 @@ import (
"vitess.io/vitess/go/vt/logutil"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/memorytopo"
+ "vitess.io/vitess/go/vt/topotools"
"vitess.io/vitess/go/vt/vttablet/tmclient"
"vitess.io/vitess/go/vt/wrangler"
@@ -43,6 +44,12 @@ func TestDeleteShardCleanup(t *testing.T) {
slave := NewFakeTablet(t, wr, "cell1", 1, topodatapb.TabletType_REPLICA, nil)
remoteSlave := NewFakeTablet(t, wr, "cell2", 2, topodatapb.TabletType_REPLICA, nil)
+ // Build keyspace graph
+ err := topotools.RebuildKeyspace(context.Background(), logutil.NewConsoleLogger(), ts, master.Tablet.Keyspace, []string{"cell1", "cell2"})
+ if err != nil {
+ t.Fatalf("RebuildKeyspaceLocked failed: %v", err)
+ }
+
// Delete the ShardReplication record in cell2
if err := ts.DeleteShardReplication(ctx, "cell2", remoteSlave.Tablet.Keyspace, remoteSlave.Tablet.Shard); err != nil {
t.Fatalf("DeleteShardReplication failed: %v", err)
|
Fix wrangler tests. Mostly generate SrvKeyspace before running them
|
vitessio_vitess
|
train
|
e85a77d6d258a4a06303ebd554c23f183d26fbb9
|
diff --git a/src/main/java/com/frostwire/jlibtorrent/SessionManager.java b/src/main/java/com/frostwire/jlibtorrent/SessionManager.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/frostwire/jlibtorrent/SessionManager.java
+++ b/src/main/java/com/frostwire/jlibtorrent/SessionManager.java
@@ -1068,6 +1068,15 @@ public class SessionManager {
}
}
+ private void onListenFailed(ListenFailedAlert alert) {
+ LOG.error("onListenFailed(): iface= " + alert.listenInterface() +
+ ", address= " + alert.address() +
+ ", port= " + alert.port() +
+ ", socketType= " + alert.socketType() +
+ ", errorCode= " + alert.error());
+ LOG.error("onListenFailed(): error_message=" + alert.message());
+ }
+
private void toggleDht(boolean on) {
if (session == null || isDhtRunning() == on) {
return;
@@ -1169,6 +1178,10 @@ public class SessionManager {
alert = Alerts.cast(a);
onListenSucceeded((ListenSucceededAlert) alert);
break;
+ case LISTEN_FAILED:
+ alert = Alerts.cast(a);
+ onListenFailed((ListenFailedAlert) alert);
+ break;
case EXTERNAL_IP:
alert = Alerts.cast(a);
onExternalIpAlert((ExternalIpAlert) alert);
|
SessionManager::onListenFailed alert logging (private)
|
frostwire_frostwire-jlibtorrent
|
train
|
869b07f75a000cc34762152ec7fee1ea7b0a8bc0
|
diff --git a/modules/pipefetchpage.py b/modules/pipefetchpage.py
index <HASH>..<HASH> 100644
--- a/modules/pipefetchpage.py
+++ b/modules/pipefetchpage.py
@@ -92,7 +92,7 @@ def pipe_fetchpage(context, _INPUT, conf, **kwargs):
print "--------------item data --------------------"
print res_item
print "--------------EOF item data ----------------"
- yield [{ "content" : res_item }]
+ yield { "content" : res_item }
except Exception, e:
if context.verbose:
diff --git a/modules/pipeloop.py b/modules/pipeloop.py
index <HASH>..<HASH> 100644
--- a/modules/pipeloop.py
+++ b/modules/pipeloop.py
@@ -62,13 +62,18 @@ def pipe_loop(context, _INPUT, conf, embed=None, **kwargs):
results.append(i)
else:
results = [i]
+ if results and mode == 'assign':
+ #this is a hack to make sure fetchpage works in an out of a loop while not disturbing strconcat in a loop etc.
+ #(goes with the comment below about checking the delivery capability of the source)
+ if len(results) == 1 and isinstance(results[0], dict):
+ results = [results]
except HTTPError: #todo any other errors we want to continue looping after?
if context.verbose:
print "Submodule gave HTTPError - continuing the loop"
continue
if mode == 'assign':
- if results and len(results) == 1:
+ if results and len(results) == 1: #note: i suspect this needs to be more discerning and only happen if the source can only ever deliver 1 result, e.g. strconcat vs. fetchpage
results = results[0]
util.set_value(item, assign_to, results)
yield item
diff --git a/test/testbasics.py b/test/testbasics.py
index <HASH>..<HASH> 100644
--- a/test/testbasics.py
+++ b/test/testbasics.py
@@ -272,9 +272,9 @@ class TestBasics(unittest.TestCase):
count += 1
if i == {'media:thumbnail': {'url': u'http://example.com/a.jpg'}, u'link': u'http://example.com/test.php?this=that', u'description': u'b', u'y:title': u'a', u'title': u'a'}:
match +=1
- if i == {u'newtitle': u'NEWTITLE', u'loop:itembuilder': {u'description': {u'content': u'DESCRIPTION'}, u'title': u'NEWTITLE'}, u'title': u'TITLE1'}:
+ if i == {u'newtitle': u'NEWTITLE', u'loop:itembuilder': [{u'description': {u'content': u'DESCRIPTION'}, u'title': u'NEWTITLE'}], u'title': u'TITLE1'}:
match +=1
- if i == {u'newtitle': u'NEWTITLE', u'loop:itembuilder': {u'description': {u'content': u'DESCRIPTION'}, u'title': u'NEWTITLE'}, u'title': u'TITLE2'}:
+ if i == {u'newtitle': u'NEWTITLE', u'loop:itembuilder': [{u'description': {u'content': u'DESCRIPTION'}, u'title': u'NEWTITLE'}], u'title': u'TITLE2'}:
match +=1
self.assertTrue(count == 3)
|
Fix fetchpage to work in and out of loops
|
ggaughan_pipe2py
|
train
|
66872da552dec5d855f22a90d8c1657bec73a279
|
diff --git a/Tests/Functional/Entity/JMSUser.php b/Tests/Functional/Entity/JMSUser.php
index <HASH>..<HASH> 100644
--- a/Tests/Functional/Entity/JMSUser.php
+++ b/Tests/Functional/Entity/JMSUser.php
@@ -89,6 +89,11 @@ class JMSUser
private $bestFriend;
/**
+ * Whether this user is enabled or disabled.
+ *
+ * Only enabled users may be used in actions.
+ *
+ * @var string
* @Serializer\Type("string")
* @Serializer\Expose
*
diff --git a/Tests/Functional/JMSFunctionalTest.php b/Tests/Functional/JMSFunctionalTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Functional/JMSFunctionalTest.php
+++ b/Tests/Functional/JMSFunctionalTest.php
@@ -55,6 +55,8 @@ class JMSFunctionalTest extends WebTestCase
],
'status' => [
'type' => 'string',
+ 'title' => 'Whether this user is enabled or disabled.',
+ 'description' => 'Only enabled users may be used in actions.',
'enum' => ['disabled', 'enabled'],
],
],
|
add functional test for docblock model describer
|
nelmio_NelmioApiDocBundle
|
train
|
9eeed7837cc668f18589dc19550bcc57eb76a2a1
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -85,9 +85,9 @@ In Unix-like environment, the cli utility can also be piped into :
- name: A name for the model, not directly used.
- n: The order of the model (1: unigram, 2: bigram, 3: trigram, etc.). Default to 3.
- - minLength: The minimum length of the word included in the generation of the model. Default to 4.
+ - minLength: The minimum length of the word considered in the generation of the model. Default to 4.
- unique: Usually if multiple instances of a specific word is included in the source file, the model will be skewed toward generating similar words. Setting this option ensure this doesn't happen.
- - compress: Reduce the size of the model file, making it less readable and slightly less precise.
+ - compress: Reduce the size of the model file, making it less readable and slightly less accurate.
- excludeOriginal: The model will include the full list of the words included in the source file so that the generation can blacklist them.
- filter: Character filtering option, either one the filters listed below or a regex. Default to 'extended'.
@@ -118,6 +118,49 @@ With a custom regular expressions as filter (all characters out of the A-U range
ngram-word-generator source.txt --n=3 --minLength=4 --filter=/[^a-u]+/ig --compress --unique --excludeOriginal > model.json
```
+## Model generation without the CLI utility
+
+The model generation being a costly process, it is recommended to use the cli utility described above.
+
+```js
+var generateModel = require('ngram-word-generator/model-generation'); // specific entry point
+
+var textData = ...; // retrieve a large text as a single string somehow
+
+var ngramModel = generateModel(textData, {
+ name: 'My n-gram model',
+ filter: 'noSymbols',
+ n: 3,
+ minLength: 4,
+ unique: false,
+ excludeOriginal: true,
+ compress: true
+});
+
+console.log(ngramModel);
+
+// generate a word with the model
+
+var makeGenerator = require('ngram-word-generator');
+
+var generator = makeGenerator(ngramModel);
+
+console.log(generator(10));
+```
+
+### generateModel(textData, options)
+
+Generate an n-gram model based on a given text.
+
+ - *textData:* Text corpus as a single, preferably large, string.
+ - *options.name:* Name of the n-gram model, not directly used.
+ - *options.n:* Order of the model (1: unigram, 2: bigram, 3: trigram, ...). Default to 3.
+ - *options.minLength:* Minimum length of the word considered in the generation of the model. Default to options.n. Must be larger than or equal to options.n, an error will be thrown otherwise.
+ - *options.unique:* Avoid skewing the generation toward the most repeated words in the text corpus. Default to false.
+ - *options.compress:* Reduce the size of the model file, making it slightly less accurate. Default to false.
+ - *options.excludeOriginal:* Include the full list of the words considered in the generation so they can be blacklisted. Default to false.
+ - *options.filter:* Character filtering option, either one the existing filters (see CLI) or a RegExp object. Default to 'extended'.
+
## Changemap
### [1.1.0](https://github.com/kchapelier/ngram-word-generator/tree/1.1.0) (2016-08-19) :
@@ -132,7 +175,7 @@ ngram-word-generator source.txt --n=3 --minLength=4 --filter=/[^a-u]+/ig --compr
## Roadmap
- - Make it possible (and document how) to use the model generation outside of the cli utility
+ - Fix issue where a model with exclude could lead to an infinite loop with a text corpus of poor quality
- Make an online tool to generate the n-gram models
## License
diff --git a/bin/cli.js b/bin/cli.js
index <HASH>..<HASH> 100755
--- a/bin/cli.js
+++ b/bin/cli.js
@@ -25,7 +25,7 @@ stream.on('readable', function() {
chunk = stream.read();
if (chunk !== null) {
- data+= chunk.toString().toLowerCase();
+ data+= chunk.toString();
}
});
diff --git a/src/ngram-process.js b/src/ngram-process.js
index <HASH>..<HASH> 100644
--- a/src/ngram-process.js
+++ b/src/ngram-process.js
@@ -151,6 +151,8 @@ var stringToRegExp = function stringToRegExp (string) {
};
var preProcessString = function preProcessString (string, config) {
+ string = string.toLowerCase();
+
if (config.filter) {
var filterRegex = null;
@@ -214,7 +216,6 @@ module.exports = function generateModel (data, config) {
var resultConfig = {
name: config.name,
- type: config.type,
n: config.n,
minLength: config.minLength,
unique: config.unique ? 1 : 0,
|
document the model generation method outside the cli utility
|
kchapelier_ngram-word-generator
|
train
|
cad10ed75293571facb7273b7fa86739b0b72a51
|
diff --git a/syn/tree/b/node.py b/syn/tree/b/node.py
index <HASH>..<HASH> 100644
--- a/syn/tree/b/node.py
+++ b/syn/tree/b/node.py
@@ -93,8 +93,12 @@ class Node(ListWrapper):
def parent(self):
return self._parent
- def children(self):
- for c in self._children:
+ def children(self, reverse=False):
+ cs = self._children
+ if reverse:
+ cs = reversed(cs)
+
+ for c in cs:
yield c
def id(self):
@@ -140,16 +144,22 @@ class Node(ListWrapper):
nodes.extend(c.collect_by_type(typ))
return nodes
- def depth_first(self, func=identity, filt=true, include_toplevel=True,
- top_level=True):
+ def depth_first(self, func=identity, filt=true, reverse=False,
+ include_toplevel=True, top_level=True):
if implies(top_level, include_toplevel):
if filt(self):
- yield func(self)
+ res = func(self)
+ if not reverse:
+ yield res
- for c in self._children:
- for x in c.depth_first(func, filt, include_toplevel, False):
+ for c in self.children(reverse=reverse):
+ for x in c.depth_first(func, filt, reverse,
+ include_toplevel, False):
yield x
+ if reverse:
+ yield res
+
def rootward(self, func=identity, filt=true, include_toplevel=True,
top_level=True):
if implies(top_level, include_toplevel):
@@ -188,17 +198,17 @@ class Node(ListWrapper):
def preceding(self):
pass
- def siblings(self, preceding=False, following=False):
+ def siblings(self, preceding=False, following=False, axis=False):
if self._parent is not None:
idx = self._parent._children.index(self)
for k, c in enumerate(self._parent.children()):
if c is not self:
- if preceding:
- if k < idx:
- yield c
- elif following:
+ if following:
if k > idx:
yield c
+ elif preceding:
+ if k < idx:
+ yield c
else:
yield c
diff --git a/syn/tree/b/tests/test_node.py b/syn/tree/b/tests/test_node.py
index <HASH>..<HASH> 100644
--- a/syn/tree/b/tests/test_node.py
+++ b/syn/tree/b/tests/test_node.py
@@ -136,6 +136,7 @@ def treenode_tst_3(cls):
filt=lambda n: n._id <= 3)) == [3, 1]
assert list(n1.depth_first()) == [n1, n2, n3, n4, n5]
+ assert list(n1.depth_first(reverse=True)) == [n5, n4, n3, n2, n1]
assert list(n1.depth_first(func=attrgetter('_id'),
filt=lambda n: n._id % 2 == 0)) == [2, 4]
@@ -145,6 +146,9 @@ def treenode_tst_3(cls):
assert n3._parent is n1
assert n4._parent is n3
assert n5._parent is n1
+
+ assert list(n1.children()) == [n2, n3, n5]
+ assert list(n1.children(reverse=True)) == [n5, n3, n2]
assert list(n5.siblings()) == [n2, n3]
assert list(n4.siblings()) == []
|
Adding reverisble depth-first iteration to Node
|
mbodenhamer_syn
|
train
|
a22fc79d49b4537461dc6c0f4f5651d9dbf33b34
|
diff --git a/nodeconductor/monitoring/zabbix/db_client.py b/nodeconductor/monitoring/zabbix/db_client.py
index <HASH>..<HASH> 100644
--- a/nodeconductor/monitoring/zabbix/db_client.py
+++ b/nodeconductor/monitoring/zabbix/db_client.py
@@ -418,4 +418,4 @@ class ZabbixDBClient(object):
return 'OK' if value == 1 else 'NOT OK'
else:
logger.warn('Cannot retrieve installation state of instance %s. Host does not exist.', instance)
- return 'NO DATA'
\ No newline at end of file
+ return 'NO DATA'
|
Add new line to end of file
- itacloud-<I>
|
opennode_waldur-core
|
train
|
c5cba9c08b4595dc8c7f99e1cfcef823b605bd36
|
diff --git a/evcache-client/src/main/java/com/netflix/evcache/EVCacheImpl.java b/evcache-client/src/main/java/com/netflix/evcache/EVCacheImpl.java
index <HASH>..<HASH> 100644
--- a/evcache-client/src/main/java/com/netflix/evcache/EVCacheImpl.java
+++ b/evcache-client/src/main/java/com/netflix/evcache/EVCacheImpl.java
@@ -89,7 +89,7 @@ final public class EVCacheImpl implements EVCache {
private final EVCacheClientPoolManager _poolManager;
private DistributionSummary setTTLSummary, replaceTTLSummary, touchTTLSummary, setDataSizeSummary, replaceDataSizeSummary, appendDataSizeSummary;
private Counter touchCounter;
- private final ChainedDynamicProperty.BooleanProperty _eventsUsingLatchFP;
+ private final ChainedDynamicProperty.BooleanProperty _eventsUsingLatchFP, autoHashKeys;
EVCacheImpl(String appName, String cacheName, int timeToLive, Transcoder<?> transcoder, boolean enableZoneFallback,
boolean throwException, EVCacheClientPoolManager poolManager) {
@@ -114,7 +114,8 @@ final public class EVCacheImpl implements EVCache {
_eventsUsingLatchFP = config.getChainedBooleanProperty(_appName + ".events.using.latch", "evcache.events.using.latch", Boolean.FALSE, null);
this.hashKey = config.getDynamicBooleanProperty(appName + ".hash.key", Boolean.FALSE);
- this.hashingAlgo = config.getDynamicStringProperty(appName + ".hash.algo", "MD5");
+ this.hashingAlgo = config.getDynamicStringProperty(appName + ".hash.algo", "siphash24");
+ this.autoHashKeys = config.getChainedBooleanProperty(_appName + ".auto.hash.keys", "evcache.auto.hash.keys", Boolean.FALSE, null);
this.evcacheValueTranscoder = new EVCacheTranscoder();
evcacheValueTranscoder.setCompressionThreshold(Integer.MAX_VALUE);
@@ -124,7 +125,7 @@ final public class EVCacheImpl implements EVCache {
private String getCanonicalizedKey(String key) {
if(key == null || key.length() == 0) throw new NullPointerException("Key cannot be null or empty");
int keyLength = key.length();
- final String cKey;
+ String cKey;
if (this._cacheName == null) {
cKey = key;
} else {
@@ -132,10 +133,6 @@ final public class EVCacheImpl implements EVCache {
cKey = new StringBuilder(keyLength).append(_cacheName).append(':').append(key).toString();
}
- if (keyLength > MemcachedClientIF.MAX_KEY_LENGTH) {
- throw new IllegalArgumentException("Key is too long (maxlen = " + MemcachedClientIF.MAX_KEY_LENGTH + ')');
- }
-
for(int i = 0; i < cKey.length(); i++) {
if(Character.isWhitespace(cKey.charAt(i))){
throw new IllegalArgumentException("Key contains invalid characters: ``" + key + "''");
@@ -143,10 +140,17 @@ final public class EVCacheImpl implements EVCache {
}
if(hashKey.get()) {
- return KeyHasher.getHashedKey(cKey, hashingAlgo.get());
- } else {
- return cKey;
+ cKey = KeyHasher.getHashedKey(cKey, hashingAlgo.get());
+ } else if(autoHashKeys.get() && cKey.length() > MemcachedClientIF.MAX_KEY_LENGTH) {
+ cKey = KeyHasher.getHashedKey(cKey, hashingAlgo.get());
}
+
+ if (cKey.length() > MemcachedClientIF.MAX_KEY_LENGTH) {
+ throw new IllegalArgumentException("Key is too long (maxlen = " + MemcachedClientIF.MAX_KEY_LENGTH + ')');
+ }
+ if (log.isDebugEnabled() && shouldLog()) log.debug("Key : " + key + "; CanonicalizedKey : " + cKey);
+
+ return cKey;
}
private String getKey(String canonicalizedKey) {
|
Support for auto hashing of keys greater than <I> characters
|
Netflix_EVCache
|
train
|
3f68ce0fc5bed31026800be964721115484cd840
|
diff --git a/lib/ronin/platform/platform.rb b/lib/ronin/platform/platform.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/platform/platform.rb
+++ b/lib/ronin/platform/platform.rb
@@ -21,9 +21,9 @@
#++
#
-require 'ronin/platform/overlay'
+require 'ronin/platform/overlay_cache'
require 'ronin/platform/object_cache'
-require 'ronin/platform/extension'
+require 'ronin/platform/extension_cache'
module Ronin
module Platform
@@ -123,10 +123,18 @@ module Ronin
end
#
- # See Extension.names.
+ # Returns the names of all extensions within the overlay cache.
#
def Platform.extension_names
- Extension.names
+ names = []
+
+ Platform.overlays.each do |overlay|
+ overlay.extensions.each do |name|
+ names << name unless names.include?(name)
+ end
+ end
+
+ return names
end
#
|
Rewrote Platform.extension_names.
|
ronin-ruby_ronin
|
train
|
17786d00542f9dbe78b39d761023092421c4e36d
|
diff --git a/src/Plugin.php b/src/Plugin.php
index <HASH>..<HASH> 100644
--- a/src/Plugin.php
+++ b/src/Plugin.php
@@ -76,7 +76,7 @@ final class Plugin implements PluginInterface, EventSubscriberInterface
return;
}
- $synchronizersMaster = new SynchronizersMaster(
+ $synchronizersMaster = new SynchronizersManager(
$synchronizerConfiguration, $eventType, $event->getComposer()->getConfig()->get('vendor-dir')
);
|
- SynchronizersMaster renamed to SynchronizersManager
|
composer-synchronizer_composer-synchronizer
|
train
|
640ce5e61d5f11cc47c2f425b4b224dc538a06cd
|
diff --git a/lib/rbUtil.js b/lib/rbUtil.js
index <HASH>..<HASH> 100644
--- a/lib/rbUtil.js
+++ b/lib/rbUtil.js
@@ -9,7 +9,7 @@ var P = require('bluebird');
var util = require('util');
var url = require('url');
var Busboy = require('busboy');
-var uuid = require('cassandra-uuid');
+var uuid = require('cassandra-uuid').TimeUuid;
var rbUtil = {};
@@ -108,7 +108,7 @@ rbUtil.tidFromDate = function tidFromDate(date) {
throw new Error('Invalid date');
}
// Create a new, deterministic timestamp
- return uuid.TimeUuid.fromDate(date,
+ return uuid.fromDate(date,
0,
new Buffer([0x01, 0x23, 0x45, 0x67, 0x89, 0xab]),
new Buffer([0x12, 0x34])).toString();
@@ -118,14 +118,14 @@ rbUtil.tidFromDate = function tidFromDate(date) {
* Check if a string is a valid timeuuid
*/
rbUtil.isTimeUUID = function (s) {
- return uuid.TimeUuid.test(s);
+ return uuid.test(s);
};
/**
* Generates a new request ID
*/
rbUtil.generateRequestId = function() {
- return uuid.Uuid.random().toRawString();
+ return uuid.now().toString();
};
/*
|
Request id in proper form and using the time uuid
|
wikimedia_restbase
|
train
|
58f0f5a495e8721e61fcfaa4f241616b88c36781
|
diff --git a/Controller/QuestionController.php b/Controller/QuestionController.php
index <HASH>..<HASH> 100755
--- a/Controller/QuestionController.php
+++ b/Controller/QuestionController.php
@@ -989,6 +989,7 @@ class QuestionController extends Controller
*/
public function manageDocAction()
{
+ $allowToDel = array();
$user = $this->container->get('security.context')->getToken()->getUser();
$request = $this->get('request');
|
[ExoBundle] Correction Bug for the Manage Document button (#<I>)
|
claroline_Distribution
|
train
|
ac020b3f06d079f74d5ffa195b329413c9ddb428
|
diff --git a/lib/meurio_ui/view_helpers.rb b/lib/meurio_ui/view_helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/meurio_ui/view_helpers.rb
+++ b/lib/meurio_ui/view_helpers.rb
@@ -8,7 +8,7 @@ module MeurioUi
end
def application_name app
- return "Meu Rio" if app == :mr20
+ return "Minhas Cidades" if app == :mr20
return "Panela de Pressão" if app == :pdp
return "Verão do Saneamento" if app == :vds
return "Imagine" if app == :imagine
@@ -17,7 +17,7 @@ module MeurioUi
return "De Guarda" if app == :deguarda
return "Multitude" if app == :multitude
end
-
+
def meurio_ui_assets
return nil if request.protocol == 'https://'
content_tag :link, nil, rel: "stylesheet", href: "http://i.icomoon.io/public/b6dafa29d0/MeuRio/style.css"
|
[#<I>] change copy
|
nossas_meurio_ui
|
train
|
c1e89aa7cace980432fd23c651673fb5f2019c31
|
diff --git a/OpenSSL/__init__.py b/OpenSSL/__init__.py
index <HASH>..<HASH> 100644
--- a/OpenSSL/__init__.py
+++ b/OpenSSL/__init__.py
@@ -16,7 +16,7 @@ from OpenSSL import crypto
sys.setdlopenflags(orig)
del sys, orig
-from OpenSSL import rand, SSL, tsafe
+from OpenSSL import rand, SSL
from OpenSSL.version import __version__
__all__ = [
|
skip tsafe for the time being
|
pyca_pyopenssl
|
train
|
cbbca354e118140b44995bc9b119a3da28fc0edb
|
diff --git a/src/Database/CollectionDelegator.php b/src/Database/CollectionDelegator.php
index <HASH>..<HASH> 100644
--- a/src/Database/CollectionDelegator.php
+++ b/src/Database/CollectionDelegator.php
@@ -1,8 +1,9 @@
<?php
namespace Hook\Database;
-use Hook\Model\App as App;
-use Hook\Model\Collection as Collection;
+use Hook\Model\App;
+use Hook\Model\Collection;
+use Hook\Exceptions\UnauthorizedException;
use ArrayIterator;
use IteratorAggregate;
@@ -55,6 +56,10 @@ class CollectionDelegator implements IteratorAggregate
$name = str_plural($name);
$is_collection = true;
+ if ($name == "modules") {
+ throw new UnauthorizedException("not_authorized");
+ }
+
$query = null;
if (isset(static::$custom_collections[$name])) {
$query = call_user_func(array(static::$custom_collections[$name], 'query'));
|
prevent 'modules' from being accessed as collections
|
doubleleft_hook
|
train
|
d324d4b7dbf77776f550787bd66122fe3e220f10
|
diff --git a/questionary/prompt.py b/questionary/prompt.py
index <HASH>..<HASH> 100644
--- a/questionary/prompt.py
+++ b/questionary/prompt.py
@@ -25,9 +25,10 @@ def prompt(
if isinstance(questions, dict):
questions = [questions]
- answers = answers or {}
+ answers = dict(answers or {})
for question_config in questions:
+ question_config = dict(question_config)
# import the question
if "type" not in question_config:
raise PromptParameterException("type")
|
Avoid modifying input parameters
As dicts are mutable, it's unexpected that they get modified after calling this function. This should fix the type errors too.
|
tmbo_questionary
|
train
|
73a89bf9e53c0f7f00f193e1b1bb195a71ab761f
|
diff --git a/src/server/optimizing-compiler/modules.js b/src/server/optimizing-compiler/modules.js
index <HASH>..<HASH> 100644
--- a/src/server/optimizing-compiler/modules.js
+++ b/src/server/optimizing-compiler/modules.js
@@ -77,7 +77,7 @@ function genAttrSegment (name: string, value: string): StringSegment {
? ` ${name}="${name}"`
: value === '""'
? ` ${name}`
- : ` ${name}=${value}`
+ : ` ${name}="${JSON.parse(value)}"`
}
} else {
return {
|
fix(ssr): fix double escaping of ssrNode attribute values (#<I>)
This fixes a double escaping of attribute values in the SSR optimizing
compiler by unescaping the value in `genAttrSegment` because literal
attribute values get escaped early during `processAttrs` before it is
known, if this attribute will be optimized to an _ssrNode string template,
which is escaped as well, causing the double escape.
fix #<I>
|
kaola-fed_megalo
|
train
|
8c620564ab9766033a886aca12e966df1205075b
|
diff --git a/src/Comparator/BackwardsCompatibility/ClassBased/MethodRemoved.php b/src/Comparator/BackwardsCompatibility/ClassBased/MethodRemoved.php
index <HASH>..<HASH> 100644
--- a/src/Comparator/BackwardsCompatibility/ClassBased/MethodRemoved.php
+++ b/src/Comparator/BackwardsCompatibility/ClassBased/MethodRemoved.php
@@ -9,6 +9,7 @@ use Roave\ApiCompare\Changes;
use Roave\ApiCompare\Formatter\ReflectionFunctionAbstractName;
use Roave\BetterReflection\Reflection\ReflectionClass;
use Roave\BetterReflection\Reflection\ReflectionMethod;
+use const CASE_UPPER;
use function array_change_key_case;
use function array_combine;
use function array_diff_key;
@@ -16,7 +17,6 @@ use function array_filter;
use function array_map;
use function array_values;
use function sprintf;
-use const CASE_UPPER;
final class MethodRemoved implements ClassBased
{
|
#<I> imported constants are before imported functions
|
Roave_BackwardCompatibilityCheck
|
train
|
07c834ea3e39f7f5e4c55fea09b208d0164c2901
|
diff --git a/test/test_max_staleness.py b/test/test_max_staleness.py
index <HASH>..<HASH> 100644
--- a/test/test_max_staleness.py
+++ b/test/test_max_staleness.py
@@ -122,15 +122,21 @@ class TestMaxStaleness(unittest.TestCase):
# From max-staleness-tests.rst, "Parse lastWriteDate".
client = rs_or_single_client(heartbeatFrequencyMS=500)
client.pymongo_test.test.insert_one({})
- time.sleep(2)
+ # Wait for the server description to be updated.
+ time.sleep(1)
server = client._topology.select_server(writable_server_selector)
- last_write = server.description.last_write_date
- self.assertTrue(last_write)
+ first = server.description.last_write_date
+ self.assertTrue(first)
+ # The first last_write_date may correspond to a internal server write,
+ # sleep so that the next write does not occur within the same second.
+ time.sleep(1)
client.pymongo_test.test.insert_one({})
- time.sleep(2)
+ # Wait for the server description to be updated.
+ time.sleep(1)
server = client._topology.select_server(writable_server_selector)
- self.assertGreater(server.description.last_write_date, last_write)
- self.assertLess(server.description.last_write_date, last_write + 10)
+ second = server.description.last_write_date
+ self.assertGreater(second, first)
+ self.assertLess(second, first + 10)
@client_context.require_version_max(3, 3)
def test_last_write_date_absent(self):
|
PYTHON-<I> Fix race in test_last_write_date
|
mongodb_mongo-python-driver
|
train
|
865aed07d83cebe61f60ea760ff40f1724d2e726
|
diff --git a/handshake/crypto_setup_client.go b/handshake/crypto_setup_client.go
index <HASH>..<HASH> 100644
--- a/handshake/crypto_setup_client.go
+++ b/handshake/crypto_setup_client.go
@@ -146,7 +146,12 @@ func (h *cryptoSetupClient) handleREJMessage(cryptoData map[Tag][]byte) error {
if crt, ok := cryptoData[TagCERT]; ok {
err := h.certManager.SetData(crt)
if err != nil {
- return err
+ return qerr.Error(qerr.InvalidCryptoMessageParameter, "Certificate data invalid")
+ }
+
+ err = h.certManager.Verify(h.hostname)
+ if err != nil {
+ return qerr.ProofInvalid
}
}
diff --git a/handshake/crypto_setup_client_test.go b/handshake/crypto_setup_client_test.go
index <HASH>..<HASH> 100644
--- a/handshake/crypto_setup_client_test.go
+++ b/handshake/crypto_setup_client_test.go
@@ -44,6 +44,7 @@ type mockCertManager struct {
setDataCalledWith []byte
leafCert []byte
+ setDataError error
verifyServerProofError error
verifyServerProofValue bool
@@ -52,7 +53,7 @@ type mockCertManager struct {
func (m *mockCertManager) SetData(data []byte) error {
m.setDataCalledWith = data
- return nil
+ return m.setDataError
}
func (m *mockCertManager) GetLeafCert() []byte {
@@ -154,6 +155,20 @@ var _ = Describe("Crypto setup", func() {
Expect(certManager.setDataCalledWith).To(Equal(tagMap[TagCERT]))
})
+ It("returns an InvalidCryptoMessageParameter error if it can't parse the cert chain", func() {
+ tagMap[TagCERT] = []byte("cert")
+ certManager.setDataError = errors.New("can't parse")
+ err := cs.handleREJMessage(tagMap)
+ Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "Certificate data invalid")))
+ })
+
+ It("returns a ProofInvalid error if the certificate chain is not valid", func() {
+ tagMap[TagCERT] = []byte("cert")
+ certManager.verifyError = errors.New("invalid")
+ err := cs.handleREJMessage(tagMap)
+ Expect(err).To(MatchError(qerr.ProofInvalid))
+ })
+
It("verifies the signature", func() {
certManager.verifyServerProofValue = true
certManager.verifyServerProofError = nil
|
verify certificate chain when receiving it, return correct errors
|
lucas-clemente_quic-go
|
train
|
fedd321ea6e9b907dec6b4fac6ba9f9e35db507f
|
diff --git a/libpebble2/communication/__init__.py b/libpebble2/communication/__init__.py
index <HASH>..<HASH> 100644
--- a/libpebble2/communication/__init__.py
+++ b/libpebble2/communication/__init__.py
@@ -111,8 +111,8 @@ class PebbleConnection(object):
while len(message) >= 4:
if self.log_protocol_level is not None:
logger.log(self.log_protocol_level, "<- %s", hexlify(message).decode())
- self.event_handler.broadcast_event("raw_inbound", message)
packet, length = PebblePacket.parse_message(message)
+ self.event_handler.broadcast_event("raw_inbound", message[:length])
if self.log_packet_level is not None:
logger.log(self.log_packet_level, "<- %s", packet)
message = message[length:]
|
Avoid include trailing bytes in raw_inbound event.
|
pebble_libpebble2
|
train
|
593da79f3a2e7ebba5a02fd312bdfb17053fd67b
|
diff --git a/httpcache4j-api/src/main/java/org/codehaus/httpcache4j/Status.java b/httpcache4j-api/src/main/java/org/codehaus/httpcache4j/Status.java
index <HASH>..<HASH> 100644
--- a/httpcache4j-api/src/main/java/org/codehaus/httpcache4j/Status.java
+++ b/httpcache4j-api/src/main/java/org/codehaus/httpcache4j/Status.java
@@ -18,7 +18,6 @@ package org.codehaus.httpcache4j;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Range;
import java.util.Collection;
import java.util.Map;
@@ -78,14 +77,16 @@ public final class Status implements Comparable<Status> {
CLIENT_ERROR(400, 499),
SERVER_ERROR(500, 599);
- private final Range<Integer> range;
+ private final int min;
+ private final int max;
private Category(int min, int max) {
- range = Range.closed(min, max);
+ this.min = min;
+ this.max = max;
}
public boolean contains(Status status) {
- return range.contains(status.getCode());
+ return status.getCode() >= min && status.getCode() <= max;
}
public static Category valueOf(Status status) {
diff --git a/httpcache4j-api/src/test/java/org/codehaus/httpcache4j/StatusTest.java b/httpcache4j-api/src/test/java/org/codehaus/httpcache4j/StatusTest.java
index <HASH>..<HASH> 100644
--- a/httpcache4j-api/src/test/java/org/codehaus/httpcache4j/StatusTest.java
+++ b/httpcache4j-api/src/test/java/org/codehaus/httpcache4j/StatusTest.java
@@ -1,6 +1,6 @@
package org.codehaus.httpcache4j;
-import junit.framework.Assert;
+import org.junit.Assert;
import org.junit.Test;
/**
|
Make it possible to use lower version of guava.
|
httpcache4j_httpcache4j
|
train
|
8a4ecd1fc5b2d32de527b3d2f635e57a66fd6c96
|
diff --git a/public/js/core.searchform.js b/public/js/core.searchform.js
index <HASH>..<HASH> 100644
--- a/public/js/core.searchform.js
+++ b/public/js/core.searchform.js
@@ -15,13 +15,15 @@
function resetSearchForm(event)
{
var $form = $(event.target);
- win.setTimeout(function() { loadPaginator($form); $form.find('select').change(); }, 1);
+ win.setTimeout(function() { loadPaginator($form); $form.find('select').trigger('change', [ true ]); }, 1);
}
- function submitSearchForm(event)
+ function submitSearchForm(event, isSelect2change)
{
- var $form = $(event.target);
- loadPaginator($form);
+ if (!isSelect2change) {
+ var $form = $(event.target);
+ loadPaginator($form);
+ }
return false;
}
@@ -63,12 +65,17 @@
if (searchParams) {
for (var key in searchParams) {
- $form.find('[name="' + key + '"]').val(searchParams[key]);
+ if (searchParams.hasOwnProperty(key)) {
+ $form.find('[name="' + key + '"]').val(searchParams[key]);
+ }
}
+ $form.find('select').trigger('change', [ true ]);
}
$form.on('reset.yk.core.search-form', resetSearchForm)
- .on('submit.yk.core.search-form', submitSearchForm);
+ .on('submit.yk.core.search-form', submitSearchForm)
+ .on('change.yk.core.search-form', '[data-submit-on-change="true"]', submitSearchForm)
+ .on('click.yk.core.search-form', '[data-submit-on-click="true"]', submitSearchForm);
});
};
|
[Jobs,Core] Improves SearchForm of the job list in the admin section.
* Initial values of select elements are now correctly rendered.
* Select and button elements can now be set to automatically trigger form submit.
|
yawik_core
|
train
|
11a73ead941a2069fd6d2295fcb6b1909f6f5e02
|
diff --git a/Core/Config.php b/Core/Config.php
index <HASH>..<HASH> 100644
--- a/Core/Config.php
+++ b/Core/Config.php
@@ -29,6 +29,9 @@ class Config {
} else if ($number != 0 && isset($value[$name])) {
$value = $value[$name];
+ } else {
+
+ return false;
}
}
|
return false when config key does not exist
|
prototypemvc_prototypemvc
|
train
|
2a23bef575a11dd408ac0a7de95a3cc3bd4ad6e4
|
diff --git a/spec/acts-as-messageable_spec.rb b/spec/acts-as-messageable_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/acts-as-messageable_spec.rb
+++ b/spec/acts-as-messageable_spec.rb
@@ -152,6 +152,12 @@ describe "ActsAsMessageable" do
@bob.messages.with_id(message_id).count.should == 1
end
+ it "finds proper message" do
+ message = send_message
+ message_id = message.id
+ @bob.messages.find(message_id) == message
+ end
+
it "message should have proper topic" do
send_message
@bob.messages.count.should == 1
|
Add spec for #find method [#<I>]
|
LTe_acts-as-messageable
|
train
|
cb330e3adbb8f3294d3f701c1f77ea80f5f79d08
|
diff --git a/flat/script/flat.editor.js b/flat/script/flat.editor.js
index <HASH>..<HASH> 100644
--- a/flat/script/flat.editor.js
+++ b/flat/script/flat.editor.js
@@ -1205,7 +1205,12 @@ function editor_loadmenus() {
editannotations[annotationtype + "/" + set] = true;
}
label = folia_label(annotationtype, set);
- menu.push([annotationtype, "<li id=\"annotationtypeedit_" +annotationtype+"_" + hash(set) + "\" class=\"on\"><a href=\"javascript:toggleannotationedit('" + annotationtype + "', '" + set + "')\">" + label + "<span class=\"setname\">" + set + "</span></a></li>"]);
+ var labelhtml = "<li id=\"annotationtypeedit_" +annotationtype+"_" + hash(set) + "\" class=\"on\"><a href=\"javascript:toggleannotationedit('" + annotationtype + "', '" + set + "')\">" + label;
+ if (set != "null") {
+ labelhtml += "<span class=\"setname\">" + set + "</span>";
+ }
+ labelhtml += "</a></li>";
+ menu.push([annotationtype, labelhtml]);
}
});
});
diff --git a/flat/script/flat.viewer.js b/flat/script/flat.viewer.js
index <HASH>..<HASH> 100644
--- a/flat/script/flat.viewer.js
+++ b/flat/script/flat.viewer.js
@@ -1209,7 +1209,12 @@ function viewer_loadmenus() {
state = "";
}
label = folia_label(annotationtype, set);
- viewmenu.push([annotationtype, "<li id=\"annotationtypeview_" +annotationtype+"_" + hash(set) + "\" " + state + "><a href=\"javascript:toggleannotationview('" + annotationtype + "', '" + set + "')\">" + label + "<span class=\"setname\">" + set + "</span></a></li>"]);
+ var labelhtml = "<li id=\"annotationtypeview_" +annotationtype+"_" + hash(set) + "\" " + state + "><a href=\"javascript:toggleannotationview('" + annotationtype + "', '" + set + "')\">" + label;
+ if (set != "null") {
+ labelhtml += "<span class=\"setname\">" + set + "</span>";
+ }
+ labelhtml += "</a></li>";
+ viewmenu.push([annotationtype, labelhtml]);
if (globannotationsorder.indexOf(annotationtype) != -1) {
if (('initialglobviewannotations' in configuration ) && ((configuration.initialglobviewannotations === true) || (configuration.initialglobviewannotations.indexOf(annotationtype + '/' + set) != -1) || (configuration.initialglobviewannotations.indexOf(annotationtype) != -1))) {
viewglobannotations[annotationtype + "/" + set] = true;
@@ -1217,11 +1222,21 @@ function viewer_loadmenus() {
} else {
state = "";
}
- globmenu.push([annotationtype, "<li id=\"globannotationtypeview_" +annotationtype+"_" + hash(set) + "\" " + state + "><a href=\"javascript:toggleglobannotationview('" + annotationtype + "', '" + set + "')\">" + label + "<span class=\"setname\">" + set + "</span></a></li>"]);
+ var glabelhtml = "<li id=\"globannotationtypeview_" +annotationtype+"_" + hash(set) + "\" " + state + "><a href=\"javascript:toggleglobannotationview('" + annotationtype + "', '" + set + "')\">" + label;
+ if (set != "null") {
+ glabelhtml += "<span class=\"setname\">" + set + "</span>";
+ }
+ glabelhtml += "</a></li>";
+ globmenu.push([annotationtype, glabelhtml]);
}
}
if ((configuration.allowedannotationfocus === true) || (configuration.allowedannotationfocus.indexOf(annotationtype + '/' + set) != -1) || (configuration.allowedannotationfocus.indexOf(annotationtype) != -1)) {
- focusmenu.push([annotationtype,"<li id=\"annotationtypefocus_" +annotationtype+"_" + hash(set) + "\"><a href=\"javascript:setannotationfocus('" + annotationtype + "','" + set + "')\">" + label + "<span class=\"setname\">" + set + "</span></a></li>"]);
+ var labelhtml = "<li id=\"annotationtypefocus_" +annotationtype+"_" + hash(set) + "\"><a href=\"javascript:setannotationfocus('" + annotationtype + "','" + set + "')\">" + label;
+ if (set != "null") {
+ labelhtml += "<span class=\"setname\">" + set + "</span>";
+ }
+ labelhtml += "</a></li>";
+ focusmenu.push([annotationtype,labelhtml]);
}
});
|
cleaner menus for setless annotations (relates to #<I>)
|
proycon_flat
|
train
|
f969c393e3ea565d0c8ed5c979d710cc1a905549
|
diff --git a/src/Bugsnag/Error.php b/src/Bugsnag/Error.php
index <HASH>..<HASH> 100644
--- a/src/Bugsnag/Error.php
+++ b/src/Bugsnag/Error.php
@@ -225,7 +225,7 @@ class Bugsnag_Error
return $cleanArray;
} elseif (is_string($obj)) {
// UTF8-encode if not already encoded
- if (!mb_detect_encoding($obj, 'UTF-8', true)) {
+ if (function_exists('mb_detect_encoding') && !mb_detect_encoding($obj, 'UTF-8', true)) {
return utf8_encode($obj);
} else {
return $obj;
|
Only do encoding magic if mb_detect_encoding is available
|
bugsnag_bugsnag-php
|
train
|
b2bf4d08130e9a3850aebfabf2b4383c47f9f938
|
diff --git a/fsock.go b/fsock.go
index <HASH>..<HASH> 100644
--- a/fsock.go
+++ b/fsock.go
@@ -340,10 +340,14 @@ func (self *FSock) ReadEvents() {
// Dispatch events to handlers in async mode
func (self *FSock) dispatchEvent(event string) {
eventName := headerVal(event, "Event-Name")
- if _, hasHandlers := self.eventHandlers[eventName]; hasHandlers {
- // We have handlers, dispatch to all of them
- for _, handlerFunc := range self.eventHandlers[eventName] {
- go handlerFunc(event)
+ handleNames := []string{eventName, "ALL"}
+
+ for _, handleName := range handleNames {
+ if _, hasHandlers := self.eventHandlers[handleName]; hasHandlers {
+ // We have handlers, dispatch to all of them
+ for _, handlerFunc := range self.eventHandlers[handleName] {
+ go handlerFunc(event)
+ }
}
}
}
|
adds support for registering an ALL event handle
|
cgrates_fsock
|
train
|
63a3b78fcb902fb65bc9ece19ff0624e4cfc8c19
|
diff --git a/resources/views/layout.blade.php b/resources/views/layout.blade.php
index <HASH>..<HASH> 100644
--- a/resources/views/layout.blade.php
+++ b/resources/views/layout.blade.php
@@ -12,9 +12,9 @@
<!-- Style sheets-->
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
@if(\Laravel\Telescope\Telescope::$useDarkTheme)
- <link href='{{mix('app-dark.css', 'vendor/telescope')}}' rel='stylesheet' type='text/css'>
+ <link href='{{asset(mix('app-dark.css', 'vendor/telescope'))}}' rel='stylesheet' type='text/css'>
@else
- <link href='{{mix('app.css', 'vendor/telescope')}}' rel='stylesheet' type='text/css'>
+ <link href='{{asset(mix('app.css', 'vendor/telescope'))}}' rel='stylesheet' type='text/css'>
@endif
</head>
<body>
@@ -182,6 +182,6 @@
)); ?>;
</script>
-<script src="{{mix('app.js', 'vendor/telescope')}}"></script>
+<script src="{{asset(mix('app.js', 'vendor/telescope'))}}"></script>
</body>
</html>
|
Fix: Assets not loading when Laravel is installed in a subdirectory
|
laravel_telescope
|
train
|
f270b460eaca0c9d70a7cb6783ab91e56508f231
|
diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/persistentvolume/persistentvolume_claim_binder_controller.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/persistentvolume/persistentvolume_claim_binder_controller.go
index <HASH>..<HASH> 100644
--- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/persistentvolume/persistentvolume_claim_binder_controller.go
+++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/persistentvolume/persistentvolume_claim_binder_controller.go
@@ -238,7 +238,7 @@ func syncVolume(volumeIndex *persistentVolumeOrderedIndex, binderClient binderCl
if volume.Spec.ClaimRef != nil {
claim, err := binderClient.GetPersistentVolumeClaim(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name)
- if errors.IsNotFound(err) {
+ if errors.IsNotFound(err) || (claim != nil && claim.UID != volume.Spec.ClaimRef.UID) {
if volume.Spec.PersistentVolumeReclaimPolicy == api.PersistentVolumeReclaimRecycle {
// Pending volumes that have a ClaimRef where the claim is missing were recently recycled.
// The Recycler set the phase to VolumePending to start the volume at the beginning of this lifecycle.
|
UPSTREAM: <I>: Check claimRef UID when processing a recycled PV
|
openshift_origin
|
train
|
69e86d4f98a362d3834adf1bf4c32ed8e433f135
|
diff --git a/src/event.js b/src/event.js
index <HASH>..<HASH> 100644
--- a/src/event.js
+++ b/src/event.js
@@ -229,13 +229,13 @@ jQuery.event = {
} catch (e) {}
}
+ this.triggered = false;
+
if ( !event.isPropagationStopped() ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent )
jQuery.event.trigger(event, data, parent, true);
}
-
- this.triggered = false;
},
handle: function(event) {
|
The triggered flag was being set too early, which was preventing bubbling form working when a
native event existed.
|
jquery_jquery
|
train
|
554d2dd56bd21eb677a71bf60482b38bae99a181
|
diff --git a/test/test-creation.js b/test/test-creation.js
index <HASH>..<HASH> 100644
--- a/test/test-creation.js
+++ b/test/test-creation.js
@@ -159,7 +159,7 @@ describe('react-webpack generator', function() {
var generatorTest = function(name, generatorType, specType, targetDirectory, scriptNameFn, specNameFn, suffix, done) {
var deps = [path.join('../..', generatorType)];
- genOptions.appPath += '/scripts'
+ genOptions.appPath = 'src/scripts'
var reactGenerator = helpers.createGenerator('react-webpack:' + generatorType, deps, [name], genOptions);
|
Modify appPath to support multiple function call
|
react-webpack-generators_generator-react-webpack
|
train
|
bd1f7be5b74a83ada99bfd62fc77883f1ebd5cf9
|
diff --git a/cifsdk/client/client.py b/cifsdk/client/client.py
index <HASH>..<HASH> 100644
--- a/cifsdk/client/client.py
+++ b/cifsdk/client/client.py
@@ -166,6 +166,25 @@ def main():
logger.error('unauthorized')
else:
print(FORMATS[options.get('format')](data=rv))
+
+ elif options.get('tags'):
+ logger.info("filtering for {0}".format(options.get("tags")))
+ try:
+ rv = cli.indicators_search({
+ 'tags': options['tags'],
+ 'limit': options['limit'],
+ 'nolog': options['nolog']
+ }
+ )
+ except RuntimeError as e:
+ import traceback
+ traceback.print_exc()
+ logger.error(e)
+ except AuthError as e:
+ logger.error('unauthorized')
+ else:
+ print(FORMATS[options.get('format')](data=rv))
+
elif options.get("submit"):
logger.info("submitting {0}".format(options.get("submit")))
i = Indicator(indicator=args.indicator, tags=args.tags, confidence=args.confidence)
diff --git a/cifsdk/client/http.py b/cifsdk/client/http.py
index <HASH>..<HASH> 100644
--- a/cifsdk/client/http.py
+++ b/cifsdk/client/http.py
@@ -9,10 +9,20 @@ import zlib
from base64 import b64decode
import binascii
from cifsdk.client.plugin import Client
+import os
-logger = logging.getLogger(__name__)
requests.packages.urllib3.disable_warnings()
+TRACE = os.environ.get('CIFSDK_CLIENT_HTTP_TRACE')
+
+logger = logging.getLogger(__name__)
+
+logger.setLevel(logging.ERROR)
+
+if TRACE:
+ logger.setLevel(logging.DEBUG)
+
+
class HTTP(Client):
def __init__(self, remote, token, proxy=None, timeout=300, verify_ssl=True, **kwargs):
diff --git a/cifsdk/client/zeromq.py b/cifsdk/client/zeromq.py
index <HASH>..<HASH> 100644
--- a/cifsdk/client/zeromq.py
+++ b/cifsdk/client/zeromq.py
@@ -23,6 +23,15 @@ FIREBALL_SIZE = 500
logger = logging.getLogger(__name__)
+TRACE = os.environ.get('CIFSDK_CLIENT_ZEROMQ_TRACE')
+
+logger = logging.getLogger(__name__)
+
+logger.setLevel(logging.ERROR)
+
+if TRACE:
+ logger.setLevel(logging.DEBUG)
+
class ZMQ(Client):
def __init__(self, remote, token, **kwargs):
|
adding TRACE handlers to logging (#<I>)
|
csirtgadgets_bearded-avenger-sdk-py
|
train
|
644471bd618cbda84485209dba7c92e4cac760bf
|
diff --git a/spec/Judopay/Models/TransactionSpec.php b/spec/Judopay/Models/TransactionSpec.php
index <HASH>..<HASH> 100644
--- a/spec/Judopay/Models/TransactionSpec.php
+++ b/spec/Judopay/Models/TransactionSpec.php
@@ -4,9 +4,7 @@ namespace spec\Judopay\Models;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
-use GuzzleHttp\Client;
-use GuzzleHttp\Subscriber\Mock;
-use GuzzleHttp\Message\Response;
+use Guzzle\Http\Client;
class TransactionSpec extends ObjectBehavior
{
@@ -17,16 +15,12 @@ class TransactionSpec extends ObjectBehavior
public function it_should_list_all_transactions()
{
- $client = new Client();
- $mockResponse = new Response(200);
-// $mockResponse->setBody('banana');
- $mock = new Mock([
- $mockResponse
- ]);
-
- // Add the mock subscriber to the client.
- $client->getEmitter()->attach($mock);
+ $plugin = new \Guzzle\Plugin\Mock\MockPlugin();
+ $mockResponse = new \Guzzle\Http\Message\Response(200, null, 'banana');
+ $plugin->addResponse($mockResponse);
+ $client = new \Guzzle\Http\Client();
+ $client->addSubscriber($plugin);
$this->setClient($client);
$this->all()->shouldReturn('banana');
diff --git a/src/Judopay/Model.php b/src/Judopay/Model.php
index <HASH>..<HASH> 100644
--- a/src/Judopay/Model.php
+++ b/src/Judopay/Model.php
@@ -6,13 +6,15 @@ class Model
{
protected $client;
- public function setClient(\GuzzleHttp\Client $client)
+ public function setClient(\Guzzle\Http\Client $client)
{
$this->client = $client;
}
public function all()
{
- print_r($this->client->get('/')->getBody());
+ $request = $this->client->get('http://www.test.com/');
+ $response = $request->send();
+ return (string)$response->getBody();
}
}
\ No newline at end of file
|
Added simple test for Guzzle3 response mocking
|
Judopay_Judo-PHP
|
train
|
18de6c82f8f5b677448b31a5c457e616bb208887
|
diff --git a/shared/actions/people.js b/shared/actions/people.js
index <HASH>..<HASH> 100644
--- a/shared/actions/people.js
+++ b/shared/actions/people.js
@@ -12,6 +12,9 @@ import {peopleTab} from '../constants/tabs'
import {getPath} from '../route-tree'
import flags from '../util/feature-flags'
+// set this to true to have all todo items show up all the time
+const debugTodo = false
+
const getPeopleData = (state, action) => {
// more logging to understand why this fails so much
logger.info(
@@ -42,6 +45,27 @@ const getPeopleData = (state, action) => {
.filter(item => item.badged || item.data.t === RPCTypes.homeHomeScreenItemType.todo)
.reduce(Constants.reduceRPCItemToPeopleItem, I.List())
+ if (debugTodo) {
+ // $FlowIssue this is true
+ const allTodos: Array<Types.TodoType> = Object.values(Constants.todoTypeEnumToType)
+ allTodos.forEach(todoType => {
+ if (newItems.some(t => t.type === 'todo' && t.todoType === todoType)) {
+ return
+ }
+ newItems = newItems.push(
+ Constants.makeTodo({
+ badged: true,
+ confirmLabel: Constants.todoTypeToConfirmLabel[todoType],
+ dismissable: Constants.todoTypeToDismissable[todoType],
+ icon: Constants.todoTypeToIcon[todoType],
+ instructions: Constants.todoTypeToInstructions[todoType],
+ todoType,
+ type: 'todo',
+ })
+ )
+ })
+ }
+
const followSuggestions: I.List<Types.FollowSuggestion> = (data.followSuggestions || []).reduce(
(list, suggestion) => {
const followsMe = followers.has(suggestion.username)
diff --git a/shared/people/todo/container.js b/shared/people/todo/container.js
index <HASH>..<HASH> 100644
--- a/shared/people/todo/container.js
+++ b/shared/people/todo/container.js
@@ -12,6 +12,7 @@ import * as Tracker2Gen from '../../actions/tracker2-gen'
import * as RouteTreeGen from '../../actions/route-tree-gen'
import * as ProfileGen from '../../actions/profile-gen'
import openURL from '../../util/open-url'
+import flags from '../../util/feature-flags'
type TodoOwnProps = {|
badged: boolean,
@@ -43,6 +44,10 @@ const AvatarUserConnector = connect<TodoOwnProps, _, _, _, _>(
mapStateToProps,
dispatch => ({
_onConfirm: username => {
+ if (flags.useNewRouter) {
+ dispatch(ProfileGen.createEditAvatar())
+ return
+ }
// make sure we have tracker state & profile is up to date
dispatch(Tracker2Gen.createShowUser({asTracker: false, username}))
dispatch(RouteTreeGen.createSwitchTo({path: [Tabs.profileTab, 'profileEditAvatar']}))
@@ -62,7 +67,6 @@ const BioConnector = connect<TodoOwnProps, _, _, _, _>(
_onConfirm: (username: string) => {
// make sure we have tracker state & profile is up to date
dispatch(Tracker2Gen.createShowUser({asTracker: false, username}))
- dispatch(RouteTreeGen.createNavigateAppend({parentPath: [Tabs.peopleTab], path: ['profileEdit']}))
},
onDismiss: () => {},
}),
@@ -118,6 +122,15 @@ const PaperKeyConnector = connect<TodoOwnProps, _, _, _, _>(
() => ({}),
dispatch => ({
onConfirm: () => {
+ if (flags.useNewRouter) {
+ dispatch(
+ RouteTreeGen.createNavigateAppend({
+ path: [{props: {highlight: ['paper key']}, selected: 'deviceAdd'}],
+ })
+ )
+ return
+ }
+
if (!isMobile) {
dispatch(RouteTreeGen.createSwitchTo({path: [Tabs.devicesTab]}))
dispatch(RouteTreeGen.createNavigateAppend({parentPath: [Tabs.devicesTab], path: ['deviceAdd']}))
@@ -125,7 +138,7 @@ const PaperKeyConnector = connect<TodoOwnProps, _, _, _, _>(
dispatch(
RouteTreeGen.createNavigateTo({
parentPath: [Tabs.settingsTab],
- path: [SettingsTabs.devicesTab, 'addDevice'],
+ path: [SettingsTabs.devicesTab, 'deviceAdd'],
})
)
dispatch(RouteTreeGen.createSwitchTo({path: [Tabs.settingsTab]}))
|
Fix a couple people page TODOs in nav2 (#<I>)
* edit profile todo and WIP debugTodo
* fix paper key + avatar user and finish debugTodo
|
keybase_client
|
train
|
9905dce8974fc087a15d58d2548e61127b869852
|
diff --git a/src/Kernels/Distance/Cosine.php b/src/Kernels/Distance/Cosine.php
index <HASH>..<HASH> 100644
--- a/src/Kernels/Distance/Cosine.php
+++ b/src/Kernels/Distance/Cosine.php
@@ -4,8 +4,6 @@ namespace Rubix\ML\Kernels\Distance;
use Rubix\ML\DataType;
-use const Rubix\ML\EPSILON;
-
/**
* Cosine
*
@@ -80,7 +78,7 @@ class Cosine implements Distance
return 2.0;
}
- return 1.0 - ($sigma / (sqrt($ssA * $ssB) ?: EPSILON));
+ return 1.0 - ($sigma / sqrt($ssA * $ssB));
}
/**
|
No need to check for divide by zero
|
RubixML_RubixML
|
train
|
4e9f65aea00f91f261d9ee2c8ae9759c7d0ec6e9
|
diff --git a/Paybox/DirectPlus/ParameterResolver.php b/Paybox/DirectPlus/ParameterResolver.php
index <HASH>..<HASH> 100644
--- a/Paybox/DirectPlus/ParameterResolver.php
+++ b/Paybox/DirectPlus/ParameterResolver.php
@@ -100,7 +100,7 @@ class ParameterResolver extends AbstractParameterResolver
{
$this->resolver->setRequired($this->requiredParameters);
- $this->resolver->setDefined(array_diff(array_keys($this->knownParameters), $this->requiredParameters));
+ $this->resolver->setOptional(array_diff(array_keys($this->knownParameters), $this->requiredParameters));
$this->initAllowed();
|
OptionsResolver::setDefined() not present in version < <I>
|
lexik_LexikPayboxBundle
|
train
|
a6ed18de4120ab266db794ee6d55cb2756a37016
|
diff --git a/salt/config.py b/salt/config.py
index <HASH>..<HASH> 100644
--- a/salt/config.py
+++ b/salt/config.py
@@ -250,6 +250,7 @@ VALID_OPTS = {
'random_reauth_delay': int,
'syndic_event_forward_timeout': float,
'syndic_max_event_process_time': float,
+ 'syndic_jid_forward_cache_hwm': int,
'ssh_passwd': str,
'ssh_port': str,
'ssh_sudo': bool,
@@ -583,6 +584,7 @@ DEFAULT_MASTER_OPTS = {
'gather_job_timeout': 5,
'syndic_event_forward_timeout': 0.5,
'syndic_max_event_process_time': 0.5,
+ 'syndic_jid_forward_cache_hwm': 100,
'ssh_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
|
Add syndic_jid_forward_cache_hwm configuration
|
saltstack_salt
|
train
|
b06cb06d5399f3a3246d0a4c2f7d8975a98782dd
|
diff --git a/packages/banner/src/Banner.js b/packages/banner/src/Banner.js
index <HASH>..<HASH> 100644
--- a/packages/banner/src/Banner.js
+++ b/packages/banner/src/Banner.js
@@ -47,7 +47,9 @@ export default class Banner extends Component {
actions: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
/** Accessibility text for the dismiss button */
dismissButtonTitle: PropTypes.string,
- /** Called when the banner is dismissed */
+ /** Called when the banner is dismissed
+ * If this is not supplied the close button will not appear
+ */
onDismiss: PropTypes.func,
/** Animation; Determines the visibility of the banner */
isVisible: PropTypes.bool,
|
docs: add additional info for onDismiss prop
|
Autodesk_hig
|
train
|
635f11512549c4b6c12bdd7336b8539bfb184b60
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -39,6 +39,8 @@ setup(
package_data={
'config': [
os.path.join('config',
+ 'config_internal'),
+ os.path.join('config',
'*.cfg')
]
},
|
add internal config file to package data
|
openego_eDisGo
|
train
|
c92cdedc8de2391e9520a0c7c530548b75025c76
|
diff --git a/salt/runner.py b/salt/runner.py
index <HASH>..<HASH> 100644
--- a/salt/runner.py
+++ b/salt/runner.py
@@ -45,7 +45,7 @@ class RunnerClient(mixins.SyncClientMixin, mixins.AsyncClientMixin, object):
def __init__(self, opts):
self.opts = opts
self.functions = salt.loader.runner(opts) # Must be self.functions for mixin to work correctly :-/
- self.event = salt.utils.event.MasterEvent(self.opts['sock_dir'])
+ self.event = salt.utils.event.get_event('master', self.opts['sock_dir'], self.opts['transport'])
def cmd(self, fun, arg, pub_data=None, kwarg=None):
'''
|
Switch to RAET-compatible event listener
|
saltstack_salt
|
train
|
1945578e6a78cedd9201dc4bd380bfe72fe300a3
|
diff --git a/django_grip.py b/django_grip.py
index <HASH>..<HASH> 100644
--- a/django_grip.py
+++ b/django_grip.py
@@ -26,6 +26,7 @@ def _is_basestring_instance(instance):
return False
def _get_pubcontrol():
+ global _pubcontrol
_lock.acquire()
if _pubcontrol is None:
_pubcontrol = GripPubControl()
|
explicitly declare _pubcontrol as global
|
fanout_django-grip
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.