hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
72c0e9dd648d64da2f54c9436f2b73b4cca54fee
|
diff --git a/lib/api/routes/preconditions/authentication.js b/lib/api/routes/preconditions/authentication.js
index <HASH>..<HASH> 100644
--- a/lib/api/routes/preconditions/authentication.js
+++ b/lib/api/routes/preconditions/authentication.js
@@ -32,7 +32,7 @@ module.exports = function(req, res, next){
response.write(response.STATUS_CODES.UNAUTHORIZED, JSON.stringify({ message: strings.group('http')[response.STATUS_CODES.UNAUTHORIZED]}), res);
}
else {
- users.getById(token.profile._id, onGetIdentity);
+ users.getById(token.uid, onGetIdentity);
}
}
|
Changed key to use uid instead of profile._id
|
grasshopper-cms_grasshopper-api-js
|
train
|
e6ba8eb0e4cf2350216324e29ac839eaee854dd0
|
diff --git a/lib/apipie_bindings/api.rb b/lib/apipie_bindings/api.rb
index <HASH>..<HASH> 100644
--- a/lib/apipie_bindings/api.rb
+++ b/lib/apipie_bindings/api.rb
@@ -74,6 +74,8 @@ module ApipieBindings
headers.merge!(config[:headers]) unless config[:headers].nil?
headers.merge!(options.delete(:headers)) unless options[:headers].nil?
+ log.debug "Global headers: #{headers.ai}"
+
resource_config = {
:user => config[:username],
:password => config[:password],
@@ -180,6 +182,7 @@ module ApipieBindings
log.info "#{http_method.to_s.upcase} #{path}"
log.debug "Params: #{params.ai}"
+ log.debug "Headers: #{headers.ai}"
args << headers if headers
@@ -188,8 +191,14 @@ module ApipieBindings
ex = options[:fake_response ] || empty_response
response = RestClient::Response.create(ex.response, ex.status, args)
else
- response = @client[path].send(*args)
- update_cache(response.headers[:apipie_checksum])
+ begin
+ response = @client[path].send(*args)
+ update_cache(response.headers[:apipie_checksum])
+ rescue => e
+ log.error e.message + "\n" +
+ (e.respond_to?(:response) ? process_data(e.response).ai : e.ai)
+ raise
+ end
end
result = options[:response] == :raw ? response : process_data(response)
|
Fexes #8 - Error responses are not logged
|
Apipie_apipie-bindings
|
train
|
23fd38be12f4d9bd2058c952947dd3af4341f527
|
diff --git a/app/assets/javascripts/fae/form/_ajax.js b/app/assets/javascripts/fae/form/_ajax.js
index <HASH>..<HASH> 100644
--- a/app/assets/javascripts/fae/form/_ajax.js
+++ b/app/assets/javascripts/fae/form/_ajax.js
@@ -10,7 +10,6 @@ Fae.form.ajax = {
init: function() {
this.$addedit_form = $('.js-addedit-form, .js-index-addedit-form');
this.$filter_form = $('.js-filter-form');
- this.$nested_form = $('.nested-form');
this.addEditLinks();
this.addEditSubmission();
@@ -67,6 +66,8 @@ Fae.form.ajax = {
$wrapper.find('.input.file').fileinputer();
}
+ this.$nested_form = $('.nested-form');
+
// Bind validation to nested form fields added by AJAX
Fae.form.validator.bindValidationEvents(this.$nested_form);
|
fix issue with undefined value being passed into validator function
|
wearefine_fae
|
train
|
fdb8879ea983582cc4602e9bc8c37f53c1a71bf0
|
diff --git a/lib/remi/data_set.rb b/lib/remi/data_set.rb
index <HASH>..<HASH> 100644
--- a/lib/remi/data_set.rb
+++ b/lib/remi/data_set.rb
@@ -9,6 +9,8 @@ module Remi
def_delegators :@interface, :open_for_write, :open_for_read, :close, :delete
def_delegators :@active_row, :row_number, :last_row
+ class UnknownByGroupVariableError < StandardError; end
+
# Public: DataSet initializer.
#
# data_set_name - The name (symbol) associated with the data set.
@@ -36,10 +38,11 @@ module Remi
@lead_rows = lead_rows
@lag_rows = lag_rows
@lag_offset = 0
- @by_groups = by_groups
+ @by_groups = Array(by_groups)
+ validate_by_group_variables unless @by_groups.empty?
@interface.open_for_read
- @row_set = RowSet.new(lag_rows: lag_rows, lead_rows: lead_rows, by_groups: by_groups, key_map: @variable_set)
+ @row_set = RowSet.new(lag_rows: lag_rows, lead_rows: lead_rows, by_groups: Array(by_groups), key_map: @variable_set)
end
# Public: Opens a dataset for write access.
@@ -208,5 +211,11 @@ module Remi
@interface.read_row(key_map: @variable_set)
end
end
+
+
+ # Private: Validates whether the given by group variables exist.
+ def validate_by_group_variables
+ raise UnknownByGroupVariableError, "Unknown by-group variable #{@by_groups - @variable_set.keys}" unless (@by_groups - @variable_set.keys).empty?
+ end
end
end
diff --git a/spec/data_set_spec.rb b/spec/data_set_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/data_set_spec.rb
+++ b/spec/data_set_spec.rb
@@ -135,21 +135,26 @@ describe DataSet do
end
groupset.close
+ end
- groupset.open_for_read(by_groups: [:group1, :group2])
+ it 'fails when given bad by group variables' do
+ expect { groupset.open_for_read(by_groups: :invalid) }.to raise_error Remi::DataSet::UnknownByGroupVariableError
end
- after { groupset.close }
-
- it 'gives the expected first/last indicators' do
- while !groupset.last_row
- groupset.read_row
- expect(groupset.first).to eq groupset[:expected_first1]
- expect(groupset.last).to eq groupset[:expected_last1]
- expect(groupset.first(:group1)).to eq groupset[:expected_first1]
- expect(groupset.last(:group1)).to eq groupset[:expected_last1]
- expect(groupset.first(:group2)).to eq groupset[:expected_first2]
- expect(groupset.last(:group2)).to eq groupset[:expected_last2]
+ context 'open for reading with by groups' do
+ before { groupset.open_for_read(by_groups: [:group1, :group2]) }
+ after { groupset.close }
+
+ it 'gives the expected first/last indicators' do
+ while !groupset.last_row
+ groupset.read_row
+ expect(groupset.first).to eq groupset[:expected_first1]
+ expect(groupset.last).to eq groupset[:expected_last1]
+ expect(groupset.first(:group1)).to eq groupset[:expected_first1]
+ expect(groupset.last(:group1)).to eq groupset[:expected_last1]
+ expect(groupset.first(:group2)).to eq groupset[:expected_first2]
+ expect(groupset.last(:group2)).to eq groupset[:expected_last2]
+ end
end
end
end
|
DataSet by-group variable validation and spec.
|
inside-track_remi
|
train
|
54c7228b60b033c2638a01612d283351f1d10a9c
|
diff --git a/src/clc/APIv2/queue.py b/src/clc/APIv2/queue.py
index <HASH>..<HASH> 100644
--- a/src/clc/APIv2/queue.py
+++ b/src/clc/APIv2/queue.py
@@ -11,6 +11,15 @@ Requests object variables:
requests.error_requests
requests.success_requests
+Request object variables:
+
+ (undocumented)
+
+Requestv2Exprimental (extends request) variables:
+
+ request.id - operational ID
+ request.uri - status uri
+
"""
@@ -49,6 +58,8 @@ class Requests(object):
if requests_lst is None: raise(Exception("Unexpected requests response"))
elif 'isQueued' in requests_lst: requests_lst = [requests_lst]
elif 'href' in requests_lst: requests_lst = [{'isQueued': True, 'links': [requests_lst]}]
+ elif 'uri' in requests_lst: requests_lst = [{'isQueued': True, 'operation_id': requests_lst['operationId'], 'uri': requests_lst['uri']}]
+ # {"operationId":"0edee81c15154b82a0d5a6dddee7c24d","uri":"/v2-experimental/operations/KRAP/status/0edee81c15154b82a0d5a6dddee7c24d"}
for r in requests_lst:
@@ -67,7 +78,10 @@ class Requests(object):
context_val = "Unknown"
if r['isQueued']:
- self.requests.append(Request([obj['id'] for obj in r['links'] if obj['rel']=='status'][0],
+ if 'uri' in r:
+ self.requests.append(Requestv2Experimental(r['operation_id'],r['uri']))
+ else:
+ self.requests.append(Request([obj['id'] for obj in r['links'] if obj['rel']=='status'][0],
alias=self.alias,request_obj={'context_key': context_key, 'context_val': context_val}))
else:
# If we're dealing with a list of responses and we have an error with one I'm not sure how
@@ -121,7 +135,7 @@ class Requests(object):
cur_requests = []
for request in self.requests:
status = request.Status()
- if status in ('notStarted','executing','resumed'): cur_requests.append(request)
+ if status in ('notStarted','executing','resumed','queued'): cur_requests.append(request)
elif status == 'succeeded': self.success_requests.append(request)
elif status in ("failed", "unknown"): self.error_requests.append(request)
@@ -135,11 +149,12 @@ class Requests(object):
class Request(object):
+ """This is the current prod incantation for requests. """
def __init__(self,id,alias=None,request_obj=None):
"""Create Request object.
- https://t3n.zendesk.com/entries/43699144-Get-Status
+ https://www.ctl.io/api-docs/v2/#queue-get-status
"""
@@ -220,3 +235,33 @@ class Request(object):
def __str__(self):
return(self.id)
+
+class Requestv2Experimental(Request):
+ """This is the v2-experimental implementation for requests. """
+
+ def __init__(self,id,uri):
+ """Create Request object.
+
+ Response string feeding this looks like:
+ {"operationId":"OPERATIONAL_ID","uri":"/v2-experimental/operations/$ALIAS/status/$OPERATION_ID"}
+ """
+
+ self.id = id
+ self.uri = uri
+ self.data = {'context_key': None, 'context_val': None, 'status': None}
+
+ self.time_created = time.time()
+ self.time_executed = None
+ self.time_completed = None
+
+
+ def Status(self,cached=False):
+ if not cached or not self.data['status']:
+ try:
+ self.data['status'] = clc.v2.API.Call('GET',self.uri,{})['status']
+ except clc.APIFailedResponse as e:
+ if e.response_status_code == 500: pass
+ else: raise(e)
+ return(self.data['status'])
+
+
diff --git a/src/clc/APIv2/server.py b/src/clc/APIv2/server.py
index <HASH>..<HASH> 100644
--- a/src/clc/APIv2/server.py
+++ b/src/clc/APIv2/server.py
@@ -388,6 +388,31 @@ class Server(object):
alias=self.alias))
+ def AddNIC(self,network_id,ip=''):
+ """Execute an existing Bluerprint package on the server.
+
+ https://www.ctl.io/api-docs/v2/#servers-add-secondary-network
+
+ Requires package ID, currently only available by browsing control and browsing
+ for the package itself. The UUID parameter is the package ID we need.
+
+ network_id - ID associated with the network to add
+ ip - Explicit IP address to assgin (optional)
+
+ Need to reinstantiate the server object after execution completes to see the assigned IP address.
+
+ >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT06'). \
+ AddNIC(package_id="77ab3844-579d-4c8d-8955-c69a94a2ba1a", \
+ WaitUntilComplete()
+ 0
+
+ """
+
+ return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/networks' % (self.alias,self.id),
+ json.dumps({'networkId': network_id, 'ipAddress': ip})),
+ alias=self.alias))
+
+
def GetSnapshots(self):
"""Returns list of all snapshot names.
|
+add NIC support +requestv2experimental support
|
CenturyLinkCloud_clc-python-sdk
|
train
|
306f7469c3ba8dcf11348d206258f991368979b3
|
diff --git a/lib/DataDragon/DataDragonHelper.js b/lib/DataDragon/DataDragonHelper.js
index <HASH>..<HASH> 100644
--- a/lib/DataDragon/DataDragonHelper.js
+++ b/lib/DataDragon/DataDragonHelper.js
@@ -39,7 +39,7 @@ const cache = new NodeCache({ // TODO: replace with settable cache? (see endpoin
stdTTL: 4 * 60 * 60, // 4h
checkperiod: 5 * 60, // 1h
errorOnMissing: false,
- useClones: false
+ useClones: true
});
const events = new EventEmitter();
@@ -449,44 +449,54 @@ function gettingLocalList(version, type, locale = 'en_US', skipLatestVersionFall
.then(() => ddV);
})
.then((ddV) => {
- try {
- const content = require(path.join(DataDragonHelper.buildStoragePath({
+ return new Promise((resolve, reject) => {
+ const filePath = path.join(DataDragonHelper.buildStoragePath({
version: ddV,
locale
- }), '/', type + '.json'));
- return (type === 'runesReforged') ? content : content.data;
- } catch (err) {
- if (!err.message.includes('Cannot find module')) {
- emitError(err);
- }
-
-
- if (!wasLatestVersionUsed && !skipLatestVersionFallback) {
- // we did not use the latest available version yet, so let's try that
- return gettingLocalList(null, type, locale);
- }
+ }), '/', type + '.json');
+
+ fs.readFile(filePath, 'utf8', (err, fileContent) => {
+ if (!err) {
+ const content = JSON.parse(fileContent);
+ resolve((type === 'runesReforged') ? content : content.data);
+ } else {
+ if (!err.message.includes('ENOENT')) {
+ emitError(err);
+ reject(err);
+ return null;
+ }
+ if (!wasLatestVersionUsed && !skipLatestVersionFallback) {
+ // we did not use the latest available version yet, so let's try that
+ gettingLocalList(null, type, locale)
+ .then(resolve).catch(reject);
+ return null;
+ }
- if (wasLatestVersionUsed && !skipLatestVersionFallback) {
- // we did already fall back to the most recent version,
- // let's try to find ANY working data file from already downloaded files
- return DataDragonHelper.gettingLatestVersionFromDownloads(locale).then(ddV => gettingLocalList(ddV, type, locale, true));
- }
+ if (wasLatestVersionUsed && !skipLatestVersionFallback) {
+ // we did already fall back to the most recent version,
+ // let's try to find ANY working data file from already downloaded files
+ DataDragonHelper.gettingLatestVersionFromDownloads(locale).then(ddV => gettingLocalList(ddV, type, locale, true))
+ .then(resolve).catch(reject);
+ return null;
+ }
- // otherwise we give up now
- throw new Error('Could not receive data for ' + locale + ' ' + type);
+ // otherwise we give up now
+ reject(new Error('Could not receive data for ' + locale + ' ' + type));
- // TODO(improve): here, it might still happen, that the most recent working file is not downloaded yet, so for a bullet-proof approach,
- // we would need to try to find it within each version given from the ddragon versions-array (descending, starting with the version that we initially put in)
- // e.g. we started with 8.5.1 as input were not able to load the files, we then should try to download and deliver files from 8.4.1 and so on
- // currently, it would happen that we are not able to deliver 8.5.1 and then just deliver the absolute newest file (e.g. 8.14.1), which might include changes we don't want to deliver.
- // This should be an extreme edge case though, so might or might not try to solve this. Generally, two use-cases should be most common:
- // 1) just trying to get the latest files
- // 2) trying to get a specific version (derived from either the versions array, or a matchHistory or other historical data with access to the respective ddV)
- // So the automatic fix should not be neccessary, but as mentioned, using the absolute latest version as fallback might lead to unexpected results.
- // Most likely scenario when this might happen is when a lot of different versions are downloaded in short amount of time, and the ddragon cdn times out or something,
- // which would lead to the download-promise rejecting and the newest version being used.
- }
+ // TODO(improve): here, it might still happen, that the most recent working file is not downloaded yet, so for a bullet-proof approach,
+ // we would need to try to find it within each version given from the ddragon versions-array (descending, starting with the version that we initially put in)
+ // e.g. we started with 8.5.1 as input were not able to load the files, we then should try to download and deliver files from 8.4.1 and so on
+ // currently, it would happen that we are not able to deliver 8.5.1 and then just deliver the absolute newest file (e.g. 8.14.1), which might include changes we don't want to deliver.
+ // This should be an extreme edge case though, so might or might not try to solve this. Generally, two use-cases should be most common:
+ // 1) just trying to get the latest files
+ // 2) trying to get a specific version (derived from either the versions array, or a matchHistory or other historical data with access to the respective ddV)
+ // So the automatic fix should not be neccessary, but as mentioned, using the absolute latest version as fallback might lead to unexpected results.
+ // Most likely scenario when this might happen is when a lot of different versions are downloaded in short amount of time, and the ddragon cdn times out or something,
+ // which would lead to the download-promise rejecting and the newest version being used.
+ }
+ });
+ });
});
}
|
fix(DataDragonHelper): use fs.readFile instead of require
Require does have the advantage of caching files it reads, but that's also its
drawback in this case. Objects could be mutated and lead to obfuscated bugs.
Now reading files with fs to always get a new object.
|
Colorfulstan_LeagueJS
|
train
|
a5707bee656dfe4c59b8ec8f65c32f204480a593
|
diff --git a/hellocharts-library/src/lecho/lib/hellocharts/renderer/PieChartRenderer.java b/hellocharts-library/src/lecho/lib/hellocharts/renderer/PieChartRenderer.java
index <HASH>..<HASH> 100644
--- a/hellocharts-library/src/lecho/lib/hellocharts/renderer/PieChartRenderer.java
+++ b/hellocharts-library/src/lecho/lib/hellocharts/renderer/PieChartRenderer.java
@@ -36,7 +36,6 @@ public class PieChartRenderer extends AbstractChartRenderer {
private Paint arcPaint = new Paint();
private float maxSum;
- private float circleRadius;
private RectF orginCircleOval = new RectF();
private RectF drawCircleOval = new RectF();
private PointF arcVector = new PointF();
@@ -90,6 +89,7 @@ public class PieChartRenderer extends AbstractChartRenderer {
final PieChartData data = dataProvider.getPieChartData();
final float centerX = orginCircleOval.centerX();
final float centerY = orginCircleOval.centerY();
+ final float circleRadius = orginCircleOval.width() / 2f;
// Check if touch is on circle area, if not return false;
arcVector.set(touchX - centerX, touchY - centerY);
if (arcVector.length() > circleRadius + touchAdditional) {
@@ -150,6 +150,7 @@ public class PieChartRenderer extends AbstractChartRenderer {
// TODO: Maybe move centerX/Y out of this method.
final float centerX = orginCircleOval.centerX();
final float centerY = orginCircleOval.centerY();
+ final float circleRadius = orginCircleOval.width() / 2f;
final float arcCenterX = (float) (circleRadius * DEFAULT_ARC_VECTOR_RADIUS_FACTOR
* Math.cos(Math.toRadians(lastAngle + angle / 2)) + centerX);
final float arcCenterY = (float) (circleRadius * DEFAULT_ARC_VECTOR_RADIUS_FACTOR
@@ -219,7 +220,7 @@ public class PieChartRenderer extends AbstractChartRenderer {
*/
private void calculateCircleOval() {
Rect contentRect = chart.getChartCalculator().getContentRect();
- circleRadius = Math.min(contentRect.width() / 2f, contentRect.height() / 2f);
+ final float circleRadius = Math.min(contentRect.width() / 2f, contentRect.height() / 2f);
final float centerX = contentRect.centerX();
final float centerY = contentRect.centerY();
final float left = centerX - circleRadius + touchAdditional;
|
Remove circleRadius member variable from PieChartRenderer
|
lecho_hellocharts-android
|
train
|
0313fe879dc023a09a39b9738f2a7e458b162082
|
diff --git a/src/javascript/file/FileDrop.js b/src/javascript/file/FileDrop.js
index <HASH>..<HASH> 100644
--- a/src/javascript/file/FileDrop.js
+++ b/src/javascript/file/FileDrop.js
@@ -13,11 +13,12 @@ define('moxie/file/FileDrop', [
'moxie/core/utils/Dom',
'moxie/core/Exceptions',
'moxie/core/utils/Basic',
+ 'moxie/core/utils/Env',
'moxie/file/File',
'moxie/runtime/RuntimeClient',
'moxie/core/EventTarget',
'moxie/core/utils/Mime'
-], function(I18n, Dom, x, Basic, File, RuntimeClient, EventTarget, Mime) {
+], function(I18n, Dom, x, Basic, Env, File, RuntimeClient, EventTarget, Mime) {
/**
Turn arbitrary DOM element to a drop zone accepting files. Converts selected files to _File_ objects, to be used
in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through
@@ -94,6 +95,10 @@ define('moxie/file/FileDrop', [
];
function FileDrop(options) {
+ if (MXI_DEBUG) {
+ Env.log("Instantiating FileDrop...");
+ }
+
var self = this, defaults;
// if flat argument passed it should be drop_zone id
diff --git a/src/javascript/file/FileInput.js b/src/javascript/file/FileInput.js
index <HASH>..<HASH> 100644
--- a/src/javascript/file/FileInput.js
+++ b/src/javascript/file/FileInput.js
@@ -10,6 +10,7 @@
define('moxie/file/FileInput', [
'moxie/core/utils/Basic',
+ 'moxie/core/utils/Env',
'moxie/core/utils/Mime',
'moxie/core/utils/Dom',
'moxie/core/Exceptions',
@@ -17,7 +18,7 @@ define('moxie/file/FileInput', [
'moxie/core/I18n',
'moxie/runtime/Runtime',
'moxie/runtime/RuntimeClient'
-], function(Basic, Mime, Dom, x, EventTarget, I18n, Runtime, RuntimeClient) {
+], function(Basic, Env, Mime, Dom, x, EventTarget, I18n, Runtime, RuntimeClient) {
/**
Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click,
converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory
@@ -123,6 +124,10 @@ define('moxie/file/FileInput', [
];
function FileInput(options) {
+ if (MXI_DEBUG) {
+ Env.log("Instantiating FileInput...");
+ }
+
var self = this,
container, browseButton, defaults;
|
Debug, FileInput/FileDrop: Log when instantiating.
|
moxiecode_moxie
|
train
|
8173b03d33a4bcc67302f92da347417c3583ebf3
|
diff --git a/CoreAsset.php b/CoreAsset.php
index <HASH>..<HASH> 100644
--- a/CoreAsset.php
+++ b/CoreAsset.php
@@ -16,7 +16,7 @@ class CoreAsset extends AssetBundle
* [$sourcePath description]
* @var string
*/
- public $sourcePath = '@bower/fullcalendar/tag/dist';
+ public $sourcePath = '@bower/fullcalendar/dist';
/**
* the language the calender will be displayed in
|
Wrong path to "dist" directory
"dist" directory is not inside "tag" directory
|
philippfrenzel_yii2fullcalendar
|
train
|
1b12d46001328a77bb7fac6c18134af2a14fe226
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,14 @@ CHANGELOG](http://keepachangelog.com/) for how to update this file. This project
adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased][unreleased]
+### Fixed
+- `setTimeout` is now called when metrics are recorded instead of recursively.
+ This fixes an issue in environments like AWS Lambda where the execution waits
+ for the event loop to empty.
+
+### Added
+- Use `Honeybadger.flushMetrics()` to clear the timeout interval and flush
+ metrics immediately.
## [1.1.1] - 2016-06-16
### Fixed
diff --git a/lib/honeybadger.js b/lib/honeybadger.js
index <HASH>..<HASH> 100644
--- a/lib/honeybadger.js
+++ b/lib/honeybadger.js
@@ -19,15 +19,10 @@ function Honeybadger(opts) {
var metrics = metricsFactory.call(self);
- function collectMetrics() {
- metrics.collect();
- setTimeout(collectMetrics, self.metricsInterval);
- }
- process.nextTick(collectMetrics.bind(this));
-
self.metricsInterval = 60000;
self.timing = metrics.timing;
self.increment = metrics.increment;
+ self.flushMetrics = metrics.collect;
self.configure = configure;
self.setContext = setContext;
diff --git a/lib/metrics.js b/lib/metrics.js
index <HASH>..<HASH> 100644
--- a/lib/metrics.js
+++ b/lib/metrics.js
@@ -4,10 +4,18 @@ var backend = require('./backend').metrics;
var stats = require('./stats');
function metrics() {
+ var interval;
var collector;
var counters = {};
var timings = {};
+ function intervalCollect() {
+ if (interval) { return; }
+ interval = setTimeout(function() {
+ collect.call(this);
+ }.bind(this), this.metricsInterval);
+ }
+
function collect(callback) {
if (!callback) { callback = function(){}; }
var metrics = [];
@@ -31,6 +39,12 @@ function metrics() {
counters = {};
timings = {};
+ // Clear the timeout interval since the collector is now empty.
+ if (interval) {
+ clearTimeout(interval);
+ interval = undefined;
+ }
+
if (metrics.length < 1) { return; }
if (this.developmentEnvironments.indexOf(this.environment) !== -1) { return; }
@@ -59,12 +73,14 @@ function metrics() {
function increment(name, value) {
if (!counters[name]) { counters[name] = 0; }
counters[name] += value;
+ intervalCollect.call(this);
return this;
}
function timing(name, duration) {
if (!timings[name]) { timings[name] = []; }
timings[name].push(duration);
+ intervalCollect.call(this);
return this;
}
|
Schedule metrics interval on demand instead of recursively. Fixes #9
|
honeybadger-io_honeybadger-node
|
train
|
317405caf90c9c0653f0138827383ac5085f1a4a
|
diff --git a/openquake/job/__init__.py b/openquake/job/__init__.py
index <HASH>..<HASH> 100644
--- a/openquake/job/__init__.py
+++ b/openquake/job/__init__.py
@@ -77,10 +77,10 @@ def run_job(job_file, output_type):
try:
results = a_job.launch()
- except Exception as e:
+ except:
a_job.set_status('failed')
- raise e
+ raise
else:
a_job.set_status('succeeded')
|
Fixed the catch all/raise idiom in run_job.
The broken one was discarding the stack trace.
Former-commit-id: <I>de<I>b<I>d<I>aaa<I>c<I>bf<I>cccbe<I>a<I>a
|
gem_oq-engine
|
train
|
92a96e2003eae4a16bc1e4fc2704ab204ae04188
|
diff --git a/auth/config/auth.social.php b/auth/config/auth.social.php
index <HASH>..<HASH> 100644
--- a/auth/config/auth.social.php
+++ b/auth/config/auth.social.php
@@ -92,7 +92,7 @@ $config['auth_social_signon_providers'] = [
],
'wrapper' => [
'class' => 'Hybrid_Providers_Instagram',
- 'path' => FCPATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-instagram/Providers/Instagram.php',
+ 'path' => NAILS_APP_PATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-instagram/Providers/Instagram.php',
],
],
[
@@ -107,7 +107,7 @@ $config['auth_social_signon_providers'] = [
],
'wrapper' => [
'class' => 'Hybrid_Providers_GitHub',
- 'path' => FCPATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-github/Providers/GitHub.php',
+ 'path' => NAILS_APP_PATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-github/Providers/GitHub.php',
],
],
[
@@ -122,7 +122,7 @@ $config['auth_social_signon_providers'] = [
],
'wrapper' => [
'class' => 'Hybrid_Providers_px500',
- 'path' => FCPATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-500px/Providers/px500.php',
+ 'path' => NAILS_APP_PATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-500px/Providers/px500.php',
],
],
[
@@ -137,7 +137,7 @@ $config['auth_social_signon_providers'] = [
],
'wrapper' => [
'class' => 'Hybrid_Providers_Tumblr',
- 'path' => FCPATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-tumblr/Providers/Tumblr.php',
+ 'path' => NAILS_APP_PATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-tumblr/Providers/Tumblr.php',
],
],
[
@@ -152,7 +152,7 @@ $config['auth_social_signon_providers'] = [
],
'wrapper' => [
'class' => 'Hybrid_Providers_Vimeo',
- 'path' => FCPATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-vimeo/Providers/Vimeo.php',
+ 'path' => NAILS_APP_PATH . 'vendor/hybridauth/hybridauth/additional-providers/hybridauth-vimeo/Providers/Vimeo.php',
],
],
];
|
chore: Replaced constant FCPATH with NAILS_APP_PATH
|
nails_module-auth
|
train
|
ec541a22b4ad15743e3685d00794375ed29e4ff7
|
diff --git a/resource_aws_network_acl_test.go b/resource_aws_network_acl_test.go
index <HASH>..<HASH> 100644
--- a/resource_aws_network_acl_test.go
+++ b/resource_aws_network_acl_test.go
@@ -182,6 +182,18 @@ func TestAccAWSNetworkAcl_SubnetChange(t *testing.T) {
}
func TestAccAWSNetworkAcl_Subnets(t *testing.T) {
+ var networkAcl ec2.NetworkACL
+
+ checkACLSubnets := func(acl *ec2.NetworkACL, count int) resource.TestCheckFunc {
+ return func(*terraform.State) (err error) {
+ if count != len(acl.Associations) {
+ return fmt.Errorf("ACL association count does not match, expected %d, got %d", count, len(acl.Associations))
+ }
+
+ return nil
+ }
+ }
+
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
@@ -190,17 +202,21 @@ func TestAccAWSNetworkAcl_Subnets(t *testing.T) {
resource.TestStep{
Config: testAccAWSNetworkAclSubnet_SubnetIds,
Check: resource.ComposeTestCheckFunc(
+ testAccCheckAWSNetworkAclExists("aws_network_acl.bar", &networkAcl),
testAccCheckSubnetIsAssociatedWithAcl("aws_network_acl.bar", "aws_subnet.one"),
testAccCheckSubnetIsAssociatedWithAcl("aws_network_acl.bar", "aws_subnet.two"),
+ checkACLSubnets(&networkAcl, 2),
),
},
resource.TestStep{
Config: testAccAWSNetworkAclSubnet_SubnetIdsUpdate,
Check: resource.ComposeTestCheckFunc(
+ testAccCheckAWSNetworkAclExists("aws_network_acl.bar", &networkAcl),
testAccCheckSubnetIsAssociatedWithAcl("aws_network_acl.bar", "aws_subnet.one"),
testAccCheckSubnetIsAssociatedWithAcl("aws_network_acl.bar", "aws_subnet.three"),
testAccCheckSubnetIsAssociatedWithAcl("aws_network_acl.bar", "aws_subnet.four"),
+ checkACLSubnets(&networkAcl, 3),
),
},
},
|
provider/aws: Add tests for Network ACL subnets
|
terraform-providers_terraform-provider-aws
|
train
|
d198e286a07aefc82311b470c130a3631e5a7779
|
diff --git a/MarkdownPP/Modules/TableOfContents.py b/MarkdownPP/Modules/TableOfContents.py
index <HASH>..<HASH> 100644
--- a/MarkdownPP/Modules/TableOfContents.py
+++ b/MarkdownPP/Modules/TableOfContents.py
@@ -1,7 +1,7 @@
# Copyright (C) 2010 John Reese
# Licensed under the MIT license
-import re
+import re, sys
from MarkdownPP.Module import Module
from MarkdownPP.Transform import Transform
@@ -10,7 +10,7 @@ tocre = re.compile("^!TOC(\s+[1-6])?\s*$")
atxre = re.compile("^(#+)\s*(.+)$")
setextre = re.compile("^(=+|-+)\s*$")
fencedcodere = re.compile("^```\w*$")
-linkre = re.compile("(\[(.*?)\]\(.*?\))")
+linkre = re.compile("(\[(.*?)\][\(\[].*?[\)\]])")
class TableOfContents(Module):
"""
@@ -26,6 +26,7 @@ class TableOfContents(Module):
return title
def transform(self, data):
+ print data
transforms = []
lowestdepth = 10
@@ -141,7 +142,7 @@ class TableOfContents(Module):
section = ".".join([str(x) for x in stack]) + ".%d\\. " % headernum
tocdata += "%s [%s](#%s) \n" % (section, TableOfContents.clean_title(title), short)
- transforms.append(Transform(linenum, "swap", re.sub(title, section + title, data[linenum])))
+ transforms.append(Transform(linenum, "swap", data[linenum].replace(title, section + title)))
transforms.append(Transform(linenum, "prepend", "<a name=\"%s\"></a>\n\n" % short))
# create transforms for the !TOC markers
|
Add support for [text][link] style links, fix re.sub bug with string.replace since we're not using re.sub with a regex anyway
|
jreese_markdown-pp
|
train
|
e48c761787af8eb3304172ccd8c9357adcaf3405
|
diff --git a/werkzeug/datastructures.py b/werkzeug/datastructures.py
index <HASH>..<HASH> 100644
--- a/werkzeug/datastructures.py
+++ b/werkzeug/datastructures.py
@@ -1596,10 +1596,8 @@ class Accept(ImmutableList):
list.__init__(self, values)
else:
self.provided = True
- values = [(a, b) for b, a in values]
- values.sort()
- values.reverse()
- list.__init__(self, [(a, b) for b, a in values])
+ values = sorted(values, key=lambda x: (x[1], x[0]), reverse=True)
+ list.__init__(self, values)
def _value_matches(self, value, item):
"""Check if a value matches a given accept item."""
|
Simplifies Accept header constructor.
This commit removes the function calls and in-place sorting in favor of
using the built-in `sorted` method with the appropriate `key` and
`reverse` keyword arguments.
|
pallets_werkzeug
|
train
|
9e301e2a9d8bb0a011f75c78e346398fc82608e6
|
diff --git a/lib/lazy_resource/request.rb b/lib/lazy_resource/request.rb
index <HASH>..<HASH> 100644
--- a/lib/lazy_resource/request.rb
+++ b/lib/lazy_resource/request.rb
@@ -30,7 +30,6 @@ module LazyResource
def log_response(response)
LazyResource.logger.info "[#{response.code}](#{(response.time * 1000).ceil}ms): #{self.url}"
- LazyResource.logger.info "\t#{response.body}"
end
def parse
|
Response logger: Remove the body.
|
ahlatimer_lazy_resource
|
train
|
af9ca983ad0aeda516ace93d38bebc305c9bef2d
|
diff --git a/lib/Gitlab/Model/Event.php b/lib/Gitlab/Model/Event.php
index <HASH>..<HASH> 100644
--- a/lib/Gitlab/Model/Event.php
+++ b/lib/Gitlab/Model/Event.php
@@ -13,8 +13,10 @@ class Event extends AbstractModel
'target_id',
'target_type',
'author_id',
+ 'author_username',
'data',
'target_title',
+ 'author',
'project'
);
@@ -22,6 +24,10 @@ class Event extends AbstractModel
{
$event = new static($project, $client);
+ if (isset($data['author_id'])) {
+ $data['author'] = new User($data['author_id'], $client);
+ }
+
return $event->hydrate($data);
}
|
Expose username in project events and adder user object based on author_id to Event. Fixes #<I>
|
m4tthumphrey_php-gitlab-api
|
train
|
869499b0b6d5858994af3146edadae680cd09a38
|
diff --git a/trunk/JLanguageTool/src/java/de/danielnaber/languagetool/rules/de/CaseRule.java b/trunk/JLanguageTool/src/java/de/danielnaber/languagetool/rules/de/CaseRule.java
index <HASH>..<HASH> 100644
--- a/trunk/JLanguageTool/src/java/de/danielnaber/languagetool/rules/de/CaseRule.java
+++ b/trunk/JLanguageTool/src/java/de/danielnaber/languagetool/rules/de/CaseRule.java
@@ -78,6 +78,8 @@ public class CaseRule extends GermanRule {
private static final Set<String> exceptions = new HashSet<String>();
static {
+ exceptions.add("Für"); // "das Für und Wider"
+ exceptions.add("Wider"); // "das Für und Wider"
exceptions.add("Nachts"); // "des Nachts", "eines Nachts"
exceptions.add("Genüge");
exceptions.add("Zusage");
|
add "Für" and "Wider" as exceptions
|
languagetool-org_languagetool
|
train
|
09537344547dd6c52f8737c68ed7735b7ea6fcb3
|
diff --git a/src/Composer/ExtensionAutoloader.php b/src/Composer/ExtensionAutoloader.php
index <HASH>..<HASH> 100644
--- a/src/Composer/ExtensionAutoloader.php
+++ b/src/Composer/ExtensionAutoloader.php
@@ -2,6 +2,7 @@
namespace Bolt\Composer;
+use Bolt\Extension\ExtensionInterface;
use Bolt\Filesystem\FilesystemInterface;
use Bolt\Filesystem\Handler\File;
use Bolt\Filesystem\Handler\JsonFile;
@@ -30,6 +31,38 @@ class ExtensionAutoloader
}
/**
+ * Load a collection of extension classes.
+ *
+ * @return \Bolt\Extension\ExtensionInterface[]
+ */
+ public function load()
+ {
+ /** @var JsonFile $autoloadJson */
+ $autoloadJson = $this->filesystem->get('autoload.json');
+ if (!$autoloadJson->exists()) {
+ return [];
+ }
+ $autoloadPhp = $this->filesystem->get('vendor/autoload.php');
+ if (!$autoloadPhp->exists()) {
+ return [];
+ }
+ require_once dirname(dirname(__DIR__)) . '/extensions/vendor/autoload.php';
+
+ /** @var ExtensionInterface[] $classes */
+ $classes = [];
+ foreach ($autoloadJson->parse() as $loader) {
+ if (class_exists($loader['class'])) {
+ /** @var ExtensionInterface $class */
+ $class = new $loader['class']();
+ $name = $class->getName();
+ $classes[$name] = $class;
+ }
+ }
+
+ return $classes;
+ }
+
+ /**
* Build the autoload data for all extensions.
*/
public function build()
|
Load a collection of extension classes
|
bolt_bolt
|
train
|
14c9b85b7947a9a6128a86498a469f50148415b3
|
diff --git a/atoma/simple.py b/atoma/simple.py
index <HASH>..<HASH> 100644
--- a/atoma/simple.py
+++ b/atoma/simple.py
@@ -1,7 +1,9 @@
"""Simple API that abstracts away the differences between feed types."""
from datetime import datetime, timedelta
+import os
from typing import Optional, List, Tuple
+import urllib.parse
import attr
@@ -59,7 +61,8 @@ def _adapt_atom_feed(atom_feed: atom.AtomFeed) -> Feed:
article_link = candidate_link.href
elif candidate_link.rel == 'enclosure':
attachments.append(Attachment(
- title=candidate_link.title,
+ title=_get_attachment_title(candidate_link.title,
+ candidate_link.href),
link=candidate_link.href,
mime_type=candidate_link.type_,
size_in_bytes=candidate_link.length,
@@ -97,7 +100,7 @@ def _adapt_rss_channel(rss_channel: rss.RSSChannel) -> Feed:
for item in rss_channel.items:
attachments = [
Attachment(link=e.url, mime_type=e.type, size_in_bytes=e.length,
- title=None, duration=None)
+ title=_get_attachment_title(None, e.url), duration=None)
for e in item.enclosures
]
articles.append(Article(
@@ -126,7 +129,8 @@ def _adapt_json_feed(json_feed: json_feed.JSONFeed) -> Feed:
articles = list()
for item in json_feed.items:
attachments = [
- Attachment(a.url, a.mime_type, a.title,
+ Attachment(a.url, a.mime_type,
+ _get_attachment_title(a.title, a.url),
a.size_in_bytes, a.duration)
for a in item.attachments
]
@@ -164,6 +168,14 @@ def _get_article_dates(published_at: Optional[datetime],
raise FeedParseError('Article does not have proper dates')
+def _get_attachment_title(attachment_title: Optional[str], link: str) -> str:
+ if attachment_title:
+ return attachment_title
+
+ parsed_link = urllib.parse.urlparse(link)
+ return os.path.basename(parsed_link.path)
+
+
def _simple_parse(pairs, content) -> Feed:
is_xml = True
is_json = True
|
Generate fallback attachment title in simple API if needed
|
NicolasLM_atoma
|
train
|
817c1f74ae9a6c0ac5fe6c2e7960d5633b721d00
|
diff --git a/lib/subtle/param_constructor.rb b/lib/subtle/param_constructor.rb
index <HASH>..<HASH> 100644
--- a/lib/subtle/param_constructor.rb
+++ b/lib/subtle/param_constructor.rb
@@ -5,8 +5,8 @@ class Object
params.each do |attr, value|
self.public_send("#{attr}=", value)
end if params
- block.call(self) if block
constructor_method(self) if respond_to?(:constructor_method)
+ block.call(self) if block
end')
unless block_for_each.nil?
self.send(:define_method, :constructor_method, &block_for_each)
diff --git a/spec/subtle/param_constructor_spec.rb b/spec/subtle/param_constructor_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/subtle/param_constructor_spec.rb
+++ b/spec/subtle/param_constructor_spec.rb
@@ -15,6 +15,15 @@ class ThirdParamConstructorTest
attr_accessor :first_name, :last_name
end
+class FourthParamConstructorTest
+ param_constructor do |p|
+ p.middle_name = 'm'
+ p.first_name = 'f'
+ p.last_name = 'l'
+ end
+ attr_accessor :first_name, :last_name, :middle_name
+end
+
describe "param_constructor" do
describe 'just the constructor itself' do
it "should let the object be instantiated with a hash" do
@@ -45,4 +54,16 @@ describe "param_constructor" do
test.first_name.must_equal 'expected value'
end
end
+
+ describe 'pass a block with the constructor AND to the constructor' do
+ it "should run both and let the last one win" do
+ test = FourthParamConstructorTest.new(first_name: "", last_name: "") do |o|
+ o.last_name = "second"
+ o.first_name = "first"
+ end
+ test.first_name.must_equal 'first'
+ test.last_name.must_equal 'second'
+ test.middle_name.must_equal 'm'
+ end
+ end
end
|
Make sure the instance-specific block is called last.
|
darrencauthon_subtle
|
train
|
fa5e644b745e7a15e105b782c455a549cd4734c9
|
diff --git a/writer.go b/writer.go
index <HASH>..<HASH> 100644
--- a/writer.go
+++ b/writer.go
@@ -48,13 +48,15 @@ func NewMasterPlaylist() *MasterPlaylist {
return p
}
-// Append variant to master playlist
+// Append variant to master playlist.
+// This operation does reset playlist cache.
func (p *MasterPlaylist) Append(uri string, chunklist *MediaPlaylist, params VariantParams) {
v := new(Variant)
v.URI = uri
v.Chunklist = chunklist
v.VariantParams = params
p.Variants = append(p.Variants, v)
+ p.buf.Reset()
}
func (p *MasterPlaylist) ResetCache() {
@@ -177,21 +179,22 @@ func NewMediaPlaylist(winsize uint, capacity uint) (*MediaPlaylist, error) {
}
// Remove current segment from the head of chunk slice form a media playlist. Useful for sliding playlists.
-// This operation does reset cache.
+// This operation does reset playlist cache.
func (p *MediaPlaylist) Remove() (err error) {
if p.count == 0 {
return errors.New("playlist is empty")
}
p.head = (p.head + 1) % p.capacity
p.count--
- p.buf.Reset()
if !p.Closed {
p.SeqNo++
}
+ p.buf.Reset()
return nil
}
-// Append general chunk to the tail of chunk slice for a media playlist. This operation doesn't reset playlist cache.
+// Append general chunk to the tail of chunk slice for a media playlist.
+// This operation does reset playlist cache.
func (p *MediaPlaylist) Append(uri string, duration float64, title string) error {
if p.head == p.tail && p.count > 0 {
return errors.New("playlist is full")
@@ -206,6 +209,7 @@ func (p *MediaPlaylist) Append(uri string, duration float64, title string) error
if p.TargetDuration < duration {
p.TargetDuration = duration
}
+ p.buf.Reset()
return nil
}
@@ -213,7 +217,9 @@ func (p *MediaPlaylist) Append(uri string, duration float64, title string) error
// next chunk. Secondly it appends one chunk to the tail of chunk slice. Useful for sliding playlists.
// This operation does reset cache.
func (p *MediaPlaylist) Slide(uri string, duration float64, title string) {
- p.Remove()
+ if !p.Closed && p.count > p.winsize {
+ p.Remove()
+ }
p.Append(uri, duration, title)
}
|
Changed logic of Slide(). Now it will not remove chunks until playlist length is equal winsize.
|
grafov_m3u8
|
train
|
e56e03c816285f59066bfc2fd5648fa2339375b1
|
diff --git a/test/Channel.js b/test/Channel.js
index <HASH>..<HASH> 100644
--- a/test/Channel.js
+++ b/test/Channel.js
@@ -34,6 +34,7 @@ describe('Channel', function() {
server2 = new Server(new MemorySocket());
server1.on('error', function() {});
+ server2.on('error', function() {});
server1.on('connection', function() {
@@ -366,7 +367,7 @@ describe('Channel', function() {
});
});
});
-
+
server2.on('end', function() {
closedConnection = true;
checkDone();
diff --git a/test/Client.js b/test/Client.js
index <HASH>..<HASH> 100644
--- a/test/Client.js
+++ b/test/Client.js
@@ -1,6 +1,6 @@
/*
* Test stompit.Client
- * Copyright (c) 2013 Graham Daws <graham.daws@gmail.com>
+ * Copyright (c) 2013-2015 Graham Daws <graham.daws@gmail.com>
* MIT licensed
*/
@@ -11,6 +11,7 @@ var BufferWritable = require('../lib/util/buffer/BufferWritable');
var assert = require('assert');
var fail = function() {assert(false);};
+var noop = function() {};
describe('Client', function() {
@@ -26,6 +27,8 @@ describe('Client', function() {
beforeSendResponse(null);
};
+ server.on('error', noop);
+
client = new Client(socket.getPeerSocket());
});
@@ -107,6 +110,7 @@ describe('Client', function() {
// The remote host has ended the connection
client.on('end', function() {
+
ended = true;
assert(finished);
done();
@@ -121,8 +125,6 @@ describe('Client', function() {
server._send = function(frame, beforeSendResponse) {};
- server.on('error', function() {});
-
client.on('error', function(e) {
assert(e.message === 'cannot send frame on closed stream');
done();
@@ -524,7 +526,7 @@ describe('Client', function() {
assert(error && error.message === 'testing');
done();
});
-
+
client.destroy(new Error('testing'));
});
});
|
Fix client and channel tests; mock server should expect error event.
|
gdaws_node-stomp
|
train
|
db9a7204d2304c36313a772afa3ab3632e093406
|
diff --git a/encoding/ewkb/scan_test.go b/encoding/ewkb/scan_test.go
index <HASH>..<HASH> 100644
--- a/encoding/ewkb/scan_test.go
+++ b/encoding/ewkb/scan_test.go
@@ -20,7 +20,7 @@ func Example_scan() {
}
defer db.Close()
- mock.ExpectQuery(`SELECT name, location FROM cities WHERE name = \?;`).
+ mock.ExpectQuery(`SELECT name, ST_AsEWKB\(location\) FROM cities WHERE name = \?;`).
WithArgs("London").
WillReturnRows(
sqlmock.NewRows([]string{"name", "location"}).
@@ -28,7 +28,7 @@ func Example_scan() {
)
var c City
- if err := db.QueryRow(`SELECT name, location FROM cities WHERE name = ?;`, "London").Scan(&c.Name, &c.Location); err != nil {
+ if err := db.QueryRow(`SELECT name, ST_AsEWKB(location) FROM cities WHERE name = ?;`, "London").Scan(&c.Name, &c.Location); err != nil {
log.Fatal(err)
}
diff --git a/encoding/wkb/scan_test.go b/encoding/wkb/scan_test.go
index <HASH>..<HASH> 100644
--- a/encoding/wkb/scan_test.go
+++ b/encoding/wkb/scan_test.go
@@ -20,7 +20,7 @@ func Example_scan() {
}
defer db.Close()
- mock.ExpectQuery(`SELECT name, location FROM cities WHERE name = \?;`).
+ mock.ExpectQuery(`SELECT name, ST_AsBinary\(location\) FROM cities WHERE name = \?;`).
WithArgs("London").
WillReturnRows(
sqlmock.NewRows([]string{"name", "location"}).
@@ -28,7 +28,7 @@ func Example_scan() {
)
var c City
- if err := db.QueryRow(`SELECT name, location FROM cities WHERE name = ?;`, "London").Scan(&c.Name, &c.Location); err != nil {
+ if err := db.QueryRow(`SELECT name, ST_AsBinary(location) FROM cities WHERE name = ?;`, "London").Scan(&c.Name, &c.Location); err != nil {
log.Fatal(err)
}
|
Make use of ST_AsBinary and ST_AsEWKB explicit in examples
|
twpayne_go-geom
|
train
|
6edc93707fc55e45403f07d4d1dc42be0ca6265e
|
diff --git a/src/main/java/com/github/webdriverextensions/internal/DefaultWebComponentFactory.java b/src/main/java/com/github/webdriverextensions/internal/DefaultWebComponentFactory.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/webdriverextensions/internal/DefaultWebComponentFactory.java
+++ b/src/main/java/com/github/webdriverextensions/internal/DefaultWebComponentFactory.java
@@ -16,13 +16,7 @@ public class DefaultWebComponentFactory implements WebComponentFactory {
T webComponent = (T) webComponentClass.newInstance();
webComponent.init(webElement);
return webComponent;
- } catch (IllegalArgumentException e) {
- throw new RuntimeException(e);
- } catch (SecurityException e) {
- throw new RuntimeException(e);
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
+ } catch (IllegalArgumentException|SecurityException|InstantiationException|IllegalAccessException e) {
throw new RuntimeException(e);
}
}
diff --git a/src/main/java/com/github/webdriverextensions/internal/ReflectionUtils.java b/src/main/java/com/github/webdriverextensions/internal/ReflectionUtils.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/webdriverextensions/internal/ReflectionUtils.java
+++ b/src/main/java/com/github/webdriverextensions/internal/ReflectionUtils.java
@@ -20,9 +20,7 @@ public class ReflectionUtils {
ElementLocator locator = (ElementLocator) locatorField.get(locatorField);
locatorField.setAccessible(false);
return locator;
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (NoSuchFieldException e) {
+ } catch (IllegalAccessException|NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
diff --git a/src/main/java/com/github/webdriverextensions/internal/WebDriverExtensionAnnotations.java b/src/main/java/com/github/webdriverextensions/internal/WebDriverExtensionAnnotations.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/webdriverextensions/internal/WebDriverExtensionAnnotations.java
+++ b/src/main/java/com/github/webdriverextensions/internal/WebDriverExtensionAnnotations.java
@@ -32,9 +32,7 @@ public class WebDriverExtensionAnnotations extends Annotations {
try {
fields[0].setAccessible(true); // Make sure field is accessible if it is not declared as public
delegate = (WebElement) fields[0].get(webComponent);
- } catch (IllegalArgumentException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
+ } catch (IllegalArgumentException|IllegalAccessException e) {
throw new RuntimeException(e);
}
return delegate;
diff --git a/src/main/java/com/github/webdriverextensions/internal/generator/WebRepositoryBuilder.java b/src/main/java/com/github/webdriverextensions/internal/generator/WebRepositoryBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/webdriverextensions/internal/generator/WebRepositoryBuilder.java
+++ b/src/main/java/com/github/webdriverextensions/internal/generator/WebRepositoryBuilder.java
@@ -53,11 +53,7 @@ public class WebRepositoryBuilder implements Builder<Boolean> {
createFields();
generate();
return true;
- } catch (IOException ex) {
- error("Failed to generate GeneratedWebRepository!", processingEnv);
- error(ExceptionUtils.getStackTrace(ex), processingEnv);
- return false;
- } catch (JClassAlreadyExistsException ex) {
+ } catch (IOException|JClassAlreadyExistsException ex) {
error("Failed to generate GeneratedWebRepository!", processingEnv);
error(ExceptionUtils.getStackTrace(ex), processingEnv);
return false;
diff --git a/src/main/java/com/github/webdriverextensions/internal/generator/WebSiteBuilder.java b/src/main/java/com/github/webdriverextensions/internal/generator/WebSiteBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/webdriverextensions/internal/generator/WebSiteBuilder.java
+++ b/src/main/java/com/github/webdriverextensions/internal/generator/WebSiteBuilder.java
@@ -51,11 +51,7 @@ public class WebSiteBuilder implements Builder<Boolean> {
createFields();
generate();
return true;
- } catch (IOException ex) {
- error("Failed to generate GeneratedWebSite!", processingEnv);
- error(ExceptionUtils.getStackTrace(ex), processingEnv);
- return false;
- } catch (JClassAlreadyExistsException ex) {
+ } catch (IOException|JClassAlreadyExistsException ex) {
error("Failed to generate GeneratedWebSite!", processingEnv);
error(ExceptionUtils.getStackTrace(ex), processingEnv);
return false;
|
Fixing squid:S<I> - Catches should be combined.
|
webdriverextensions_webdriverextensions
|
train
|
5195161253a269c4c2e04971465c888503c43536
|
diff --git a/image.go b/image.go
index <HASH>..<HASH> 100644
--- a/image.go
+++ b/image.go
@@ -19,7 +19,6 @@ import (
"image"
"image/color"
"math"
- "runtime"
"sync/atomic"
"github.com/hajimehoshi/ebiten/internal/graphics"
@@ -639,7 +638,6 @@ func (i *Image) Dispose() error {
}
i.mipmap.dispose()
i.resolvePixelsToSet(false)
- runtime.SetFinalizer(i, nil)
return nil
}
@@ -724,7 +722,6 @@ func NewImage(width, height int, filter Filter) (*Image, error) {
filter: filter,
}
i.addr = i
- runtime.SetFinalizer(i, (*Image).Dispose)
return i, nil
}
@@ -766,7 +763,6 @@ func NewImageFromImage(source image.Image, filter Filter) (*Image, error) {
filter: filter,
}
i.addr = i
- runtime.SetFinalizer(i, (*Image).Dispose)
_ = i.ReplacePixels(graphics.CopyImage(source))
return i, nil
@@ -778,7 +774,6 @@ func newImageWithScreenFramebuffer(width, height int) *Image {
filter: FilterDefault,
}
i.addr = i
- runtime.SetFinalizer(i, (*Image).Dispose)
return i
}
|
graphics: Remove SetFinalizer at Image
Package shareable should take care of this.
Finalizers are called at arbitrary timing in a different goroutine
and might cause tough problems. This might be related to #<I>.
|
hajimehoshi_ebiten
|
train
|
87069c1bc9d4bb1b77b7854d2311c51450d4d8f6
|
diff --git a/src/ValuSo/Service/BatchService.php b/src/ValuSo/Service/BatchService.php
index <HASH>..<HASH> 100644
--- a/src/ValuSo/Service/BatchService.php
+++ b/src/ValuSo/Service/BatchService.php
@@ -83,7 +83,7 @@ class BatchService
$options = is_array($options) ? $options : array();
$options = array_merge(
- array(),
+ array('verbose' => false),
$options
);
@@ -122,6 +122,8 @@ class BatchService
}
$responses = array();
+ $errors = array();
+
foreach ($workers as $key => $worker) {
try{
$responses[$key] = $worker
@@ -130,10 +132,23 @@ class BatchService
} catch(\Exception $e) {
$responses[$key] = false;
+
+ if ($e instanceof Exception\ServiceException) {
+ $errors[$key] = ['m' => $e->getRawMessage(), 'c' => $e->getCode(), 'a' => $e->getVars()];
+ } else {
+ $errors[$key] = ['m' => 'Unknown error', 'c' => $e->getCode()];
+ }
}
}
- return $responses;
+ if ($options['verbose']) {
+ return [
+ 'results' => $responses,
+ 'errors' => $errors
+ ];
+ } else {
+ return $responses;
+ }
}
/**
|
Adds 'verbose' option to batch API
|
valu-digital_valuso
|
train
|
f08badea97836271bdfcb0fb36c14bdcbaf80cf3
|
diff --git a/test/mp/compiler/compile-to-template-alipay.spec.js b/test/mp/compiler/compile-to-template-alipay.spec.js
index <HASH>..<HASH> 100644
--- a/test/mp/compiler/compile-to-template-alipay.spec.js
+++ b/test/mp/compiler/compile-to-template-alipay.spec.js
@@ -28,14 +28,15 @@ function wrapHtml (code) {
}
function wrapMP (code, options = {}) {
- const { imports = {}, name = 'defaultName' } = options
+ const { imports = {}, name = 'defaultName', scopeId } = options
+ const scopedClass = scopeId ? ` ${scopeId}` : ''
const importStr = Object.keys(imports)
.map(k => `<import src="${imports[k].src}"/>`)
.join('')
return (
importStr +
`<template name="${name}">` +
- `<view class="_div">${code}</view>` +
+ `<view class="_div${scopedClass}">${code}</view>` +
`</template>`
)
}
@@ -45,7 +46,7 @@ function assertCodegen (body, assertTemplate, options = {}, callback) {
target: 'alipay'
})
- const template = wrapHtml(body)
+ const template = wrapHtml(body, options)
const output = compileToTemplate(template, options)
expect(output.body).toEqual(wrapMP(assertTemplate, options))
diff --git a/test/mp/compiler/compile-to-template-swan.spec.js b/test/mp/compiler/compile-to-template-swan.spec.js
index <HASH>..<HASH> 100644
--- a/test/mp/compiler/compile-to-template-swan.spec.js
+++ b/test/mp/compiler/compile-to-template-swan.spec.js
@@ -28,14 +28,15 @@ function wrapHtml (code) {
}
function wrapMP (code, options = {}) {
- const { imports = {}, name = 'defaultName' } = options
+ const { imports = {}, name = 'defaultName', scopeId } = options
+ const scopedClass = scopeId ? ` ${scopeId}` : ''
const importStr = Object.keys(imports)
.map(k => `<import src="${imports[k].src}"/>`)
.join('')
return (
importStr +
`<template name="${name}">` +
- `<view class="_div">${code}</view>` +
+ `<view class="_div${scopedClass}">${code}</view>` +
`</template>`
)
}
@@ -45,7 +46,7 @@ function assertCodegen (body, assertTemplate, options = {}, callback) {
target: 'swan'
})
- const template = wrapHtml(body)
+ const template = wrapHtml(body, options)
const output = compileToTemplate(template, options)
expect(output.body).toEqual(wrapMP(assertTemplate, options))
diff --git a/test/mp/compiler/compile-to-template-wechat.spec.js b/test/mp/compiler/compile-to-template-wechat.spec.js
index <HASH>..<HASH> 100644
--- a/test/mp/compiler/compile-to-template-wechat.spec.js
+++ b/test/mp/compiler/compile-to-template-wechat.spec.js
@@ -28,20 +28,21 @@ function wrapHtml (code) {
}
function wrapMP (code, options = {}) {
- const { imports = {}, name = 'defaultName' } = options
+ const { imports = {}, name = 'defaultName', scopeId } = options
+ const scopedClass = scopeId ? ` ${scopeId}` : ''
const importStr = Object.keys(imports)
.map(k => `<import src="${imports[k].src}"/>`)
.join('')
return (
importStr +
`<template name="${name}">` +
- `<view class="_div">${code}</view>` +
+ `<view class="_div${scopedClass}">${code}</view>` +
`</template>`
)
}
function assertCodegen (body, assertTemplate, options = {}, callback) {
- const template = wrapHtml(body)
+ const template = wrapHtml(body, options)
const output = compileToTemplate(template, options)
expect(output.body).toEqual(wrapMP(assertTemplate, options))
|
test: update test for scope-id
|
kaola-fed_megalo
|
train
|
bd26306339513c29668e7b8a8b96bcbcf6f03805
|
diff --git a/src/server_core.js b/src/server_core.js
index <HASH>..<HASH> 100644
--- a/src/server_core.js
+++ b/src/server_core.js
@@ -127,7 +127,8 @@ module.exports = function(React, ReactDOMServer, static_files, html_base, tools)
var entry = route.entry || "boot";
try {
- var initial_data = await state_builder.get(entry);
+ await state_builder.get(entry);
+ var initial_data = state_builder.getOutput();
Object.assign(initial_data, state_builder.getAllCookies());
} catch(error) {
var initial_data = null;
diff --git a/src/state_builder.js b/src/state_builder.js
index <HASH>..<HASH> 100644
--- a/src/state_builder.js
+++ b/src/state_builder.js
@@ -11,6 +11,7 @@ var StateBuilder = function(params, sequelize, db, logger, decorators, statelets
var m_StateletPromises = {};
var m_Statelets = {};
var m_Cookies = {};
+ var m_OutputData = {};
var m_OutputHeaders = {};
var m_OutputCookies = {};
var m_OutputFile = null;
@@ -56,6 +57,13 @@ var StateBuilder = function(params, sequelize, db, logger, decorators, statelets
logger[level](msg);
}
};
+ m_Api.output = function(key, value) {
+ if(typeof key === "string") {
+ m_OutputData[key] = value;
+ } else {
+ m_OutputData = Object.assign({}, m_OutputData, key);
+ }
+ };
m_Api.outputCookie = function(name, value) {
m_OutputCookies[name] = value;
};
@@ -122,6 +130,12 @@ var StateBuilder = function(params, sequelize, db, logger, decorators, statelets
m_StateletPromises[name] = promise;
return promise;
};
+ m_Api.getOutput = function(key) {
+ if(key) {
+ return m_OutputData[key];
+ }
+ return m_OutputData;
+ };
m_Api.getAllOutputHeaders = function(base) {
var output = Object.assign({}, base, m_OutputHeaders);
|
Refactored statelets to use output pattern for public consumption rather than return value
|
GrigoryGraborenko_boc
|
train
|
50481e76b27c0b4aa230fe86faeda82cd3c97be7
|
diff --git a/pysoa/server/server.py b/pysoa/server/server.py
index <HASH>..<HASH> 100644
--- a/pysoa/server/server.py
+++ b/pysoa/server/server.py
@@ -634,12 +634,12 @@ class Server(object):
try:
settings = cls.settings_class(django_settings.SOA_SERVER_SETTINGS)
except AttributeError:
- raise ValueError('Cannot find SOA_SERVER_SETTINGS in the Django settings')
+ raise ValueError('Cannot find `SOA_SERVER_SETTINGS` in the Django settings.')
else:
try:
settings_module = importlib.import_module(cmd_options.settings)
except ImportError as e:
- raise ValueError('Cannot import settings module %s: %s' % (cmd_options.settings, e))
+ raise ValueError('Cannot import settings module `%s`: %s' % (cmd_options.settings, e))
try:
settings_dict = getattr(settings_module, 'SOA_SERVER_SETTINGS')
except AttributeError:
@@ -647,7 +647,7 @@ class Server(object):
settings_dict = getattr(settings_module, 'settings')
except AttributeError:
raise ValueError(
- "Cannot find 'SOA_SERVER_SETTINGS' or 'settings' variable in settings module {}.".format(
+ "Cannot find `SOA_SERVER_SETTINGS` or `settings` variable in settings module `{}`.".format(
cmd_options.settings,
)
)
diff --git a/pysoa/server/standalone.py b/pysoa/server/standalone.py
index <HASH>..<HASH> 100644
--- a/pysoa/server/standalone.py
+++ b/pysoa/server/standalone.py
@@ -3,6 +3,8 @@ from __future__ import (
unicode_literals,
)
+import importlib
+import logging
import sys
@@ -164,7 +166,34 @@ def django_main(server_getter):
if args.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = args.settings
+ warn_about_logging = False
+
+ try:
+ # We have to import it manually, because we need to manipulate the settings before setup() is called, but we
+ # can't import django.conf.settings until after setup() is called.
+ django_settings = importlib.import_module(os.environ['DJANGO_SETTINGS_MODULE'])
+ if (
+ getattr(django_settings, 'LOGGING', None) and
+ django_settings.LOGGING != django_settings.SOA_SERVER_SETTINGS['logging']
+ ):
+ warn_about_logging = True
+ django_settings.LOGGING = django_settings.SOA_SERVER_SETTINGS['logging']
+ except ImportError:
+ raise ValueError('Cannot import Django settings module `{}`.'.format(os.environ['DJANGO_SETTINGS_MODULE']))
+ except AttributeError:
+ raise ValueError('Cannot find `SOA_SERVER_SETTINGS` in the Django settings module.')
+ except KeyError:
+ raise ValueError(
+ "Cannot configure Django `LOGGING` setting because no setting `SOA_SERVER_SETTINGS['logging']` was found.",
+ )
+
if django.VERSION >= (1, 7):
django.setup()
+ if warn_about_logging:
+ logging.warning(
+ "Django setting `LOGGING` differs from `SOA_SERVER_SETTINGS['logging']` and has been overwritten with "
+ "the value of `SOA_SERVER_SETTINGS['logging']`."
+ )
+
_run_server_reloader_wrapper(args, server_getter())
|
[MINOR] Improve logging configuration to not conflict with Django
If Django `settings.LOGGING` is present, Django will call `logging.config.dictConfig`. This can conflict with PySOA's call to `logging.config.dictConfig` with `settings.SOA_SERVER_SETTINGS['logging']`. This change ensures that the two logging configs are identical so that we'll have consistent behavior.
|
eventbrite_pysoa
|
train
|
4024b27084eaf1088cdf748b3b5d76827e9dc1b1
|
diff --git a/mongorest/__init__.py b/mongorest/__init__.py
index <HASH>..<HASH> 100644
--- a/mongorest/__init__.py
+++ b/mongorest/__init__.py
@@ -1,4 +1,4 @@
# -*- encoding: UTF-8 -*-
from __future__ import absolute_import, unicode_literals
-__version__ = '2.5.1'
+__version__ = '2.5.2'
diff --git a/mongorest/resource.py b/mongorest/resource.py
index <HASH>..<HASH> 100644
--- a/mongorest/resource.py
+++ b/mongorest/resource.py
@@ -132,7 +132,9 @@ class RetrieveResourceMixin(Resource):
"""
Returns the document containing the given _id or 404
"""
- document = self.collection.find_one(deserialize(_id))
+ document = self.collection.find_one(
+ dict(request.args, **{'_id': deserialize(_id)})
+ )
if document:
return Response(
@@ -163,7 +165,9 @@ class UpdateResourceMixin(Resource):
"""
Updates the document with the given _id using the given data
"""
- to_update = self.collection.find_one(deserialize(_id))
+ to_update = self.collection.find_one(
+ dict(request.args, **{'_id': deserialize(_id)})
+ )
if to_update:
document = self.collection(
@@ -199,7 +203,9 @@ class DeleteResourceMixin(Resource):
"""
Deletes the document with the given _id if it exists
"""
- to_delete = self.collection.find_one(deserialize(_id))
+ to_delete = self.collection.find_one(
+ dict(request.args, **{'_id': deserialize(_id)})
+ )
if to_delete:
deleted = self.collection.delete_one({'_id': deserialize(_id)})
|
<I> now every resource uses the args as parameters on finding
|
lvieirajr_mongorest
|
train
|
eb676519ba644036f302bb3dc65d7c4d97438385
|
diff --git a/superset/connectors/druid/models.py b/superset/connectors/druid/models.py
index <HASH>..<HASH> 100644
--- a/superset/connectors/druid/models.py
+++ b/superset/connectors/druid/models.py
@@ -1331,10 +1331,10 @@ class DruidDatasource(Model, BaseDatasource):
client=client, query_obj=query_obj, phase=2)
df = client.export_pandas()
- df = self.homogenize_types(df, query_obj.get('groupby', []))
-
if df is None or df.size == 0:
raise Exception(_('No data was returned.'))
+
+ df = self.homogenize_types(df, query_obj.get('groupby', []))
df.columns = [
DTTM_ALIAS if c in ('timestamp', '__time') else c
for c in df.columns
|
Moving homogenize_types to after no data exception (#<I>)
|
apache_incubator-superset
|
train
|
f0af4e449a21d7918f00ef0ebc26c793a8276d44
|
diff --git a/test/integration/test_buildconfigurations_api.py b/test/integration/test_buildconfigurations_api.py
index <HASH>..<HASH> 100644
--- a/test/integration/test_buildconfigurations_api.py
+++ b/test/integration/test_buildconfigurations_api.py
@@ -1,7 +1,9 @@
import pytest
+from pnc_cli import products
from pnc_cli import projects
from pnc_cli import environments
from pnc_cli import buildconfigurations
+from pnc_cli import productversions
from pnc_cli.swagger_client import BuildconfigurationsApi
from pnc_cli.swagger_client import RunningbuildrecordsApi
from pnc_cli import utils
@@ -17,17 +19,26 @@ def get_configs_api():
global configs_api
configs_api = BuildconfigurationsApi(utils.get_api_client())
+
+@pytest.fixture(scope='function')
+def new_product(request):
+ product = products.create_product(name=testutils.gen_random_name() + '-product')
+ return product
+
+
@pytest.fixture(scope='function')
def new_project(request):
- project = projects.create_project(name=testutils.gen_random_name()+'-project')
+ project = projects.create_project(name=testutils.gen_random_name() + '-project')
return project
+
@pytest.fixture(scope='function')
def new_environment(request):
randname = testutils.gen_random_name()
env = environments.create_environment(name=randname + '-environment', build_type='JAVA', image_id=randname)
return env
+
@pytest.fixture(scope='function')
def new_config(request, new_project, new_environment):
created_bc = configs_api.create_new(
@@ -38,7 +49,7 @@ def new_config(request, new_project, new_environment):
build_script='mvn clean install',
product_version_ids=[1],
scm_repo_url='https://github.com/thauser/simple-maven-build-pnc.git',
- )).content
+ )).content
return created_bc
@@ -158,7 +169,8 @@ def test_update(new_config):
updated = configs_api.get_specific(id=new_config.id).content
keys_updated = set(updated.attribute_map).difference(ignored_keys)
keys_new_config = set(new_config.attribute_map).difference(ignored_keys)
- assert keys_updated == keys_new_config and (getattr(updated, key) == getattr(new_config, key) for key in keys_updated)
+ assert keys_updated == keys_new_config and (getattr(updated, key) == getattr(new_config, key) for key in
+ keys_updated)
def test_delete_specific_no_id():
@@ -308,8 +320,24 @@ def test_add_product_version_invalid_param():
# get_product_versions
# remove_product_version
# TODO: cannot test due to test_productversions_api incomplete
-def test_product_version_operations(new_config):
- pass
+def test_product_version_operations(new_product, new_config):
+ randversion = testutils.gen_random_version()
+
+ #create a test ProductVersion
+ version_rest = productversions.create_product_version(product_id=new_product.id,version=randversion)
+
+ #add_product_version
+ configs_api.add_product_version(id=new_config.id, body=version_rest)
+
+ #get_product_versions
+ config_versions = configs_api.get_product_versions(id=new_config.id)
+ assert version_rest.id in [x.id for x in config_versions.content]
+
+ #remove_product_version
+ configs_api.remove_product_version(id=new_config.id, product_version_id=version_rest.id)
+ config_versions = configs_api.get_product_versions(id=new_config.id)
+ if config_versions.content is not None:
+ assert version_rest.id not in [x.id for x in config_versions.content]
def test_get_revisions_no_id():
@@ -334,7 +362,7 @@ def test_get_revision_invalid_param():
# get_revisions
# get_revision
-@pytest.mark.xfail(reason='get_revisions is currently non-functional.')
+@pytest.mark.xfail(reason='need to be able to create revisions on the new_config.')
def test_revision_operations(new_config):
revisions = configs_api.get_revisions(id=new_config.id).content
assert revisions is not None
|
fix test_product_version_operations. <I>% coverage of buildconfigurations_api reached
|
project-ncl_pnc-cli
|
train
|
1a21b4c940893a7ed1308c179513dd9b31245822
|
diff --git a/packages/list-view/tests/list_view_test.js b/packages/list-view/tests/list_view_test.js
index <HASH>..<HASH> 100644
--- a/packages/list-view/tests/list_view_test.js
+++ b/packages/list-view/tests/list_view_test.js
@@ -466,10 +466,12 @@ test("height change", function(){
deepEqual(itemPositions().map(yPosition), [0, 50, 100], "The rows are in the correct positions" );
});
-test("height change after with scroll", function(){
+test("height and width change after with scroll", function(){
var content = generateContent(100),
- height = 500,
+ height = 150,
rowHeight = 50,
+ elementWidth = 50,
+ width = 100,
itemViewClass = Ember.ListItemView.extend({
template: Ember.Handlebars.compile("{{name}}")
});
@@ -477,8 +479,10 @@ test("height change after with scroll", function(){
Ember.run(function(){
view = Ember.ListView.create({
content: content,
+ width: width,
height: height,
rowHeight: rowHeight,
+ elementWidth: elementWidth,
itemViewClass: itemViewClass
});
});
@@ -489,51 +493,46 @@ test("height change after with scroll", function(){
view.scrollTo(1000);
});
- equal(view.$('.ember-list-item-view').length, 11, "The correct number of rows were rendered");
+ equal(view.$('.ember-list-item-view').length, 8, "The correct number of rows were rendered");
- deepEqual(itemPositions().map(yPosition), [
- 1000,
- 1050,
- 1100,
- 1150,
- 1200,
- 1250,
- 1300,
- 1350,
- 1400,
- 1450,
- 1500], "The rows are in the correct positions");
+ deepEqual(itemPositions(), [
+ { x: 0, y: 1000 },
+ { x: 50, y: 1000 },
+ { x: 0, y: 1050 },
+ { x: 50, y: 1050 },
+ { x: 0, y: 1100 },
+ { x: 50, y: 1100 },
+ { x: 0, y: 1150 },
+ { x: 50, y: 1150 }], "The rows are in the correct positions");
Ember.run(function() {
view.set('height', 100);
+ view.set('width', 50);
});
equal(view.$('.ember-list-item-view').length, 3, "The correct number of rows were rendered");
- deepEqual(itemPositions().map(yPosition), [
- 1000,
- 1050,
- 1100], "The rows are in the correct positions");
+ deepEqual(itemPositions(), [
+ { x: 0, y: 1000 },
+ { x: 0, y: 1050 },
+ { x: 0, y: 1100 }], "The rows are in the correct positions");
Ember.run(function() {
- view.set('height', 500);
+ view.set('height', 150);
+ view.set('width', 100);
});
- equal(view.$('.ember-list-item-view').length, 11, "The correct number of rows were rendered");
-
- deepEqual(itemPositions().map(yPosition), [
- 1000,
- 1050,
- 1100,
- 1150,
- 1200,
- 1250,
- 1300,
- 1350,
- 1400,
- 1450,
- 1500], "The rows are in the correct positions");
-
+ deepEqual(itemPositions(), [
+ { x: 0, y: 1000 },
+ { x: 50, y: 1000 },
+ { x: 0, y: 1050 },
+ { x: 50, y: 1050 },
+ { x: 0, y: 1100 },
+ { x: 50, y: 1100 },
+ { x: 0, y: 1150 },
+ { x: 50, y: 1150 }], "The rows are in the correct positions");
+
+ equal(view.$('.ember-list-item-view').length, 8, "The correct number of rows were rendered");
});
test("elementWidth change", function(){
|
add height and width change post scroll test
|
emberjs_list-view
|
train
|
baa66b0babf407d54f2146b61c497621ae8f40e4
|
diff --git a/examples/fetch.js b/examples/fetch.js
index <HASH>..<HASH> 100644
--- a/examples/fetch.js
+++ b/examples/fetch.js
@@ -4,8 +4,10 @@ var path = require("path");
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
.then(function(repo) {
return repo.fetch("origin", {
- credentials: function(url, userName) {
- return nodegit.Cred.sshKeyFromAgent(userName);
+ callbacks: {
+ credentials: function(url, userName) {
+ return nodegit.Cred.sshKeyFromAgent(userName);
+ }
}
});
}).done(function() {
|
Fixed fetch call.
Fetch requires the credentials function to be wrapped in the callbacks object (otherwise the promise succeeds even though it has failed silently).
|
nodegit_nodegit
|
train
|
60257238deac86ec6fdd4f506ea80292909205b5
|
diff --git a/keanu-project/src/main/java/io/improbable/keanu/algorithms/variational/QDistribution.java b/keanu-project/src/main/java/io/improbable/keanu/algorithms/variational/QDistribution.java
index <HASH>..<HASH> 100644
--- a/keanu-project/src/main/java/io/improbable/keanu/algorithms/variational/QDistribution.java
+++ b/keanu-project/src/main/java/io/improbable/keanu/algorithms/variational/QDistribution.java
@@ -3,8 +3,8 @@ package io.improbable.keanu.algorithms.variational;
import io.improbable.keanu.network.NetworkState;
/**
- * {@link QDistribution} represents Q in D(P‖Q) = sum_i P(i) log(P(i)/Q(i)), which is the
- * {@link KLDivergence} (Kullback–Leibler divergence) from probability distributions P to Q.
+ * {@link QDistribution} represents Q in D(P|Q) = sum_i P(i) log(P(i)/Q(i)), which is the
+ * {@link KLDivergence} (Kullback Leibler divergence) from probability distributions P to Q.
*/
public interface QDistribution {
double getLogOfMasterP(NetworkState state);
|
Remove bad character from java docs
|
improbable-research_keanu
|
train
|
af1d65ac01314cddc8a8142f4b666c2ee7b2acbe
|
diff --git a/VERSION b/VERSION
index <HASH>..<HASH> 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.6.2
+0.6.3
diff --git a/lib/iron_worker_ng/feature/base.rb b/lib/iron_worker_ng/feature/base.rb
index <HASH>..<HASH> 100644
--- a/lib/iron_worker_ng/feature/base.rb
+++ b/lib/iron_worker_ng/feature/base.rb
@@ -6,7 +6,7 @@ module IronWorkerNG
end
def rebase(path)
- File.expand_path path, @code.base_dir
+ File.expand_path(path, @code.base_dir)
end
def zip_add(zip, dest, src)
diff --git a/lib/iron_worker_ng/feature/ruby/merge_gem.rb b/lib/iron_worker_ng/feature/ruby/merge_gem.rb
index <HASH>..<HASH> 100644
--- a/lib/iron_worker_ng/feature/ruby/merge_gem.rb
+++ b/lib/iron_worker_ng/feature/ruby/merge_gem.rb
@@ -24,13 +24,10 @@ module IronWorkerNG
def gem_path
path = @spec.full_gem_path
- # when running under bundle exec it sometimes duplicates gem path suffix
-
- suffix_index = path.rindex('/gems/')
- suffix = path[suffix_index .. -1]
+ # bundler fix
- if path.end_with?(suffix + suffix)
- path = path[0 .. suffix_index - 1]
+ ['/gems//gems', '/gems/gems'].each do |bad_part|
+ path.gsub!(bad_part, '/gems')
end
path
|
Yet another bundler fix (and version bump).
|
iron-io_iron_worker_ruby_ng
|
train
|
34b81ebace4bb6108f2fc4b57256bcb070683a42
|
diff --git a/src/unity/python/turicreate/toolkits/activity_classifier/util.py b/src/unity/python/turicreate/toolkits/activity_classifier/util.py
index <HASH>..<HASH> 100644
--- a/src/unity/python/turicreate/toolkits/activity_classifier/util.py
+++ b/src/unity/python/turicreate/toolkits/activity_classifier/util.py
@@ -27,7 +27,7 @@ def random_split_by_session(dataset, session_id, fraction=0.9, seed=None):
The name of the column in `dataset` that corresponds to the
a unique identifier for each session.
- fraction : float, optiona;
+ fraction : float, optional
Fraction of the sessions to fetch for the first returned SFrame. Must
be between 0 and 1. Once the sessions are split, all data from a single
session is in the same SFrame.
|
Fixed another typo in the same documentation.
|
apple_turicreate
|
train
|
9bb75615986862cea97ebc4ca26d22fd9c2fc86e
|
diff --git a/auto_ml/utils.py b/auto_ml/utils.py
index <HASH>..<HASH> 100644
--- a/auto_ml/utils.py
+++ b/auto_ml/utils.py
@@ -2,11 +2,12 @@ import csv
import datetime
import os
+from keras.models import load_model as keras_load_model
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.utils.metaestimators import if_delegate_has_method
-
+from keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor
import pandas as pd
@@ -175,3 +176,10 @@ def clean_params(params):
return cleaned_params
+class ExtendedKerasRegressor(KerasRegressor):
+
+ def __init__(self, build_fn=None, **sk_params):
+ super(self.__class__, self).__init__(build_fn, sk_params)
+
+ def load_saved_model(self, model_name):
+ self.model = keras_load_model(temp_file_name)
|
adds extended keras, which can load a model without fitting it
|
ClimbsRocks_auto_ml
|
train
|
6741518162b8a79f8c554faed0baa03be720fe8b
|
diff --git a/agent.go b/agent.go
index <HASH>..<HASH> 100644
--- a/agent.go
+++ b/agent.go
@@ -50,7 +50,7 @@ type discoveryS struct {
Args []string `json:"args"`
Fd string `json:"fd"`
Inode string `json:"inode"`
- CpuSetFileContent string `json:"cpuSetFileContent"`
+ CPUSetFileContent string `json:"cpuSetFileContent"`
}
type fromS struct {
|
rename var in announcement request
|
instana_go-sensor
|
train
|
89480bcffdd393563a31366444a5801431772eda
|
diff --git a/addon/components/hot-replacement-component.js b/addon/components/hot-replacement-component.js
index <HASH>..<HASH> 100644
--- a/addon/components/hot-replacement-component.js
+++ b/addon/components/hot-replacement-component.js
@@ -99,6 +99,9 @@ const HotReplacementComponent = Component.extend(HotComponentMixin, {
clearRequirejs(this, baseComponentName);
}
},
+ __isAlive() {
+ return !this.isDestroyed && !this.isDestroying;
+ },
__rerenderOnTemplateUpdate (modulePath) {
const baseComponentName = this.get('baseComponentName');
const wrappedComponentName = this.get('wrappedComponentName');
@@ -112,6 +115,9 @@ const HotReplacementComponent = Component.extend(HotComponentMixin, {
});
this.rerender();
later(() => {
+ if (!this.__isAlive()) {
+ return;
+ }
this.setProperties({
wrappedComponentName: wrappedComponentName,
baseComponentName: baseComponentName
|
Fix for Assertion Failed: calling set on destroyed object (clean)
|
adopted-ember-addons_ember-cli-hot-loader
|
train
|
880442553fae2d5ad909c968719848a62c2a104c
|
diff --git a/openquake/calculators/base.py b/openquake/calculators/base.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/base.py
+++ b/openquake/calculators/base.py
@@ -739,6 +739,11 @@ def get_gmfs(calculator):
def save_gmf_data(dstore, sitecol, gmfs):
+ """
+ :param dstore: a :class:`openquake.baselib.datastore.DataStore` instance
+ :param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance
+ :param gmfs: an array of shape (R, N, E, I)
+ """
offset = 0
dstore['gmf_data/data'] = gmfa = get_gmv_data(sitecol.sids, gmfs)
dic = general.group_array(gmfa, 'sid')
|
Updated a docstring [skip CI]
Former-commit-id: c5aebd1d<I>f<I>ab<I>d<I>e4ba<I>e6ca<I>cb
|
gem_oq-engine
|
train
|
2386ee6de4aa64072c291023b7b494d105c63cda
|
diff --git a/skink/static/skink.js b/skink/static/skink.js
index <HASH>..<HASH> 100644
--- a/skink/static/skink.js
+++ b/skink/static/skink.js
@@ -76,7 +76,7 @@ setup_skink_websocket = function() {
"callback": callback_id,
"name": err.name,
"description": err.message
- }))
+ }));
}
}
console.log("log" + evt.data);
|
Fixed missing semicolon in Javascript
|
oksome_Skink
|
train
|
332f4ab2d48686ba563a0452898345ae379f89fb
|
diff --git a/src/test/java/com/codahale/shamir/tests/SecretSharingTest.java b/src/test/java/com/codahale/shamir/tests/SecretSharingTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/codahale/shamir/tests/SecretSharingTest.java
+++ b/src/test/java/com/codahale/shamir/tests/SecretSharingTest.java
@@ -88,7 +88,7 @@ public class SecretSharingTest {
qt().forAll(integers().between(2, 5), integers().between(2, 5), byteArrays())
.asWithPrecursor((top, k, secret) -> SecretSharing.split(top + k, k, secret))
.check((top, k, secret, shares) ->
- Sets.powerSet(shares).stream().filter(s -> !s.isEmpty())
+ Sets.powerSet(shares).stream().filter(s -> !s.isEmpty()).parallel()
.allMatch(subset -> {
final byte[] recovered = SecretSharing.combine(subset);
if (subset.size() < k) {
|
Use a parallel stream for round trips.
|
codahale_shamir
|
train
|
72c11aa71b539478e7522ae91fd5d6b1e30d5db8
|
diff --git a/services/master/master.go b/services/master/master.go
index <HASH>..<HASH> 100644
--- a/services/master/master.go
+++ b/services/master/master.go
@@ -27,6 +27,20 @@ func branchParam(r *http.Request) string {
return "master"
}
+func cat(w http.ResponseWriter, name string, fs *btrfs.FS) {
+ f, err := fs.Open(name)
+ defer f.Close()
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ log.Print(err)
+ }
+
+ if _, err := io.Copy(w, f); err != nil {
+ http.Error(w, err.Error(), 500)
+ log.Print(err)
+ }
+}
+
// PfsHandler is the core route for modifying the contents of the fileystem.
// Changes are not replicated until a call to CommitHandler.
func PfsHandler(w http.ResponseWriter, r *http.Request, fs *btrfs.FS) {
@@ -37,12 +51,26 @@ func PfsHandler(w http.ResponseWriter, r *http.Request, fs *btrfs.FS) {
branchFile := path.Join(append([]string{path.Join("repo", branchParam(r))}, url[2:]...)...)
if r.Method == "GET" {
- if f, err := fs.Open(commitFile); err != nil {
- http.Error(w, err.Error(), 500)
- log.Print(err)
- return
+ if strings.Contains(commitFile, "*") {
+ if !strings.HasSuffix(commitFile, "*") {
+ http.Error(w, "Illegal path containing internal `*`. `*` is currently only allowed as the last character of a path.", 400)
+ } else {
+ files, err := fs.ReadDir(path.Dir(commitFile))
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ } else {
+ for _, fi := range files {
+ if fi.IsDir() {
+ continue
+ } else {
+ cat(w, fi.Name(), fs)
+ }
+ }
+ }
+ }
} else {
- io.Copy(w, f)
+ cat(w, commitFile, fs)
}
} else if r.Method == "POST" {
size, err := fs.CreateFromReader(branchFile, r.Body)
|
First stab at supporting wildcards in the master.
|
pachyderm_pachyderm
|
train
|
55e3acd9fa0bfb9fb008de6e13fb84f135b88923
|
diff --git a/tests/integration/upload-test.js b/tests/integration/upload-test.js
index <HASH>..<HASH> 100644
--- a/tests/integration/upload-test.js
+++ b/tests/integration/upload-test.js
@@ -28,7 +28,7 @@ module('Integration | upload', function (hooks) {
let uploadedPhoto = this.server.db.photos[0];
assert.strictEqual(uploadedPhoto.filename, 'image.png');
- assert.strictEqual(uploadedPhoto.filesize, 1192);
+ assert.strictEqual(uploadedPhoto.filesize, 1179);
assert.strictEqual(uploadedPhoto.type, 'image');
assert.strictEqual(
@@ -49,7 +49,7 @@ module('Integration | upload', function (hooks) {
let uploadedPhoto = this.server.db.photos[0];
assert.strictEqual(uploadedPhoto.filename, 'image.png');
- assert.strictEqual(uploadedPhoto.filesize, 1192);
+ assert.strictEqual(uploadedPhoto.filesize, 1179);
assert.strictEqual(uploadedPhoto.type, 'image');
assert.strictEqual(
|
test(upload): updated filesize since chrome <I> reports it differently (#<I>)
|
adopted-ember-addons_ember-file-upload
|
train
|
0044724be83f1b9f1623e47547b136f7c85a24da
|
diff --git a/app/models/chouette/trident_active_record.rb b/app/models/chouette/trident_active_record.rb
index <HASH>..<HASH> 100644
--- a/app/models/chouette/trident_active_record.rb
+++ b/app/models/chouette/trident_active_record.rb
@@ -19,12 +19,13 @@ class Chouette::TridentActiveRecord < Chouette::ActiveRecord
def prepare_auto_columns
# logger.info 'calling before_validation'
# logger.info 'start before_validation : '+self.objectid.to_s
- if self.objectid.blank?
+ if self.objectid.nil? || self.objectid.blank?
# if empty, generate a pending objectid which will be completed after creation
if self.id.nil?
self.objectid = "#{prefix}:#{self.class.object_id_key}:__pending_id__#{rand(1000)}"
else
self.objectid = "#{prefix}:#{self.class.object_id_key}:#{self.id}"
+ fix_uniq_objectid
end
elsif not self.objectid.include? ':'
# if one token : technical token : completed by prefix and key
@@ -51,11 +52,25 @@ class Chouette::TridentActiveRecord < Chouette::ActiveRecord
end
end
+ def fix_uniq_objectid
+ base_objectid = self.objectid.rpartition(":").first
+ self.objectid = "#{base_objectid}:#{self.id}"
+ if !self.valid?
+ base_objectid="#{self.objectid}_"
+ cnt=1
+ while !self.valid?
+ self.objectid = "#{base_objectid}#{cnt}"
+ cnt += 1
+ end
+ end
+
+ end
+
def build_objectid
#logger.info 'start after_create : '+self.objectid
if self.objectid.include? ':__pending_id__'
- base_objectid = self.objectid.rpartition(":").first
- self.update_attributes( :objectid => "#{base_objectid}:#{self.id}", :object_version => (self.object_version - 1) )
+ fix_uniq_objectid
+ self.update_attributes( :objectid => self.objectid, :object_version => (self.object_version - 1) )
end
#logger.info 'end after_create : '+self.objectid
end
|
protect objectid auto generation from conflicts, Mantis <I>
|
afimb_ninoxe
|
train
|
f731b49b6954dd3006cf9039ed3b37c38d5b86ac
|
diff --git a/lib/rb/spec/nonblockingserver_spec.rb b/lib/rb/spec/nonblockingserver_spec.rb
index <HASH>..<HASH> 100644
--- a/lib/rb/spec/nonblockingserver_spec.rb
+++ b/lib/rb/spec/nonblockingserver_spec.rb
@@ -142,7 +142,7 @@ class ThriftNonblockingServerSpec < Spec::ExampleGroup
when :hello
result << client.greeting(true) # ignore result
when :sleep
- client.sleep(0.5)
+ client.sleep(args[0] || 0.5)
result << :slept
when :shutdown
client.shutdown
@@ -227,11 +227,12 @@ class ThriftNonblockingServerSpec < Spec::ExampleGroup
it "should kill active messages when they don't expire while shutting down" do
result = Queue.new
client = setup_client_thread(result)
- client << :block
+ client << [:sleep, 10]
sleep 0.1 # start processing the client's message
@server.shutdown(1)
@catch_exceptions = true
@server_thread.join(3).should_not be_nil
+ result.should be_empty
end
it "should allow shutting down in response to a message" do
|
rb: Switch NonblockingServer spec from Queue to sleep
Using sleep instead of Queue#pop means the thread is killable under JRuby
git-svn-id: <URL>
|
limingxinleo_thrift
|
train
|
8e87b107a98eddf34a9e96802620f0a0e66ec8a5
|
diff --git a/builtin/providers/ns1/resource_record.go b/builtin/providers/ns1/resource_record.go
index <HASH>..<HASH> 100644
--- a/builtin/providers/ns1/resource_record.go
+++ b/builtin/providers/ns1/resource_record.go
@@ -236,7 +236,7 @@ func resourceDataToRecord(r *dns.Record, d *schema.ResourceData) error {
var a *dns.Answer
v := answer["answer"].(string)
switch d.Get("type") {
- case "TXT":
+ case "TXT", "SPF":
a = dns.NewTXTAnswer(v)
default:
a = dns.NewAnswer(strings.Split(v, " "))
diff --git a/builtin/providers/ns1/resource_record_test.go b/builtin/providers/ns1/resource_record_test.go
index <HASH>..<HASH> 100644
--- a/builtin/providers/ns1/resource_record_test.go
+++ b/builtin/providers/ns1/resource_record_test.go
@@ -71,6 +71,27 @@ func TestAccRecord_updated(t *testing.T) {
})
}
+func TestAccRecord_SPF(t *testing.T) {
+ var record dns.Record
+ resource.Test(t, resource.TestCase{
+ PreCheck: func() { testAccPreCheck(t) },
+ Providers: testAccProviders,
+ CheckDestroy: testAccCheckRecordDestroy,
+ Steps: []resource.TestStep{
+ resource.TestStep{
+ Config: testAccRecordSPF,
+ Check: resource.ComposeTestCheckFunc(
+ testAccCheckRecordExists("ns1_record.spf", &record),
+ testAccCheckRecordDomain(&record, "terraform-record-test.io"),
+ testAccCheckRecordTTL(&record, 86400),
+ testAccCheckRecordUseClientSubnet(&record, true),
+ testAccCheckRecordAnswerRdata(&record, "v=DKIM1; k=rsa; p=XXXXXXXX"),
+ ),
+ },
+ },
+ })
+}
+
func testAccCheckRecordExists(n string, record *dns.Record) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
@@ -297,3 +318,20 @@ resource "ns1_zone" "test" {
zone = "terraform-record-test.io"
}
`
+
+const testAccRecordSPF = `
+resource "ns1_record" "spf" {
+ zone = "${ns1_zone.test.zone}"
+ domain = "${ns1_zone.test.zone}"
+ type = "SPF"
+ ttl = 86400
+ use_client_subnet = "true"
+ answers = {
+ answer = "v=DKIM1; k=rsa; p=XXXXXXXX"
+ }
+}
+
+resource "ns1_zone" "test" {
+ zone = "terraform-record-test.io"
+}
+`
|
provider/ns1: No splitting answer on spf records. (#<I>)
* provider/ns1: No splitting answer on spf records.
* provider/ns1: Adds acctest for SPF records.
|
hashicorp_terraform
|
train
|
ecf85c4b2dce71812db67ed1250db4309bbde207
|
diff --git a/lib/client.js b/lib/client.js
index <HASH>..<HASH> 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -5,6 +5,7 @@ var Connection = require('./connection');
var protocol = require('./protocol');
var errors = require('./errors');
var _ = require('lodash');
+var Kafka = require('./index');
function Client (options){
@@ -49,23 +50,35 @@ Client.prototype.updateMetadata = function() {
var self = this;
self.updateMetadata._running = self.metadataRequest().then(function (response) {
- response.broker.forEach(function (broker) {
- if(self.brokerConnections[broker.nodeId]){
- self.brokerConnections[broker.nodeId].close();
- }
- self.brokerConnections[broker.nodeId] = new Connection({
+ var oldConnections = self.brokerConnections;
+ self.brokerConnections = {};
+
+ _.each(response.broker, function (broker) {
+ var connection = _.find(oldConnections, function (c, i) {
+ return c.equal(broker.host, broker.port) && delete oldConnections[i];
+ });
+ self.brokerConnections[broker.nodeId] = connection || new Connection({
host: broker.host,
port: broker.port,
auto_connect: true
});
});
- response.topicMetadata.forEach(function (topic) {
+ _.each(oldConnections, function (c) {c.close()});
+
+ _.each(response.topicMetadata, function (topic) {
self.topicMetadata[topic.topicName] = {};
topic.partitionMetadata.forEach(function (partition) {
self.topicMetadata[topic.topicName][partition.partitionId] = partition;
});
});
+
+ if(_.isEmpty(self.brokerConnections)){
+ Kafka.warn('No broker metadata received, retrying metadata request in 1000ms');
+ return Promise.delay(1000).then(function () {
+ return self.updateMetadata();
+ });
+ }
})
.tap(function () {
self.updateMetadata._running = false;
@@ -116,6 +129,9 @@ Client.prototype.findLeader = function(topic, partition, notfoundOK) {
if(r instanceof Error){
reject(r);
} else {
+ if(!self.brokerConnections[r]){
+ return reject(errors.byName('LeaderNotAvailable'));
+ }
resolve(r);
}
});
diff --git a/lib/connection.js b/lib/connection.js
index <HASH>..<HASH> 100644
--- a/lib/connection.js
+++ b/lib/connection.js
@@ -19,6 +19,10 @@ function Connection(options) {
module.exports = Connection;
+Connection.prototype.equal = function(host, port) {
+ return this.host === host && this.port === port;
+};
+
Connection.prototype.connect = function (timeout) {
var self = this;
@@ -87,6 +91,7 @@ Connection.prototype._growReadBuffer = function (newLength) {
};
Connection.prototype.close = function () {
+ // console.log('Closing connection', this.host + ':' + this.port);
this.auto_connect = false;
this._disconnect(new Error('Connection closed'));
};
diff --git a/lib/protocol/common.js b/lib/protocol/common.js
index <HASH>..<HASH> 100644
--- a/lib/protocol/common.js
+++ b/lib/protocol/common.js
@@ -66,9 +66,11 @@ protocol.define('string', {
// array
protocol.define('array', {
read: function(fn) {
- this
- .Int32BE('length')
- .loop('items', fn, this.context.length);
+ this.Int32BE('length');
+ if(this.context.length <= 0){
+ return [];
+ }
+ this.loop('items', fn, this.context.length);
return this.context.items;
},
write: function(value, fn) {
diff --git a/lib/simple_consumer.js b/lib/simple_consumer.js
index <HASH>..<HASH> 100644
--- a/lib/simple_consumer.js
+++ b/lib/simple_consumer.js
@@ -63,7 +63,7 @@ SimpleConsumer.prototype._fetch = function() {
return self._offset(s.leader, t.topicName, p.partition, null, Kafka.LATEST_OFFSET).then(function (offset) {
s.offset = offset;
});
- } else if (/UnknownTopicOrPartition|NotLeaderForPartition/.test(p.error.code)) {
+ } else if (/UnknownTopicOrPartition|NotLeaderForPartition|LeaderNotAvailable/.test(p.error.code)) {
Kafka.warn('Received', p.error.code, 'error for', t.topicName + ':' + p.partition);
return self.client.updateMetadata().then(function () {
return self.subscribe(t.topicName, p.partition, { offset: s.offset });
|
Re-map connections on metadata request, retry metadata request when broker information is not yet available
|
oleksiyk_kafka
|
train
|
60daf98c9619eece705d3c61c3ca9c21e1473e2a
|
diff --git a/grade/report/grader/module.js b/grade/report/grader/module.js
index <HASH>..<HASH> 100644
--- a/grade/report/grader/module.js
+++ b/grade/report/grader/module.js
@@ -323,9 +323,9 @@ M.gradereport_grader.classes.ajax = function(report, cfg) {
this.existingfields[userid][itemid] = new M.gradereport_grader.classes.existingfield(this, userid, itemid);
}
}
- // Hide the Update button
+ // Disable the Update button as we're saving using ajax.
submitbutton = this.report.Y.one('#gradersubmit');
- submitbutton.setStyle('visibility', 'hidden');
+ submitbutton.set('disabled', true);
}
};
/**
|
MDL-<I> core_grade:switched from hiding the submit button to disabling it if ajax is enabled
|
moodle_moodle
|
train
|
21c7b50a672707adf762460e01cbaf8dda55c5db
|
diff --git a/pymatgen/core/composition.py b/pymatgen/core/composition.py
index <HASH>..<HASH> 100644
--- a/pymatgen/core/composition.py
+++ b/pymatgen/core/composition.py
@@ -14,7 +14,7 @@ import re
import string
from functools import total_ordering
from itertools import combinations_with_replacement, product
-from typing import List, Tuple, Union, Dict, Literal
+from typing import List, Tuple, Union, Dict
from monty.fractions import gcd, gcd_float
from monty.json import MSONable
@@ -518,25 +518,7 @@ class Composition(collections.abc.Hashable, collections.abc.Mapping, MSONable):
def contains_element_type(
self,
- category: Literal[
- "noble_gas",
- "transition_metal",
- "post_transition_metal",
- "rare_earth_metal",
- "metal",
- "metalloid",
- "alkali",
- "alkaline",
- "halogen",
- "chalcogen",
- "lanthanoid",
- "actinoid",
- "quadrupolar",
- "s-block",
- "p-block",
- "d-block",
- "f-block",
- ],
+ category: str,
):
"""
Check if Composition contains any elements matching a given category.
diff --git a/pymatgen/electronic_structure/dos.py b/pymatgen/electronic_structure/dos.py
index <HASH>..<HASH> 100644
--- a/pymatgen/electronic_structure/dos.py
+++ b/pymatgen/electronic_structure/dos.py
@@ -12,7 +12,7 @@ import warnings
import numpy as np
from monty.json import MSONable
from scipy.constants.codata import value as _cd
-from typing import Dict, Literal
+from typing import Dict
from pymatgen.core.periodic_table import get_el_sp
from pymatgen.core.sites import PeriodicSite
@@ -706,7 +706,7 @@ class CompleteDos(Dos):
spd_dos[orbital_type] = pdos
return {orb: Dos(self.efermi, self.energies, densities) for orb, densities in spd_dos.items()}
- def get_site_t2g_eg_resolved_dos(self, site: PeriodicSite) -> Dict[Literal["t2g", "e_g"], Dos]:
+ def get_site_t2g_eg_resolved_dos(self, site: PeriodicSite) -> Dict[str, Dos]:
"""
Get the t2g, eg projected DOS for a particular site.
@@ -901,7 +901,7 @@ class LobsterCompleteDos(CompleteDos):
raise ValueError("orbital is not correct")
return Dos(self.efermi, self.energies, self.pdos[site][orbital]) # type: ignore
- def get_site_t2g_eg_resolved_dos(self, site: PeriodicSite) -> Dict[Literal["t2g", "e_g"], Dos]:
+ def get_site_t2g_eg_resolved_dos(self, site: PeriodicSite) -> Dict[str, Dos]:
"""
Get the t2g, eg projected DOS for a particular site.
Args:
|
Do not use Literal types for now
|
materialsproject_pymatgen
|
train
|
a6e4ba4b438851d8669f73337b3b766faa8f60f7
|
diff --git a/core/src/test/java/org/modelmapper/functional/circular/CircularDependencies1.java b/core/src/test/java/org/modelmapper/functional/circular/CircularDependencies1.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/org/modelmapper/functional/circular/CircularDependencies1.java
+++ b/core/src/test/java/org/modelmapper/functional/circular/CircularDependencies1.java
@@ -1,8 +1,10 @@
package org.modelmapper.functional.circular;
-import static org.testng.Assert.assertNull;
+import static org.testng.Assert.*;
import org.modelmapper.AbstractTest;
+import org.modelmapper.ConfigurationException;
+import org.modelmapper.PropertyMap;
import org.testng.annotations.Test;
/**
@@ -21,8 +23,68 @@ public class CircularDependencies1 extends AbstractTest {
A value;
}
+ static class Tree {
+ Node node;
+ }
+
+ static class Node {
+ Tree tree;
+ String value;
+ }
+
+ static class DTree {
+ DNode node;
+
+ public DNode getNode() {
+ return node;
+ }
+ }
+
+ static class DNode {
+ DTree tree;
+ String value;
+
+ public void setTree(DTree tree) {
+ this.tree = tree;
+ }
+ }
+
public void shouldNotThrowOnMatchingCircularReference() {
B b2 = modelMapper.map(new A(), B.class);
assertNull(b2.value);
}
+
+ @Test(expectedExceptions = ConfigurationException.class)
+ public void shouldThrowOnNonSkippedCircularReference() {
+ modelMapper.map(new Tree(), DTree.class);
+ }
+
+ public void shouldAllowSkippedCircularReference() {
+ modelMapper.addMappings(new PropertyMap<Tree, DTree>() {
+ @Override
+ protected void configure() {
+ skip().getNode().setTree(null);
+ }
+ });
+
+ modelMapper.map(new Tree(), DTree.class);
+ }
+
+ // Asserts that the Node->DNode mapping is merged into the Tree->DTree mapping, and skipped
+ public void shouldAllowSkippedCircularReferenceForInnerProperty() {
+ modelMapper.addMappings(new PropertyMap<Node, DNode>() {
+ @Override
+ protected void configure() {
+ skip().setTree(null);
+ }
+ });
+
+ Tree tree = new Tree();
+ tree.node = new Node();
+ tree.node.value = "test";
+ DTree dt = modelMapper.map(tree, DTree.class);
+
+ assertNull(dt.node.tree);
+ assertEquals(dt.node.value, "test");
+ }
}
|
Updated circular dependency test for skipped properties
|
modelmapper_modelmapper
|
train
|
90928b173dff8e10b533bf5c3b701d5a158228e6
|
diff --git a/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ModelManagerListener.java b/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ModelManagerListener.java
index <HASH>..<HASH> 100644
--- a/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ModelManagerListener.java
+++ b/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ModelManagerListener.java
@@ -20,7 +20,7 @@ import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
-import java.io.IOException;
+import java.io.Closeable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
@@ -61,7 +61,7 @@ import com.cloudera.oryx.kafka.util.KafkaUtils;
* @param <U> type of update/model read from update topic
*/
@WebListener
-public final class ModelManagerListener<K,M,U> implements ServletContextListener {
+public final class ModelManagerListener<K,M,U> implements ServletContextListener, Closeable {
private static final Logger log = LoggerFactory.getLogger(ModelManagerListener.class);
@@ -142,9 +142,16 @@ public final class ModelManagerListener<K,M,U> implements ServletContextListener
modelManager = loadManagerInstance();
new Thread(new LoggingRunnable() {
@Override
- public void doRun() throws IOException {
+ public void doRun() {
// Can we do better than a default Hadoop config? Nothing else provides it here
- modelManager.consume(transformed, new Configuration());
+ try {
+ modelManager.consume(transformed, new Configuration());
+ } catch (Throwable t) {
+ log.error("Error while consuming updates", t);
+ // Ideally we would shut down ServingLayer, but not clear how to plumb that through
+ // without assuming this has been run from ServingLayer and not a web app deployment
+ close();
+ }
}
}, "OryxServingLayerUpdateConsumerThread").start();
@@ -155,13 +162,26 @@ public final class ModelManagerListener<K,M,U> implements ServletContextListener
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("ModelManagerListener destroying");
-
// Slightly paranoid; remove objects from app scope manually
ServletContext context = sce.getServletContext();
for (Enumeration<String> names = context.getAttributeNames(); names.hasMoreElements();) {
context.removeAttribute(names.nextElement());
}
+ close();
+
+ // Hacky, but prevents Tomcat from complaining that ZK's cleanup thread 'leaked' since
+ // it has a short sleep at its end
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ie) {
+ // continue
+ }
+ }
+
+ @Override
+ public synchronized void close() {
+ log.info("ModelManagerListener closing");
if (modelManager != null) {
log.info("Shutting down model manager");
modelManager.close();
@@ -178,13 +198,6 @@ public final class ModelManagerListener<K,M,U> implements ServletContextListener
consumer.shutdown();
consumer = null;
}
- // Hacky, but prevents Tomcat from complaining that ZK's cleanup thread 'leaked' since
- // it has a short sleep at its end
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ie) {
- // continue
- }
}
@SuppressWarnings("unchecked")
diff --git a/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/speed/SpeedLayer.java b/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/speed/SpeedLayer.java
index <HASH>..<HASH> 100644
--- a/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/speed/SpeedLayer.java
+++ b/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/speed/SpeedLayer.java
@@ -15,7 +15,6 @@
package com.cloudera.oryx.lambda.speed;
-import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
@@ -128,8 +127,13 @@ public final class SpeedLayer<K,M,U> extends AbstractSparkLayer<K,M> {
modelManager = loadManagerInstance();
new Thread(new LoggingRunnable() {
@Override
- public void doRun() throws IOException {
- modelManager.consume(transformed, streamingContext.sparkContext().hadoopConfiguration());
+ public void doRun() {
+ try {
+ modelManager.consume(transformed, streamingContext.sparkContext().hadoopConfiguration());
+ } catch (Throwable t) {
+ log.error("Error while consuming updates", t);
+ close();
+ }
}
}, "OryxSpeedLayerUpdateConsumerThread").start();
|
If update consumer fails, try to shut down the serving/speed layer
|
OryxProject_oryx
|
train
|
9043e1b7739d984e449524d6cc5d9b3812dd07a2
|
diff --git a/package/environments/base.js b/package/environments/base.js
index <HASH>..<HASH> 100644
--- a/package/environments/base.js
+++ b/package/environments/base.js
@@ -30,7 +30,7 @@ const getPluginList = () => {
const result = new ConfigList()
result.append(
'Environment',
- new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env)))
+ new webpack.EnvironmentPlugin(process.env)
)
result.append('CaseSensitivePaths', new CaseSensitivePathsPlugin())
result.append(
|
Fixed no need parsing (#<I>)
|
rails_webpacker
|
train
|
3e7c9f3d5c12e99b76c4dfaccb982f0fcc177281
|
diff --git a/blinkpy/sync_module.py b/blinkpy/sync_module.py
index <HASH>..<HASH> 100644
--- a/blinkpy/sync_module.py
+++ b/blinkpy/sync_module.py
@@ -189,7 +189,7 @@ class BlinkSyncModule():
clip = entry['media']
timestamp = entry['created_at']
if self.check_new_video_time(timestamp):
- self.motion[name] = True
+ self.motion[name] = True and self.arm
self.last_record[name] = {'clip': clip, 'time': timestamp}
except KeyError:
_LOGGER.debug("No new videos since last refresh.")
diff --git a/tests/test_sync_module.py b/tests/test_sync_module.py
index <HASH>..<HASH> 100644
--- a/tests/test_sync_module.py
+++ b/tests/test_sync_module.py
@@ -43,6 +43,7 @@ class TestBlinkSyncModule(unittest.TestCase):
None,
{'devicestatus': {}},
]
+ self.blink.sync['test'].network_info = {'network': {'armed': True}}
def tearDown(self):
"""Clean up after test."""
@@ -109,6 +110,24 @@ class TestBlinkSyncModule(unittest.TestCase):
self.assertTrue(sync_module.check_new_videos())
self.assertEqual(sync_module.motion, {'foo': False})
+ def test_check_no_motion_if_not_armed(self, mock_resp):
+ """Test that motion detection is not set if module unarmed."""
+ mock_resp.return_value = {
+ 'media': [{
+ 'device_name': 'foo',
+ 'media': '/foo/bar.mp4',
+ 'created_at': '1990-01-01T00:00:00+00:00'
+ }]
+ }
+ sync_module = self.blink.sync['test']
+ sync_module.cameras = {'foo': None}
+ sync_module.blink.last_refresh = 1000
+ self.assertTrue(sync_module.check_new_videos())
+ self.assertEqual(sync_module.motion, {'foo': True})
+ sync_module.network_info = {'network': {'armed': False}}
+ self.assertTrue(sync_module.check_new_videos())
+ self.assertEqual(sync_module.motion, {'foo': False})
+
def test_check_multiple_videos(self, mock_resp):
"""Test motion found even with multiple videos."""
mock_resp.return_value = {
|
Mask motion detection with sync module arm status
|
fronzbot_blinkpy
|
train
|
2de7de3bc31c99236d70a31477e66652988ae89d
|
diff --git a/lib/plucky/options_hash.rb b/lib/plucky/options_hash.rb
index <HASH>..<HASH> 100644
--- a/lib/plucky/options_hash.rb
+++ b/lib/plucky/options_hash.rb
@@ -17,16 +17,24 @@ module Plucky
def initialize_copy(source)
super
@source = @source.dup
- each do |key, value|
+ @source.each do |key, value|
self[key] = value.clone if value.duplicable?
end
end
+ def [](key)
+ @source[key]
+ end
+
def []=(key, value)
key = normalized_key(key)
source[key] = normalized_value(key, value)
end
+ def keys
+ @source.keys
+ end
+
def ==(other)
source == other.source
end
@@ -73,9 +81,5 @@ module Plucky
})
}
end
-
- def method_missing(method, *args, &block)
- @source.send(method, *args, &block)
- end
end
end
diff --git a/spec/plucky/options_hash_spec.rb b/spec/plucky/options_hash_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/plucky/options_hash_spec.rb
+++ b/spec/plucky/options_hash_spec.rb
@@ -1,14 +1,6 @@
require 'helper'
describe Plucky::OptionsHash do
- it "delegates missing methods to the source hash" do
- hash = {:limit => 1, :skip => 1}
- options = described_class.new(hash)
- options[:skip].should == 1
- options[:limit].should == 1
- options.keys.to_set.should == [:limit, :skip].to_set
- end
-
describe "#initialize_copy" do
before do
@original = described_class.new(:fields => {:name => true}, :sort => :name, :limit => 10)
|
Explicit > method missing for options hash
|
mongomapper_plucky
|
train
|
69e8609e2d0934be7838f05eccc14b7dc369fd02
|
diff --git a/ExpressionBuilderTest.php b/ExpressionBuilderTest.php
index <HASH>..<HASH> 100644
--- a/ExpressionBuilderTest.php
+++ b/ExpressionBuilderTest.php
@@ -20,6 +20,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testAndX()
{
$expr = $this->builder->andX($this->builder->eq("a", "b"));
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\CompositeExpression", $expr);
$this->assertEquals(CompositeExpression::TYPE_AND, $expr->getType());
}
@@ -27,6 +28,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testOrX()
{
$expr = $this->builder->orX($this->builder->eq("a", "b"));
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\CompositeExpression", $expr);
$this->assertEquals(CompositeExpression::TYPE_OR, $expr->getType());
}
@@ -40,6 +42,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testEq()
{
$expr = $this->builder->eq("a", "b");
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::EQ, $expr->getOperator());
}
@@ -47,6 +50,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testNeq()
{
$expr = $this->builder->neq("a", "b");
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::NEQ, $expr->getOperator());
}
@@ -54,6 +58,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testLt()
{
$expr = $this->builder->lt("a", "b");
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::LT, $expr->getOperator());
}
@@ -61,6 +66,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testGt()
{
$expr = $this->builder->gt("a", "b");
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::GT, $expr->getOperator());
}
@@ -68,6 +74,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testGte()
{
$expr = $this->builder->gte("a", "b");
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::GTE, $expr->getOperator());
}
@@ -75,6 +82,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testLte()
{
$expr = $this->builder->lte("a", "b");
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::LTE, $expr->getOperator());
}
@@ -82,6 +90,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testIn()
{
$expr = $this->builder->in("a", array("b"));
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::IN, $expr->getOperator());
}
@@ -89,6 +98,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testNotIn()
{
$expr = $this->builder->notIn("a", array("b"));
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::NIN, $expr->getOperator());
}
@@ -96,6 +106,7 @@ class ExpressionBuilderTest extends \PHPUnit_Framework_TestCase
public function testIsNull()
{
$expr = $this->builder->isNull("a");
+
$this->assertInstanceOf("Doctrine\Common\Collections\Expr\Comparison", $expr);
$this->assertEquals(Comparison::IS, $expr->getOperator());
}
|
[DDC-<I>] Some refactorings.
|
doctrine_collections
|
train
|
24d6e1be38ff9025e35a26509338dbd23bb1d60e
|
diff --git a/tests/helpers/PahoutHelper.php b/tests/helpers/PahoutHelper.php
index <HASH>..<HASH> 100644
--- a/tests/helpers/PahoutHelper.php
+++ b/tests/helpers/PahoutHelper.php
@@ -3,6 +3,7 @@
namespace Pahout\Test\helper;
use Pahout\Pahout;
+use Pahout\Config;
use Pahout\Tool\Base;
use \ast\Node;
@@ -18,6 +19,13 @@ class PahoutHelper
public static function create(Base $tool)
{
+ Config::load([
+ 'php-version' => null,
+ 'ignore-tools' => null,
+ 'ignore-paths' => null,
+ 'vendor' => null,
+ 'format' => null,
+ ]);
$pahout = new Pahout([]);
$klass = new \ReflectionClass('\Pahout\Pahout');
$property = $klass->getProperty('tools');
|
Fix the problem that the test is failed when running specific test
|
wata727_pahout
|
train
|
350530fd4cf92321a36c13e10284291cce1de212
|
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index <HASH>..<HASH> 100644
--- a/kubespawner/spawner.py
+++ b/kubespawner/spawner.py
@@ -1360,6 +1360,10 @@ class KubeSpawner(Spawner):
if not self.events.stopped():
self.events.stop()
self.events = None
+
+ if self.pod_name not in self.pods:
+ self.log.info("No pod %s to delete", self.pod_name)
+ return
delete_options = client.V1DeleteOptions()
if now:
@@ -1371,13 +1375,22 @@ class KubeSpawner(Spawner):
delete_options.grace_period_seconds = grace_seconds
self.log.info("Deleting pod %s", self.pod_name)
- yield self.asynchronize(
- self.api.delete_namespaced_pod,
- name=self.pod_name,
- namespace=self.namespace,
- body=delete_options,
- grace_period_seconds=grace_seconds
- )
+ try:
+ yield self.asynchronize(
+ self.api.delete_namespaced_pod,
+ name=self.pod_name,
+ namespace=self.namespace,
+ body=delete_options,
+ grace_period_seconds=grace_seconds,
+ )
+ except ApiException as e:
+ if e.status == 404:
+ self.log.warning(
+ "No pod %s to delete. Assuming already deleted.",
+ self.pod_name,
+ )
+ else:
+ raise
yield exponential_backoff(
lambda: self.pod_reflector.pods.get(self.pod_name, None) is None,
'pod/%s did not disappear in %s seconds!' % (self.pod_name, self.start_timeout),
|
avoid failure to delete pods that don’t exist
stopping could raise <I> if it doesn’t exist (e.g. already deleted). Log this as a warning instead of raising.
|
jupyterhub_kubespawner
|
train
|
003a1d411e7dc65e03d871711e692b1b8d85dc18
|
diff --git a/ratcave/physical.py b/ratcave/physical.py
index <HASH>..<HASH> 100644
--- a/ratcave/physical.py
+++ b/ratcave/physical.py
@@ -141,6 +141,10 @@ class PhysicalGraph(Physical, SceneGraph):
self._model_matrix_global = np.identity(4, dtype=np.float32)
self._normal_matrix_global = np.identity(4, dtype=np.float32)
self._view_matrix_global = np.identity(4, dtype=np.float32)
+
+ self._model_matrix_transform = np.identity(4, dtype=np.float32)
+ self._normal_matrix_transform = np.identity(4, dtype=np.float32)
+
super(PhysicalGraph, self).__init__(**kwargs)
@@ -173,35 +177,28 @@ class PhysicalGraph(Physical, SceneGraph):
def on_change(self):
Physical.on_change(self)
- if self.parent:
- self.model_matrix_global = np.dot(self.parent.model_matrix_global, self._model_matrix)
- self.normal_matrix_global = np.dot(self.parent.normal_matrix_global, self._normal_matrix)
- self.view_matrix_global = trans.inverse_matrix(self._model_matrix_global)
- # self.view_matrix_global = np.dot(self.parent.view_matrix_global, self._view_matrix)
- else:
- self.model_matrix_global = self._model_matrix
- self.normal_matrix_global = self._normal_matrix
- self.view_matrix_global = self._view_matrix
+ mm_pg = self.parent.model_matrix_global if self.parent else np.identity(4, dtype=np.float32)
+ nn_pg = self.parent.normal_matrix_global if self.parent else np.identity(4, dtype=np.float32)
+ mm, mm_t = self._model_matrix, self._model_matrix_transform
+ nn, nn_t = self._normal_matrix, self._normal_matrix_transform
+
+ self.model_matrix_global = mm_pg.dot(mm_t).dot(mm)
+ self.normal_matrix_global = nn_pg.dot(nn_t).dot(nn)
+ self.view_matrix_global = trans.inverse_matrix(self._model_matrix_global)
def notify(self):
super(Physical, self).notify()
for child in self.children:
child.notify()
- @staticmethod
- def child_update(parent, child):
- """Prevents the changes of the coordinates of the child when it gets parented, by pre-calculating childs model_matrix """
- model_matrix_new = np.dot(trans.inverse_matrix(parent.model_matrix), child.model_matrix)
- child.position.xyz = model_matrix_new[:-1, 3]
- child.rotation = coordinates.RotationEulerDegrees.from_matrix(model_matrix_new)
- #child.scale.xyz = model_matrix_new.diagonal()[:-1] / child.rotation.to_matrix().diagonal()[:-1]
-
def add_child(self, child, modify=False):
+ """ Adds an object as a child in the scene graph. With modify=True, model_matrix_transform gets change from identity and prevents the changes of the coordinates of the child"""
SceneGraph.add_child(self, child)
self.notify()
if modify:
- self.child_update(self, child)
+ child._model_matrix_transform[:] = trans.inverse_matrix(self.model_matrix_global)
+ child._normal_matrix_transform[:] = trans.inverse_matrix(self.normal_matrix_global)
@property
def position_global(self):
|
PhysicalGraph.on_change() has now calculations of model_matrix_transform in each iteration
|
ratcave_ratcave
|
train
|
6e663f500ced34f6c94e0e65fdfc38315704a612
|
diff --git a/lib/pkgcloud/amazon/storage/client/files.js b/lib/pkgcloud/amazon/storage/client/files.js
index <HASH>..<HASH> 100644
--- a/lib/pkgcloud/amazon/storage/client/files.js
+++ b/lib/pkgcloud/amazon/storage/client/files.js
@@ -109,7 +109,7 @@ exports.multipartUpload = function (options, callback) {
// Wait for first data event, probably file is less than 5 mbs and
// we don't need that multipart thing at all
- stream.once('data', function(data) {
+ stream.once('data', function (data) {
// Good case - all data fits in one chunk
if (data.length < chunk) {
options.headers['content-length'] = data.length;
@@ -133,7 +133,7 @@ exports.multipartUpload = function (options, callback) {
// Upload rest
function onChunk(chunk) {
stream.pause();
- uploadChunk(body.UploadId, chunk, function(err, chunk) {
+ uploadChunk(body.UploadId, chunk, function (err, chunk) {
if (err) return cb(err);
finish(chunk);
@@ -148,7 +148,7 @@ exports.multipartUpload = function (options, callback) {
);
});
- stream.on('end', function() {
+ stream.on('end', function () {
ended = true;
finish();
});
@@ -202,12 +202,12 @@ exports.multipartUpload = function (options, callback) {
}
// Sort chunks in ascending order
- chunksFinished.sort(function(a, b) {
+ chunksFinished.sort(function (a, b) {
return a.id > b.id ? 1 : a.id < b.id ? -1 : 0;
});
var body = '<CompleteMultipartUpload>' +
- chunksFinished.map(function(chunk) {
+ chunksFinished.map(function (chunk) {
return '<Part>' +
'<PartNumber>' + chunk.id + '</PartNumber>' +
'<ETag>' + chunk.etag + '</ETag>' +
@@ -228,7 +228,7 @@ exports.multipartUpload = function (options, callback) {
'Content-Length': Buffer.byteLength(body)
},
body: body
- }, cb, function(body, res) {
+ }, cb, function (body, res) {
cb(null, res.statusCode == 200);
});
}
@@ -285,18 +285,27 @@ exports.getFile = function (container, file, callback) {
});
}
-exports.getFiles = function (container, download, callback) {
- var containerName = container instanceof base.Container ?
- container.name
- :
- container,
+exports.getFiles = function (container, options, callback) {
+ var containerName = container instanceof base.Container ? container.name : container,
self = this;
-
- this.xmlRequest([ containerName ], callback, function (body, res) {
- callback(null, self._toArray(body.Contents).map(function (file) {
- file.container = container;
- return new storage.File(self, file);
- }));
- });
+
+ if (typeof options === 'function') {
+ callback = options;
+ options = null;
+ }
+
+ this.xmlRequest(
+ {
+ path: [containerName],
+ qs: options
+ },
+ callback,
+ function (body, res) {
+ callback(null, self._toArray(body.Contents).map(function (file) {
+ file.container = container;
+ return new storage.File(self, file);
+ }));
+ }
+ );
};
diff --git a/lib/pkgcloud/amazon/storage/client/index.js b/lib/pkgcloud/amazon/storage/client/index.js
index <HASH>..<HASH> 100644
--- a/lib/pkgcloud/amazon/storage/client/index.js
+++ b/lib/pkgcloud/amazon/storage/client/index.js
@@ -24,15 +24,23 @@ var Client = exports.Client = function (options) {
utile.inherits(Client, amazon.Client);
Client.prototype.xmlRequest = function query(method, url, errback, callback) {
- // .xmlRequest(['url'], errback, callback)
- if (typeof url === 'function') {
+ var options;
+
+ if (arguments.length === 4) {
+ options = {
+ method: method,
+ path: url
+ };
+ }
+ else if (arguments.length === 3) {
callback = errback;
errback = url;
- url = method;
- method = 'GET';
+ options = typeof method !== 'object'
+ ? { method: 'GET', path: method }
+ : method
}
- return this.request(method, url, errback, function (body, res) {
+ return this.request(options, errback, function (body, res) {
var parser = new xml2js.Parser();
parser.parseString(body || '', function (err, data) {
diff --git a/lib/pkgcloud/amazon/storage/utils.js b/lib/pkgcloud/amazon/storage/utils.js
index <HASH>..<HASH> 100644
--- a/lib/pkgcloud/amazon/storage/utils.js
+++ b/lib/pkgcloud/amazon/storage/utils.js
@@ -30,7 +30,7 @@ ChunkedStream.prototype.write = function write(data, encoding) {
var total = 0,
parts = [];
- this.buffer = this.buffer.filter(function(part) {
+ this.buffer = this.buffer.filter(function (part) {
if (total >= this.chunk) return true;
parts.push(part);
@@ -90,7 +90,7 @@ ChunkedStream.prototype.resume = function resume() {
this.paused = false;
// Emit all accumulated data
- this.chunkBuffer.forEach(function(chunk) {
+ this.chunkBuffer.forEach(function (chunk) {
this.emit('data', chunk);
}, this);
this.chunkBuffer = [];
|
[api] Allow querystring params to be sent on Amazon requests
|
pkgcloud_pkgcloud
|
train
|
92264908208a4abc75410925c3bd35ea8723b5bd
|
diff --git a/src/Traits/PathTrait.php b/src/Traits/PathTrait.php
index <HASH>..<HASH> 100644
--- a/src/Traits/PathTrait.php
+++ b/src/Traits/PathTrait.php
@@ -277,53 +277,58 @@ trait PathTrait
$filename = null;
$isAbsolute = false;
$aboveBaseLevel = 0;
+ $i = 0;
- // Go through all parts.
- for ($i = 0; $i < $partsCount; ++$i) {
- $part = $parts[$i];
-
- // If the first part is empty and other parts follow, the path begins with directory separator and is therefore absolute.
- if ($i === 0 && $part === '' && $partsCount > 1) {
- $isAbsolute = true;
-
- continue;
- }
-
- // Skip empty parts.
- if ($part === '') {
- continue;
- }
+ // If the first part is empty and other parts follow, the path begins with directory separator and is therefore absolute.
+ if ($partsCount > 1 && $parts[0] === '') {
+ $isAbsolute = true;
+ ++$i;
+ }
- // Handle current directory-part.
- if ($part === '.') {
- continue;
+ // Go through all parts.
+ for (; $i < $partsCount; ++$i) {
+ if (!self::myParsePart($parts[$i], $i === $partsCount - 1, $partValidator, $stringDecoder, $isAbsolute, $aboveBaseLevel, $directoryParts, $filename, $error)) {
+ return false;
}
+ }
- // Handle parent directory-part.
- if ($part === '..') {
- if (!self::myHandleParentDirectoryPart($isAbsolute, $aboveBaseLevel, $directoryParts, $error)) {
- return false;
- }
-
- continue;
- }
+ return true;
+ }
- // Handle last (i.e. filename) part.
- if ($i === $partsCount - 1) {
- if (!self::myHandleFilenamePart($part, $partValidator, $stringDecoder, $filename, $error)) {
- return false;
- }
+ /**
+ * Tries to parse a part of a path and returns the result or error text.
+ *
+ * @param string $part The part of the path.
+ * @param bool $isLastPart True if this is the last part, false otherwise.
+ * @param callable $partValidator The part validator.
+ * @param callable|null $stringDecoder The string decoding function or null if parts should not be decoded.
+ * @param bool|null $isAbsolute Whether the path is absolute or relative if parsing was successful, undefined otherwise.
+ * @param int|null $aboveBaseLevel The number of directory parts above base level if parsing was successful, undefined otherwise.
+ * @param string[]|null $directoryParts The directory parts if parsing was successful, undefined otherwise.
+ * @param string|null $filename The file if parsing was not successful, undefined otherwise.
+ * @param string|null $error The error text if validation was not successful, undefined otherwise.
+ *
+ * @return bool True if parsing was successful, false otherwise.
+ */
+ private static function myParsePart($part, $isLastPart, callable $partValidator, callable $stringDecoder = null, $isAbsolute, &$aboveBaseLevel, array &$directoryParts = null, &$filename = null, &$error = null)
+ {
+ // Skip empty and current directory parts.
+ if ($part === '' || $part === '.') {
+ return true;
+ }
- continue;
- }
+ // Handle parent directory-part.
+ if ($part === '..') {
+ return self::myHandleParentDirectoryPart($isAbsolute, $aboveBaseLevel, $directoryParts, $error);
+ }
- // Handle directory part.
- if (!self::myHandleDirectoryPart($part, $partValidator, $stringDecoder, $directoryParts, $error)) {
- return false;
- }
+ // Handle directory part.
+ if (!$isLastPart) {
+ return self::myHandleDirectoryPart($part, $partValidator, $stringDecoder, $directoryParts, $error);
}
- return true;
+ // Handle last (i.e. filename) part.
+ return self::myHandleFilenamePart($part, $partValidator, $stringDecoder, $filename, $error);
}
/**
|
Refactor myParse method in PathTrait
|
themichaelhall_datatypes
|
train
|
b076785c4600ec23dcd37787a1dbd841fae82521
|
diff --git a/packages/neos-ui-editors/src/Library/LinkInput.js b/packages/neos-ui-editors/src/Library/LinkInput.js
index <HASH>..<HASH> 100644
--- a/packages/neos-ui-editors/src/Library/LinkInput.js
+++ b/packages/neos-ui-editors/src/Library/LinkInput.js
@@ -174,9 +174,13 @@ export default class LinkInput extends PureComponent {
this.props.linkLookupDataLoader.search(this.getDataLoaderOptions(), searchTerm)
.then(searchOptions => {
if (searchTermWhenLookupWasTriggered === this.state.searchTerm) {
+ const groupedSearchOption = searchOptions.map(searchOption => {
+ searchOption.group = 'assetSourceLabel' in searchOption ? searchOption.assetSourceLabel : this.props.i18nRegistry.translate('Neos.Neos:Main:document');
+ return searchOption;
+ });
this.setState({
isLoading: false,
- searchOptions
+ searchOptions: groupedSearchOption
});
}
});
|
TASK: Improve visibility of assets sources
As we now see more than local assets and documents in the look up search, we also need to group the output. For instance the AssetEditor handles search results in grouped option lists.
|
neos_neos-ui
|
train
|
5a6d99b83030b8da33e1655a97f9fbd45aa21247
|
diff --git a/lib/sass/css.rb b/lib/sass/css.rb
index <HASH>..<HASH> 100644
--- a/lib/sass/css.rb
+++ b/lib/sass/css.rb
@@ -266,7 +266,7 @@ module Sass
rules = OrderedHash.new
root.children.select { |c| Tree::RuleNode === c }.each do |child|
root.children.delete child
- first, rest = child.rule.scan(/^(&?.[^.#: \[]*)([.#: \[].*)?$/).first
+ first, rest = child.rule.scan(/^(&?(?: .|[^ ])[^.#: \[]*)([.#: \[].*)?$/).first
rules[first] ||= Tree::RuleNode.new(first, nil)
if rest
child.rule = "&" + rest
|
css2sass doesn't get confused by CSS rules starting with . or #
This caused it to trip up on stuff like
.a.b .c { a: b }
.a.b .d { a: b }
|
sass_ruby-sass
|
train
|
be5d0e4f610136882b77bd9c96905cc47cfd554e
|
diff --git a/src/javascript/runtime/silverlight/image/Image.js b/src/javascript/runtime/silverlight/image/Image.js
index <HASH>..<HASH> 100644
--- a/src/javascript/runtime/silverlight/image/Image.js
+++ b/src/javascript/runtime/silverlight/image/Image.js
@@ -15,13 +15,14 @@
define("moxie/runtime/silverlight/image/Image", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
+ "moxie/file/Blob",
"moxie/runtime/flash/image/Image"
-], function(extensions, Basic, Image) {
+], function(extensions, Basic, Blob, Image) {
return (extensions.Image = Basic.extend({}, Image, {
getInfo: function() {
var self = this.getRuntime()
- , grps = ['tiff', 'exif', 'gps']
+ , grps = ['tiff', 'exif', 'gps', 'thumb']
, info = { meta: {} }
, rawInfo = self.shimExec.call(this, 'Image', 'getInfo')
;
@@ -51,6 +52,11 @@ define("moxie/runtime/silverlight/image/Image", [
}
}
});
+
+ // save thumb data as blob
+ if (info.meta && info.meta.thumb) {
+ info.meta.thumb.data = new Blob(self.uid, info.meta.thumb.data);
+ }
}
info.width = parseInt(rawInfo.width, 10);
|
Image, Silverlight: Adapt getInfo() for thumb extraction.
|
moxiecode_moxie
|
train
|
269173940d7353957956425d50eb27071698f960
|
diff --git a/CHANGES.rst b/CHANGES.rst
index <HASH>..<HASH> 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -52,3 +52,7 @@ v1.0.0
v1.0.1
-----------
* Use MEDIA_URL setting in test cases
+
+v1.0.2[unreleased]
+-----------
+* Remove ovp_users as dependency
diff --git a/ovp_uploads/models.py b/ovp_uploads/models.py
index <HASH>..<HASH> 100644
--- a/ovp_uploads/models.py
+++ b/ovp_uploads/models.py
@@ -1,15 +1,13 @@
import uuid
from django.db import models
+from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.utils.deconstruct import deconstructible
from django_resized import ResizedImageField
-from ovp_users.models import User
-
-
@deconstructible
class ImageName(object):
def __init__(self, sub_path=""):
@@ -49,7 +47,7 @@ class UploadedImage(models.Model):
verbose_name = _('uploaded image')
verbose_name_plural = _('uploaded images')
- user = models.ForeignKey('ovp_users.User', default=None, null=True, blank=True)
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, null=True, blank=True)
image = models.ImageField(_('Image 350x260'), upload_to=image)
image_small = ResizedImageField(size=[350, 260], upload_to=image_small, blank=True, null=True, default=None)
image_medium = ResizedImageField(size=[420, 312], upload_to=image_medium, blank=True, null=True, default=None)
diff --git a/ovp_uploads/tests/runtests.py b/ovp_uploads/tests/runtests.py
index <HASH>..<HASH> 100644
--- a/ovp_uploads/tests/runtests.py
+++ b/ovp_uploads/tests/runtests.py
@@ -17,7 +17,6 @@ sys.path.insert(0, os.path.abspath(os.path.join(BASE_DIR, '../..')))
CUSTOM_INSTALLED_APPS = (
'ovp_core',
'ovp_uploads',
- 'ovp_users',
'django.contrib.admin',
)
diff --git a/ovp_uploads/tests/test_serializers.py b/ovp_uploads/tests/test_serializers.py
index <HASH>..<HASH> 100644
--- a/ovp_uploads/tests/test_serializers.py
+++ b/ovp_uploads/tests/test_serializers.py
@@ -7,7 +7,7 @@ from rest_framework.test import APIRequestFactory
from ovp_uploads.models import UploadedImage
from ovp_uploads.serializers import UploadedImageSerializer
-from ovp_users.models import User
+from django.contrib.auth import get_user_model
from PIL import Image
@@ -17,7 +17,7 @@ from tempfile import NamedTemporaryFile
class UploadedImageSerializerTestCase(TestCase):
def test_image_urls(self):
"""Assert that image object returns url"""
- user = User.objects.create_user('test_image_urls@test.com', 'validpassword')
+ user = get_user_model().objects.create_user('test_image_urls@test.com', 'validpassword')
client = APIClient()
client.force_authenticate(user=user)
diff --git a/ovp_uploads/tests/test_views.py b/ovp_uploads/tests/test_views.py
index <HASH>..<HASH> 100644
--- a/ovp_uploads/tests/test_views.py
+++ b/ovp_uploads/tests/test_views.py
@@ -4,8 +4,7 @@ from rest_framework.reverse import reverse
from rest_framework.test import APIClient
from django.http.request import QueryDict
-
-from ovp_users.models import User
+from django.contrib.auth import get_user_model
from PIL import Image
@@ -23,7 +22,7 @@ class UploadedImageViewSetTestCase(TestCase):
def test_cant_upload_no_image(self):
"""Assert that error is raised on no image"""
- user = User.objects.create_user('test_cant_upload_no_image@test.com', 'validpassword')
+ user = get_user_model().objects.create_user('test_cant_upload_no_image@test.com', 'validpassword')
client = APIClient()
client.force_authenticate(user=user)
@@ -34,7 +33,7 @@ class UploadedImageViewSetTestCase(TestCase):
def test_can_upload_authenticated(self):
"""Assert that it's possible to upload while authenticated"""
- user = User.objects.create_user('test_can_upload@test.com', 'validpassword')
+ user = get_user_model().objects.create_user('test_can_upload@test.com', 'validpassword')
client = APIClient()
client.force_authenticate(user=user)
diff --git a/requirements.txt b/requirements.txt
index <HASH>..<HASH> 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -5,5 +5,4 @@ djangorestframework==3.4.7
django-resized==0.3.5
Pillow==3.4.2
ovp_core==1.1.2
-ovp-users==1.0.20
django-storages==1.5.1
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -21,7 +21,6 @@ setup(
'django-resized>=0.3.5,<0.4.0',
'Pillow>=3.4.2,<3.5',
'ovp-core>=1.1.0,<2.0.0',
- 'ovp-users>=1.0.0,<2.0.0',
'django-storages>=1.5.1,<1.6',
]
)
|
Remove ovp_users as dependency
|
OpenVolunteeringPlatform_django-ovp-uploads
|
train
|
efe9077071ede5b6646b91b697238d790bcb7120
|
diff --git a/tools/scheduler.py b/tools/scheduler.py
index <HASH>..<HASH> 100644
--- a/tools/scheduler.py
+++ b/tools/scheduler.py
@@ -494,10 +494,14 @@ class MPIScheduler(BaseScheduler):
cpus, mem = self.getResource(offer)
logger.debug('got resource offer %s: cpus:%s, mem:%s at %s',
offer.id.value, cpus, mem, offer.hostname)
- if launched >= self.options.tasks or offer.hostname in used_hosts:
+ if launched >= self.options.tasks:
driver.declineOffer(offer.id, REFUSE_FILTER)
continue
+ if offer.hostname in used_hosts:
+ driver.declineOffer(offer.id)
+ continue
+
attrs = self.getAttributes(offer)
group = attrs.get('group', 'None')
if (self.options.group or group.startswith(
|
reject offer temporarily when resources are still pending.
|
douban_dpark
|
train
|
8b37e36e72cba24c4fc9a52f9a577293fa067e66
|
diff --git a/test/second-test.js b/test/second-test.js
index <HASH>..<HASH> 100644
--- a/test/second-test.js
+++ b/test/second-test.js
@@ -31,6 +31,21 @@ vows.describe("Test 2").addBatch({
assert.equal(4, topic.iact[3]);
assert.equal(1, topic.iact[4]);
assert.equal(13, topic.iact[5]);
+ assert.equal(0.000049541083784517924, topic.Lagrangian[1]);
+ assert.equal(0, topic.Lagrangian[2]);
+ assert.equal(0.000053902979003092, topic.Lagrangian[3]);
+ assert.equal(0.000030704949904724455, topic.Lagrangian[4]);
+ assert.equal(0.00008464760953664744, topic.Lagrangian[5]);
+ assert.equal(0, topic.Lagrangian[6]);
+ assert.equal(0, topic.Lagrangian[7]);
+ assert.equal(0, topic.Lagrangian[8]);
+ assert.equal(0, topic.Lagrangian[9]);
+ assert.equal(0, topic.Lagrangian[10]);
+ assert.equal(0, topic.Lagrangian[11]);
+ assert.equal(0, topic.Lagrangian[12]);
+ assert.equal(0.0000373182859218225, topic.Lagrangian[13]);
+ assert.equal(0, topic.Lagrangian[14]);
+ assert.equal(0, topic.Lagrangian[15]);
}
}
|
Add Lagrange test for second-test.
|
albertosantini_node-quadprog
|
train
|
e1f478633e1e6e86da29b1f4d58e0af3a6b0641f
|
diff --git a/src/server/worker/master.go b/src/server/worker/master.go
index <HASH>..<HASH> 100644
--- a/src/server/worker/master.go
+++ b/src/server/worker/master.go
@@ -409,11 +409,14 @@ func (a *APIServer) runJob(ctx context.Context, jobInfo *pps.JobInfo, pool *pool
}
tree := hashtree.NewHashTree()
var statsTree hashtree.OpenHashTree
+ var skippedTree hashtree.OpenHashTree
if jobInfo.EnableStats {
statsTree = hashtree.NewHashTree()
+ skippedTree = hashtree.NewHashTree()
}
var processStats []*pps.ProcessStats
var treeMu sync.Mutex
+ var skippedTreeMu sync.Mutex
processedData := int64(0)
skippedData := int64(0)
@@ -558,6 +561,25 @@ func (a *APIServer) runJob(ctx context.Context, jobInfo *pps.JobInfo, pool *pool
logger.Logf("failed to retrieve stats hashtree after processing for datum %v: %v", files, err)
return nil
}
+ if resp.Skipped {
+ // write file to skipped stats tree
+ nodes, err := statsSubtree.Glob("*")
+ if err != nil {
+ logger.Logf("failed to retrieve datum ID from hashtree for datum %v: %v", files, err)
+ }
+ if len(nodes) != 1 {
+ logger.Logf("should have a single stats object for datum %v", files)
+ return nil
+ }
+ datumID := nodes[0].Name
+ fmt.Printf("datum skipped: %v\n", datumID)
+ skippedTreeMu.Lock()
+ err = skippedTree.PutFile(fmt.Sprintf("%v/skipped", datumID), nil, 0)
+ skippedTreeMu.Unlock()
+ if err != nil {
+ logger.Logf("unable to put skipped file to tree: %", err)
+ }
+ }
nodes, err := statsSubtree.Glob("*/stats")
if err != nil {
logger.Logf("failed to retrieve process stats from hashtree for datum %v: %v", files, err)
@@ -634,6 +656,11 @@ func (a *APIServer) runJob(ctx context.Context, jobInfo *pps.JobInfo, pool *pool
}(); err != nil {
logger.Logf("error aggregating stats")
}
+ if skippedTree != nil {
+ if err := statsTree.Merge(skippedTree); err != nil {
+ logger.Logf("failed to merge skipped files into stats tree: %v", err)
+ }
+ }
statsObject, err := a.putTree(ctx, statsTree)
if err != nil {
return err
|
Update worker master to write skipped state
|
pachyderm_pachyderm
|
train
|
33ab5db81ae175032c725f4c3e1bf379b519a1fc
|
diff --git a/livereload/__init__.py b/livereload/__init__.py
index <HASH>..<HASH> 100644
--- a/livereload/__init__.py
+++ b/livereload/__init__.py
@@ -1,5 +1,5 @@
"""django-livereload"""
-__version__ = '1.3'
+__version__ = '1.4'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
|
Bumping to version <I>
|
Fantomas42_django-livereload
|
train
|
e7850bb3d98f43ec110c5a9f1381b93c0ec6ccd4
|
diff --git a/tests/db_loader_unittest.py b/tests/db_loader_unittest.py
index <HASH>..<HASH> 100644
--- a/tests/db_loader_unittest.py
+++ b/tests/db_loader_unittest.py
@@ -467,6 +467,7 @@ class CsvLoaderTestCase(unittest.TestCase):
self.assertEqual(csv_headers, expected_headers)
# Skip the end-to-end test for now, until database on CI system is setup
+ # TODO: move the test in db_tests folder
@helpers.skipit
def test_csv_to_db_loader_end_to_end(self):
"""
|
will move end_to_end tests to db_tests/ folder after CI is setup to run
db_tests
Former-commit-id: a<I>c<I>b<I>d<I>b4c<I>d6f<I>ae<I>
|
gem_oq-engine
|
train
|
8055323fb622604c7ce633b59097ae270f93661f
|
diff --git a/lib/kat/search.rb b/lib/kat/search.rb
index <HASH>..<HASH> 100644
--- a/lib/kat/search.rb
+++ b/lib/kat/search.rb
@@ -130,10 +130,6 @@ module Kat
build_query
end
- def sort?
- sorts.any? { |k, v| @options[:sort] && k == @options[:sort].intern }
- end
-
#
# Perform the search, supplying an optional page number to search on. Returns
# a result set limited to the 25 results Kickass Torrents returns itself. Will
@@ -150,7 +146,6 @@ module Kat
if res.code == '301'
path = Net::HTTP::Get.new(res.header['location'])
res = Net::HTTP.start(uri.host) { |http| http.request path }
- @message = { message: 'Sort is not functioning' } if sort?
end
@pages = 0 and return if res.code == '404'
diff --git a/lib/kat/version.rb b/lib/kat/version.rb
index <HASH>..<HASH> 100644
--- a/lib/kat/version.rb
+++ b/lib/kat/version.rb
@@ -1,6 +1,6 @@
module Kat
NAME = 'Kickass Torrents Search'
- VERSION = '2.0.7'
+ VERSION = '2.0.8'
MALEVOLENT_DICTATOR_FOR_LIFE = 'Fission Xuiptz'
AUTHOR = MALEVOLENT_DICTATOR_FOR_LIFE
VERSION_STR = "#{ NAME } #{ VERSION } (c) 2013 #{ MALEVOLENT_DICTATOR_FOR_LIFE }"
|
Removed busted 'sort is not functioning' message
|
fissionxuiptz_kat
|
train
|
82c37742811c3fc7a0fd2abd9a5ffc9de2aa69fb
|
diff --git a/src/main/java/com/relayrides/pushy/apns/FeedbackServiceConnection.java b/src/main/java/com/relayrides/pushy/apns/FeedbackServiceConnection.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/relayrides/pushy/apns/FeedbackServiceConnection.java
+++ b/src/main/java/com/relayrides/pushy/apns/FeedbackServiceConnection.java
@@ -62,7 +62,7 @@ import org.slf4j.LoggerFactory;
* reregistered, stop sending notifications.</p></blockquote>
*
* <p>Generally, users of Pushy should <em>not</em> instantiate a {@code FeedbackServiceConnection} directly, but should
- * instead call {@link com.relayrides.pushy.apns.PushManager#getExpiredTokens()}, which will manage the creation and
+ * instead call {@link com.relayrides.pushy.apns.PushManager#requestExpiredTokens()}, which will manage the creation and
* configuration of a {@code FeedbackServiceConnection} internally.</p>
*
* @author <a href="mailto:jon@relayrides.com">Jon Chambers</a>
@@ -71,7 +71,7 @@ import org.slf4j.LoggerFactory;
* Local and Push Notification Programming Guide - Provider Communication with Apple Push Notification Service - The
* Feedback Service</a>
*/
-class FeedbackServiceConnection {
+public class FeedbackServiceConnection {
private final ApnsEnvironment environment;
private final SSLContext sslContext;
@@ -228,17 +228,12 @@ class FeedbackServiceConnection {
}
/**
- * <p>Retrieves a list of expired tokens from the APNs feedback service. Be warned that this is a
+ * <p>Connects to the APNs feedback service and waits for expired tokens to arrive. Be warned that this is a
* <strong>destructive operation</strong>. According to Apple's documentation:</p>
*
* <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback
* service, the information it returns lists only the failures that have happened since you last
* connected.</blockquote>
- *
- * @return a list of tokens that have expired since the last connection to the feedback service
- *
- * @throws InterruptedException if interrupted while waiting for a response from the feedback service
- * @throws FeedbackConnectionException if the connection to the feedback service failed for any reason
*/
public synchronized void connect() {
@@ -323,6 +318,10 @@ class FeedbackServiceConnection {
});
}
+ /**
+ * Closes this feedback connection as soon as possible. Calling this method when the feedback connection is not
+ * connected has no effect.
+ */
public synchronized void shutdownImmediately() {
if (this.connectFuture != null) {
synchronized (this.channelRegistrationMonitor) {
|
Publicized FeedbackServiceConnetion and de-horrible-ized its docs.
|
relayrides_pushy
|
train
|
5a210c15620d30b9cd00dda08c8efd079e4d0aa5
|
diff --git a/spec/httparty/request_spec.rb b/spec/httparty/request_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/httparty/request_spec.rb
+++ b/spec/httparty/request_spec.rb
@@ -1,14 +1,18 @@
require File.join(File.dirname(__FILE__), '..', 'spec_helper')
describe HTTParty::Request do
- def stub_response(body, type = Net::HTTPOK, code = 200)
- http = Net::HTTP.new('localhost', 80)
- @request.stub!(:http).and_return(http)
+ def stub_response(body, code = 200)
+ unless @http
+ @http = Net::HTTP.new('localhost', 80)
+ @request.stub!(:http).and_return(@http)
+ @request.stub!(:uri).and_return(URI.parse("http://foo.com/foobar"))
+ end
- @response = type.new("1.1", code, body)
- @response.stub!(:body).and_return(body)
+ response = Net::HTTPResponse::CODE_TO_OBJ[code.to_s].new("1.1", code, body)
+ response.stub!(:body).and_return(body)
- http.stub!(:request).and_return(@response)
+ @http.stub!(:request).and_return(response)
+ response
end
before do
@@ -93,7 +97,7 @@ describe HTTParty::Request do
describe 'with non-200 responses' do
it 'should return a valid object for 4xx response' do
- stub_response '<foo><bar>yes</bar></foo>', Net::HTTPUnauthorized, 401
+ stub_response '<foo><bar>yes</bar></foo>', 401
resp = @request.perform
resp.code.should == 401
resp.body.should == "<foo><bar>yes</bar></foo>"
@@ -101,7 +105,7 @@ describe HTTParty::Request do
end
it 'should return a valid object for 5xx response' do
- stub_response '<foo><bar>error</bar></foo>', Net::HTTPInternalServerError, 500
+ stub_response '<foo><bar>error</bar></foo>', 500
resp = @request.perform
resp.code.should == 500
resp.body.should == "<foo><bar>error</bar></foo>"
@@ -112,13 +116,10 @@ describe HTTParty::Request do
end
it "should not attempt to parse empty responses" do
- stub_response nil, Net::HTTPNoContent, 204
+ stub_response "", 204
@request.options[:format] = :xml
@request.perform.should be_nil
-
- @response.stub!(:body).and_return("")
- @request.perform.should be_nil
end
it "should not fail for missing mime type" do
@@ -129,15 +130,10 @@ describe HTTParty::Request do
describe "a request that redirects" do
before(:each) do
- @http = Net::HTTP.new('localhost', 80)
- @request.stub!(:http).and_return(@http)
- @request.stub!(:uri).and_return(URI.parse("http://foo.com/foobar"))
-
- @redirect = Net::HTTPFound.new("1.1", 302, "")
+ @redirect = stub_response("", 302)
@redirect['location'] = '/foo'
- @ok = Net::HTTPOK.new("1.1", 200, "Content for you")
- @ok.stub!(:body).and_return('<hash><foo>bar</foo></hash>')
+ @ok = stub_response('<hash><foo>bar</foo></hash>', 200)
end
describe "once" do
|
I lied, more refactoring of request_spec to slim it down.
|
jnunemaker_httparty
|
train
|
e779d771fab3fe19bcb852aa71c1d86226e02c24
|
diff --git a/PhpAmqpLib/Channel/AMQPChannel.php b/PhpAmqpLib/Channel/AMQPChannel.php
index <HASH>..<HASH> 100644
--- a/PhpAmqpLib/Channel/AMQPChannel.php
+++ b/PhpAmqpLib/Channel/AMQPChannel.php
@@ -35,6 +35,17 @@ class AMQPChannel extends AbstractChannel
"90,21" => "tx_commit_ok",
"90,31" => "tx_rollback_ok"
);
+ /**
+ *
+ * @var callable these parameters will be passed to function
+ * in case of basic_return:
+ * param int $reply_code
+ * param string $reply_text
+ * param string $exchange
+ * param string $routing_key
+ * param AMQPMessage $msg
+ */
+ protected $basic_return_callback = null;
public function __construct($connection,
$channel_id=null,
@@ -624,16 +635,25 @@ class AMQPChannel extends AbstractChannel
/**
* return a failed message
*/
- protected function basic_return($args)
+ protected function basic_return($args, $msg)
{
$reply_code = $args->read_short();
$reply_text = $args->read_shortstr();
$exchange = $args->read_shortstr();
$routing_key = $args->read_shortstr();
- $msg = $this->wait();
+
+ if( !is_null($this->basic_return_callback )){
+ call_user_func_array($this->basic_return_callback, array(
+ $reply_code,
+ $reply_text,
+ $exchange,
+ $routing_key,
+ $msg,
+ ));
+ } else if ($this->debug) {
+ MiscHelper::debug_msg("Skipping unhandled basic_return message");
+ }
}
-
-
public function tx_commit()
{
$this->send_method_frame(array(90, 20));
@@ -695,5 +715,15 @@ class AMQPChannel extends AbstractChannel
{
return (null === $ticket) ? $this->default_ticket : $ticket;
}
-
+ /**
+ * set callback for basic_return
+ * @param callable $callback
+ * @throws \InvalidArgumentException if $callback is not callable
+ */
+ public function set_return_listener($callback){
+ if(!is_callable($callback))
+ throw new \InvalidArgumentException('$callback should be callable.');
+ $this->basic_return_callback = $callback;
+ }
+
}
|
Added basic_return message handling.
New function AMQPChannel.set_return_listener.
In case the the callback is not set, it will sent the debug message.
|
php-amqplib_php-amqplib
|
train
|
f69ad08cb985972e66af4782f5d08ed06eca94de
|
diff --git a/aeron-system-tests/src/test/java/io/aeron/archive/ReplayMergeTest.java b/aeron-system-tests/src/test/java/io/aeron/archive/ReplayMergeTest.java
index <HASH>..<HASH> 100644
--- a/aeron-system-tests/src/test/java/io/aeron/archive/ReplayMergeTest.java
+++ b/aeron-system-tests/src/test/java/io/aeron/archive/ReplayMergeTest.java
@@ -263,7 +263,7 @@ public class ReplayMergeTest
"publication position: %d, current position: %d, time since last change: %.6f ms",
position, currentPosition, (System.nanoTime() - initialTimestampNs) / 1_000_000.0);
}
- while (currentPosition == counters.getCounterValue(counterId));
+ while (currentPosition == counters.getCounterValue(counterId) && currentPosition < position);
}
private long offerMessage(final Publication publication, final int index)
|
[Java] Make sure we don't timeout unnecessarily.
|
real-logic_aeron
|
train
|
fa680bded718653a64ba747887c71a956e044223
|
diff --git a/command/agent/http.go b/command/agent/http.go
index <HASH>..<HASH> 100644
--- a/command/agent/http.go
+++ b/command/agent/http.go
@@ -393,7 +393,7 @@ func (s *HTTPServer) wrap(handler func(resp http.ResponseWriter, req *http.Reque
// marshalJSON marshals the object into JSON, respecting the user's pretty-ness
// configuration.
func (s *HTTPServer) marshalJSON(req *http.Request, obj interface{}) ([]byte, error) {
- if _, ok := req.URL.Query()["pretty"]; ok {
+ if _, ok := req.URL.Query()["pretty"]; ok || s.agent.config.DevMode {
buf, err := json.MarshalIndent(obj, "", " ")
if err != nil {
return nil, err
|
Defaults to pretty JSON in dev mode.
|
hashicorp_consul
|
train
|
974946c730a4a5004243cdfd9a1f96710c4b7c51
|
diff --git a/object/src/main/java/com/orientechnologies/orient/object/db/ODatabasePojoAbstract.java b/object/src/main/java/com/orientechnologies/orient/object/db/ODatabasePojoAbstract.java
index <HASH>..<HASH> 100644
--- a/object/src/main/java/com/orientechnologies/orient/object/db/ODatabasePojoAbstract.java
+++ b/object/src/main/java/com/orientechnologies/orient/object/db/ODatabasePojoAbstract.java
@@ -491,12 +491,14 @@ public abstract class ODatabasePojoAbstract<T extends Object> extends ODatabaseW
Map<String, Object> map = (Map<String, Object>) iParameter;
for (Entry<String, Object> e : map.entrySet()) {
- map.put(e.getKey(), convertParameter(e.getValue()));
- }
-
- } else if (iParameter != null && !OType.isSimpleType(iParameter)) {
- final ORID rid = getIdentity(iParameter);
- if (rid != null && rid.isValid())
+ map.put(e.getKey(), convertParameter(e.getValue()));
+ }
+
+ } else if (iParameter != null && iParameter.getClass().isEnum()) {
+ return ((Enum<?>) iParameter).name();
+ } else if (iParameter != null && !OType.isSimpleType(iParameter)) {
+ final ORID rid = getIdentity(iParameter);
+ if (rid != null && rid.isValid())
// REPLACE OBJECT INSTANCE WITH ITS RECORD ID
return rid;
}
|
Fix by Enrico Risa about the handling of ENUMs as parameter of a query
|
orientechnologies_orientdb
|
train
|
c6a68ef904ccfd51a0d57292d848f2ecf42f1d8d
|
diff --git a/test/StoragelessSessionTest/Session/DataTest.php b/test/StoragelessSessionTest/Session/DataTest.php
index <HASH>..<HASH> 100644
--- a/test/StoragelessSessionTest/Session/DataTest.php
+++ b/test/StoragelessSessionTest/Session/DataTest.php
@@ -61,4 +61,13 @@ final class DataTest extends PHPUnit_Framework_TestCase
self::assertFalse($data->isEmpty());
}
+
+ public function testContainerIsEmptyWhenDataIsRemovedFromIt()
+ {
+ $data = Data::fromTokenData(['foo' => 'bar']);
+
+ $data->remove('foo');
+
+ self::assertTrue($data->isEmpty());
+ }
}
|
Containers are empty if data is removed from it
|
psr7-sessions_storageless
|
train
|
7195c5dca5fd52d89b471659ae865ed00082efd3
|
diff --git a/sramongo/xml_helpers.py b/sramongo/xml_helpers.py
index <HASH>..<HASH> 100644
--- a/sramongo/xml_helpers.py
+++ b/sramongo/xml_helpers.py
@@ -17,7 +17,7 @@ def valid_path(func):
def new_func(*args, **kwargs):
# If the current path is present
if args[1] is None:
- logger.warn(('Not valid path.', func, args))
+ logger.debug(('Not valid path.', func, args))
return {}
else:
return func(*args, **kwargs)
|
Changes warnging to debug message.
|
jfear_sramongo
|
train
|
0d92860e23c0b7843dd5fe8dbe20ee314b9ce6ce
|
diff --git a/src/RemoteProcessor.php b/src/RemoteProcessor.php
index <HASH>..<HASH> 100644
--- a/src/RemoteProcessor.php
+++ b/src/RemoteProcessor.php
@@ -24,16 +24,25 @@ abstract class RemoteProcessor {
{
$target = $this->getConfiguredServer($host) ?: $host;
- $script = 'set -e'.PHP_EOL.$task->script;
+ // Here we'll run the task on the localhost without any sort of SSH. This
+ // lets us run Envoy tasks locally just like any other remote connection.
+ if( in_array($target, ['local', 'localhost', '127.0.0.1']) )
+ {
+ $process = new Process($task->script);
+ }
- // Here will run the SSH task on the server inline. We do not need to write the
+ // Here we'll run the SSH task on the server inline. We do not need to write the
// script out to a file or anything. We will start the SSH process then pass
// these lines of output back to the parent callback for display purposes.
- $process = new Process(
- 'ssh '.$target.' \'bash -s\' << EOF
+ else
+ {
+ $script = 'set -e'.PHP_EOL.$task->script;
+ $process = new Process(
+ 'ssh '.$target.' \'bash -s\' << EOF
'.$script.'
EOF'
- );
+ );
+ }
return [$target, $process->setTimeout(null)];
}
|
Added ability to run scripts locally without SSH.
|
laravel_envoy
|
train
|
cb77cf12621ab7d3eddb4ccbe60f23716b5cc47c
|
diff --git a/course/lib.php b/course/lib.php
index <HASH>..<HASH> 100644
--- a/course/lib.php
+++ b/course/lib.php
@@ -1227,9 +1227,9 @@ function print_section_add_menus($course, $section, $modnames, $vertical=false,
}
// we need to loop through the forms and check to see if we can add them.
- foreach ($modnames as $key) {
+ foreach ($modnames as $key=>$value) {
if (!course_allowed_module($course,$key))
- unset($modnames[strtolower($key)]);
+ unset($modnames[$key]);
}
// this is stupid but labels get put into resource, so if resource is hidden and label is not, we're in trouble.
@@ -2096,7 +2096,7 @@ function course_allowed_module($course,$mod) {
if (is_numeric($mod)) {
$modid = $mod;
} else if (is_string($mod)) {
- if ($mod = get_field("modules","id","name",strtolower($mod)))
+ if ($mod = get_field("modules","id","name",$mod))
$modid = $mod;
}
if (empty($modid)) {
|
fixed problem in restricted modules - mods were accessed using strtolower(translated module name) instead of directory name as usual, it partially worked for English; merged from MOODLE_<I>_STABLE
|
moodle_moodle
|
train
|
bdf65de6ff948df1f44b0c983df87ff9d89ab688
|
diff --git a/spec/buster.js b/spec/buster.js
index <HASH>..<HASH> 100644
--- a/spec/buster.js
+++ b/spec/buster.js
@@ -6,6 +6,7 @@ config["Converter"] = {
, sources: [
"../vendor/marked.js"
, "../src/remark/namespace.js"
+ , "../src/remark/config.js"
, "../src/remark/converter.js"
]
, tests: [
diff --git a/spec/remark/converterSpec.js b/spec/remark/converterSpec.js
index <HASH>..<HASH> 100644
--- a/spec/remark/converterSpec.js
+++ b/spec/remark/converterSpec.js
@@ -156,6 +156,18 @@ describe('converter', function () {
it('should unescape escaped code class', function () {
expect(convert('\\.ruby\na = 5', 'pre').innerHTML).toEqual('.ruby\na = 5');
});
+
+ it('should use configured code class by default', function () {
+ remark.config({highlightLanguage: 'not-a-language'});
+
+ expect(convert('a = 5', 'pre').className).toEqual('not-a-language');
+ });
+
+ it('should ignore configured code class if class is given', function () {
+ remark.config({highlightLanguage: 'not-a-language'});
+
+ expect(convert('.ruby a = 5', 'pre').className).toEqual('ruby');
+ });
});
});
diff --git a/src/remark/converter.js b/src/remark/converter.js
index <HASH>..<HASH> 100644
--- a/src/remark/converter.js
+++ b/src/remark/converter.js
@@ -105,6 +105,7 @@
converter.convertCodeClasses = function (content) {
var codeBlocks = content.getElementsByTagName('code')
+ , defaultClass = remark.config.highlightLanguage
, block
, i
, foundClass
@@ -120,6 +121,9 @@
if (!foundClass && isInlineCode) {
block.className = 'no-highlight';
}
+ else if (!foundClass && defaultClass) {
+ block.className = defaultClass;
+ }
}
};
|
Add support for highlightLanguage configuation option.
|
gnab_remark
|
train
|
9b9c1a7a91ba6c0c9f48241571dcaf54e5a61406
|
diff --git a/plaso/output/l2t_csv.py b/plaso/output/l2t_csv.py
index <HASH>..<HASH> 100644
--- a/plaso/output/l2t_csv.py
+++ b/plaso/output/l2t_csv.py
@@ -137,10 +137,6 @@ class L2TCSVFieldFormattingHelper(formatting_helper.FieldFormattingHelper):
NoFormatterFound: if no event formatter can be found to match the data
type in the event data.
"""
- event_attributes = list(event_data.GetAttributes())
- if event_data_stream:
- event_attributes.extend(event_data_stream.GetAttributes())
-
# TODO: reverse logic and get formatted attributes instead.
unformatted_attributes = (
formatters_manager.FormattersManager.GetUnformattedAttributes(
@@ -151,12 +147,8 @@ class L2TCSVFieldFormattingHelper(formatting_helper.FieldFormattingHelper):
'Unable to find event formatter for: {0:s}.'.format(
event_data.data_type))
- event_attributes = list(event_data.GetAttributes())
- if event_data_stream:
- event_attributes.extend(event_data_stream.GetAttributes())
-
extra_attributes = []
- for attribute_name, attribute_value in sorted(event_attributes):
+ for attribute_name, attribute_value in event_data.GetAttributes():
if attribute_name in unformatted_attributes:
# Some parsers have written bytes values to storage.
if isinstance(attribute_value, bytes):
@@ -172,7 +164,13 @@ class L2TCSVFieldFormattingHelper(formatting_helper.FieldFormattingHelper):
extra_attributes.append('{0:s}: {1!s}'.format(
attribute_name, attribute_value))
- extra_attributes = '; '.join(extra_attributes)
+ if event_data_stream:
+ for attribute_name, attribute_value in event_data_stream.GetAttributes():
+ if attribute_name != 'path_spec':
+ extra_attributes.append('{0:s}: {1!s}'.format(
+ attribute_name, attribute_value))
+
+ extra_attributes = '; '.join(sorted(extra_attributes))
return extra_attributes.replace('\n', '-').replace('\r', '')
|
Changed l2tcsv output module to include event data stream in extra field #<I> (#<I>)
|
log2timeline_plaso
|
train
|
f091ec7edf2b9e83770268a60e10f64389ae9c9e
|
diff --git a/optlang/glpk_interface.py b/optlang/glpk_interface.py
index <HASH>..<HASH> 100644
--- a/optlang/glpk_interface.py
+++ b/optlang/glpk_interface.py
@@ -152,9 +152,7 @@ class Constraint(interface.Constraint):
ia = intArray(col_num + 1)
da = doubleArray(col_num + 1)
nnz = glp_get_mat_row(self.problem.problem, self.index, ia, da)
- # variables = self.problem.variables
- # constraint_variables = [variables[ia[i] - 1] for i in range(1, nnz + 1)]
- constraint_variables = [self.problem.variables[glp_get_col_name(self.problem.problem, ia[i])] for i in
+ constraint_variables = [self.problem._variables[glp_get_col_name(self.problem.problem, ia[i])] for i in
range(1, nnz + 1)]
expression = sympy.Add._from_args(
[sympy.Mul._from_args((sympy.RealNumber(da[i]), constraint_variables[i - 1])) for i in
@@ -264,7 +262,7 @@ class Objective(interface.Objective):
def _get_expression(self):
if self.problem is not None:
- variables = self.problem.variables
+ variables = self.problem._variables
def term_generator():
for index in range(1, glp_get_num_cols(self.problem.problem) + 1):
|
fix: avoid infinite recursion in model.update() by replacing problem.variables with problem._variables
|
biosustain_optlang
|
train
|
079b1a1595db2eb640636bda3a2eccb5f03d506b
|
diff --git a/authority/tests.py b/authority/tests.py
index <HASH>..<HASH> 100644
--- a/authority/tests.py
+++ b/authority/tests.py
@@ -150,10 +150,9 @@ class AssignExceptionsTest(TestCase):
self.fail()
-class PerformanceTest(TestCase):
+class SmartCacheingTestCase(TestCase):
"""
- Tests that permission are actually cached and that the number of queries
- stays constant.
+ The base test case for all tests that have to do with smart caching.
"""
fixtures = ['tests.json']
@@ -161,6 +160,24 @@ class PerformanceTest(TestCase):
self.user = User.objects.get(username='jezdez')
self.check = UserPermission(self.user)
+ def _old_permission_check(self):
+ # This is what the old, pre-cache system would check to see if a user
+ # had a given permission.
+ return Permission.objects.user_permissions(
+ self.user,
+ 'foo',
+ self.user,
+ approved=True,
+ check_groups=True,
+ )
+
+
+class PerformanceTest(SmartCacheingTestCase):
+ """
+ Tests that permission are actually cached and that the number of queries
+ stays constant.
+ """
+
def test_has_user_perms(self):
# Show that when calling has_user_perms multiple times no additional
# queries are done.
@@ -189,26 +206,10 @@ class PerformanceTest(TestCase):
self.check.has_user_perms('foo', self.user, True, True)
-class ExpectedBehaviourTestCase(TestCase):
+class ExpectedBehaviourTestCase(SmartCacheingTestCase):
"""
Tests that peg expected behaviour
"""
- fixtures = ['tests.json']
-
- def setUp(self):
- self.user = User.objects.get(username='jezdez')
- self.check = UserPermission(self.user)
-
- def _old_permission_check(self):
- # This is what the old, pre-cache system would check to see if a user
- # had a given permission.
- return Permission.objects.user_permissions(
- self.user,
- 'foo',
- self.user,
- approved=True,
- check_groups=True,
- )
def test_has_user_perms_with_groups(self):
perms = self._old_permission_check()
|
refs #4: made a base test case for smart caching
|
jazzband_django-authority
|
train
|
0383e3f464df5c7fae84474c744bb6bbe08bcb59
|
diff --git a/ladybug/epw.py b/ladybug/epw.py
index <HASH>..<HASH> 100644
--- a/ladybug/epw.py
+++ b/ladybug/epw.py
@@ -427,7 +427,8 @@ class EPW(object):
# parse typical and extreme periods into analysis periods.
week_data = header_lines[2].split(',')
- num_weeks = int(week_data[1]) if len(week_data) >= 2 else 0
+ num_weeks = int(week_data[1]) if len(week_data) >= 2 \
+ and week_data[1] != '' else 0
st_ind = 2
for _ in xrange(num_weeks):
week_dat = week_data[st_ind:st_ind + 4]
@@ -447,7 +448,8 @@ class EPW(object):
# parse the monthly ground temperatures in the header.
grnd_data = header_lines[3].strip().split(',')
- num_depths = int(grnd_data[1]) if len(grnd_data) >= 2 else 0
+ num_depths = int(grnd_data[1]) if len(grnd_data) >= 2 \
+ and grnd_data[1] != '' else 0
st_ind = 2
for _ in xrange(num_depths):
header_meta = dict(self._metadata) # copying the metadata dictionary
|
fix(epw): Ensure header parsing does not block EPW import
|
ladybug-tools_ladybug
|
train
|
e7ea0baebde4f612d4c1c1065d76d01f2a5e6f58
|
diff --git a/packages/utils-applications/pm2.js b/packages/utils-applications/pm2.js
index <HASH>..<HASH> 100644
--- a/packages/utils-applications/pm2.js
+++ b/packages/utils-applications/pm2.js
@@ -21,13 +21,12 @@ const hiddenKeys = [
const visibleKeys = [
'env',
'env_production',
- 'error_file',
'exec_mode',
'ignore_watch',
'instances',
'max_restarts',
'name',
- 'out_file',
+ 'log',
'watch'
]
@@ -84,6 +83,9 @@ class Application {
this.watch = ['config/**/**', 'lib/**/**', 'src/**/**']
this.ignore_watch = ['node_modules/**', '*.log']
+ this.output = '/dev/null'
+ this.error = '/dev/null'
+
this.targetInstances = 1
this.max_restarts = 100
this.development = dev
@@ -145,13 +147,7 @@ class Application {
this._max_restarts = val
}
- get error_file () {
- return this.development
- ? 'NULL'
- : path.resolve(config.get('paths.log'), `${this.name}.log`)
- }
-
- get out_file () {
+ get log () {
return this.development
? 'NULL'
: path.resolve(config.get('paths.log'), `${this.name}.log`)
|
PM2 v3 ecosystem upgrade [Phobos<I>]
|
CactusTechnologies_cactus-utils
|
train
|
ed9fa0bd5b71e82732ede0173e05b37bae00971c
|
diff --git a/lib/api/2011-02-01/search.js b/lib/api/2011-02-01/search.js
index <HASH>..<HASH> 100644
--- a/lib/api/2011-02-01/search.js
+++ b/lib/api/2011-02-01/search.js
@@ -59,7 +59,7 @@ exports.createHandler = function(context) {
if (!query && booleanQuery) {
var translator = new BooleanQueryTranslator();
- var translatedQuery = translator.translateTinia(booleanQuery);
+ var translatedQuery = translator.translate(booleanQuery);
if (translatedQuery) {
query = translatedQuery;
} else {
diff --git a/lib/bq-translator.js b/lib/bq-translator.js
index <HASH>..<HASH> 100644
--- a/lib/bq-translator.js
+++ b/lib/bq-translator.js
@@ -1,3 +1,4 @@
+// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*-
/*
Translates Boolean Queries used in tinia https://github.com/dlangevin/tinia
into groonga query.
@@ -13,6 +14,9 @@ function BooleanQueryTranslator() {
}
BooleanQueryTranslator.prototype = {
+ translate: function(query) {
+ return this.translateTinia(query);
+ },
translateTinia: function(query) {
var matched = null;
diff --git a/test/bq-translator.test.js b/test/bq-translator.test.js
index <HASH>..<HASH> 100644
--- a/test/bq-translator.test.js
+++ b/test/bq-translator.test.js
@@ -7,7 +7,7 @@ var BooleanQueryTranslator = require('../lib/bq-translator').BooleanQueryTransla
function testTranslate(expected, query) {
test('translate: <' + query + '> -> <' + expected + '>', function() {
var translator = new BooleanQueryTranslator();
- assert.equal(expected, translator.translateTinia(query));
+ assert.equal(expected, translator.translate(query));
});
}
|
BqTranslator: use "translate" as public method
Supporting only bq format used by Tinia is internal information.
It should be capsuled in BqTranslator.
|
groonga_gcs
|
train
|
b89e0de75065677f5d8b6b751d44bafabd8c6ce0
|
diff --git a/upload/catalog/controller/extension/openbay/ebay.php b/upload/catalog/controller/extension/openbay/ebay.php
index <HASH>..<HASH> 100644
--- a/upload/catalog/controller/extension/openbay/ebay.php
+++ b/upload/catalog/controller/extension/openbay/ebay.php
@@ -94,6 +94,17 @@ class ControllerExtensionOpenbayEbay extends Controller {
$this->response->setOutput(json_encode(array('error' => 'Log file not found')));
}
}
+
+ if($data['action'] == 'config') {
+ $this->openbay->ebay->log('Action: config / Check store php limits for import options');
+
+ $post_size = ini_get('post_max_size');
+ $post_size = (int)str_replace(array('M','m','Mb','MB'), '', $post_size);
+ $version = (int)$this->config->get('feed_openbaypro_version');
+
+ $this->response->addHeader('Content-Type: application/json');
+ $this->response->setOutput(json_encode(array('msg' => 'ok', 'max_post' => $post_size, 'version' => $version)));
+ }
} else {
$this->openbay->ebay->log('Secret incorrect or module not active.');
diff --git a/upload/catalog/controller/extension/openbay/openbay.php b/upload/catalog/controller/extension/openbay/openbay.php
index <HASH>..<HASH> 100644
--- a/upload/catalog/controller/extension/openbay/openbay.php
+++ b/upload/catalog/controller/extension/openbay/openbay.php
@@ -4,7 +4,9 @@ class ControllerExtensionOpenbayOpenbay extends Controller {
$this->response->addHeader('Cache-Control: no-cache, must-revalidate');
$this->response->addHeader('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
$this->response->addHeader('Content-type: application/json; charset=utf-8');
+ $this->response->addHeader('X-Openbay-Header: hello');
+ http_response_code(200);
$this->response->setOutput(json_encode(array('reply' => 'hello')));
}
}
|
Added back the store memory and limit check but behind auth process.
|
opencart_opencart
|
train
|
7c9b474f171e4e729b3e0fb0b00a67543687cd4f
|
diff --git a/pyinfra/api/util.py b/pyinfra/api/util.py
index <HASH>..<HASH> 100644
--- a/pyinfra/api/util.py
+++ b/pyinfra/api/util.py
@@ -229,6 +229,9 @@ def get_file_sha1(filename_or_io):
buff = file_io.read(BLOCKSIZE)
while len(buff) > 0:
+ if isinstance(buff, six.text_type):
+ buff = buff.encode('utf-8')
+
hasher.update(buff)
buff = file_io.read(BLOCKSIZE)
|
Encode unicode data before hashing.
|
Fizzadar_pyinfra
|
train
|
ad6fd5767773622780685683b41c41e331fb3d29
|
diff --git a/lib/marty/monkey.rb b/lib/marty/monkey.rb
index <HASH>..<HASH> 100644
--- a/lib/marty/monkey.rb
+++ b/lib/marty/monkey.rb
@@ -67,7 +67,7 @@ module ActiveRecord
super
end
- def type_cast_for_database(value)
+ def deserialize(value)
super
end
end
@@ -84,7 +84,7 @@ module ActiveRecord
class Array
# In the 4.2.1 version of this code, under Mutable, the code
- # checks for raw_old_value != type_cast_for_database(new_value)
+ # checks for raw_old_value != deserialize(new_value)
#
# Since this is comparing db (string) version, we end up
# comparing "{1}"!="{1.0}" for float arrays. The following
@@ -95,7 +95,7 @@ module ActiveRecord
def changed_in_place?(raw_old_value, new_value)
- new_value != type_cast_from_database(raw_old_value)
+ new_value != deserialize(raw_old_value)
end
end
|
Use deserialize instead of type_cast_for_database
|
arman000_marty
|
train
|
e4958f975748b1f22d2ac36269ef36a73ce8f3d2
|
diff --git a/posix-utils.go b/posix-utils.go
index <HASH>..<HASH> 100644
--- a/posix-utils.go
+++ b/posix-utils.go
@@ -17,19 +17,15 @@
package main
import (
- "regexp"
"runtime"
"strings"
"unicode/utf8"
)
-// validVolname regexp.
-var validVolname = regexp.MustCompile(`^.{3,63}$`)
-
// isValidVolname verifies a volname name in accordance with object
// layer requirements.
func isValidVolname(volname string) bool {
- if !validVolname.MatchString(volname) {
+ if len(volname) < 3 || len(volname) > 63 {
return false
}
switch runtime.GOOS {
|
Removing regexp check and adding string based check, regexp check was unnecessary here (#<I>)
|
minio_minio
|
train
|
9368820245467df40b5f01b42dedd8057c577ce9
|
diff --git a/spec/lib/wechat/responder_corp_spec.rb b/spec/lib/wechat/responder_corp_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/wechat/responder_corp_spec.rb
+++ b/spec/lib/wechat/responder_corp_spec.rb
@@ -40,8 +40,8 @@ RSpec.describe WechatCorpController, type: :controller do
{ timestamp: timestamp, nonce: nonce, echostr: encrypt_echostr, msg_signature: msg_signature }
end
- def xml_to_hash(response)
- Hash.from_xml(response.body)['xml'].symbolize_keys
+ def xml_to_hash(xml_message)
+ Hash.from_xml(xml_message)['xml'].symbolize_keys
end
describe 'Verify signature' do
@@ -71,6 +71,12 @@ RSpec.describe WechatCorpController, type: :controller do
request.reply.text "echo: #{content}"
end
+ on :text, with: 'mpnews' do |request|
+ request.reply.news(0...1) do |article|
+ article.item title: 'title', description: 'desc', pic_url: 'http://www.baidu.com/img/bdlogo.gif', url: 'http://www.baidu.com/'
+ end
+ end
+
on :event, with: 'subscribe' do |request|
request.reply.text 'welcome!'
end
@@ -125,6 +131,28 @@ RSpec.describe WechatCorpController, type: :controller do
expect(message['Content']).to eq 'echo: hello'
end
+ it 'on mpnews' do
+ post :create, signature_params(MsgType: 'text', Content: 'mpnews')
+ expect(response.code).to eq '200'
+ expect(response.body.empty?).to eq false
+
+ data = Hash.from_xml(response.body)['xml']
+
+ xml_message, app_id = unpack(decrypt(Base64.decode64(data['Encrypt']), ENCODING_AES_KEY))
+
+ expect(app_id).to eq 'appid'
+ expect(xml_message.empty?).to eq false
+
+ message = Hash.from_xml(xml_message)['xml']
+ articles = { 'item' => { 'Title' => 'title',
+ 'Description' => 'desc',
+ 'PicUrl' => 'http://www.baidu.com/img/bdlogo.gif',
+ 'Url' => 'http://www.baidu.com/' } }
+ expect(message['MsgType']).to eq 'news'
+ expect(message['ArticleCount']).to eq '1'
+ expect(message['Articles']).to eq articles
+ end
+
it 'on subscribe' do
post :create, signature_params(MsgType: 'event', Event: 'subscribe')
expect(response.code).to eq '200'
|
Add test case for issue #<I>
|
Eric-Guo_wechat
|
train
|
81b47225a828fd20cd7c83471a8e79305751c3b5
|
diff --git a/src/js/bootstrap-datetimepicker.js b/src/js/bootstrap-datetimepicker.js
index <HASH>..<HASH> 100644
--- a/src/js/bootstrap-datetimepicker.js
+++ b/src/js/bootstrap-datetimepicker.js
@@ -1048,7 +1048,14 @@ THE SOFTWARE.
}
};
}
- picker.widget.show();
+ if (picker.widget.hasClass("picker-open")) {
+ picker.widget.hide();
+ picker.widget.removeClass("picker-open");
+ }
+ else {
+ picker.widget.show();
+ picker.widget.addClass("picker-open");
+ }
picker.height = picker.component ? picker.component.outerHeight() : picker.element.outerHeight();
place();
picker.element.trigger({
|
Changed picker.show to hide when already open
With this change it is possible to close the datetimepicker on the button it is opened when it's already open.
Short called this is normal toggle behaviour
|
Eonasdan_bootstrap-datetimepicker
|
train
|
6dfaacd8e0d664a032efc75a1c6b89e7b6328af5
|
diff --git a/activejdbc/src/main/java/org/javalite/activejdbc/StatementCache.java b/activejdbc/src/main/java/org/javalite/activejdbc/StatementCache.java
index <HASH>..<HASH> 100644
--- a/activejdbc/src/main/java/org/javalite/activejdbc/StatementCache.java
+++ b/activejdbc/src/main/java/org/javalite/activejdbc/StatementCache.java
@@ -46,6 +46,11 @@ class StatementCache {
}
void cleanStatementCache(Connection connection) {
- statementCache.remove(connection);
+ Map<String, PreparedStatement> stmsMap = statementCache.remove(connection);
+ if(stmsMap != null) { //Close prepared statements to release cursors on connection pools
+ for(PreparedStatement stmt : stmsMap.values()) {
+ try{stmt.close();}catch(Exception e){}
+ }
+ }
}
}
|
Closing statement cache prepared statements on cleanStatementCache.
This will close database cursors when using a connection pool. See problem description at <URL>
|
javalite_activejdbc
|
train
|
bf3f0b15046bcf00ac9f2fcdbe137302e12d5a46
|
diff --git a/net/backend.go b/net/backend.go
index <HASH>..<HASH> 100644
--- a/net/backend.go
+++ b/net/backend.go
@@ -31,6 +31,7 @@ type Config struct {
RetryAfterMin time.Duration
RetryAfterMax time.Duration
FlushTimeout time.Duration
+ WriteTimeout time.Duration
Dial func(string, string) (net.Conn, error)
Fail func(error)
}
@@ -79,6 +80,10 @@ func setConfigDefaults(config Config) Config {
config.FlushTimeout = 5 * time.Second
}
+ if config.WriteTimeout == 0 {
+ config.WriteTimeout = 1 * time.Second
+ }
+
return config
}
@@ -222,14 +227,16 @@ func write(conn net.Conn, cbuf *bufio.Writer, mbuf *bytes.Buffer, job job, confi
return conn
}
- if (mbuf.Len() + cbuf.Buffered()) > config.BufferSize {
- conn = flush(conn, cbuf, config)
- }
+ if err = conn.SetWriteDeadline(time.Now().Add(config.WriteTimeout)); err == nil {
+ if (mbuf.Len() + cbuf.Buffered()) > config.BufferSize {
+ conn = flush(conn, cbuf, config)
+ }
- if mbuf.Len() >= config.BufferSize {
- _, err = conn.Write(mbuf.Bytes())
- } else {
- _, err = cbuf.Write(mbuf.Bytes())
+ if mbuf.Len() >= config.BufferSize {
+ _, err = conn.Write(mbuf.Bytes())
+ } else {
+ _, err = cbuf.Write(mbuf.Bytes())
+ }
}
if err != nil {
@@ -242,11 +249,18 @@ func write(conn net.Conn, cbuf *bufio.Writer, mbuf *bytes.Buffer, job job, confi
func flush(conn net.Conn, cbuf *bufio.Writer, config *Config) net.Conn {
if conn != nil {
- if err := cbuf.Flush(); err != nil {
+ var err error
+
+ if err = conn.SetWriteDeadline(time.Now().Add(config.WriteTimeout)); err == nil {
+ err = cbuf.Flush()
+ }
+
+ if err != nil {
conn = reset(conn, cbuf)
handleError(err, config)
}
}
+
return conn
}
diff --git a/net/backend_test.go b/net/backend_test.go
index <HASH>..<HASH> 100644
--- a/net/backend_test.go
+++ b/net/backend_test.go
@@ -82,7 +82,7 @@ func TestFlushSuccess(t *testing.T) {
b := bufio.NewWriter(c)
b.WriteString("Hello World!")
- if flush(c, b, nil) != c {
+ if flush(c, b, &Config{}) != c {
t.Error("flush should return the connection on success")
}
|
support timeout on write operations in network backends
|
segmentio_stats
|
train
|
0f8f5f2b5d6939b0ba9f01a85a1eb67c13861ab7
|
diff --git a/lib/ardes/resources_controller/request_path_introspection.rb b/lib/ardes/resources_controller/request_path_introspection.rb
index <HASH>..<HASH> 100644
--- a/lib/ardes/resources_controller/request_path_introspection.rb
+++ b/lib/ardes/resources_controller/request_path_introspection.rb
@@ -19,9 +19,15 @@ module Ardes
@nesting_segments ||= segments_for_path_and_keys(nesting_request_path, param_keys)
end
+ # returns an array of segments correspopnding to the namespace of the controller.
+ # If your controller is at a non standard location wrt it's path, you can modify this array in a before filter
+ # to help resources_controller do the right thing
def namespace_segments
- namespace = controller_path.sub(%r(#{controller_name}$), '')
- request_path =~ %r(^/#{namespace}) ? namespace.split('/') : []
+ unless @namespace_segments
+ namespace = controller_path.sub(%r(#{controller_name}$), '')
+ @namespace_segments = (request_path =~ %r(^/#{namespace}) ? namespace.split('/') : [])
+ end
+ @namespace_segments
end
def param_keys
|
Make namespace_segments persist in a request, so it can be tweaked for non-standard controllers
|
ianwhite_resources_controller
|
train
|
5e7771e528545dafa15f4e3517025a027bd4c2f4
|
diff --git a/Server.php b/Server.php
index <HASH>..<HASH> 100644
--- a/Server.php
+++ b/Server.php
@@ -21,7 +21,7 @@ class Server extends EventEmitter implements ServerInterface
$server = $this;
- $this->io->on('connect', function ($conn) use ($server) {
+ $this->io->on('connection', function ($conn) use ($server) {
// TODO: http 1.1 keep-alive
// TODO: chunked transfer encoding (also for outgoing data)
// TODO: multipart parsing
|
[Socket] Rename connect event to connection
This is consistent with the nodejs naming.
|
reactphp_http
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.