hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
1f4b2562b9292f385a7322f1010f535c8022ef29
|
diff --git a/src/Javascript/RuleParser.php b/src/Javascript/RuleParser.php
index <HASH>..<HASH> 100644
--- a/src/Javascript/RuleParser.php
+++ b/src/Javascript/RuleParser.php
@@ -93,7 +93,7 @@ class RuleParser
{
foreach ((array) $attribute as $key) {
$current = isset($this->conditional[$key]) ? $this->conditional[$key] : [];
- $merge = head($this->validator->explodeRules([$rules]));
+ $merge = head($this->validator->explodeRules((array) $rules));
$this->conditional[$key] = array_merge($current, $merge);
}
}
|
Fix #<I>
(cherry picked from commit <I>e9b<I>)
|
proengsoft_laravel-jsvalidation
|
train
|
49b31000efd80bcea3cdfe5b35c868198b4e9fb6
|
diff --git a/functions/timber-post-getter.php b/functions/timber-post-getter.php
index <HASH>..<HASH> 100644
--- a/functions/timber-post-getter.php
+++ b/functions/timber-post-getter.php
@@ -1,7 +1,6 @@
<?php
-class TimberPostGetter
-{
+class TimberPostGetter {
/**
* @param mixed $query
@@ -11,14 +10,14 @@ class TimberPostGetter
public static function get_post($query = false, $PostClass = 'TimberPost') {
$posts = self::get_posts( $query, $PostClass );
if ( $post = reset( $posts ) ) {
- return $post;
+ return apply_filters('timber_post_getter_get_post', $post);
}
return false;
}
public static function get_posts( $query = false, $PostClass = 'TimberPost', $return_collection = false ) {
$posts = self::query_posts( $query, $PostClass );
- return apply_filters('timber_post_getter_posts',$posts->get_posts( $return_collection ));
+ return apply_filters('timber_post_getter_get_posts', $posts->get_posts( $return_collection ));
}
/**
|
tweaked filter name and gave one to get_post as well
|
timber_timber
|
train
|
1bac4f166ad01d81dd0d7c3fbc02ac78a7a856b5
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -56,7 +56,7 @@ module.exports = function(options) {
stream.end();
});
- return src(stream).pipe(handle(this, 'onStream'));
+ return src(stream.pipe(handle(this, 'onStream')));
});
if (app.isApp) {
|
passing entire stream created after piping to `handle` to `src-stream` to ensure any files piped into `.toStream` are passed through correctly.
|
assemble_assemble-streams
|
train
|
40afea5b8f3f582bc34ef4c2f90db2663590577e
|
diff --git a/src/pipeline.js b/src/pipeline.js
index <HASH>..<HASH> 100644
--- a/src/pipeline.js
+++ b/src/pipeline.js
@@ -87,6 +87,17 @@ class Pipeline extends Array {
this.push(handler);
}
+ // Remove a request or response handler.
+ removeHandler(handler) {
+ assert(handler.call, 'Handler must be a function');
+ for(var key in this){
+ if(this[key] === handler){
+ delete this[key];
+ break;
+ }
+ }
+ }
+
// Add a request or response handler. This handler will be used by any new
// pipeline instance (browser).
static addHandler(handler) {
@@ -94,6 +105,17 @@ class Pipeline extends Array {
assert(handler.length === 2 || handler.length === 3, 'Handler function takes 2 (request handler) or 3 (response handler) arguments');
this._default.push(handler);
}
+
+ // Remove a request or response handler.
+ static removeHandler(handler) {
+ assert(handler.call, 'Handler must be a function');
+ for(var key in this._default){
+ if(this[key] === handler){
+ delete this._default[key];
+ break;
+ }
+ }
+ }
// -- Prepare request --
diff --git a/test/resources_test.js b/test/resources_test.js
index <HASH>..<HASH> 100644
--- a/test/resources_test.js
+++ b/test/resources_test.js
@@ -195,6 +195,43 @@ describe('Resources', function() {
browser.pipeline.pop();
});
});
+
+ describe('removeHandler request', function() {
+ let pipelineHandler;
+ before(function(){
+ pipelineHandler = function(browser, request){
+ return new Fetch.Response('empty', { status: 204 });
+ }
+ browser.pipeline.addHandler(pipelineHandler);
+ return browser.visit('/resources/resource');
+ });
+ it('should remove the handler from the pipeline', function() {
+ let pipelineHasHandler = false
+ , pipelineHasHandlerAfter = false;
+ for (let i=0; i<browser.pipeline.length; i++) {
+ if (browser.pipeline[i] === pipelineHandler) {
+ pipelineHasHandler = true;
+ break;
+ }
+ }
+ browser.assert.status(204);
+ assert(pipelineHasHandler, 'Browser\'s pipeline should have a handler');
+ browser.pipeline.removeHandler(pipelineHandler);
+ for (let i=0; i<browser.pipeline.length; i++) {
+ if (browser.pipeline[i] === pipelineHandler) {
+ pipelineHasHandlerAfter = true;
+ break;
+ }
+ }
+ assert(!pipelineHasHandlerAfter, 'Pipeline should not have a handler after its removal');
+ });
+
+ it('should not use the handler after it has been removed', function(){
+ return browser.visit('/resources/resource').then(function(){
+ browser.assert.status(200);
+ })
+ })
+ });
describe('addHandler redirect', function () {
before(function() {
|
Implement removeHandler method in Pipeline
|
assaf_zombie
|
train
|
eea6d8327b793a897091d843413ae2cb77420133
|
diff --git a/core/src/main/java/hudson/model/BallColor.java b/core/src/main/java/hudson/model/BallColor.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/model/BallColor.java
+++ b/core/src/main/java/hudson/model/BallColor.java
@@ -67,6 +67,8 @@ public enum BallColor implements StatusIcon {
DISABLED_ANIME("grey_anime",Messages._BallColor_InProgress(), ColorPalette.GREY),
ABORTED("grey",Messages._BallColor_Aborted(), ColorPalette.GREY),
ABORTED_ANIME("grey_anime",Messages._BallColor_InProgress(), ColorPalette.GREY),
+ NOTBUILT("grey",Messages._BallColor_NotBuilt(), ColorPalette.GREY),
+ NOTBUILT_ANIME("grey_anime",Messages._BallColor_InProgress(), ColorPalette.GREY),
;
private final Localizable description;
diff --git a/core/src/main/java/hudson/model/Result.java b/core/src/main/java/hudson/model/Result.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/model/Result.java
+++ b/core/src/main/java/hudson/model/Result.java
@@ -62,7 +62,7 @@ public final class Result implements Serializable, CustomExportedBean {
* This status code is used in a multi-stage build (like maven2)
* where a problem in earlier stage prevented later stages from building.
*/
- public static final Result NOT_BUILT = new Result("NOT_BUILT",BallColor.GREY,3);
+ public static final Result NOT_BUILT = new Result("NOT_BUILT",BallColor.NOTBUILT,3);
/**
* The build was manually aborted.
*
diff --git a/core/src/main/resources/hudson/model/Messages.properties b/core/src/main/resources/hudson/model/Messages.properties
index <HASH>..<HASH> 100644
--- a/core/src/main/resources/hudson/model/Messages.properties
+++ b/core/src/main/resources/hudson/model/Messages.properties
@@ -70,6 +70,7 @@ BallColor.Aborted=Aborted
BallColor.Disabled=Disabled
BallColor.Failed=Failed
BallColor.InProgress=In progress
+BallColor.NotBuilt=Not built
BallColor.Pending=Pending
BallColor.Success=Success
BallColor.Unstable=Unstable
|
JENKINS-<I> NOT_BUILT & other build status are reported inconsistently
The tooltip for the grey ball is "Pending" when it should be "Not built".
|
jenkinsci_jenkins
|
train
|
320e7feb0ef63ed45e376330508ed59131e856dc
|
diff --git a/ghost/job-manager/lib/job-manager.js b/ghost/job-manager/lib/job-manager.js
index <HASH>..<HASH> 100644
--- a/ghost/job-manager/lib/job-manager.js
+++ b/ghost/job-manager/lib/job-manager.js
@@ -112,6 +112,21 @@ class JobManager {
}
/**
+ * Removes a job from sqcheduled (offloaded) jobs queue.
+ * There is no way to remove jovs from in-line (same event loop) jobs
+ * added through `addJob` method.
+ * The method will throw an Error if job with provided name does not exist.
+ *
+ * NOTE: current implementation does not guarante running job termination
+ * for details see https://github.com/breejs/bree/pull/64
+ *
+ * @param {String} name - job name
+ */
+ async removeJob(name) {
+ await this.bree.remove(name);
+ }
+
+ /**
* @param {import('p-wait-for').Options} [options]
*/
async shutdown(options) {
diff --git a/ghost/job-manager/test/job-manager.test.js b/ghost/job-manager/test/job-manager.test.js
index <HASH>..<HASH> 100644
--- a/ghost/job-manager/test/job-manager.test.js
+++ b/ghost/job-manager/test/job-manager.test.js
@@ -59,7 +59,7 @@ describe('Job Manager', function () {
});
});
- describe('Schedule Job', function () {
+ describe('Schedule a Job', function () {
it('fails to schedule for invalid scheduling expression', function () {
const jobManager = new JobManager(logging);
@@ -115,6 +115,22 @@ describe('Job Manager', function () {
});
});
+ describe('Remove a Job', function () {
+ it('removes a scheduled job from the queue', async function () {
+ const jobManager = new JobManager(logging);
+
+ const timeInTenSeconds = new Date(Date.now() + 10);
+ const jobPath = path.resolve(__dirname, './jobs/simple.js');
+
+ jobManager.scheduleJob(timeInTenSeconds, jobPath, null, 'job-in-ten');
+ jobManager.bree.config.jobs[0].name.should.equal('job-in-ten');
+
+ await jobManager.removeJob('job-in-ten');
+
+ should(jobManager.bree.config.jobs[0]).be.undefined;
+ });
+ });
+
describe('Shutdown', function () {
it('gracefully shuts down a synchronous jobs', async function () {
const jobManager = new JobManager(logging);
|
✨ Added ability to remove scheduled jobs
closes #<I>
- A future use-case which this feature caters for is allowing to migrate "post scheduler" to use job manager instead of managing scheduling itself
- removeJob method will be needed to allow "rescheduling" of the post
|
TryGhost_Ghost
|
train
|
ad2b8e7818fac6c854a105b05ff919cf59f56b04
|
diff --git a/dynaphopy/interface/iofile/__init__.py b/dynaphopy/interface/iofile/__init__.py
index <HASH>..<HASH> 100644
--- a/dynaphopy/interface/iofile/__init__.py
+++ b/dynaphopy/interface/iofile/__init__.py
@@ -608,12 +608,12 @@ def save_quasiparticle_data_to_file(quasiparticle_data, filename):
output_dict = {}
for i, q_point in enumerate(quasiparticle_data['q_points']):
- q_point_dict = {'q_point': q_point.tolist()}
+ q_point_dict = {'reduced_wave_vector': q_point.tolist()}
for j, frequency in enumerate(quasiparticle_data['frequencies'][i]):
quasiparticle_dict = {'frequency': frequency.tolist(),
'linewidth': quasiparticle_data['linewidths'][i][j].tolist()}
- q_point_dict.update({'quasiparticle_{}'.format(j): quasiparticle_dict})
- output_dict.update({'wave_vector_{}'.format(i): q_point_dict})
+ q_point_dict.update({'{}'.format(j): quasiparticle_dict})
+ output_dict.update({'q_point_{}'.format(i): q_point_dict})
with open(filename, 'w') as outfile:
yaml.dump(output_dict, outfile, default_flow_style=False)
\ No newline at end of file
|
Added save quasiparticle data using YAML formatted file
|
abelcarreras_DynaPhoPy
|
train
|
b5a302e2840df0c10d4d7ba63f1e8436b5085158
|
diff --git a/src/v1/data_transfer_service_client.js b/src/v1/data_transfer_service_client.js
index <HASH>..<HASH> 100644
--- a/src/v1/data_transfer_service_client.js
+++ b/src/v1/data_transfer_service_client.js
@@ -54,7 +54,7 @@ class DataTransferServiceClient {
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
- * @param {string} [options.servicePath] - The domain name of the
+ * @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts) {
|
docs: document apiEndpoint over servicePath (#<I>)
|
googleapis_nodejs-bigquery-data-transfer
|
train
|
0060e719ec84d0b1fcf15fcf4a1213f58592002c
|
diff --git a/packages/site/pages/components/badge.js b/packages/site/pages/components/badge.js
index <HASH>..<HASH> 100644
--- a/packages/site/pages/components/badge.js
+++ b/packages/site/pages/components/badge.js
@@ -1,5 +1,6 @@
import React from 'react'
import Badge from '@pluralsight/ps-design-system-badge'
+import * as core from '@pluralsight/ps-design-system-core'
import * as Text from '@pluralsight/ps-design-system-text'
import {
@@ -52,31 +53,19 @@ export default _ => (
]}
/>
- <SectionHeading>Appearance</SectionHeading>
+ <SectionHeading>Colors & appearance</SectionHeading>
<P>
- In either solid or stroked styles. The stroke appearance should not be
- used with the light theme
- </P>
- <Example.React
- includes={{ Badge }}
- themeToggle
- codes={Object.values(Badge.appearances).map(
- a => `<Badge appearance={Badge.appearances.${a}}>Badge</Badge>`
- )}
- />
-
- <SectionHeading>Colors</SectionHeading>
- <P>Colors come from the Design System. Semantics come from your heart.</P>
- <P>
- To get the light colors, <Text.Code>Badge.appearances.subtle</Text.Code>{' '}
- must be used.
+ Colors come from the Design System. Semantics come from your heart.
</P>
<Example.React
includes={{ Badge }}
themeToggle
+ outputStyle={{display:'grid',gap:core.layout.spacingMedium}}
+ outputChildStyle={{margin:0,display:'grid',gridTemplateColumns:'min-content min-content',gap:core.layout.spacingMedium}}
orient="vertical"
codes={Object.values(Badge.colors).map(
- color => `<Badge color={Badge.colors.${color}}>Badge</Badge>`
+ color => `<Badge color={Badge.colors.${color}}>Badge</Badge>
+<Badge color={Badge.colors.${color}} appearance={Badge.appearances.subtle}>Badge</Badge>`
)}
/>
</Content>
|
docs(site): badge color & appearance
|
pluralsight_design-system
|
train
|
08d670eeb0a2592b92f1ff9a767e4d2f73fa3851
|
diff --git a/lib/index_shotgun/analyzer.rb b/lib/index_shotgun/analyzer.rb
index <HASH>..<HASH> 100644
--- a/lib/index_shotgun/analyzer.rb
+++ b/lib/index_shotgun/analyzer.rb
@@ -9,19 +9,19 @@ module IndexShotgun
indexes = table_indexes(table)
indexes.permutation(2).each_with_object([]) do |(source_index, target_index), response|
- if source_index.columns.start_with?(target_index.columns)
- if target_index.unique
- last_column = source_index.columns.last
- response << {
- index: source_index,
- result: "#{source_index.name} has unnecessary column #{last_column} (#{target_index.name} is unique index!)",
- }
- else
- response << {
- index: target_index,
- result: "#{target_index.name} is a left-prefix of #{source_index.name}",
- }
- end
+ next unless source_index.columns.start_with?(target_index.columns)
+
+ if target_index.unique
+ last_column = source_index.columns.last
+ response << {
+ index: source_index,
+ result: "#{source_index.name} has unnecessary column #{last_column} (#{target_index.name} is unique index!)",
+ }
+ else
+ response << {
+ index: target_index,
+ result: "#{target_index.name} is a left-prefix of #{source_index.name}",
+ }
end
end
end
|
Resolve Style/Next: Use next to skip iteration
|
sue445_index_shotgun
|
train
|
fe89cb5551f23e22f01ffe62834799876d0cf342
|
diff --git a/client/js/Widgets/DiagramDesigner/DiagramDesignerWidget.js b/client/js/Widgets/DiagramDesigner/DiagramDesignerWidget.js
index <HASH>..<HASH> 100644
--- a/client/js/Widgets/DiagramDesigner/DiagramDesignerWidget.js
+++ b/client/js/Widgets/DiagramDesigner/DiagramDesignerWidget.js
@@ -331,12 +331,12 @@ define(['logManager',
"icon": "icon-th",
"data": { "mode": "grid" }}, this.skinParts.$btnGroupItemAutoOptions );
- /*this.toolBar.addButton({ "title": "Diagonal",
- "icon": "icon-signal",
- "data": { "mode": "diagonal" }}, this.skinParts.$btnGroupItemAutoOptions );*/
-
/************** ROUTING MANAGER SELECTION **************************/
if (DEBUG === true) {
+ this.toolBar.addButton({ "title": "Cozy Grid layout",
+ "icon": "icon-th-large",
+ "data": { "mode": "cozygrid" }}, this.skinParts.$btnGroupItemAutoOptions );
+
//progress text in toolbar for debug only
this.skinParts.$progressText = this.toolBar.addLabel();
@@ -883,8 +883,15 @@ define(['logManager',
y += h + dy;
}
break;
+ case "cozygrid":
case "grid":
default:
+ dx = 20;
+ dy = 20;
+ if (mode === "cozygrid") {
+ dx = 100;
+ dy = 100;
+ }
while (i--) {
w = this.items[this.itemIds[i]].width;
h = Math.max(h, this.items[this.itemIds[i]].height);
|
cozy grid layout in DEBUG mode just for testing purpose
Former-commit-id: <I>fda<I>d<I>ebb<I>f<I>b5b8fd2
|
webgme_webgme-engine
|
train
|
7368e3bc08a6d1f9cad3dd2bc204c73fa1225647
|
diff --git a/pysd/py_backend/functions.py b/pysd/py_backend/functions.py
index <HASH>..<HASH> 100644
--- a/pysd/py_backend/functions.py
+++ b/pysd/py_backend/functions.py
@@ -1181,6 +1181,9 @@ def random_uniform(m, x, s):
-------
A random number from the uniform distribution between m and x (exclusive of the endpoints).
"""
+ if(s!=0):
+ warnings.warn("Random uniform with a nonzero seed value, may not give the same result as vensim", RuntimeWarning)
+
return np.random.uniform(m, x)
|
Throw a warning when a nonzero seed value is used in random uniform function
|
JamesPHoughton_pysd
|
train
|
182ebdf3ca6976306de04bc01b65bf5b36327530
|
diff --git a/lib/net/ssh/authentication/pageant.rb b/lib/net/ssh/authentication/pageant.rb
index <HASH>..<HASH> 100644
--- a/lib/net/ssh/authentication/pageant.rb
+++ b/lib/net/ssh/authentication/pageant.rb
@@ -1,7 +1,7 @@
if RUBY_VERSION < "1.9"
require 'dl/import'
require 'dl/struct'
-elsif RUBY_VERSION < "2.2"
+elsif RUBY_VERSION < "2.1"
require 'dl/import'
require 'dl/types'
require 'dl'
@@ -46,7 +46,7 @@ module Net; module SSH; module Authentication
dlload 'advapi32'
SIZEOF_DWORD = DL.sizeof('L')
- elsif RUBY_VERSION < "2.2"
+ elsif RUBY_VERSION < "2.1"
extend DL::Importer
dlload 'user32','kernel32', 'advapi32'
include DL::Win32Types
@@ -88,7 +88,7 @@ module Net; module SSH; module Authentication
extern 'HANDLE CreateFileMapping(HANDLE, void *, DWORD, ' +
'DWORD, DWORD, LPCTSTR)'
- # args: hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh,
+ # args: hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh,
# dwfileOffsetLow, dwNumberOfBytesToMap
extern 'LPVOID MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, DWORD)'
@@ -101,7 +101,7 @@ module Net; module SSH; module Authentication
# args: hWnd, Msg, wParam, lParam, fuFlags, uTimeout, lpdwResult
extern 'LRESULT SendMessageTimeout(HWND, UINT, WPARAM, LPARAM, ' +
'UINT, UINT, PDWORD_PTR)'
-
+
# args: none
extern 'DWORD GetLastError()'
@@ -127,8 +127,8 @@ module Net; module SSH; module Authentication
extern 'BOOL IsValidSecurityDescriptor(LPVOID)'
# Constants needed for security attribute retrieval.
- # Specifies the access mask corresponding to the desired access
- # rights.
+ # Specifies the access mask corresponding to the desired access
+ # rights.
TOKEN_QUERY = 0x8
# The value of TOKEN_USER from the TOKEN_INFORMATION_CLASS enum.
@@ -295,7 +295,7 @@ module Net; module SSH; module Authentication
new
end
- # Create a new instance that communicates with the running pageant
+ # Create a new instance that communicates with the running pageant
# instance. If no such instance is running, this will cause an error.
def initialize
@win = Win.FindWindow("Pageant", "Pageant")
@@ -313,20 +313,20 @@ module Net; module SSH; module Authentication
# the first.
def send(data, *args)
@input_buffer.append(data)
-
+
ret = data.length
-
+
while true
return ret if @input_buffer.length < 4
msg_length = @input_buffer.read_long + 4
@input_buffer.reset!
-
+
return ret if @input_buffer.length < msg_length
msg = @input_buffer.read!(msg_length)
@output_buffer.append(send_query(msg))
end
end
-
+
# Reads +n+ bytes from the cached result of the last query. If +n+
# is +nil+, returns all remaining data from the last query.
def read(n = nil)
@@ -358,7 +358,7 @@ module Net; module SSH; module Authentication
"Creation of file mapping failed with error: #{Win.GetLastError}"
end
- ptr = Win.MapViewOfFile(filemap, Win::FILE_MAP_WRITE, 0, 0,
+ ptr = Win.MapViewOfFile(filemap, Win::FILE_MAP_WRITE, 0, 0,
0)
if ptr.nil? || ptr.null?
|
Need using Fiddler on Ruby <I> and must using, other will break due to #<I>
<URL>
|
net-ssh_net-ssh
|
train
|
acef68502c004f9daad37b250386a62de6daf25e
|
diff --git a/LiSE/gui/charsheet/charsheet.py b/LiSE/gui/charsheet/charsheet.py
index <HASH>..<HASH> 100644
--- a/LiSE/gui/charsheet/charsheet.py
+++ b/LiSE/gui/charsheet/charsheet.py
@@ -750,7 +750,7 @@ class CharSheet(StackLayout):
uberskel = self.character.closet.skeleton[
u'character_sheet_item_type'][unicode(self.character)]
bone = uberskel[i]
- del uberskel[i]
+ self.character.closet.set_bone(bone, mode='delete')
for tab in csitem_type_table_d[bone.type]:
unterskel = self.character.closet.skeleton[tab][
unicode(self.character)]
diff --git a/LiSE/orm.py b/LiSE/orm.py
index <HASH>..<HASH> 100644
--- a/LiSE/orm.py
+++ b/LiSE/orm.py
@@ -1692,13 +1692,17 @@ class Closet(object):
def upd_on_set(self, skel, child, k, v):
"""Supposing that the bone is equipped to write its own SQL, keep it
- in my ``altered_bones`` so as to do so later."""
+ in my ``altered_bones`` so as to see it."""
+ if not self.extraskels:
+ return
if hasattr(v, 'keynames'):
self.set_bone(v, 'alter')
def upd_on_del(self, skel, child, k, v):
"""Supposing that the bone is equipped to write its own SQL, keep it
- in my ``deleted_bones`` so as to do so later."""
+ in my ``deleted_bones`` so as to see it."""
+ if not self.extraskels:
+ return
if hasattr(v, 'keynames'):
self.set_bone(v, 'delete')
# if it's been altered in the same session, it must be removed
@@ -1789,8 +1793,9 @@ class Closet(object):
# if getattr(bone, f) is not None))
self.connector.commit()
Logger.debug("closet: saved game")
- self.deleted = self.empty.deepcopy()
- self.altered = self.empty.deepcopy()
+ if self.extraskels:
+ self.deleted = self.empty.deepcopy()
+ self.altered = self.empty.deepcopy()
self.c.execute("BEGIN;")
self.recording = True
@@ -2177,7 +2182,7 @@ class Closet(object):
for bone in self.skeleton[u"graphic_img"][graphicn].iterbones():
yield self.get_img(bone.img)
- def set_bone(self, bone, mode='main'):
+ def set_bone(self, bone, mode='alter'):
"""Take a bone of arbitrary type and put it in the right place in the
skeleton.
@@ -2186,16 +2191,8 @@ class Closet(object):
PlaceBone to describe it.
"""
- if mode == 'main' or not self.extraskels:
- skeleton = self.skeleton
- elif self.extraskels and mode in ('alter', 'delete'):
- if mode == 'alter':
- skeleton = self.altered
- elif mode == 'delete':
- skeleton = self.deleted
- else:
- raise ValueError("I only recognize modes"
- " 'main', 'alter', and 'delete'")
+ if mode not in ('alter', 'delete'):
+ raise ValueError("Valid modes are 'alter', 'delete'")
def init_keys(skeleton, keylst):
"""Make sure skeleton goes deep enough to put a value in, at the
@@ -2206,6 +2203,15 @@ class Closet(object):
skeleton = skeleton[key]
return skeleton
+ def dig_in(skeleton):
+ keynames = bone.keynames
+ keys = [bone._name] + [
+ getattr(bone, keyn)
+ for keyn in keynames[:-1]]
+ skelly = init_keys(skeleton, keys)
+ final_key = getattr(bone, keynames[-1])
+ return (skelly, final_key)
+
def set_place_maybe(host, place, branch, tick):
"""Set a PlaceBone, but only if I don't have one for that place
already"""
@@ -2215,9 +2221,9 @@ class Closet(object):
if isinstance(bone, PlaceBone):
init_keys(
- skeleton,
+ self.skeleton,
[u"place", bone.host, bone.place, bone.branch])
- skeleton[u"place"][bone.host][bone.place][
+ self.skeleton[u"place"][bone.host][bone.place][
bone.branch][bone.tick] = bone
return
@@ -2253,21 +2259,22 @@ class Closet(object):
if hasattr(bone, 'branch') and hasattr(bone, 'tick'):
self.timestream.upd_time(bone.branch, bone.tick)
- keynames = bone.keynames
- keys = [bone._name] + [
- getattr(bone, keyn)
- for keyn in keynames[:-1]]
- skelly = init_keys(skeleton, keys)
- final_key = getattr(bone, keynames[-1])
- if mode == 'delete' and skeleton is self.skeleton:
- del skelly[final_key]
+ (final_skel, final_key) = dig_in(self.skeleton)
+ if mode == 'delete':
+ del final_skel[final_key]
+ if self.extraskels:
+ (dskel, dkey) = dig_in(self.deleted)
+ dskel[dkey] = bone
else:
- skelly[final_key] = bone
+ final_skel[final_key] = bone
+ if self.extraskels:
+ (askel, akey) = dig_in(self.altered)
+ askel[akey] = bone
if self.recording:
self.c.execute(bone.sql_del, tuple(
getattr(bone, a) for a in bone.keynames))
- if mode in ('main', 'alter'):
+ if mode == 'alter':
self.c.execute(bone.sql_ins, tuple(
getattr(bone, b) for b in bone._fields
if getattr(bone, b) is not None))
@@ -2531,7 +2538,6 @@ def load_closet(dbfn, gettext=None, load_img=False, load_img_tags=[],
r.load_charsheet(load_charsheet)
if load_board:
r.load_board(*load_board)
- r.listen_to_skeleton()
r.c.execute("BEGIN;")
r.recording = True
return r
|
To properly cut out the event handlers previously responsible for
tracking changes, I had to change the way it works to delete things from
the skeleton. There's gotta be a better way.
|
LogicalDash_LiSE
|
train
|
094910df5a523e0517c6b71f403fcc0e6f679d63
|
diff --git a/lib/util/log.js b/lib/util/log.js
index <HASH>..<HASH> 100644
--- a/lib/util/log.js
+++ b/lib/util/log.js
@@ -100,6 +100,11 @@ module.exports = function logger() {
return this;
};
+ log.error = function (msg) {
+ this.write('✗ '.red + util.format.apply(util, arguments) + '\n');
+ return this;
+ };
+
log.on('up', function () {
padding = padding + step;
});
|
adding to complement
log.error appends a red x, the same as log.ok appends a green check.
|
yeoman_environment
|
train
|
7526584aca6e1230c4ff03728bb8f9aeb3ecfa42
|
diff --git a/internal/service/amplify/app_test.go b/internal/service/amplify/app_test.go
index <HASH>..<HASH> 100644
--- a/internal/service/amplify/app_test.go
+++ b/internal/service/amplify/app_test.go
@@ -3,21 +3,18 @@ package amplify_test
import (
"encoding/base64"
"fmt"
- "log"
"os"
"regexp"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/amplify"
- "github.com/hashicorp/go-multierror"
sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tfamplify "github.com/hashicorp/terraform-provider-aws/internal/service/amplify"
- "github.com/hashicorp/terraform-provider-aws/internal/sweep"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)
diff --git a/internal/service/amplify/tags_gen.go b/internal/service/amplify/tags_gen.go
index <HASH>..<HASH> 100644
--- a/internal/service/amplify/tags_gen.go
+++ b/internal/service/amplify/tags_gen.go
@@ -7,7 +7,6 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/amplify"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
- "github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)
// ListTags lists amplify service tags.
|
amplify: Fix more import problems
|
terraform-providers_terraform-provider-aws
|
train
|
0d639f6fb7cc9c8780a1368471507b1087f78a60
|
diff --git a/lib/rollbar/item.rb b/lib/rollbar/item.rb
index <HASH>..<HASH> 100644
--- a/lib/rollbar/item.rb
+++ b/lib/rollbar/item.rb
@@ -85,7 +85,7 @@ module Rollbar
:notifier => {
:name => 'rollbar-gem',
:version => VERSION,
- :configured_options => scrub(configuration.configured_options.configured)
+ :configured_options => configured_options
},
:body => build_body
}
@@ -103,6 +103,17 @@ module Rollbar
data
end
+ def configured_options
+ if Gem.loaded_specs['activesupport'] && Gem.loaded_specs['activesupport'].version < Gem::Version.new('4.1')
+ # There are too many types that crash ActiveSupport JSON serialization, and not worth
+ # the risk just to send this diagnostic object. In versions < 4.1, ActiveSupport hooks
+ # Ruby's JSON.generate so deeply there's no workaround.
+ 'not serialized in ActiveSupport < 4.1'
+ else
+ scrub(configuration.configured_options.configured)
+ end
+ end
+
def dump
# Ensure all keys are strings since we can receive the payload inline or
# from an async handler job, which can be serialized.
diff --git a/spec/rollbar/item_spec.rb b/spec/rollbar/item_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rollbar/item_spec.rb
+++ b/spec/rollbar/item_spec.rb
@@ -125,10 +125,18 @@ describe Rollbar::Item do
payload['data'][:body][:message][:extra][:b][2].should == 4
end
- it 'should have correct configured_options object' do
- payload['data'][:notifier][:configured_options][:access_token].should == '********'
- payload['data'][:notifier][:configured_options][:root].should == '/foo/'
- payload['data'][:notifier][:configured_options][:framework].should == 'Rails'
+ context 'ActiveSupport >= 4.1', :if => Gem.loaded_specs['activesupport'].version >= Gem::Version.new('4.1') do
+ it 'should have correct configured_options object' do
+ payload['data'][:notifier][:configured_options][:access_token].should == '********'
+ payload['data'][:notifier][:configured_options][:root].should == '/foo/'
+ payload['data'][:notifier][:configured_options][:framework].should == 'Rails'
+ end
+ end
+
+ context 'ActiveSupport < 4.1', :if => Gem.loaded_specs['activesupport'].version < Gem::Version.new('4.1') do
+ it 'should have configured_options message' do
+ payload['data'][:notifier][:configured_options].class == 'String'
+ end
end
context do
|
fix: bypass sending configured_options in ActiveSupport < <I>
|
rollbar_rollbar-gem
|
train
|
52daf73faa86692675e2083e6799a0e60e4bef47
|
diff --git a/pylisp/packet/lisp/control/map_referral.py b/pylisp/packet/lisp/control/map_referral.py
index <HASH>..<HASH> 100644
--- a/pylisp/packet/lisp/control/map_referral.py
+++ b/pylisp/packet/lisp/control/map_referral.py
@@ -122,7 +122,7 @@ class LISPMapReferralMessage(LISPControlMessage):
# Add the records
for record in self.records:
- bitstream += record.to_bytes()
+ bitstream += record.to_bitstream()
return bitstream.bytes
|
Fix bug in MapReferral packet building
|
steffann_pylisp
|
train
|
b748b27e1610b750dddabe95274413a1c0f0e020
|
diff --git a/climdir/__init__.py b/climdir/__init__.py
index <HASH>..<HASH> 100644
--- a/climdir/__init__.py
+++ b/climdir/__init__.py
@@ -17,7 +17,10 @@ ATTR_KEYS = [
'version_number',
'variable_name',
'temporal_subset',
- 'geographical_info'
+ 'geographical_info',
+ 't_start',
+ 't_end',
+ 'temporal_suffix'
]
CMOR_FNAME_REQUIRED_ATTS = ['variable_name','mip_table','model','experiment','ensemble_member']
@@ -194,7 +197,7 @@ def get_cmor_fname_meta(fname):
return res
-class Cmip5File:
+class Cmip5File(object):
"""Represents a Cmip5File.
.. _Metadata Requirements:
@@ -245,6 +248,8 @@ class Cmip5File:
return not self.__eq__(other)
def _update_known_atts(self, **kwargs):
+ """Updates instance attributes with supplied keyword arguments
+ """
for k, v in kwargs.items():
if k not in ATTR_KEYS:
# Warn if passed in unknown kwargs
@@ -258,6 +263,38 @@ class Cmip5File:
self._update_known_atts(**kwargs)
+ # Temporal subset elements
+ @property
+ def t_start(self):
+ return self.temporal_subset.split('-')[0]
+
+ @t_start.setter
+ def t_start(self, value):
+ l = self.temporal_subset.split('-')
+ l[0] = value
+ self.temporal_subset = '-'.join(l)
+
+ @property
+ def t_end(self):
+ return self.temporal_subset.split('-')[1]
+
+ @t_end.setter
+ def t_end(self, value):
+ l = self.temporal_subset.split('-')
+ l[1] = value
+ self.temporal_subset = '-'.join(l)
+
+ @property
+ def temporal_suffix(self):
+ return self.temporal_subset.split('-')[2]
+
+ @temporal_suffix.setter
+ def temporal_suffix(self, value):
+ l = self.temporal_subset.split('-')
+ l[2] = value
+ self.temporal_subset = '-'.join(l)
+
+ # Path generators
@property
def cmor_fname(self):
"""Generates a CMOR filename from object attributes.
diff --git a/tests/conftest.py b/tests/conftest.py
index <HASH>..<HASH> 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -14,6 +14,18 @@ def cmip5_cmor_fname():
return 'tas_Amon_HADCM3_decadal1990_r3i2p1.nc'
@pytest.fixture(scope='module')
+def cmip5_cmor_fname_temporal_suffix():
+ return 'tas_Amon_HADCM3_decadal1990_r3i2p1_19710201-19710214-avg.nc.nc'
+
+@pytest.fixture(scope='module')
+def cmip5_cmor_fname_geographical_info():
+ return 'tas_Amon_HADCM3_decadal1990_r3i2p1_g-lat20S20Nlon170W130W.nc'
+
+@pytest.fixture(scope='module')
+def cmip5_cmor_fname_temporal_geographical_suffix():
+ return 'tas_Amon_HADCM3_decadal1990_r3i2p1_199001-199012-clim_g-global-ocn-areaavg.nc'
+
+@pytest.fixture(scope='module')
def cmip5_meta_dict():
return {
'activity': 'CMIP5',
diff --git a/tests/test_cmip5file.py b/tests/test_cmip5file.py
index <HASH>..<HASH> 100644
--- a/tests/test_cmip5file.py
+++ b/tests/test_cmip5file.py
@@ -70,6 +70,27 @@ def test_datanode_fp_generate_error(cmip5_datanode_fp):
with pytest.raises(AttributeError):
assert cf.datanode_fp in cmip5_datanode_fp
+@pytest.mark.parametrize(('fname', 'new_atts', 'expected'), [
+ (
+ 'tas_Amon_HADCM3_decadal1990_r3i2p1_19710201-19710214-avg.nc',
+ {'t_end': '19810214'},
+ '19710201-19810214-avg'
+ ), (
+ 'tas_Amon_HADCM3_decadal1990_r3i2p1_19710201-19710214-avg.nc',
+ {'t_start': '19610201'},
+ '19610201-19710214-avg'
+ ), (
+ 'tas_Amon_HADCM3_decadal1990_r3i2p1_19710201-19710214-avg.nc',
+ {'temporal_suffix': 'clim'},
+ '19710201-19710214-clim'
+ )
+])
+def test_temporal_subset_suffix(fname, new_atts, expected):
+ cf = Cmip5File(cmor_fname = fname)
+ cf.update(**new_atts)
+ assert cf.temporal_subset == expected
+
+
def test_cmip5file_extra_attrs_error(cmip5_cmor_fp):
with pytest.raises(SyntaxWarning):
cf = Cmip5File(cmor_fp=cmip5_cmor_fp, bad_arg='whoops')
|
Add temporal/geographic subset properties with tests
|
pacificclimate_cfmeta
|
train
|
136a300e2480dbd107c7010700d87df4d70ce66f
|
diff --git a/source/2.0/includes/classes/api.class.php b/source/2.0/includes/classes/api.class.php
index <HASH>..<HASH> 100644
--- a/source/2.0/includes/classes/api.class.php
+++ b/source/2.0/includes/classes/api.class.php
@@ -167,9 +167,10 @@ class API extends Base {
if(!empty($achievement['EarnDates'][$g]['EarnedOn'])) {
$achievements['achievements'][$i]['unlocked'] = true;
- $achievements['achievements'][$i]['unlockdate'] = substr(str_replace(array("/Date(", ")/"), "", $achievement['EarnDates'][$g]['EarnedOn']), 0, 10);
+ $achievements['achievements'][$i]['unlockdate'] = (int)substr(str_replace(array("/Date(", ")/"), "", $achievement['EarnDates'][$g]['EarnedOn']), 0, 10);
} else {
$achievements['achievements'][$i]['unlocked'] = false;
+ $achievements['achievements'][$i]['unlockdate'] = null;
}
$i++;
diff --git a/source/includes/classes/base.class.php b/source/includes/classes/base.class.php
index <HASH>..<HASH> 100644
--- a/source/includes/classes/base.class.php
+++ b/source/includes/classes/base.class.php
@@ -12,26 +12,26 @@
*******************************************************************************/
class Base {
- public $__cache;
+ public $__cache; // cache model resource
- public $error;
- public $stack_trace = array();
- public $logged_in = false;
- public $redirects = 0;
+ public $error; // error code
+ public $stack_trace = array(); // stack trace array for logging
+ public $logged_in = false; // flag indicating whether the current session is logged in
+ public $redirects = 0; // number of current redirects, prevents infinite loops
- public $email, $password;
- public $debug = false;
- public $timeout = 8;
+ public $email, $password; // email/password of the scraper account
+ public $debug = false; // debug mode flag
+ public $timeout = 8; // number of seconds to timeout session
- public $cookie_file = "";
- public $debug_file = "";
- public $stack_trace_file = "";
- public $access_file = "";
+ public $cookie_file = ""; // cookie jar path
+ public $debug_file = ""; // debug file path
+ public $stack_trace_file = ""; // stack trace file path
+ public $access_file = ""; // access log file path
- public $runtime = null;
- public $ip = null;
- public $format = "xml";
- public $version = null;
+ public $runtime = null; // current runtime
+ public $ip = null; // ip address to use for session, generated in __construct()
+ public $format = "xml"; // default response format
+ public $version = null; // current api version
/**
* Error Codes
@@ -166,6 +166,12 @@ class Base {
}
}
+ /**
+ * Check culture code against Xbox's list of supported regions
+ *
+ * @var $code int
+ * @return bool
+ */
public function check_culture($code) {
$valid_codes = array(
'es-AR', 'en-AU', 'de-AT', 'nl-BE',
@@ -185,6 +191,11 @@ class Base {
return in_array($code, $valid_codes, true);
}
+ /**
+ * Perform login to Xbox LIVE
+ *
+ * @return bool
+ */
protected function perform_login() {
if(empty($this->email)) {
$this->error = 601;
@@ -265,6 +276,11 @@ class Base {
}
}
+ /**
+ * Check the current session to see if it's logged in
+ *
+ * @return bool
+ */
protected function check_login() {
if(file_exists($this->cookie_file)) {
if(time() - filemtime($this->cookie_file) >= 3600 || filesize($this->cookie_file) == 0) {
@@ -285,6 +301,11 @@ class Base {
}
}
+ /**
+ * Force a new login session
+ *
+ * @return bool
+ */
protected function force_new_login() {
$this->empty_cookie_file();
$this->logged_in = false;
@@ -297,6 +318,16 @@ class Base {
return false;
}
+ /**
+ * Perform the actual HTTP request
+ *
+ * @var $url string
+ * @var $referer string
+ * @var $timeout int
+ * @var $post_data array
+ * @var $headers array
+ * @return string
+ */
protected function fetch_url($url, $referer = "", $timeout = null, $post_data = null, $headers = null) {
if($this->redirects > 4) {
$this->error = 606;
@@ -379,6 +410,14 @@ class Base {
return $result;
}
+ /**
+ * Find a given string inside a string
+ *
+ * @var $haystack string
+ * @var $start string
+ * @var $finish string
+ * @return string
+ */
protected function find($haystack, $start, $finish) {
if(!empty($haystack)) {
$s = explode($start, $haystack);
@@ -395,7 +434,7 @@ class Base {
protected function clean($string) {
$string = html_entity_decode($string, ENT_QUOTES, "UTF-8");
- $string = htmlentities(htmlentities($string, ENT_QUOTES, "UTF-8"));
+ $string = htmlentities($string, ENT_QUOTES, "UTF-8");
if(function_exists("mb_convert_encoding")) {
$string = mb_convert_encoding($string, "UTF-8");
|
Fixes #<I>
More documentation changes, made timestamps consistent throughout (ints
vs strings), removed double HTML encoding.
|
XboxLeaders_XboxLiveAPI
|
train
|
0b7dadf99f446eb5a1082816beb9cbf2bef0a704
|
diff --git a/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java b/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java
+++ b/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java
@@ -50,7 +50,7 @@ import org.languagetool.tokenizers.en.EnglishWordTokenizer;
*/
public class English extends Language implements AutoCloseable {
- private static final Language AMERICAN_ENGLISH = new AmericanEnglish();
+ private static final Language BRITISH_ENGLISH = new BritishEnglish();
private Tagger tagger;
private Chunker chunker;
@@ -70,7 +70,7 @@ public class English extends Language implements AutoCloseable {
@Override
public Language getDefaultLanguageVariant() {
- return AMERICAN_ENGLISH;
+ return BRITISH_ENGLISH;
}
@Override
|
[en] set default language variant to en-GB
|
languagetool-org_languagetool
|
train
|
9a118e8594314231927d713bb7fa569f4a56b511
|
diff --git a/tool.go b/tool.go
index <HASH>..<HASH> 100644
--- a/tool.go
+++ b/tool.go
@@ -35,12 +35,12 @@ func init() {
var err error
currentDirectory, err = os.Getwd()
if err != nil {
- fmt.Println(err)
+ fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
currentDirectory, err = filepath.EvalSymlinks(currentDirectory)
if err != nil {
- fmt.Println(err)
+ fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
@@ -55,7 +55,7 @@ func main() {
flagWatch := pflag.Lookup("watch")
pflag.BoolVarP(&options.Minify, "minify", "m", false, "minify generated code")
flagMinify := pflag.Lookup("minify")
- pflag.BoolVar(&options.Color, "color", terminal.IsTerminal(2) && os.Getenv("TERM") != "dumb", "colored output")
+ pflag.BoolVar(&options.Color, "color", terminal.IsTerminal(syscall.Stderr) && os.Getenv("TERM") != "dumb", "colored output")
flagColor := pflag.Lookup("color")
tags := pflag.String("tags", "", "a list of build tags to consider satisfied during the build")
flagTags := pflag.Lookup("tags")
|
gopherjs: Minor improvements.
Print potential errors to stderr rather than stdout.
Use syscall.Stderr instead of hardcoding a magic number. It increases
readability.
|
gopherjs_gopherjs
|
train
|
08f48284e7b8c6918405959b4fb7227640b01afe
|
diff --git a/microcosm_flask/conventions/crud.py b/microcosm_flask/conventions/crud.py
index <HASH>..<HASH> 100644
--- a/microcosm_flask/conventions/crud.py
+++ b/microcosm_flask/conventions/crud.py
@@ -21,6 +21,10 @@ from microcosm_flask.paging import Page, PaginatedList, make_paginated_list_sche
class CRUDConvention(Convention):
+ @property
+ def page_cls(self):
+ return Page
+
def configure_search(self, ns, definition):
"""
Register a search endpoint.
@@ -43,7 +47,7 @@ class CRUDConvention(Convention):
@response(paginated_list_schema)
def search(**path_data):
request_data = load_query_string_data(definition.request_schema)
- page = Page.from_query_string(request_data)
+ page = self.page_cls.from_query_string(request_data)
return_value = definition.func(**merge_data(path_data, request_data))
if len(return_value) == 3:
diff --git a/microcosm_flask/paging.py b/microcosm_flask/paging.py
index <HASH>..<HASH> 100644
--- a/microcosm_flask/paging.py
+++ b/microcosm_flask/paging.py
@@ -35,9 +35,11 @@ def make_paginated_list_schema(ns, item_schema):
class Page(object):
- def __init__(self, offset, limit):
+
+ def __init__(self, offset, limit, **rest):
self.offset = offset
self.limit = limit
+ self.rest = rest
@classmethod
def from_query_string(cls, qs):
@@ -56,12 +58,14 @@ class Page(object):
return Page(
offset=self.offset + self.limit,
limit=self.limit,
+ **self.rest
)
def prev(self):
return Page(
offset=self.offset - self.limit,
limit=self.limit,
+ **self.rest
)
def to_dict(self):
@@ -75,6 +79,9 @@ class Page(object):
return [
("offset", self.offset),
("limit", self.limit),
+ ] + [
+ (key, self.rest[key])
+ for key in sorted(self.rest.keys())
]
diff --git a/microcosm_flask/tests/test_paging.py b/microcosm_flask/tests/test_paging.py
index <HASH>..<HASH> 100644
--- a/microcosm_flask/tests/test_paging.py
+++ b/microcosm_flask/tests/test_paging.py
@@ -116,3 +116,56 @@ def test_paginated_list_relation_to_dict():
},
}
})))
+
+
+def test_custom_paginated_list():
+ graph = create_object_graph(name="example", testing=True)
+ ns = Namespace(subject="foo", object_="bar")
+
+ class CustomPage(Page):
+ @classmethod
+ def from_query_string(cls, qs):
+ dct = qs.copy()
+ offset = dct.pop("offset")
+ limit = dct.pop("limit")
+ return cls(
+ offset=offset,
+ limit=limit,
+ **dct
+ )
+
+ @graph.route(ns.relation_path, Operation.SearchFor, ns)
+ def search_foo():
+ pass
+
+ paginated_list = PaginatedList(
+ ns,
+ CustomPage.from_query_string(dict(offset=2, limit=2, baz="baz")),
+ ["1", "2"],
+ 10,
+ operation=Operation.SearchFor,
+ foo_id="FOO_ID",
+ )
+
+ with graph.flask.test_request_context():
+ assert_that(paginated_list.to_dict(), is_(equal_to({
+ "count": 10,
+ "items": [
+ "1",
+ "2",
+ ],
+ "offset": 2,
+ "limit": 2,
+ "_links": {
+ "self": {
+ "href": "http://localhost/api/foo/FOO_ID/bar?offset=2&limit=2&baz=baz",
+ },
+ "next": {
+ "href": "http://localhost/api/foo/FOO_ID/bar?offset=4&limit=2&baz=baz",
+ },
+ "prev": {
+ "href": "http://localhost/api/foo/FOO_ID/bar?offset=0&limit=2&baz=baz",
+ },
+ },
+ "baz": "baz",
+ })))
|
Support customized query string arguments during pagination
|
globality-corp_microcosm-flask
|
train
|
b37bd049ba71dea9143bb5652242254140a2081e
|
diff --git a/ppb/systems/_sdl_utils.py b/ppb/systems/_sdl_utils.py
index <HASH>..<HASH> 100644
--- a/ppb/systems/_sdl_utils.py
+++ b/ppb/systems/_sdl_utils.py
@@ -1,13 +1,21 @@
+import atexit
+
from sdl2 import (
SDL_GetError, # https://wiki.libsdl.org/SDL_GetError
SDL_ClearError, # https://wiki.libsdl.org/SDL_ClearError
SDL_InitSubSystem, # https://wiki.libsdl.org/SDL_InitSubSystem
SDL_QuitSubSystem, # https://wiki.libsdl.org/SDL_QuitSubSystem
+ SDL_Quit, # https://wiki.libsdl.org/SDL_Quit
)
from ppb.systemslib import System
+atexit.register(SDL_Quit)
+# The PPB model makes it hard to register this in connection with the actual
+# engine cleanup, so we'll do it on interpreter exit.
+
+
class SdlError(Exception):
"""
SDL raised an error
|
_sdl_utils: Arrange for SDL_Quit to be called
|
ppb_pursuedpybear
|
train
|
1d811731576d596520723414986f768927d4b923
|
diff --git a/cron/controllers/Export.php b/cron/controllers/Export.php
index <HASH>..<HASH> 100644
--- a/cron/controllers/Export.php
+++ b/cron/controllers/Export.php
@@ -20,6 +20,9 @@ class Export extends Base
{
$this->writeLog('Generating exports');
+ $oNow = Factory::factory('DateTime');
+ setAppSetting('data-export-cron-last-run', 'nailsapp/module-admin', $oNow->format('Y-m-d H:i:s'));
+
$oService = Factory::service('DataExport', 'nailsapp/module-admin');
$oModel = Factory::model('Export', 'nailsapp/module-admin');
$aRequests = $oModel->getAll(['where' => [['status', $oModel::STATUS_PENDING]]]);
@@ -28,7 +31,7 @@ class Export extends Base
$this->writeLog(count($aRequests) . ' requests');
$this->writeLog('Marking as "RUNNING"');
- $oModel->setBatchStatus($aRequests, $oModel::STATUS_PENDING);
+ $oModel->setBatchStatus($aRequests, $oModel::STATUS_RUNNING);
// Group identical requests
$aGroupedRequests = [];
@@ -52,11 +55,13 @@ class Export extends Base
// Process each request
foreach ($aGroupedRequests as $oRequest) {
try {
+ $this->writeLog('Starting ' . $oRequest->source . '->' . $oRequest->format);
$oModel->setBatchDownloadId(
$oRequest->ids,
$oService->export($oRequest->source, $oRequest->format)
);
$oModel->setBatchStatus($oRequest->ids, $oModel::STATUS_COMPLETE);
+ $this->writeLog('Completed ' . $oRequest->source . '->' . $oRequest->format);
} catch (\Exception $e) {
$this->writeLog('Exception: ' . $e->getMessage());
$oModel->setBatchStatus($oRequest->ids, $oModel::STATUS_FAILED, $e->getMessage());
|
More logging + setting timestanmp of last cron run
|
nails_module-admin
|
train
|
be7f51ac647af34d75fb857ee683dc3374292373
|
diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Support/Collection.php
+++ b/src/Illuminate/Support/Collection.php
@@ -10,7 +10,6 @@ use ArrayIterator;
use CachingIterator;
use JsonSerializable;
use IteratorAggregate;
-use InvalidArgumentException;
use Illuminate\Support\Debug\Dumper;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Support\Jsonable;
|
Apply fixes from StyleCI (#<I>)
|
laravel_framework
|
train
|
277dff77055067b5ba4db25db425754daa52f49c
|
diff --git a/sgp4/functions.py b/sgp4/functions.py
index <HASH>..<HASH> 100644
--- a/sgp4/functions.py
+++ b/sgp4/functions.py
@@ -5,6 +5,8 @@ modules to offer simple date handling, so this small module holds the
routines instead.
"""
+import datetime as dt
+
def jday(year, mon, day, hr, minute, sec):
"""Return two floats that, when added, produce the specified Julian date.
@@ -37,3 +39,50 @@ def jday(year, mon, day, hr, minute, sec):
+ 1721013.5)
fr = (sec + minute * 60.0 + hr * 3600.0) / 86400.0;
return jd, fr
+
+class _UTC(dt.tzinfo):
+ 'UTC'
+ zero = dt.timedelta(0)
+ def utcoffset(self, datetime):
+ return self.zero
+ def tzname(self, datetime):
+ return 'UTC'
+ def dst(self, datetime):
+ return self.zero
+
+UTC = _UTC()
+
+def jday_datetime(datetime):
+ """Return two floats that, when added, produce the specified Julian date.
+
+ The first float returned gives the date, while the second float
+ provides an additional offset for the particular hour, minute, and
+ second of that date. Because the second float is much smaller in
+ magnitude it can, unlike the first float, be accurate down to very
+ small fractions of a second.
+
+ >>> jd, fr = jday(2020, 2, 11, 13, 57, 0)
+ >>> jd
+ 2458890.5
+ >>> fr
+ 0.58125
+
+ Note that the first float, which gives the moment of midnight that
+ commences the given calendar date, always carries the fraction
+ ``.5`` because Julian dates begin and end at noon. This made Julian
+ dates more convenient for astronomers in Europe, by making the whole
+ night belong to a single Julian date.
+
+ The input is a native `datetime` object. Timezone of the input is
+ converted internally to UTC.
+
+ """
+ u = datetime.astimezone(UTC)
+ year = u.year
+ mon = u.month
+ day = u.day
+ hr = u.hour
+ minute = u.minute
+ sec = u.second + u.microsecond * 1e-6
+
+ return jday(year, mon, day, hr, minute, sec)
diff --git a/sgp4/tests.py b/sgp4/tests.py
index <HASH>..<HASH> 100644
--- a/sgp4/tests.py
+++ b/sgp4/tests.py
@@ -1,4 +1,5 @@
"""Test suite for SGP4."""
+
try:
from unittest2 import TestCase, main
except:
@@ -14,6 +15,7 @@ from pkgutil import get_data
from sgp4.api import WGS72OLD, WGS72, WGS84, Satrec, jday, accelerated
from sgp4.earth_gravity import wgs72
from sgp4.ext import invjday, newtonnu, rv2coe
+from sgp4.functions import jday_datetime
from sgp4.propagation import sgp4, sgp4init
from sgp4 import io
from sgp4.exporter import export_tle
@@ -109,6 +111,27 @@ def test_jday2():
assertEqual(jd, 2458765.5)
assertAlmostEqual(fr, 0.7064236111111111)
+def test_jday_datetime():
+ # define local time
+ # UTC equivalent: 2011-11-03 20:05:23+00:00
+
+ class UTC_plus_4(dt.tzinfo):
+ 'UTC'
+ offset = dt.timedelta(hours=4)
+ def utcoffset(self, datetime):
+ return self.offset
+ def tzname(self, datetime):
+ return 'UTC plus 4'
+ def dst(self, datetime):
+ return self.offset
+
+ datetime_local = dt.datetime(2011, 11, 4, 0, 5, 23, 0, UTC_plus_4())
+ jd, fr = jday_datetime(datetime_local)
+
+ # jd of this date is 2455868.5 + 0.8370717592592593
+ assertEqual(jd, 2455868.5)
+ assertAlmostEqual(fr, 0.8370717592592593)
+
def test_good_tle_checksum():
for line in LINE1, LINE2:
checksum = int(line[-1])
|
Add jday_datetime() to parse native `datetime`
Resolves #<I> by merging.
|
brandon-rhodes_python-sgp4
|
train
|
1183f270cb5aefbe8ae2d4ff6624adf4a65eb96c
|
diff --git a/pkg/features/kube_features.go b/pkg/features/kube_features.go
index <HASH>..<HASH> 100644
--- a/pkg/features/kube_features.go
+++ b/pkg/features/kube_features.go
@@ -923,7 +923,7 @@ var defaultKubernetesFeatureGates = map[featuregate.Feature]featuregate.FeatureS
NodeSwap: {Default: false, PreRelease: featuregate.Alpha},
PodDeletionCost: {Default: true, PreRelease: featuregate.Beta},
StatefulSetAutoDeletePVC: {Default: false, PreRelease: featuregate.Alpha},
- TopologyAwareHints: {Default: false, PreRelease: featuregate.Beta},
+ TopologyAwareHints: {Default: true, PreRelease: featuregate.Beta},
PodAffinityNamespaceSelector: {Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // remove in 1.26
ServiceLoadBalancerClass: {Default: true, PreRelease: featuregate.Beta},
IngressClassNamespacedParams: {Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // remove in 1.25
|
Updating TopologyAwareHints feature gate to be on by default
Change-Id: Ib<I>b2dc5f8c2cc<I>cb9b<I>e6e<I>de1
|
kubernetes_kubernetes
|
train
|
7c5edf5d6b3dbae6c5e552027ca9cd423f27f0d9
|
diff --git a/yapsydir/trunk/test/test_All.py b/yapsydir/trunk/test/test_All.py
index <HASH>..<HASH> 100644
--- a/yapsydir/trunk/test/test_All.py
+++ b/yapsydir/trunk/test/test_All.py
@@ -18,6 +18,7 @@ import test_Singleton
import test_ConfigPlugin
import test_VersionedPlugin
import test_AutoInstallPlugin
+import test_FilterPlugin
# add them to a common test suite
@@ -28,5 +29,6 @@ MainTestSuite = unittest.TestSuite(
test_ConfigPlugin.suite,
test_VersionedPlugin.suite,
test_AutoInstallPlugin.suite,
+ test_FilterPlugin.suite,
])
|
- include the test for FilteredPlugin to the whole test battery
--HG--
extra : convert_revision : svn%3A3e6e<I>ca-<I>-<I>-a<I>-d<I>c<I>b3c<I>e%<I>
|
benhoff_pluginmanager
|
train
|
19a0b2edad9a0f39c4774534f484328f43ae28e1
|
diff --git a/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/impl/MongoDBEntityMappingValidator.java b/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/impl/MongoDBEntityMappingValidator.java
index <HASH>..<HASH> 100644
--- a/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/impl/MongoDBEntityMappingValidator.java
+++ b/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/impl/MongoDBEntityMappingValidator.java
@@ -33,12 +33,9 @@ public class MongoDBEntityMappingValidator extends BaseSchemaDefiner {
private void validateGenerators(Iterable<PersistentNoSqlIdentifierGenerator> generators) {
for ( PersistentNoSqlIdentifierGenerator identifierGenerator : generators ) {
String keyColumn = identifierGenerator.getGeneratorKeyMetadata().getKeyColumnName();
+
if ( !keyColumn.equals( MongoDBDialect.ID_FIELDNAME ) ) {
- log.warnf(
- "Cannot use primary key column name '%s' for id generator, going to use '%s' instead",
- keyColumn,
- MongoDBDialect.ID_FIELDNAME
- );
+ log.cannotUseGivenPrimaryKeyColumnName( keyColumn, MongoDBDialect.ID_FIELDNAME );
}
}
}
diff --git a/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/logging/impl/Log.java b/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/logging/impl/Log.java
index <HASH>..<HASH> 100644
--- a/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/logging/impl/Log.java
+++ b/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/logging/impl/Log.java
@@ -68,4 +68,7 @@ public interface Log extends org.hibernate.ogm.util.impl.Log {
@Message(id = 1217, value = "The following native does neither specify the collection name nor is its result type mapped to an entity: %s")
HibernateException unableToDetermineCollectionName(String nativeQuery);
+
+ @Message(id = 1218, value = "Cannot use primary key column name '%s' for id generator, going to use '%s' instead")
+ HibernateException cannotUseGivenPrimaryKeyColumnName(String givenKeyColumnName, String usedKeyColumnName);
}
|
OGM-<I> Using specific logger method rather than warnf()
|
hibernate_hibernate-ogm
|
train
|
7bed2052769b29cb453df78fb4ff15d0a33be765
|
diff --git a/src/com/mebigfatguy/fbcontrib/detect/ConfusingArrayAsList.java b/src/com/mebigfatguy/fbcontrib/detect/ConfusingArrayAsList.java
index <HASH>..<HASH> 100644
--- a/src/com/mebigfatguy/fbcontrib/detect/ConfusingArrayAsList.java
+++ b/src/com/mebigfatguy/fbcontrib/detect/ConfusingArrayAsList.java
@@ -18,6 +18,7 @@
*/
package com.mebigfatguy.fbcontrib.detect;
+import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -40,17 +41,19 @@ import edu.umd.cs.findbugs.ba.ClassContext;
*/
public class ConfusingArrayAsList extends BytecodeScanningDetector {
- private static Set<String> PRIMITIVE_ARRAYS = new HashSet<String>(8);
+ private static final Set<String> PRIMITIVE_ARRAYS;
static {
- PRIMITIVE_ARRAYS.add("[[B");
- PRIMITIVE_ARRAYS.add("[[C");
- PRIMITIVE_ARRAYS.add("[[S");
- PRIMITIVE_ARRAYS.add("[[I");
- PRIMITIVE_ARRAYS.add("[[J");
- PRIMITIVE_ARRAYS.add("[[F");
- PRIMITIVE_ARRAYS.add("[[D");
- PRIMITIVE_ARRAYS.add("[[Z");
+ Set<String> pa = new HashSet<String>();
+ pa.add("[[B");
+ pa.add("[[C");
+ pa.add("[[S");
+ pa.add("[[I");
+ pa.add("[[J");
+ pa.add("[[F");
+ pa.add("[[D");
+ pa.add("[[Z");
+ PRIMITIVE_ARRAYS = Collections.<String> unmodifiableSet(pa);
}
private BugReporter bugReporter;
|
make constant sets unmodifiable
|
mebigfatguy_fb-contrib
|
train
|
649a9bdd0d8211fab62e61f3fa4d37e048949a97
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -8,23 +8,6 @@ import codecs
here = os.path.abspath(os.path.dirname(__file__))
-def find_version(*file_paths):
- """
- Read the version number from a source file.
- Why read it, and not import?
- see https://groups.google.com/d/topic/pypa-dev/0PkjVpcxTzQ/discussion
- """
- with codecs.open(os.path.join(here, *file_paths), 'r', 'utf-8') as f:
- version_file = f.read()
-
- # The version line must have the form
- # __version__ = 'ver'
- version_match = re.search(r'^__version__ = [\'"]([^"\']*)["\']', version_file, re.M)
- if version_match:
- return version_match.group(1)
- raise RuntimeError("Unable to find version string.")
-
-
def read(filename):
"""
Get the long description from a file.
@@ -38,7 +21,7 @@ test_deps = ['nose2']
setup(
name='sllurp',
- version=find_version('sllurp', '__init__.py'),
+ version='0.1.7',
description=read('README.md'),
author='Ben Ransford',
author_email='ben@ransford.org',
diff --git a/sllurp/__init__.py b/sllurp/__init__.py
index <HASH>..<HASH> 100644
--- a/sllurp/__init__.py
+++ b/sllurp/__init__.py
@@ -1,3 +1,9 @@
+"""Low Level Reader Protocol implemtnation in pure Python
+"""
+
+from pkg_resources import get_distribution
+
+
__all__ = ('llrp', 'llrp_decoder', 'llrp_errors', 'llrp_proto', 'util',
'inventory')
-__version__ = '0.0.1'
+__version__ = get_distribution('sllurp').version
|
store version number only in setup.py
|
ransford_sllurp
|
train
|
8037d00c11bf54df5de7791dbff19da3329cde31
|
diff --git a/marko/ext/gfm/elements.py b/marko/ext/gfm/elements.py
index <HASH>..<HASH> 100644
--- a/marko/ext/gfm/elements.py
+++ b/marko/ext/gfm/elements.py
@@ -57,11 +57,11 @@ class _MatchObj(object):
class Url(inline.AutoLink):
www_pattern = re.compile(
- r'(?:^|(?<=[\s*_~(]))(www\.([\w.\-]*?\.[\w.\-]+)[^<\s]*)')
+ r'(?:^|(?<=[\s*_~(\uff00-\uffef]))(www\.([\w.\-]*?\.[\w.\-]+)[^<\s]*)')
email_pattern = r'[\w.\-+]+@[\w.\-]*?\.[\w.\-]*[a-zA-Z0-9]'
bare_pattern = re.compile(
- r'(?:^|(?<=[\s*_~(]))((?:https?|ftp)://([\w.\-]*?\.[\w.\-]+)[^<\s]*'
- r'|%s(?=[\s.<]|\Z))' % email_pattern
+ r'(?:^|(?<=[\s*_~(\uff00-\uffef]))((?:https?|ftp)://([\w.\-]*?\.[\w.\-]+)'
+ r'[^<\s]*|%s(?=[\s.<]|\Z))' % email_pattern
)
priority = 5
diff --git a/tests/test_ext.py b/tests/test_ext.py
index <HASH>..<HASH> 100644
--- a/tests/test_ext.py
+++ b/tests/test_ext.py
@@ -72,5 +72,19 @@ class TestPangu(unittest.TestCase):
self.assertEqual(result, '<p>你好:中国。</p>\n')
+class TestGFM(unittest.TestCase):
+
+ def setUp(self):
+ from marko.ext.gfm import GFMarkdown
+
+ self.markdown = GFMarkdown()
+
+ def test_gfm_autolink(self):
+ content = '地址:https://google.com'
+ self.assertEqual(self.markdown(content).strip(), '<p>地址:<a href="https://google.com">https://google.com</a></p>')
+ content = '地址:www.baidu.com'
+ self.assertEqual(self.markdown(content).strip(), '<p>地址:<a href="http://www.baidu.com">www.baidu.com</a></p>')
+
+
if __name__ == '__main__':
unittest.main()
|
Recognize chinese punctuations as delimiters
Fixes #1
|
frostming_marko
|
train
|
d1bc2a4b78ac7b48e14e0195eeb27d58e41cb076
|
diff --git a/PySimpleGUIQt/PySimpleGUIQt.py b/PySimpleGUIQt/PySimpleGUIQt.py
index <HASH>..<HASH> 100644
--- a/PySimpleGUIQt/PySimpleGUIQt.py
+++ b/PySimpleGUIQt/PySimpleGUIQt.py
@@ -1579,7 +1579,7 @@ class ProgressBar(Element):
# ---------------------------------------------------------------------- #
class Image(Element):
def __init__(self, filename=None, data=None, data_base64=None, background_color=None, size=(None, None), pad=None, key=None,
- tooltip=None):
+ tooltip=None, click_submits=False):
'''
Image Element
:param filename:
@@ -1595,12 +1595,20 @@ class Image(Element):
self.DataBase64 = data_base64
self.tktext_label = None
self.BackgroundColor = background_color
+ self.ClickSubmits = click_submits
if data is None and filename is None and data_base64 is None:
print('* Warning... no image specified in Image Element! *')
super().__init__(ELEM_TYPE_IMAGE, size=size, background_color=background_color, pad=pad, key=key,
tooltip=tooltip)
return
+
+ def QtCallbackImageClicked(self, event):
+ if not self.ClickSubmits:
+ return
+ element_callback_quit_mainloop(self)
+
+
def Update(self, filename=None, data=None, data_base64=None, size=(None, None)):
if filename is not None:
qlabel = self.QT_QLabel
@@ -4678,22 +4686,20 @@ def PackFormIntoFrame(window, containing_frame, toplevel_win):
qt_row_layout.addWidget(element.QT_TextBrowser)
# ------------------------- IMAGE element ------------------------- #
elif element_type == ELEM_TYPE_IMAGE:
+ qlabel = QLabel()
if element.Filename is not None:
- qlabel = QLabel()
qlabel.setText('')
w = QtGui.QPixmap(element.Filename).width()
h = QtGui.QPixmap(element.Filename).height()
qlabel.setGeometry(QtCore.QRect(0, 0, w, h))
qlabel.setPixmap(QtGui.QPixmap(element.Filename))
elif element.Data is not None:
- qlabel = QLabel()
qlabel.setText('')
ba = QtCore.QByteArray.fromRawData(element.Data)
pixmap = QtGui.QPixmap()
pixmap.loadFromData(ba)
qlabel.setPixmap(pixmap)
elif element.DataBase64:
- qlabel = QLabel()
qlabel.setText('')
ba = QtCore.QByteArray.fromBase64(element.DataBase64)
pixmap = QtGui.QPixmap()
@@ -4706,6 +4712,10 @@ def PackFormIntoFrame(window, containing_frame, toplevel_win):
element.QT_QLabel.setStyleSheet(style)
if element.Tooltip:
element.QT_QLabel.setToolTip(element.Tooltip)
+
+ if element.ClickSubmits:
+ element.QT_QLabel.mousePressEvent = element.QtCallbackImageClicked
+
qt_row_layout.addWidget(element.QT_QLabel)
# ------------------------- Canvas element ------------------------- #
elif element_type == ELEM_TYPE_CANVAS:
|
Added click_submits option for Image Elements
|
PySimpleGUI_PySimpleGUI
|
train
|
b8ee995ec181b8b57156ee3c66b6f61336d2d1f2
|
diff --git a/decode_test.go b/decode_test.go
index <HASH>..<HASH> 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -96,29 +96,30 @@ func TestUTF16(t *testing.T) {
// a = "b" in UTF-16, without BOM and with the LE and BE BOMs.
{
[]byte{0x61, 0x00, 0x20, 0x00, 0x3d, 0x00, 0x20, 0x00, 0x22, 0x00, 0x62, 0x00, 0x22, 0x00, 0x0a, 0x00},
- `bare keys cannot contain '\x00'; probably using UTF-16; TOML files must be UTF-8`,
+ `files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8`,
},
{
[]byte{0xfe, 0xff, 0x61, 0x00, 0x20, 0x00, 0x3d, 0x00, 0x20, 0x00, 0x22, 0x00, 0x62, 0x00, 0x22, 0x00, 0x0a, 0x00},
- `document starts with UTF-16 byte-order-mark (BOM) 0xfeff; TOML files must be UTF-8`,
- },
- {
- []byte{0xff, 0xfe, 0x61, 0x00, 0x20, 0x00, 0x3d, 0x00, 0x20, 0x00, 0x22, 0x00, 0x62, 0x00, 0x22, 0x00, 0x0a, 0x00},
- `document starts with UTF-16 byte-order-mark (BOM) 0xfffe; TOML files must be UTF-8`,
+ `files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8`,
},
+ // UTF-8 with BOM
+ {[]byte("\xff\xfea = \"b\""), ``},
+ {[]byte("\xfe\xffa = \"b\""), ``},
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
- var s struct {
- A string
- }
+ var s struct{ A string }
+
_, err := Decode(string(tt.in), &s)
- if err == nil {
- t.Fatal("err is nil")
+ if !errorContains(err, tt.wantErr) {
+ t.Fatalf("wrong error\nhave: %q\nwant: %q", err, tt.wantErr)
}
- if !strings.Contains(err.Error(), tt.wantErr) {
- t.Errorf("wrong error\nhave: %q\nwant: %q", err, tt.wantErr)
+ if tt.wantErr != "" {
+ return
+ }
+ if s.A != "b" {
+ t.Errorf(`s.A is not "b" but %q`, s.A)
}
})
}
@@ -1555,3 +1556,18 @@ cauchy = "cat 2"
Decode(testSimple, &val)
}
}
+
+// errorContains checks if the error message in have contains the text in
+// want.
+//
+// This is safe when have is nil. Use an empty string for want if you want to
+// test that err is nil.
+func errorContains(have error, want string) bool {
+ if have == nil {
+ return want == ""
+ }
+ if want == "" {
+ return false
+ }
+ return strings.Contains(have.Error(), want)
+}
diff --git a/lex.go b/lex.go
index <HASH>..<HASH> 100644
--- a/lex.go
+++ b/lex.go
@@ -389,10 +389,6 @@ func lexBareKey(lx *lexer) stateFn {
lx.emit(itemText)
return lexKeyEnd
default:
- // NULL bytes probably means it's a UTF-16 file without BOM.
- if r == 0 {
- return lx.errorf("bare keys cannot contain %q; probably using UTF-16; TOML files must be UTF-8", r)
- }
return lx.errorf("bare keys cannot contain %q", r)
}
}
diff --git a/parse.go b/parse.go
index <HASH>..<HASH> 100644
--- a/parse.go
+++ b/parse.go
@@ -1,6 +1,7 @@
package toml
import (
+ "errors"
"fmt"
"strconv"
"strings"
@@ -47,10 +48,20 @@ func parse(data string) (p *parser, err error) {
}
}()
+ // Read over BOM; do this here as the lexer calls utf8.DecodeRuneInString()
+ // which mangles stuff.
if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") {
- return nil, fmt.Errorf(
- "document starts with UTF-16 byte-order-mark (BOM) 0x%x; TOML files must be UTF-8",
- data[:2])
+ data = data[2:]
+ }
+ // Examine first few bytes for NULL bytes; this probably means it's a UTF-16
+ // file (second byte in surrogate pair being NULL). Again, do this here to
+ // avoid having to deal with UTF-8/16 stuff in the lexer.
+ ex := 6
+ if len(data) < 6 {
+ ex = len(data)
+ }
+ if strings.ContainsRune(data[:ex], 0) {
+ return nil, errors.New("files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8")
}
p = &parser{
|
Read over BOM
Appearantly some UTF-8 files can start with a BOM, so read over that
instead of assuming it's UTF-<I>. Also move the check for NULL out of the
lexer, so it can remain "UTF-8 clean"; just examine the first few bytes
instead.
Ref: <URL>
|
BurntSushi_toml
|
train
|
14760f7194dff89b2c8f3310a1f095fcf5c398eb
|
diff --git a/lib/sidekiq/limit_fetch/queues.rb b/lib/sidekiq/limit_fetch/queues.rb
index <HASH>..<HASH> 100644
--- a/lib/sidekiq/limit_fetch/queues.rb
+++ b/lib/sidekiq/limit_fetch/queues.rb
@@ -32,13 +32,16 @@ class Sidekiq::LimitFetch
end
def set(limit_type, limits)
- return unless limits
- limits.each do |name, limit|
- Sidekiq::Queue[name].send "#{limit_type}=", limit
+ limits ||= {}
+ each_queue do |queue|
+ limit = limits[queue.name.to_s] || limits[queue.name.to_sym]
+ queue.send "#{limit_type}=", limit
end
end
def set_blocks(blocks)
+ each_queue(&:unblock)
+
blocks.to_a.each do |it|
if it.is_a? Array
it.each {|name| Sidekiq::Queue[name].block_except it }
@@ -66,5 +69,9 @@ class Sidekiq::LimitFetch
ensure
Thread.current[THREAD_KEY] = nil
end
+
+ def each_queue
+ @queues.uniq.each {|it| yield Sidekiq::Queue[it] }
+ end
end
end
|
Start from fresh state (no limits, blocks) after startup
|
brainopia_sidekiq-limit_fetch
|
train
|
5b86e3db3067efb6398e14cc07c25c3990450aad
|
diff --git a/contao/languages/de/tl_metamodel_attribute.php b/contao/languages/de/tl_metamodel_attribute.php
index <HASH>..<HASH> 100644
--- a/contao/languages/de/tl_metamodel_attribute.php
+++ b/contao/languages/de/tl_metamodel_attribute.php
@@ -8,9 +8,9 @@
*
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*
- * last-updated: 2013-05-13T22:12:48+02:00
+ * last-updated: 2017-05-10T00:07:24+02:00
*/
+$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes']['0'] = 'Sprachschlüssel';
$GLOBALS['TL_LANG']['tl_metamodel_attribute']['typeOptions']['langcode'] = 'Sprachschlüssel';
-$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes'][0] = 'Sprachschlüssel';
-$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes'][1] = 'Den Sprachschlüssel auswählen.';
+
diff --git a/contao/languages/el/tl_metamodel_attribute.php b/contao/languages/el/tl_metamodel_attribute.php
index <HASH>..<HASH> 100644
--- a/contao/languages/el/tl_metamodel_attribute.php
+++ b/contao/languages/el/tl_metamodel_attribute.php
@@ -8,7 +8,9 @@
*
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*
- * last-updated: 2013-05-13T22:12:48+02:00
+ * last-updated: 2017-05-10T00:07:24+02:00
*/
+$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes']['0'] = 'Μεγαλο κειμενο';
$GLOBALS['TL_LANG']['tl_metamodel_attribute']['typeOptions']['langcode'] = 'Μεγαλο κειμενο';
+
diff --git a/contao/languages/fr/tl_metamodel_attribute.php b/contao/languages/fr/tl_metamodel_attribute.php
index <HASH>..<HASH> 100644
--- a/contao/languages/fr/tl_metamodel_attribute.php
+++ b/contao/languages/fr/tl_metamodel_attribute.php
@@ -8,7 +8,9 @@
*
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*
- * last-updated: 2013-05-04T02:35:14+02:00
+ * last-updated: 2017-05-10T00:07:24+02:00
*/
+$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes']['0'] = 'Code de langue';
$GLOBALS['TL_LANG']['tl_metamodel_attribute']['typeOptions']['langcode'] = 'Code de langue';
+
diff --git a/contao/languages/it/tl_metamodel_attribute.php b/contao/languages/it/tl_metamodel_attribute.php
index <HASH>..<HASH> 100644
--- a/contao/languages/it/tl_metamodel_attribute.php
+++ b/contao/languages/it/tl_metamodel_attribute.php
@@ -8,7 +8,9 @@
*
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*
- * last-updated: 2013-05-04T02:35:14+02:00
+ * last-updated: 2017-05-10T00:07:24+02:00
*/
+$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes']['0'] = 'Langcode';
$GLOBALS['TL_LANG']['tl_metamodel_attribute']['typeOptions']['langcode'] = 'Langcode';
+
diff --git a/contao/languages/rm/tl_metamodel_attribute.php b/contao/languages/rm/tl_metamodel_attribute.php
index <HASH>..<HASH> 100644
--- a/contao/languages/rm/tl_metamodel_attribute.php
+++ b/contao/languages/rm/tl_metamodel_attribute.php
@@ -8,7 +8,9 @@
*
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*
- * last-updated: 2013-05-13T22:12:48+02:00
+ * last-updated: 2017-05-10T00:07:24+02:00
*/
+$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes']['0'] = 'Code da lingua';
$GLOBALS['TL_LANG']['tl_metamodel_attribute']['typeOptions']['langcode'] = 'Code da lingua';
+
diff --git a/contao/languages/ru/tl_metamodel_attribute.php b/contao/languages/ru/tl_metamodel_attribute.php
index <HASH>..<HASH> 100644
--- a/contao/languages/ru/tl_metamodel_attribute.php
+++ b/contao/languages/ru/tl_metamodel_attribute.php
@@ -8,9 +8,9 @@
*
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*
- * last-updated: 2014-12-14T12:14:27+01:00
+ * last-updated: 2017-05-10T00:07:24+02:00
*/
-
+$GLOBALS['TL_LANG']['tl_metamodel_attribute']['langcodes']['0'] = 'Коды языка (Langcode)';
$GLOBALS['TL_LANG']['tl_metamodel_attribute']['typeOptions']['langcode'] = 'Коды языка (Langcode)';
|
Updated translations from transifex.
|
MetaModels_attribute_langcode
|
train
|
e3ec4da898216e1c8aed880122eb76bb00efe272
|
diff --git a/manifest.php b/manifest.php
index <HASH>..<HASH> 100644
--- a/manifest.php
+++ b/manifest.php
@@ -25,7 +25,7 @@ return array(
'label' => 'Proctoring',
'description' => 'Proctoring for deliveries',
'license' => 'GPL-2.0',
- 'version' => '3.4.1',
+ 'version' => '3.4.2',
'author' => 'Open Assessment Technologies SA',
'requires' => array(
'tao' => '>=4.5.0',
diff --git a/model/monitorCache/implementation/DeliveryMonitoringService.php b/model/monitorCache/implementation/DeliveryMonitoringService.php
index <HASH>..<HASH> 100644
--- a/model/monitorCache/implementation/DeliveryMonitoringService.php
+++ b/model/monitorCache/implementation/DeliveryMonitoringService.php
@@ -179,6 +179,7 @@ class DeliveryMonitoringService extends ConfigurableService implements DeliveryM
public function find(array $criteria = [], array $options = [], $together = false)
{
$result = [];
+ $this->joins = [];
$defaultOptions = [
'order' => static::COLUMN_ID." ASC",
'offset' => 0,
diff --git a/scripts/update/Updater.php b/scripts/update/Updater.php
index <HASH>..<HASH> 100644
--- a/scripts/update/Updater.php
+++ b/scripts/update/Updater.php
@@ -469,6 +469,8 @@ class Updater extends common_ext_ExtensionUpdater {
}
$this->setVersion('3.4.1');
}
+
+ $this->skip('3.4.1','3.4.2');
}
private function refreshMonitoringData()
|
Reset joins array (#<I>)
|
oat-sa_extension-tao-proctoring
|
train
|
10f32a4b8041e6df349ba725e6deb498e91ca967
|
diff --git a/gtki/gtk.go b/gtki/gtk.go
index <HASH>..<HASH> 100644
--- a/gtki/gtk.go
+++ b/gtki/gtk.go
@@ -3,7 +3,6 @@ package gtki
import (
"github.com/coyim/gotk3adapter/gdki"
"github.com/coyim/gotk3adapter/glibi"
- "github.com/coyim/gotk3adapter/gtki"
)
type Gtk interface {
@@ -62,7 +61,7 @@ type Gtk interface {
SettingsGetDefault() (Settings, error)
SeparatorNew(Orientation) (Separator, error)
EntryCompletionNew() (EntryCompletion, error)
- WindowNew(WindowType) (gtki.Window, error)
+ WindowNew(WindowType) (Window, error)
StatusIconNew() (StatusIcon, error)
StatusIconNewFromFile(filename string) (StatusIcon, error)
|
It's a good idea to not import your own package
|
coyim_gotk3adapter
|
train
|
99c3c3294ac697e36c7a9dd9f3c9d96d626fd6bd
|
diff --git a/src/Plugin.php b/src/Plugin.php
index <HASH>..<HASH> 100644
--- a/src/Plugin.php
+++ b/src/Plugin.php
@@ -166,7 +166,7 @@ class Plugin extends AbstractPlugin
if (array_key_exists($letter, $this->array_upside_down)) {
$flippedString = $this->utf8_chr($this->array_upside_down[$letter]) . $flippedString;
} else {
- $flippedString = $this->special_char($letter) . $flippedString;
+ $flippedString = $this->specialChar($letter) . $flippedString;
}
}
$flippedString = " " . $flippedString;
@@ -202,6 +202,9 @@ class Plugin extends AbstractPlugin
}
/**
+ * This is code taken directly from a Stack Overflow answer, so leaving the naming and everything consistent
+ * http://stackoverflow.com/questions/17539412/print-unicode-characters-php
+ *
* @param string $cp
*
* @return string
@@ -241,27 +244,27 @@ class Plugin extends AbstractPlugin
*
* @return string
*/
- private function special_char($char)
+ private function specialChar($char)
{
switch($char) {
case "!":
- return $this->hex_to_char('00A1');
+ return $this->hexToChar('00A1');
case "_":
- return $this->hex_to_char('203E');
+ return $this->hexToChar('203E');
case "&":
- return $this->hex_to_char('214B');
+ return $this->hexToChar('214B');
case "?":
- return $this->hex_to_char('00BF');
+ return $this->hexToChar('00BF');
case ".":
- return $this->hex_to_char('U2D9');
+ return $this->hexToChar('U2D9');
case "\"":
- return $this->hex_to_char('201E');
+ return $this->hexToChar('201E');
case "'":
- return $this->hex_to_char('002C');
+ return $this->hexToChar('002C');
case "(":
- return $this->hex_to_char('0029');
+ return $this->hexToChar('0029');
case ")":
- return $this->hex_to_char('0028');
+ return $this->hexToChar('0028');
default:
return $char;
}
@@ -273,7 +276,7 @@ class Plugin extends AbstractPlugin
*
* @return string
*/
- private function hex_to_char($char)
+ private function hexToChar($char)
{
return $this->utf8_chr(hexdec($char));
}
|
using camelCase method names for all but the borrowed code; gave attribution for the borrowed code
|
elstamey_phergie-irc-plugin-react-tableflip
|
train
|
3158c95340a060c549aeeb3f74ba60e6c61b6689
|
diff --git a/elasticsearch-transport/spec/elasticsearch/transport/client_spec.rb b/elasticsearch-transport/spec/elasticsearch/transport/client_spec.rb
index <HASH>..<HASH> 100644
--- a/elasticsearch-transport/spec/elasticsearch/transport/client_spec.rb
+++ b/elasticsearch-transport/spec/elasticsearch/transport/client_spec.rb
@@ -307,7 +307,7 @@ describe Elasticsearch::Transport::Client do
end
it 'creates the correct full url' do
- expect(client.transport.__full_url(client.transport.hosts[0])).to eq('https://elastic:changeme@abcd.localhost:9200')
+ expect(client.transport.__full_url(client.transport.hosts[0])).to eq('https://elastic:changeme@abcd.localhost:9250')
end
end
end
|
[CLIENT] Fix test to check correct port
|
elastic_elasticsearch-ruby
|
train
|
3e080d75ef0dbb96a1396ccdd33371ae42107a26
|
diff --git a/course/report/participation/index.php b/course/report/participation/index.php
index <HASH>..<HASH> 100644
--- a/course/report/participation/index.php
+++ b/course/report/participation/index.php
@@ -2,7 +2,7 @@
require_once('../../../config.php');
require_once($CFG->libdir.'/statslib.php');
-
+
define('DEFAULT_PAGE_SIZE', 20);
define('SHOW_ALL_PAGE_SIZE', 5000);
@@ -114,7 +114,7 @@
}
}
$guestrole = get_guest_role();
- if (empty($useroptions[$gusetrole->id])) {
+ if (empty($useroptions[$guestrole->id])) {
$useroptions[$guestrole->id] = $guestrole->name;
}
$actionoptions = array('' => $strallactions,
diff --git a/course/report/participation/mod.php b/course/report/participation/mod.php
index <HASH>..<HASH> 100644
--- a/course/report/participation/mod.php
+++ b/course/report/participation/mod.php
@@ -66,7 +66,7 @@
}
}
$guestrole = get_guest_role();
- if (empty($useroptions[$gusetrole->id])) {
+ if (empty($useroptions[$guestrole->id])) {
$useroptions[$guestrole->id] = $guestrole->name;
}
$actionoptions = array('' => $strallactions,
|
Fixed 2 typos identified by Dan (guset instead of guest). MDL-<I>
|
moodle_moodle
|
train
|
14ef91e42b5f88d66302e7a4b8f0b72abdc8aee7
|
diff --git a/src/Sag.php b/src/Sag.php
index <HASH>..<HASH> 100644
--- a/src/Sag.php
+++ b/src/Sag.php
@@ -96,23 +96,6 @@ class Sag
}
}
- public function setAuthType($type)
- {
- if($type != Sag::$AUTH_BASIC && $type != Sag::$AUTH_COOKIE)
- throw new SagException("Unknown auth type for login()");
-
- $this->authType = $type;
- return $this;
- }
-
- public function setAuthSession($session_id)
- {
- // switching to cookie auth since we've got a session id now
- $this->authType = Sag::$AUTH_COOKIE;
- $this->authSession = $session_id;
- return $this;
- }
-
/**
* Sets whether Sag will decode CouchDB's JSON responses with json_decode()
* or to simply return the JSON as a string. Defaults to true.
|
Don't need these functions. AuthType is set when logging in.
|
sbisbee_sag
|
train
|
b0fc8d9085d27a00d1e68e71a3b3ca3012d2ab6e
|
diff --git a/Command/PlatformUpdateCommand.php b/Command/PlatformUpdateCommand.php
index <HASH>..<HASH> 100644
--- a/Command/PlatformUpdateCommand.php
+++ b/Command/PlatformUpdateCommand.php
@@ -45,7 +45,8 @@ class PlatformUpdateCommand extends ContainerAwareCommand
}
);
$installer->installFromOperationFile();
- $refresher->refresh($this->getContainer()->getParameter('kernel.environment'), true);
+ $refresher->dumpAssets($this->getContainer()->getParameter('kernel.environment'));
+ $refresher->compileGeneratedThemes();
MaintenanceHandler::disableMaintenance();
}
}
|
Replaced complete refresh by dump + theme compilation
|
claroline_CoreBundle
|
train
|
9628ef33605ca2aa164fc6e857a4a436e9f9f678
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -54,4 +54,4 @@ See the `example.php` file on how you could use this library.
## Developer Installation
1. Clone the project
2. Run `composer install`
-3. Verify the install by running `phpunit` or opening the `example.php` page on a PHP server
+3. Verify the install by running `./vendor/bin/phpunit` or opening the `example.php` page on a PHP server
diff --git a/example.php b/example.php
index <HASH>..<HASH> 100644
--- a/example.php
+++ b/example.php
@@ -17,9 +17,13 @@ use HabboAPI\HabboParser;
$habboParser = new HabboParser('com');
$habboApi = new HabboAPI($habboParser);
-// Find the user 'koeientemmer' and get their ID
try {
+ // Find the user 'koeientemmer' and get their ID
$myHabbo = $habboApi->getHabbo('koeientemmer');
+
+ // Get extra information about one of their groups
+ // Note: This is actually a hardcoded group ID to showcase the parseGroup() endpoint
+ $group = $habboApi->getGroup("g-hhus-b0751bd6408cc83a8e046de6949fd747");
} catch (Exception $e) {
echo '
<p>Oops. Can not find this Habbo!</p>
@@ -44,10 +48,6 @@ if ($myHabbo->hasProfile()) {
// Get all their photos
$myPhotos = $habboApi->getPhotos($myHabbo->getId());
-// Get extra information about one of their groups
-// Note: This is actually a hardcoded group ID to showcase the parseGroup() endpoint
-$group = $habboApi->getGroup("g-hhus-b0751bd6408cc83a8e046de6949fd747");
-
// Export as HTML
$html = [
'habbo' => '',
diff --git a/src/HabboAPI.php b/src/HabboAPI.php
index <HASH>..<HASH> 100644
--- a/src/HabboAPI.php
+++ b/src/HabboAPI.php
@@ -68,6 +68,7 @@ class HabboAPI
*
* @param $group_id
* @return Group
+ * @throws \Exception
*/
public function getGroup($group_id)
{
diff --git a/src/HabboParser.php b/src/HabboParser.php
index <HASH>..<HASH> 100644
--- a/src/HabboParser.php
+++ b/src/HabboParser.php
@@ -19,13 +19,13 @@ use HabboAPI\Exceptions\UserInvalidException;
/**
* Class HabboParser
*
- * Parses all the unique API endpoints
+ * Parses all the unique API endpoints, uses the curl library
*
* @package HabboAPI
*/
class HabboParser implements HabboParserInterface
{
- const VERSION = "2.3.0";
+ const VERSION = "2.3.1";
/**
* Base URL for the Habbo API
@@ -194,6 +194,7 @@ class HabboParser implements HabboParserInterface
}
/** parseAchievements will return a list of achievements belonging to a Habbo
+ *
* @param $id
* @return Achievement[]
* @throws Exception
@@ -218,7 +219,8 @@ class HabboParser implements HabboParserInterface
/**
* Helper function to extract the correct cookie data from Habbo
- * Uses the public photos page as initial example
+ * Uses the public photos page as initial example i.e. this is quite a hack
+ *
* @throws Exception
*/
private function _getCookie()
@@ -265,11 +267,19 @@ class HabboParser implements HabboParserInterface
return array($response, $info);
}
+ /** deciphers data returned from Habbo and tries to throw the correct exception
+ *
+ * @param $data
+ * @throws Exception
+ * @throws HabboNotFoundException
+ * @throws MaintenanceException
+ * @throws UserInvalidException
+ */
public static function throwHabboAPIException($data)
{
// Do we find 'maintenance' anywhere?
if (strstr($data, 'maintenance')) {
- throw new MaintenanceException("Hotel is down for maintenance");
+ throw new MaintenanceException("Hotel API is down for maintenance");
}
// Check if data is JSON
|
adds missing @throw, clean up and release patch version
|
gerbenjacobs_HabboAPI
|
train
|
58e52674162acf0506a02952648146c91af526d5
|
diff --git a/indra/sources/cwms/processor.py b/indra/sources/cwms/processor.py
index <HASH>..<HASH> 100644
--- a/indra/sources/cwms/processor.py
+++ b/indra/sources/cwms/processor.py
@@ -85,7 +85,7 @@ class CWMSProcessor(object):
# In some EKBs we get two redundant relations over the same arguments,
# we eliminate these
- self._remove_multi_extraction_artifacts()
+ #self._remove_multi_extraction_artifacts()
# Print unhandled event types
logger.debug('Unhandled event types: %s' %
@@ -254,11 +254,10 @@ class CWMSProcessor(object):
return assoc_with_grounding
return None
- def _make_statement_noun_cause_effect(self, event_element,
- cause_concept, affected_concept,
+ def _make_statement_noun_cause_effect(self, event_element, cause, effect,
polarity, context):
"""Make the Influence statement from the component parts."""
- if cause_concept is None or affected_concept is None:
+ if cause is None or effect is None:
return
# Construct evidence
@@ -267,8 +266,8 @@ class CWMSProcessor(object):
# Make statement
obj_delta = {'polarity': polarity, 'adjectives': []}
- st = Influence(cause_concept, affected_concept, obj_delta=obj_delta,
- evidence=[ev])
+ effect.delta = obj_delta
+ st = Influence(cause, effect, evidence=[ev])
self.statements.append(st)
return st
diff --git a/indra/tests/test_cwms.py b/indra/tests/test_cwms.py
index <HASH>..<HASH> 100644
--- a/indra/tests/test_cwms.py
+++ b/indra/tests/test_cwms.py
@@ -39,12 +39,12 @@ def test_cwmsreader_cause():
s0 = statements[0]
assert isinstance(s0, Influence), type(s0)
- subj = s0.subj
+ subj = s0.subj.concept
assert subj.db_refs['TEXT'] == 'government', subj.db_refs['TEXT']
assert subj.db_refs['CWMS'] == 'ONT::FEDERAL-ORGANIZATION',\
subj.db_refs['CWMS']
- obj = s0.obj
+ obj = s0.obj.concept
assert obj.db_refs['TEXT'] == 'agriculture', obj.db_refs['TEXT']
assert obj.db_refs['CWMS'] == 'ONT::AGRICULTURE',\
obj.db_refs['CWMS']
@@ -67,10 +67,10 @@ def test_cwmsreader_inhibit():
s0 = statements[0]
print('Statement:', s0)
assert isinstance(s0, Influence)
- subj = s0.subj
+ subj = s0.subj.concept
assert subj.db_refs['TEXT'] == 'Persistent insecurity and armed conflict'
- obj = s0.obj
+ obj = s0.obj.concept
assert obj.db_refs['TEXT'] == 'livelihood activities'
ev = s0.evidence[0]
@@ -89,14 +89,16 @@ def test_cwmsreader_influence():
s0 = statements[0]
assert isinstance(s0, Influence), type(s0)
subj = s0.subj
- assert subj.db_refs['TEXT'] == 'government', subj.db_refs['TEXT']
- assert subj.db_refs['CWMS'] == 'ONT::FEDERAL-ORGANIZATION',\
- subj.db_refs['CWMS']
+ assert subj.concept.db_refs['TEXT'] == 'government', \
+ subj.concept.db_refs['TEXT']
+ assert subj.concept.db_refs['CWMS'] == 'ONT::FEDERAL-ORGANIZATION', \
+ subj.concept.db_refs['CWMS']
obj = s0.obj
- assert obj.db_refs['TEXT'] == 'agriculture', obj.db_refs['TEXT']
- assert obj.db_refs['CWMS'] == 'ONT::AGRICULTURE',\
- obj.db_refs['CWMS']
+ assert obj.concept.db_refs['TEXT'] == 'agriculture', \
+ obj.concept.db_refs['TEXT']
+ assert obj.concept.db_refs['CWMS'] == 'ONT::AGRICULTURE', \
+ obj.concept.db_refs['CWMS']
ev = s0.evidence[0]
assert ev.text == 'government influences agriculture.', ev.text
@@ -195,8 +197,7 @@ def test_contextual_sentence():
assert len(cp.statements) == 1, len(cp.statements)
stmt = cp.statements[0]
assert len(stmt.evidence) == 1, len(stmt.evidence)
- ev = stmt.evidence[0]
- cont = ev.context
+ cont = stmt.obj.context
assert cont is not None
assert cont.time and cont.geo_location
|
Adapt CWMS tests to Event structure
|
sorgerlab_indra
|
train
|
8677240ad352df7fe904d8e781cecf2448139b70
|
diff --git a/PHPDaemon/Core/AppInstance.php b/PHPDaemon/Core/AppInstance.php
index <HASH>..<HASH> 100644
--- a/PHPDaemon/Core/AppInstance.php
+++ b/PHPDaemon/Core/AppInstance.php
@@ -160,7 +160,7 @@ class AppInstance {
* @return AppInstance
*/
public static function getInstance($name, $spawn = true) {
- return Daemon::$appResolver->getInstanceByAppName(get_called_class(), $name, $spawn);
+ return Daemon::$appResolver->getInstanceByAppName('\\' . get_called_class(), $name, $spawn);
}
/**
|
AppInstance::getInstance(): missing backslash before class
|
kakserpom_phpdaemon
|
train
|
c8f02475fbf8e0d125ee59c3ec497c6e6031fea3
|
diff --git a/tests/_support/AcceptanceTester.php b/tests/_support/AcceptanceTester.php
index <HASH>..<HASH> 100644
--- a/tests/_support/AcceptanceTester.php
+++ b/tests/_support/AcceptanceTester.php
@@ -61,7 +61,7 @@ class AcceptanceTester extends \Codeception\Actor
break;
case "Credit Card Reserve WPPv2 Page":
$page = new CreditCardReserveWppV2Page($this);
- $this->wait(15);
+ $this->wait(25);
break;
// Credit Card non 3D WPPv2
case "Create Credit Card UI non 3D WPPv2 Page":
|
#<I> Increase wait time for ui tests
|
wirecard_paymentSDK-php
|
train
|
e0753f9fb61e514b821108fcde665a10e1cce51c
|
diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -11,7 +11,7 @@
"google/apiclient-services": "~0.13",
"firebase/php-jwt": "~2.0||~3.0||~4.0||~5.0",
"monolog/monolog": "^1.17|^2.0",
- "phpseclib/phpseclib": "~2.0",
+ "phpseclib/phpseclib": "~2.0||^3.0.2",
"guzzlehttp/guzzle": "~5.3.3||~6.0||~7.0",
"guzzlehttp/psr7": "^1.2"
},
diff --git a/src/AccessToken/Verify.php b/src/AccessToken/Verify.php
index <HASH>..<HASH> 100644
--- a/src/AccessToken/Verify.php
+++ b/src/AccessToken/Verify.php
@@ -22,6 +22,8 @@ use Firebase\JWT\ExpiredException as ExpiredExceptionV3;
use Firebase\JWT\SignatureInvalidException;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
+use phpseclib3\Crypt\PublicKeyLoader;
+use phpseclib3\Crypt\RSA\PublicKey;
use Psr\Cache\CacheItemPoolInterface;
use Google\Auth\Cache\MemoryCacheItemPool;
use Google\Exception as GoogleException;
@@ -97,18 +99,10 @@ class Verify
// Check signature
$certs = $this->getFederatedSignOnCerts();
foreach ($certs as $cert) {
- $bigIntClass = $this->getBigIntClass();
- $rsaClass = $this->getRsaClass();
- $modulus = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['n']), 256);
- $exponent = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['e']), 256);
-
- $rsa = new $rsaClass();
- $rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
-
try {
$payload = $this->jwt->decode(
$idToken,
- $rsa->getPublicKey(),
+ $this->getPublicKey($cert),
array('RS256')
);
@@ -229,8 +223,33 @@ class Verify
return new $jwtClass;
}
+ private function getPublicKey($cert)
+ {
+ $bigIntClass = $this->getBigIntClass();
+ $modulus = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['n']), 256);
+ $exponent = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['e']), 256);
+ $component = array('n' => $modulus, 'e' => $exponent);
+
+ if (class_exists('phpseclib3\Crypt\RSA\PublicKey')) {
+ /** @var PublicKey $loader */
+ $loader = PublicKeyLoader::load($component);
+
+ return $loader->toString('PKCS8');
+ }
+
+ $rsaClass = $this->getRsaClass();
+ $rsa = new $rsaClass();
+ $rsa->loadKey($component);
+
+ return $rsa->getPublicKey();
+ }
+
private function getRsaClass()
{
+ if (class_exists('phpseclib3\Crypt\RSA')) {
+ return 'phpseclib3\Crypt\RSA';
+ }
+
if (class_exists('phpseclib\Crypt\RSA')) {
return 'phpseclib\Crypt\RSA';
}
@@ -240,6 +259,10 @@ class Verify
private function getBigIntClass()
{
+ if (class_exists('phpseclib3\Math\BigInteger')) {
+ return 'phpseclib3\Math\BigInteger';
+ }
+
if (class_exists('phpseclib\Math\BigInteger')) {
return 'phpseclib\Math\BigInteger';
}
@@ -249,6 +272,10 @@ class Verify
private function getOpenSslConstant()
{
+ if (class_exists('phpseclib3\Crypt\AES')) {
+ return 'phpseclib3\Crypt\AES::ENGINE_OPENSSL';
+ }
+
if (class_exists('phpseclib\Crypt\RSA')) {
return 'phpseclib\Crypt\RSA::MODE_OPENSSL';
}
diff --git a/tests/Google/AccessToken/VerifyTest.php b/tests/Google/AccessToken/VerifyTest.php
index <HASH>..<HASH> 100644
--- a/tests/Google/AccessToken/VerifyTest.php
+++ b/tests/Google/AccessToken/VerifyTest.php
@@ -139,6 +139,10 @@ class Google_AccessToken_VerifyTest extends BaseTest
private function getOpenSslConstant()
{
+ if (class_exists('phpseclib3\Crypt\AES')) {
+ return 'phpseclib3\Crypt\AES::ENGINE_OPENSSL';
+ }
+
if (class_exists('phpseclib\Crypt\RSA')) {
return 'phpseclib\Crypt\RSA::MODE_OPENSSL';
}
|
feat: support phpseclib3 (#<I>)
|
googleapis_google-api-php-client
|
train
|
dbe872b72dc5bc8ac164c20d6d39989fa5906079
|
diff --git a/glue/ligolw/utils/__init__.py b/glue/ligolw/utils/__init__.py
index <HASH>..<HASH> 100644
--- a/glue/ligolw/utils/__init__.py
+++ b/glue/ligolw/utils/__init__.py
@@ -387,7 +387,6 @@ def write_fileobj(xmldoc, fileobj, gz = False):
fileobj = codecs.EncodedFile(fileobj, "unicode_internal", "utf_8")
xmldoc.write(fileobj)
fileobj.flush()
- fileobj.close()
del fileobj
# restore original handlers, and report the most recently trapped
@@ -431,6 +430,7 @@ def write_filename(xmldoc, filename, verbose = False, gz = False):
else:
fileobj = sys.stdout
hexdigest = write_fileobj(xmldoc, fileobj, gz = gz)
+ fileobj.close()
if verbose:
print >>sys.stderr, "md5sum: %s %s" % (hexdigest, filename or "")
|
Don't call .close() on the file object in write_fileobj() so as to allow
the file object to be written to afterward by the calling code (or
retrieved in the case of a StringIO object). Call .close() in
write_filename() instead, after the call to write_fileobj().
|
gwastro_pycbc-glue
|
train
|
158f5b62d27b57528e7943b7825a49bbb3653d4c
|
diff --git a/test/www/jxcore/bv_tests/testTests.js b/test/www/jxcore/bv_tests/testTests.js
index <HASH>..<HASH> 100644
--- a/test/www/jxcore/bv_tests/testTests.js
+++ b/test/www/jxcore/bv_tests/testTests.js
@@ -32,9 +32,14 @@ if (!tape.coordinated) {
}
test('can pass data in setup', function (t) {
+ var uuidFound = false;
t.participants.forEach(function (participant) {
+ if (tape.uuid === participant.uuid) {
+ uuidFound = true;
+ }
t.ok(participant.uuid, 'test participant has uuid');
t.equals(participant.data, customData, 'participant data matches');
});
+ t.equals(uuidFound, true, 'own UUID is found from the participants list');
t.end();
});
diff --git a/test/www/jxcore/lib/thali-tape.js b/test/www/jxcore/lib/thali-tape.js
index <HASH>..<HASH> 100644
--- a/test/www/jxcore/lib/thali-tape.js
+++ b/test/www/jxcore/lib/thali-tape.js
@@ -206,11 +206,11 @@ thaliTape.begin = function () {
platform = 'ios';
}
- var _uuid = uuid.v4();
+ thaliTape.uuid = uuid.v4();
testServer.emit('present', JSON.stringify({
'os': platform,
'name': testUtils.getName(),
- 'uuid': _uuid,
+ 'uuid': thaliTape.uuid,
'type': 'unittest',
'tests': Object.keys(tests)
}));
|
Make own uuid accessible
This allows more easily determining which custom data is sent by
this instance of the tests (self).
|
thaliproject_Thali_CordovaPlugin
|
train
|
ac265c1ac3ed37f22fdbb85c89bd73943c1e89e5
|
diff --git a/lib/barometer/data/distance.rb b/lib/barometer/data/distance.rb
index <HASH>..<HASH> 100644
--- a/lib/barometer/data/distance.rb
+++ b/lib/barometer/data/distance.rb
@@ -123,5 +123,9 @@ module Barometer
@miles = nil unless difference.abs <= 1.0
end
+ def nil?
+ (@kilometers || @miles) ? false : true
+ end
+
end
end
\ No newline at end of file
diff --git a/lib/barometer/data/pressure.rb b/lib/barometer/data/pressure.rb
index <HASH>..<HASH> 100644
--- a/lib/barometer/data/pressure.rb
+++ b/lib/barometer/data/pressure.rb
@@ -125,5 +125,9 @@ module Barometer
@inches = nil unless difference.abs <= 1.0
end
+ def nil?
+ (@millibars || @inches) ? false : true
+ end
+
end
end
\ No newline at end of file
diff --git a/lib/barometer/data/speed.rb b/lib/barometer/data/speed.rb
index <HASH>..<HASH> 100644
--- a/lib/barometer/data/speed.rb
+++ b/lib/barometer/data/speed.rb
@@ -139,5 +139,9 @@ module Barometer
@miles = nil unless difference.abs <= 1.0
end
+ def nil?
+ (@kilometers || @miles) ? false : true
+ end
+
end
end
\ No newline at end of file
diff --git a/lib/barometer/data/temperature.rb b/lib/barometer/data/temperature.rb
index <HASH>..<HASH> 100644
--- a/lib/barometer/data/temperature.rb
+++ b/lib/barometer/data/temperature.rb
@@ -156,5 +156,9 @@ module Barometer
@fahrenheit = nil unless difference.abs <= 1.0
end
+ def nil?
+ (@celsius || @fahrenheit || @kelvin) ? false : true
+ end
+
end
end
\ No newline at end of file
diff --git a/spec/data_distance_spec.rb b/spec/data_distance_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/data_distance_spec.rb
+++ b/spec/data_distance_spec.rb
@@ -27,11 +27,17 @@ describe "Distance" do
end
it "responds to metric_default" do
- lambda { @temp.metric_default = 5 }.should_not raise_error(NotImplementedError)
+ lambda { @distance.metric_default = 5 }.should_not raise_error(NotImplementedError)
end
it "responds to imperial_default" do
- lambda { @temp.imperial_default = 5 }.should_not raise_error(NotImplementedError)
+ lambda { @distance.imperial_default = 5 }.should_not raise_error(NotImplementedError)
+ end
+
+ it "responds to nil?" do
+ @distance.nil?.should be_true
+ @distance.km = 5
+ @distance.nil?.should be_false
end
end
diff --git a/spec/data_pressure_spec.rb b/spec/data_pressure_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/data_pressure_spec.rb
+++ b/spec/data_pressure_spec.rb
@@ -27,11 +27,17 @@ describe "Pressure" do
end
it "responds to metric_default" do
- lambda { @temp.metric_default = 5 }.should_not raise_error(NotImplementedError)
+ lambda { @pressure.metric_default = 5 }.should_not raise_error(NotImplementedError)
end
it "responds to imperial_default" do
- lambda { @temp.imperial_default = 5 }.should_not raise_error(NotImplementedError)
+ lambda { @pressure.imperial_default = 5 }.should_not raise_error(NotImplementedError)
+ end
+
+ it "responds to nil?" do
+ @pressure.nil?.should be_true
+ @pressure.mb = 5
+ @pressure.nil?.should be_false
end
end
diff --git a/spec/data_speed_spec.rb b/spec/data_speed_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/data_speed_spec.rb
+++ b/spec/data_speed_spec.rb
@@ -35,11 +35,17 @@ describe "Speed" do
end
it "responds to metric_default" do
- lambda { @temp.metric_default = 5 }.should_not raise_error(NotImplementedError)
+ lambda { @speed.metric_default = 5 }.should_not raise_error(NotImplementedError)
end
it "responds to imperial_default" do
- lambda { @temp.imperial_default = 5 }.should_not raise_error(NotImplementedError)
+ lambda { @speed.imperial_default = 5 }.should_not raise_error(NotImplementedError)
+ end
+
+ it "responds to nil?" do
+ @speed.nil?.should be_true
+ @speed.kph = 5
+ @speed.nil?.should be_false
end
end
diff --git a/spec/data_temperature_spec.rb b/spec/data_temperature_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/data_temperature_spec.rb
+++ b/spec/data_temperature_spec.rb
@@ -38,6 +38,12 @@ describe "Temperature" do
lambda { @temp.imperial_default = 5 }.should_not raise_error(NotImplementedError)
end
+ it "responds to nil?" do
+ @temp.nil?.should be_true
+ @temp.c = 5
+ @temp.nil?.should be_false
+ end
+
end
describe "conversion" do
|
added nil? method to custom data classes
|
attack_barometer
|
train
|
ac77a482a9f622767b58e156d97a47d88ed892da
|
diff --git a/recipe/deploy/release.php b/recipe/deploy/release.php
index <HASH>..<HASH> 100644
--- a/recipe/deploy/release.php
+++ b/recipe/deploy/release.php
@@ -54,7 +54,12 @@ set('releases_list', function () {
if ($keepReleases === -1) {
$csv = run('cat .dep/releases');
} else {
- $csv = run("tail -n " . ($keepReleases + 5) . " .dep/releases");
+ // Instead of `tail -n` call here can be `cat` call,
+ // but on servers with a lot of deploys (more 1k) it
+ // will output a really big list of previous releases.
+ // It spoils appearance of output log, to make it pretty,
+ // we limit it to `n*2 + 5` lines from end of file (15 lines).
+ $csv = run("tail -n " . ($keepReleases * 2 + 5) . " .dep/releases");
}
$metainfo = Csv::parse($csv);
|
Increase tailed lines in releases_list
|
deployphp_deployer
|
train
|
476a5225480c0175097d38c8406bcf3bcb272308
|
diff --git a/modopt/opt/proximity.py b/modopt/opt/proximity.py
index <HASH>..<HASH> 100644
--- a/modopt/opt/proximity.py
+++ b/modopt/opt/proximity.py
@@ -463,10 +463,10 @@ class OrderedWeightedL1Norm(ProximityParent):
def __init__(self, weights):
- if any([weights_i < 0 for weights_i in np.squeeze(weights)]):
+ self.weights = np.sort(np.squeeze(weights))[::-1]
+ if (self.weights < 0).any():
raise ValueError("All the entries of the weights should be"
" positive")
- self.weights = np.sort(np.squeeze(weights))[::-1]
self.op = self._op_method
self.cost = self._cost_method
|
Squeezing the weights before starting
|
CEA-COSMIC_ModOpt
|
train
|
4f3d2b6b01436a0e8c2a06453b980f1d0762d5d7
|
diff --git a/lib/adapters/sqlite.js b/lib/adapters/sqlite.js
index <HASH>..<HASH> 100644
--- a/lib/adapters/sqlite.js
+++ b/lib/adapters/sqlite.js
@@ -113,13 +113,9 @@ function initialize(config, callback) {
callback(null, {
saveTask: saveTask,
listenTask: listenTask
- // readTask: readTask
});
}
- function readMatching(fieldtype, value) {
- }
-
function updateTask(id) {
}
|
removed deprecated methods from sqlite adapter
|
meetings_gearsloth
|
train
|
559eb4ae99c4b502b72e79a6d438f96b500d3919
|
diff --git a/avatar/models.py b/avatar/models.py
index <HASH>..<HASH> 100644
--- a/avatar/models.py
+++ b/avatar/models.py
@@ -64,6 +64,8 @@ class Avatar(models.Model):
image = image.crop((0, diff, w, h - diff))
image = image.resize((size, size), AVATAR_RESIZE_METHOD)
thumb = default_storage.open(self.avatar_path(size), 'wb')
+ if image.mode != "RGB":
+ image = image.convert("RGB")
image.save(thumb, "JPEG")
def avatar_url(self, size):
|
Fixed problem with uploading .GIF files, as they need to be conditionally converted to RGB.
git-svn-id: <URL>
|
grantmcconnaughey_django-avatar
|
train
|
8747f437650f09ead9e0d08bd74efb73530ff018
|
diff --git a/bika/lims/browser/calcs.py b/bika/lims/browser/calcs.py
index <HASH>..<HASH> 100644
--- a/bika/lims/browser/calcs.py
+++ b/bika/lims/browser/calcs.py
@@ -8,11 +8,11 @@ class ajaxCalculateAnalysisEntry():
entered. Returns a JSON dictionary, or None if no action is required or possible.
"""
- def __init__(self,context,request):
+ def __init__(self, context, request):
self.context = context
self.request = request
- def calculate(self, uid=None):
+ def calculate(self, uid = None):
recursing = uid and True or False
uid = uid or self.uid
@@ -84,7 +84,7 @@ class ajaxCalculateAnalysisEntry():
self.item_data[uid] = new_item_data
type_error = False
- for key,value in mapping.items():
+ for key, value in mapping.items():
try:
mapping[key] = float(value)
except Exception, e:
@@ -93,11 +93,11 @@ class ajaxCalculateAnalysisEntry():
return None
formula = calculation.getFormula()
- formula = formula.replace('[','%(').replace(']',')f')
+ formula = formula.replace('[', '%(').replace(']', ')f')
try:
# mapping values are keyed by ServiceKeyword or InterimField keyword
- formula = eval("'%s'%%mapping"%formula,
+ formula = eval("'%s'%%mapping" % formula,
{"__builtins__":None, 'math':math},
{'mapping': mapping})
# calculate
@@ -111,10 +111,10 @@ class ajaxCalculateAnalysisEntry():
except ZeroDivisionError, e:
return None
except KeyError, e:
- self.alerts.append({'uid': uid, 'field': 'Result','icon': 'exclamation', 'msg': "Key Error: " + str(e.args[0])})
+ self.alerts.append({'uid': uid, 'field': 'Result', 'icon': 'exclamation', 'msg': "Key Error: " + str(e.args[0])})
return None
except Exception, e:
- self.alerts.append({'uid': uid, 'field': 'Result', 'icon': 'exclamation', 'msg': "Exception: " + str(e.args[0])})
+ self.alerts.append({'uid': uid, 'field': 'Result', 'icon': 'exclamation', 'msg': "Exception: " + str(e.args[0])})
return None
else:
@@ -144,6 +144,9 @@ class ajaxCalculateAnalysisEntry():
# if it's in recurse_uids its my ancestor.
if recurse_uid in self.recurse_uids:
continue
+ # ignore analyses that no longer exist.
+ if recurse_uid in self.ignore_uids:
+ continue
# recalculate it
self.recurse_uids.append(recurse_uid)
self.calculate(recurse_uid)
@@ -169,6 +172,7 @@ class ajaxCalculateAnalysisEntry():
self.uncertainties = []
self.alerts = []
self.results = []
+ self.ignore_uids = []
self.services = {}
self.analyses = {}
@@ -180,6 +184,10 @@ class ajaxCalculateAnalysisEntry():
self.UIDtoUID = {}
for analysis_uid, result in self.form_results.items():
analysis = rc.lookupObject(analysis_uid)
+ if not analysis:
+ # ignore analysis if object no longer exists
+ self.ignore_uids.append(analysis_uid)
+ continue
service = analysis.getService()
service_uid = service.UID()
self.analyses[analysis_uid] = analysis
@@ -187,9 +195,9 @@ class ajaxCalculateAnalysisEntry():
self.UIDtoUID[service_uid] = analysis_uid
self.UIDtoUID[analysis_uid] = service_uid
- self.recurse_uids = [self.uid,]
-
- self.calculate()
+ if self.uid not in self.ignore_uids:
+ self.recurse_uids = [self.uid, ]
+ self.calculate()
return json.dumps({'item_data': self.item_data,
'alerts': self.alerts,
|
Avoid errors in calcs.py when screen contains deleted analyses
|
senaite_senaite.core
|
train
|
4e19ed964d9efeeea0e02ebb34d433e8fd68f1c0
|
diff --git a/src/API/Management.php b/src/API/Management.php
index <HASH>..<HASH> 100644
--- a/src/API/Management.php
+++ b/src/API/Management.php
@@ -157,6 +157,17 @@ final class Management implements ManagementInterface
$cache->save($cachedKey);
}
}
+ } else {
+ $response = HttpResponse::decodeContent($response);
+
+ if (isset($response['error'])) {
+ $errorMessage = (string) $response['error'];
+ if (isset($response['error_description'])) {
+ $errorMessage .= ': ' . (string) $response['error_description'];
+ }
+
+ throw \Auth0\SDK\Exception\NetworkException::requestRejected($errorMessage);
+ }
}
}
diff --git a/src/Exception/NetworkException.php b/src/Exception/NetworkException.php
index <HASH>..<HASH> 100644
--- a/src/Exception/NetworkException.php
+++ b/src/Exception/NetworkException.php
@@ -10,6 +10,7 @@ namespace Auth0\SDK\Exception;
final class NetworkException extends \Exception implements Auth0Exception
{
public const MSG_NETWORK_REQUEST_FAILED = 'Unable to complete network request; %s';
+ public const MSG_NETWORK_REQUEST_REJECTED = 'Network request was rejected; %s';
public static function requestFailed(
string $httpClientMessage,
@@ -17,4 +18,11 @@ final class NetworkException extends \Exception implements Auth0Exception
): self {
return new self(sprintf(self::MSG_NETWORK_REQUEST_FAILED, $httpClientMessage), 0, $previous);
}
+
+ public static function requestRejected(
+ string $httpClientMessage,
+ ?\Throwable $previous = null
+ ): self {
+ return new self(sprintf(self::MSG_NETWORK_REQUEST_REJECTED, $httpClientMessage), 0, $previous);
+ }
}
diff --git a/tests/Unit/API/ManagementTest.php b/tests/Unit/API/ManagementTest.php
index <HASH>..<HASH> 100644
--- a/tests/Unit/API/ManagementTest.php
+++ b/tests/Unit/API/ManagementTest.php
@@ -37,6 +37,18 @@ test('getHttpClient() fails without a managementToken, if client id and secret a
$this->sdk->management()->blacklists();
})->throws(\Auth0\SDK\Exception\ConfigurationException::class, \Auth0\SDK\Exception\ConfigurationException::MSG_REQUIRES_MANAGEMENT_KEY);
+test('getHttpClient() fails if tenant is not configured with required scope(s)', function(): void {
+ $this->configuration->setClientSecret(uniqid());
+ $this->configuration->setManagementToken(null);
+
+ $authentication = new Authentication($this->configuration);
+ $authentication->getHttpClient()->mockResponse(
+ HttpResponseGenerator::create('{"error":"access_denied","error_description":"Client is not authorized to access"}', 403),
+ );
+
+ $this->sdk->management()->getHttpClient($authentication);
+})->throws(\Auth0\SDK\Exception\NetworkException::class, sprintf(\Auth0\SDK\Exception\NetworkException::MSG_NETWORK_REQUEST_REJECTED, ''));
+
test('blacklists() returns an instance of Auth0\SDK\API\Management\Blacklists', function(): void {
$class = $this->sdk->management()->blacklists();
|
Add network exception to management (#<I>) (#<I>)
|
auth0_auth0-PHP
|
train
|
7e89d8e260b9ff585a1c4de716ac222a946fe9d9
|
diff --git a/crawler.js b/crawler.js
index <HASH>..<HASH> 100644
--- a/crawler.js
+++ b/crawler.js
@@ -148,20 +148,22 @@ Crawler.prototype._crawlUrl = function(url, depth, onSuccess, onFailure, onAllFi
if (!error && (response.statusCode === 200)) {
//If no redirects, then response.request.uri.href === url, otherwise last url
var lastUrlInRedirectChain = response.request.uri.href;
- self.crawledUrls[url] = true;
- _.each(this.redirects, function(redirect) {
- self.crawledUrls[redirect.redirectUri] = true;
- });
- onSuccess({
- url: url,
- status: response.statusCode,
- content: body,
- error: error,
- response: response,
- body: body
- });
- if (depth > 1) {
- self._crawlUrls(self._getAllUrls(lastUrlInRedirectChain, body), depth - 1, onSuccess, onFailure, onAllFinished);
+ if (self.shouldCrawl(lastUrlInRedirectChain)) {
+ self.crawledUrls[url] = true;
+ _.each(this.redirects, function(redirect) {
+ self.crawledUrls[redirect.redirectUri] = true;
+ });
+ onSuccess({
+ url: url,
+ status: response.statusCode,
+ content: body,
+ error: error,
+ response: response,
+ body: body
+ });
+ if (depth > 1) {
+ self._crawlUrls(self._getAllUrls(lastUrlInRedirectChain, body), depth - 1, onSuccess, onFailure, onAllFinished);
+ }
}
} else if (onFailure) {
onFailure({
|
Checking whether the last url in a redirect chain should be also crawled according to the 'shouldCrawl' function.
|
antivanov_js-crawler
|
train
|
1a5dea3f4790333973f80a70787704272d5a4778
|
diff --git a/shutit_global.py b/shutit_global.py
index <HASH>..<HASH> 100644
--- a/shutit_global.py
+++ b/shutit_global.py
@@ -429,9 +429,7 @@ class ShutIt(object):
# Handle OSX to get the GNU version of the command
if assume_gnu:
- cmd_arr = send.split()
- if len(cmd_arr) and cmd_arr[0] in ('md5sum','sed','head'):
- send =string.join([self._get_command(cmd_arr[0])] + cmd_arr[1:])
+ send = self._get_send_command(send)
# If check_exit is not passed in
# - if the expect matches the default, use the default check exit
@@ -589,6 +587,13 @@ $'"""
# alias send to send_and_expect
send_and_expect = send
+
+ def _get_send_command(self, send):
+ """Internal helper function to get command that's really sent"""
+ cmd_arr = send.split()
+ if len(cmd_arr) and cmd_arr[0] in ('md5sum','sed','head'):
+ send = string.join([self._get_command(cmd_arr[0])] + cmd_arr[1:])
+ return send
def _handle_note(self, note):
"""Handle notes and walkthrough option.
@@ -1911,8 +1916,7 @@ END_''' + random_id)
self._handle_note(note)
# Don't check exit, as that will pollute the output. Also, it's quite likely the
# submitted command is intended to fail.
- self.send(send, child=child, expect=expect, check_exit=False, retry=retry, echo=False, timeout=timeout)
- # TODO: make this better by creating a call to get the actual command sent.
+ self.send(self._get_send_command(send), child=child, expect=expect, check_exit=False, retry=retry, echo=False, timeout=timeout)
before = self.get_default_child().before
try:
if cfg['environment'][cfg['build']['current_environment_id']]['distro'] == 'osx':
|
_get_send_command helper function added and used
|
ianmiell_shutit
|
train
|
b3547d375bbc0bcbec6532b67511435674890bac
|
diff --git a/metpy/calc/tools.py b/metpy/calc/tools.py
index <HASH>..<HASH> 100644
--- a/metpy/calc/tools.py
+++ b/metpy/calc/tools.py
@@ -366,8 +366,7 @@ def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
# If we have heights, we know the exact height value, otherwise return standard
# atmosphere height for the pressure
if heights is not None:
- idx = np.where(pressure == bound_pressure)
- bound_height = heights[idx]
+ bound_height = heights[pressure == bound_pressure]
else:
bound_height = pressure_to_height_std(bound_pressure)
# If bound is not in the data, return the nearest or interpolated values
@@ -386,14 +385,13 @@ def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
else:
bound_height = pressure_to_height_std(bound_pressure)
- # Bound is given in length
+ # Bound is given in height
elif bound.dimensionality == {'[length]': 1.0}:
# If there is height data, see if we have the bound or need to interpolate/find nearest
if heights is not None:
if bound in heights: # Bound is in the height data
bound_height = bound
- idx = np.where(heights == bound)
- bound_pressure = pressure[idx]
+ bound_pressure = pressure[heights == bound]
else: # Bound is not in the data
if interpolate:
bound_height = bound
@@ -407,7 +405,7 @@ def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
bound_pressure = height_to_pressure_std(bound)
# If interpolation is on, this is all we need, if not, we need to go back and
# find the pressure closest to this and refigure the bounds
- if interpolate is False:
+ if not interpolate:
idx = (np.abs(pressure - bound_pressure)).argmin()
bound_pressure = pressure[idx]
bound_height = pressure_to_height_std(bound_pressure)
@@ -416,6 +414,13 @@ def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
else:
raise ValueError('Bound must be specified in units of length or pressure.')
+ # If the bound is out of the range of the data, we shouldn't extrapolate
+ if (bound_pressure < np.min(pressure)) or (bound_pressure > np.max(pressure)):
+ raise ValueError('Specified bound is outside pressure range.')
+ if heights is not None:
+ if (bound_height > np.max(heights)) or (bound_height < np.min(heights)):
+ raise ValueError('Specified bound is outside height range.')
+
return bound_pressure, bound_height
@@ -457,10 +462,10 @@ def get_layer(p, *args, **kwargs):
depth = kwargs.pop('depth', 100 * units.hPa)
interpolate = kwargs.pop('interpolate', True)
- # Make sure pressure and datavar are the same length
+ # Make sure pressure and datavars are the same length
for datavar in args:
if len(p) != len(datavar):
- raise ValueError('Pressure and data variable must have the same length.')
+ raise ValueError('Pressure and data variables must have the same length.')
# If the bottom is not specified, make it the surface pressure
if bottom is None:
|
Add check for bounds out of range of the data.
|
Unidata_MetPy
|
train
|
6459a0a30acd0c5a62940067db77e7240d3cb276
|
diff --git a/lib/helper/Nightmare.js b/lib/helper/Nightmare.js
index <HASH>..<HASH> 100644
--- a/lib/helper/Nightmare.js
+++ b/lib/helper/Nightmare.js
@@ -865,7 +865,7 @@ class Nightmare extends Helper {
}
/**
- * {{> ../webapi/waitForVisible }}
+ * {{> ../webapi/waitForInvisible }}
*/
waitForInvisible(locator, sec) {
this.browser.options.waitTimeout = sec ? sec * 1000 : this.options.waitForTimeout;
|
Fixed docs in Nightmare
|
Codeception_CodeceptJS
|
train
|
22172c170dc8d86d43a428d6165f7c08787fbbbe
|
diff --git a/config.js b/config.js
index <HASH>..<HASH> 100644
--- a/config.js
+++ b/config.js
@@ -2,13 +2,18 @@ const { join } = require('path')
const config = {
port: 5000,
- url: 'wss://localhost.holodex.is:5000',
+ url: '//localhost:5000',
entry: join(__dirname, 'browser.js'),
dbPath: join(__dirname, 'db'),
- staticPath: join(__dirname, 'dex'),
- letsencrypt: {
+ staticPath: join(__dirname, 'dex')
+}
+
+if (process.env.NODE_ENV === 'production') {
+ config.port = process.env.PORT
+ config.url = '//staging.holodex.is',
+ config.letsencrypt = {
path: join(__dirname, 'letsencrypt'),
- host: 'localhost.holodex.is',
+ host: 'staging.holodex.is',
email: 'michael.williams@enspiral.com',
agreeTos: true
}
diff --git a/dex/util/https.js b/dex/util/https.js
index <HASH>..<HASH> 100644
--- a/dex/util/https.js
+++ b/dex/util/https.js
@@ -1,13 +1,14 @@
const https = require('https')
-var Lex = require('letsencrypt-express')
-if (process.env.NODE_ENV !== 'production') {
- Lex = Lex.testing()
-}
-
module.exports = createHttpsServer
function createHttpsServer (handler, options = {}) {
+ const Lex = require('letsencrypt-express')
+
+ if (process.env.NODE_ENV !== 'production') {
+ Lex = Lex.testing()
+ }
+
const host = options.host
const email = options.email
const agreeTos = options.agreeTos
|
only use Let's Encrypt in production
|
holodex_app
|
train
|
f7cc0822895b4864784fd1589aed747b91fe28e4
|
diff --git a/examples/word_language_model/data.py b/examples/word_language_model/data.py
index <HASH>..<HASH> 100644
--- a/examples/word_language_model/data.py
+++ b/examples/word_language_model/data.py
@@ -53,20 +53,11 @@ class Corpus(object):
class Loader:
def __init__(self, source, use_cuda=False, bptt=10, batch_size=20, evaluation=False):
- # FIXME: this is kind of stupid, we supply TensorDatasets to the loader
- # except in forward (=> therefore in predict()) we don't (we just
- # supply it with what we get).
- if isinstance(source, torch.utils.data.TensorDataset):
- source = source.data_tensor
- self.prediction = False
- else:
- self.prediction = True
-
self.evaluation = evaluation
self.bptt = bptt
self.batch_size = batch_size
self.use_cuda = use_cuda
- self.batches = self.batchify(source, batch_size)
+ self.batches = self.batchify(torch.LongTensor(source.X), batch_size)
def batchify(self, data, bsz):
# Work out how cleanly we can divide the dataset into bsz parts.
@@ -82,15 +73,9 @@ class Loader:
def get_batch(self, i):
seq_len = min(self.bptt, len(self.batches) - 1 - i)
data = Variable(self.batches[i:i+seq_len], volatile=self.evaluation)
-
- if self.prediction:
- return data
- else:
- target = Variable(self.batches[i+1:i+1+seq_len].view(-1))
- return data, target
+ target = Variable(self.batches[i+1:i+1+seq_len].view(-1))
+ return data, target
def __iter__(self):
for i in range(0, self.batches.size(0) - 1, self.bptt):
yield self.get_batch(i)
-
-
diff --git a/examples/word_language_model/learner.py b/examples/word_language_model/learner.py
index <HASH>..<HASH> 100644
--- a/examples/word_language_model/learner.py
+++ b/examples/word_language_model/learner.py
@@ -3,6 +3,7 @@ import torch
from torch.autograd import Variable
from sklearn.metrics import f1_score
+
class Learner(inferno.NeuralNet):
def __init__(self,
@@ -64,17 +65,7 @@ class Learner(inferno.NeuralNet):
return word_idx
- def forward(self, X, training_behavior=False):
- self.module_.train(training_behavior)
-
- iterator = self.get_iterator(X, train=training_behavior)
- y_probas = []
- for x in iterator:
- x = inferno.utils.to_var(x, use_cuda=self.use_cuda)
- y_probas.append(self.evaluation_step(x))
- return torch.cat(y_probas, dim=0)
-
- def score(self, X, y):
+ def score(self, X, y=None):
# TODO: we cannot use predict() directly as the y supplied by GridSearchCV
# is not a "valid" y and only based on the input given to fit() down below.
# Therefore we have to generate our own batches.
diff --git a/examples/word_language_model/train.py b/examples/word_language_model/train.py
index <HASH>..<HASH> 100644
--- a/examples/word_language_model/train.py
+++ b/examples/word_language_model/train.py
@@ -64,7 +64,7 @@ params = [
]
pl = GridSearchCV(learner, params)
-pl.fit(corpus.train[:1000], corpus.train[:1000])
+pl.fit(corpus.train[:1000])
print("Results of grid search:")
print("Best parameter configuration:", pl.best_params_)
|
Simplify RNN example based on recent changes.
|
skorch-dev_skorch
|
train
|
27c9f8be7a1142a92881f2f053130e259ecab1af
|
diff --git a/cmd/bootstrap-peer-server.go b/cmd/bootstrap-peer-server.go
index <HASH>..<HASH> 100644
--- a/cmd/bootstrap-peer-server.go
+++ b/cmd/bootstrap-peer-server.go
@@ -92,7 +92,8 @@ func (s1 ServerSystemConfig) Diff(s2 ServerSystemConfig) error {
}
var skipEnvs = map[string]struct{}{
- "MINIO_OPTS": {},
+ "MINIO_OPTS": {},
+ "MINIO_CERT_PASSWD": {},
}
func getServerSystemCfg() ServerSystemConfig {
|
ignore MINIO_CERT_PASSWD to be same on all instances
|
minio_minio
|
train
|
8ba2db21aeea9ebfa10a9c1ef310b83da5d2040c
|
diff --git a/py/build_for_clone.py b/py/build_for_clone.py
index <HASH>..<HASH> 100755
--- a/py/build_for_clone.py
+++ b/py/build_for_clone.py
@@ -3,7 +3,7 @@ import unittest, time, sys, random
sys.path.extend(['.','..','py','../h2o/py','../../h2o/py'])
import h2o, h2o_cmd
-start = time.time()
+beginning = time.time()
class Basic(unittest.TestCase):
def tearDown(self):
@@ -11,7 +11,6 @@ class Basic(unittest.TestCase):
@classmethod
def setUpClass(cls):
-
global SEED, localhost
SEED = h2o.setup_random_seed()
localhost = h2o.decide_if_localhost()
@@ -25,7 +24,8 @@ class Basic(unittest.TestCase):
h2o.tear_down_cloud()
def test_build_for_clone(self):
- elapsed = time.time() - start
+ # python gets confused about which 'start' if I used start here
+ elapsed = time.time() - beginning
print "\n%0.2f seconds to get here from start" % elapsed
maxTime = 4*3600
@@ -45,9 +45,9 @@ class Basic(unittest.TestCase):
print "Checking sandbox log files"
h2o.check_sandbox_for_errors(cloudShutdownIsError=True)
- start2 = time.time()
+ start = time.time()
h2i.delete_keys_at_all_nodes()
- elapsed = time.time() - start2
+ elapsed = time.time() - start
print "delete_keys_at_all_nodes(): took", elapsed, "secs"
if __name__ == '__main__':
diff --git a/py/test_clone_basic.py b/py/test_clone_basic.py
index <HASH>..<HASH> 100755
--- a/py/test_clone_basic.py
+++ b/py/test_clone_basic.py
@@ -16,12 +16,21 @@ class Basic(unittest.TestCase):
@classmethod
def tearDownClass(cls):
- pass
# DON"T
### h2o.tear_down_cloud()
+ # Instead: All tests should delete their keys..i.e. leave things clean for the next test
+ start = time.time()
+ h2i.delete_keys_at_all_nodes()
+ elapsed = time.time() - start
+ print "delete_keys_at_all_nodes(): took", elapsed, "secs"
+
def test_clone_basic(self):
h2o.verify_cloud_size()
+ def test_B_RF_iris2(self):
+ parseResult = h2i.import_parse(bucket='smalldata', path='iris/iris2.csv', schema='put')
+ h2o_cmd.runRFOnly(parseResult=parseResult, trees=6, timeoutSecs=10)
+
if __name__ == '__main__':
h2o.unit_main()
|
add a little rf to the example
|
h2oai_h2o-2
|
train
|
11b9f9156b120d678e580bcbea0c5a2e86810ee9
|
diff --git a/modules/CUAV/camera.py b/modules/CUAV/camera.py
index <HASH>..<HASH> 100644
--- a/modules/CUAV/camera.py
+++ b/modules/CUAV/camera.py
@@ -72,6 +72,8 @@ class camera_state(object):
self.transmit = True
self.roll_stabilised = True
+
+ self.minscore = 4
# setup directory for images
self.camera_dir = os.path.join(os.path.dirname(mpstate.logfile_name),
@@ -182,6 +184,11 @@ def cmd_camera(args):
print("transmit=%s" % str(state.transmit))
else:
state.transmit = bool(int(args[1]))
+ elif args[0] == "minscore":
+ if len(args) != 2:
+ print("minscore=%u" % state.minscore)
+ else:
+ state.minscore = int(args[1])
elif args[0] == "boundary":
if len(args) != 2:
print("boundary=%s" % state.boundary)
@@ -189,7 +196,7 @@ def cmd_camera(args):
state.boundary = args[1]
state.boundary_polygon = cuav_util.polygon_load(state.boundary)
else:
- print("usage: camera <start|stop|status|view|noview|gcs|brightness|capbrightness|boundary|bandwidth|transmit|loss|save>")
+ print("usage: camera <start|stop|status|view|noview|gcs|brightness|capbrightness|boundary|bandwidth|transmit|loss|save|minscore>")
def get_base_time():
@@ -318,7 +325,7 @@ def scan_thread():
state.scan_fps = 1.0 / (t2-t1)
state.scan_count += 1
- regions = cuav_region.filter_regions(im_640, regions)
+ regions = cuav_region.filter_regions(im_full, regions, min_score=state.minscore)
state.region_count += len(regions)
if state.transmit_queue.qsize() < 100:
|
camera: use <I>x<I> images, and have settable minscore
|
ArduPilot_MAVProxy
|
train
|
417597fbf71ac9062bed1abf04139d46ec830ec4
|
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java
@@ -23,13 +23,13 @@ import org.apache.flink.runtime.checkpoint.savepoint.SavepointStore;
import org.apache.flink.runtime.jobgraph.JobStatus;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.state.StateUtil;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.util.Map;
-import java.util.Objects;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
@@ -206,29 +206,7 @@ public class CompletedCheckpoint implements Serializable {
// --------------------------------------------------------------------------------------------
@Override
- public boolean equals(Object obj) {
- if (obj instanceof CompletedCheckpoint) {
- CompletedCheckpoint other = (CompletedCheckpoint) obj;
-
- return job.equals(other.job) && checkpointID == other.checkpointID &&
- timestamp == other.timestamp && duration == other.duration &&
- taskStates.equals(other.taskStates);
- } else {
- return false;
- }
- }
-
- @Override
- public int hashCode() {
- return (int) (this.checkpointID ^ this.checkpointID >>> 32) +
- 31 * ((int) (this.timestamp ^ this.timestamp >>> 32) +
- 31 * ((int) (this.duration ^ this.duration >>> 32) +
- 31 * Objects.hash(job, taskStates)));
- }
-
- @Override
public String toString() {
return String.format("Checkpoint %d @ %d for %s", checkpointID, timestamp, job);
}
-
}
|
[hotfix] [checkpoints] Remove equals()/hashCode() from CompletedCheckpoint as semantic equality is not well defined.
|
apache_flink
|
train
|
f9e7ba07b7af053f219d48f3f5690e03793da265
|
diff --git a/pkg/volume/rbd/rbd.go b/pkg/volume/rbd/rbd.go
index <HASH>..<HASH> 100644
--- a/pkg/volume/rbd/rbd.go
+++ b/pkg/volume/rbd/rbd.go
@@ -1077,8 +1077,8 @@ func getVolumeAccessModes(spec *volume.Spec) ([]v1.PersistentVolumeAccessMode, e
func parsePodSecret(pod *v1.Pod, secretName string, kubeClient clientset.Interface) (string, error) {
secret, err := volutil.GetSecretForPod(pod, secretName, kubeClient)
if err != nil {
- klog.Errorf("failed to get secret from [%q/%q]", pod.Namespace, secretName)
- return "", fmt.Errorf("failed to get secret from [%q/%q]", pod.Namespace, secretName)
+ klog.Errorf("failed to get secret from [%q/%q]: %+v", pod.Namespace, secretName, err)
+ return "", fmt.Errorf("failed to get secret from [%q/%q]: %+v", pod.Namespace, secretName, err)
}
return parseSecretMap(secret)
}
@@ -1086,8 +1086,8 @@ func parsePodSecret(pod *v1.Pod, secretName string, kubeClient clientset.Interfa
func parsePVSecret(namespace, secretName string, kubeClient clientset.Interface) (string, error) {
secret, err := volutil.GetSecretForPV(namespace, secretName, rbdPluginName, kubeClient)
if err != nil {
- klog.Errorf("failed to get secret from [%q/%q]", namespace, secretName)
- return "", fmt.Errorf("failed to get secret from [%q/%q]", namespace, secretName)
+ klog.Errorf("failed to get secret from [%q/%q]: %+v", namespace, secretName, err)
+ return "", fmt.Errorf("failed to get secret from [%q/%q]: %+v", namespace, secretName, err)
}
return parseSecretMap(secret)
}
|
rbd: log error when unable to get Secret
|
kubernetes_kubernetes
|
train
|
6bfb37d0cc1fe1b91305bde5ddbca0248f9fbc8c
|
diff --git a/glitter/publisher/models.py b/glitter/publisher/models.py
index <HASH>..<HASH> 100644
--- a/glitter/publisher/models.py
+++ b/glitter/publisher/models.py
@@ -73,31 +73,39 @@ class PublishAction(models.Model):
def _publish(self):
"""
- Process a publish action on the related object.
+ Process a publish action on the related object, returns a boolean if a change is made.
Only objects where a version change is needed will be updated.
"""
obj = self.content_object
version = self.get_version()
+ actioned = False
# Only update if needed
if obj.current_version != version:
version = self.get_version()
obj.current_version = version
obj.save(update_fields=['current_version'])
+ actioned = True
+
+ return actioned
def _unpublish(self):
"""
- Process an unpublish action on the related object.
+ Process an unpublish action on the related object, returns a boolean if a change is made.
Only objects with a current active version will be updated.
"""
obj = self.content_object
+ actioned = False
# Only update if needed
if obj.current_version is not None:
obj.current_version = None
obj.save(update_fields=['current_version'])
+ actioned = True
+
+ return actioned
def _log_action(self):
"""
@@ -119,11 +127,15 @@ class PublishAction(models.Model):
def process_action(self):
"""
- Process the action and update the related object.
+ Process the action and update the related object, returns a boolean if a change is made.
"""
if self.publish_version == self.UNPUBLISH_CHOICE:
- self._unpublish()
+ actioned = self._unpublish()
else:
- self._publish()
+ actioned = self._publish()
+
+ # Only log if an action was actually taken
+ if actioned:
+ self._log_action()
- self._log_action()
+ return actioned
|
Return True/False if actions are actually actioned
|
developersociety_django-glitter
|
train
|
1f1771a3f977fccd9f5025c0a9c103a3704f5e79
|
diff --git a/request.go b/request.go
index <HASH>..<HASH> 100644
--- a/request.go
+++ b/request.go
@@ -18,7 +18,6 @@ import (
"gopkg.in/h2non/gentleman.v1/plugins/multipart"
"gopkg.in/h2non/gentleman.v1/plugins/query"
"gopkg.in/h2non/gentleman.v1/plugins/url"
- "gopkg.in/h2non/gentleman.v1/utils"
)
const (
@@ -321,6 +320,5 @@ func NewDefaultTransport(dialer *net.Dialer) *http.Transport {
Dial: dialer.Dial,
TLSHandshakeTimeout: TLSHandshakeTimeout,
}
- utils.SetTransportFinalizer(transport)
return transport
}
|
fix(request.go): remove finalizer statement
|
h2non_gentleman
|
train
|
765c4f256297e3863f0e9b73f62b6c3c0a2e6e7d
|
diff --git a/lib/command.js b/lib/command.js
index <HASH>..<HASH> 100644
--- a/lib/command.js
+++ b/lib/command.js
@@ -362,7 +362,7 @@ class Command extends events.EventEmitter {
next();
});
}
- const arg = toQuestion(flag, cmd, current);
+ const arg = toQuestion(flag, cmd, current, answers);
inquirer
.prompt(arg)
.then((answer) => {
@@ -533,7 +533,7 @@ function ask(name, cmd, opts, cb) {
}
-function toQuestion(flag, cmd, opts) {
+function toQuestion(flag, cmd, opts, answers) {
const arg = {
type: opts.type === Boolean ? 'confirm' : opts.mask ? 'password' : 'input'
, name: flag
@@ -541,9 +541,12 @@ function toQuestion(flag, cmd, opts) {
, default: opts.default || null
};
- arg.when = opts.when ? opts.when.bind( null, cmd ) : undefined;
- arg.validate = opts.validate ? opts.validate.bind( null, cmd ) : undefined;
- arg.filter = opts.filter ? opts.filter.bind( null, cmd ) : undefined;
+ // TODO(esatterwhite)
+ // wrap validate to throw returned errors so `ask`
+ // can return them
+ arg.when = opts.when ? opts.when.bind( null, answers) : undefined;
+ arg.validate = opts.validate ? opts.validate.bind( null, answers ) : undefined;
+ arg.filter = opts.filter ? opts.filter.bind( null, answers ) : undefined;
if( opts.choices ){
arg.type = 'list';
|
command: pass answers back to interactive questions
|
esatterwhite_node-seeli
|
train
|
b85fbfc2b9acdc8e5ac72cf48642caa10f32c115
|
diff --git a/test/e2e_node/runner/local/run_local.go b/test/e2e_node/runner/local/run_local.go
index <HASH>..<HASH> 100644
--- a/test/e2e_node/runner/local/run_local.go
+++ b/test/e2e_node/runner/local/run_local.go
@@ -41,7 +41,7 @@ func main() {
klog.InitFlags(nil)
flag.Parse()
- // Build dependencies - ginkgo, kubelet and apiserver.
+ // Build dependencies - ginkgo, kubelet, e2e_node.test, and mounter.
if *buildDependencies {
if err := builder.BuildGo(); err != nil {
klog.Fatalf("Failed to build the dependencies: %v", err)
|
Update dependencies in local node test runner
Updates comment on building dependencies step in the local node test
runner to reflect the binaries that are actually produced.
|
kubernetes_kubernetes
|
train
|
55e6da38c6718252aebae4ed8c777e6c7352a795
|
diff --git a/xchart/src/main/java/com/xeiam/xchart/Histogram.java b/xchart/src/main/java/com/xeiam/xchart/Histogram.java
index <HASH>..<HASH> 100644
--- a/xchart/src/main/java/com/xeiam/xchart/Histogram.java
+++ b/xchart/src/main/java/com/xeiam/xchart/Histogram.java
@@ -17,7 +17,6 @@ package com.xeiam.xchart;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.Iterator;
import java.util.List;
@@ -46,14 +45,19 @@ public class Histogram {
this.numBins = numBins;
this.originalData = data;
- List<Double> dataAsList = new ArrayList<Double>();
- Iterator<? extends Number> itr = data.iterator();
- while (itr.hasNext()) {
- dataAsList.add(((Number) itr.next()).doubleValue());
+ Double tempMax = Double.MIN_VALUE;
+ Double tempMin = Double.MAX_VALUE;
+ for (Number number : data) {
+ double value = number.doubleValue();
+ if (value > tempMax) {
+ tempMax = value;
+ }
+ if (value < tempMin) {
+ tempMin = value;
+ }
}
- Collections.sort(dataAsList);
- this.min = dataAsList.get(0);
- this.max = dataAsList.get(dataAsList.size() - 1);
+ max = tempMax;
+ min = tempMin;
init();
}
@@ -92,8 +96,7 @@ public class Histogram {
else if (bin > numBins) { /* this data point is bigger than max */
// System.out.println("greater than");
}
- else if (bin == numBins) { // this falls right on the edge of the max bin
- tempYAxisData[bin - 1] += 1;
+ else if (bin == numBins) { // this falls on the next bin of the max bin
}
else {
tempYAxisData[bin] += 1;
@@ -101,7 +104,7 @@ public class Histogram {
}
yAxisData = new ArrayList<Double>(numBins);
for (double d : tempYAxisData) {
- yAxisData.add(new Double(d));
+ yAxisData.add(d);
}
// x axis data
|
Fix Histogram
1. Improved the constructor. Now it has better performance when data is
vary large (e.g. >1M).
2. Fixed line <I>. When bin==numBins, the value falls on the next bin of
the max bin, not right on the edge.
|
knowm_XChart
|
train
|
54e5bcf472ef1cbbe7e98f5809e9363bf37b6734
|
diff --git a/postgres/datadog_checks/postgres/statements.py b/postgres/datadog_checks/postgres/statements.py
index <HASH>..<HASH> 100644
--- a/postgres/datadog_checks/postgres/statements.py
+++ b/postgres/datadog_checks/postgres/statements.py
@@ -128,8 +128,7 @@ class PostgresStatementMetrics(DBMAsyncJob):
# A failed query could've derived from incorrect columns within the cache. It's a rare edge case,
# but the next time the query is run, it will retrieve the correct columns.
self._stat_column_cache = []
- self._log.warning('Statement-level metrics are unavailable: %s', e)
- return []
+ raise e
def _get_pg_stat_statements_columns(self):
"""
@@ -230,10 +229,14 @@ class PostgresStatementMetrics(DBMAsyncJob):
if (
isinstance(e, psycopg2.errors.ObjectNotInPrerequisiteState)
) and 'pg_stat_statements must be loaded' in str(e.pgerror):
- error_tag = "error:database-{}-pg_stat_statements_not_enabled".format(type(e).__name__)
+ error_tag = "error:database-{}-pg_stat_statements_not_loaded".format(type(e).__name__)
+ self._log.warning(
+ "Unable to collect statement metrics because pg_stat_statements shared library is not loaded"
+ )
+ elif isinstance(e, psycopg2.errors.UndefinedTable) and 'pg_stat_statements' in str(e.pgerror):
+ error_tag = "error:database-{}-pg_stat_statements_not_created".format(type(e).__name__)
self._log.warning(
- "Unable to collect statement metrics because pg_stat_statements is not installed "
- "in this database"
+ "Unable to collect statement metrics because pg_stat_statements is not created in this database"
)
else:
self._log.warning("Unable to collect statement metrics because of an error running queries: %s", e)
diff --git a/postgres/tests/test_statements.py b/postgres/tests/test_statements.py
index <HASH>..<HASH> 100644
--- a/postgres/tests/test_statements.py
+++ b/postgres/tests/test_statements.py
@@ -641,13 +641,34 @@ class ObjectNotInPrerequisiteState(psycopg2.errors.ObjectNotInPrerequisiteState)
return super(ObjectNotInPrerequisiteState, self).__getattribute__(attr)
+class UndefinedTable(psycopg2.errors.UndefinedTable):
+ """
+ A fake UndefinedTable that allows setting pg_error on construction since UndefinedTable
+ has it as read-only and not settable at construction-time
+ """
+
+ def __init__(self, pg_error):
+ self.pg_error = pg_error
+
+ def __getattribute__(self, attr):
+ if attr == 'pgerror':
+ return self.pg_error
+ else:
+ return super(UndefinedTable, self).__getattribute__(attr)
+
+
@pytest.mark.parametrize(
"error,metric_columns,expected_error_tag",
[
(
ObjectNotInPrerequisiteState('pg_stat_statements must be loaded via shared_preload_libraries'),
[],
- 'error:database-ObjectNotInPrerequisiteState-pg_stat_statements_not_enabled',
+ 'error:database-ObjectNotInPrerequisiteState-pg_stat_statements_not_loaded',
+ ),
+ (
+ UndefinedTable('ERROR: relation "pg_stat_statements" does not exist'),
+ [],
+ 'error:database-UndefinedTable-pg_stat_statements_not_created',
),
(
ObjectNotInPrerequisiteState('cannot insert into view'),
|
Fix wrong errors related to pg_stat_statements setup (#<I>)
|
DataDog_integrations-core
|
train
|
53af01d17a512578f5fc0e3111d4eec29c49b9ca
|
diff --git a/sh.py b/sh.py
index <HASH>..<HASH> 100644
--- a/sh.py
+++ b/sh.py
@@ -3512,7 +3512,18 @@ class SelfWrapper(ModuleType):
# if we set this to None. and 3.3 needs a value for __path__
self.__path__ = []
self.__self_module = self_module
- self.__env = Environment(globals(), baked_args=baked_args)
+
+ # Copy the Command class and add any baked call kwargs to it
+ cls_attrs = Command.__dict__.copy()
+ if baked_args:
+ call_args, _ = Command._extract_call_args(baked_args)
+ cls_attrs['_call_args'] = cls_attrs['_call_args'].copy()
+ cls_attrs['_call_args'].update(call_args)
+ command_cls = type(Command.__name__, Command.__bases__, cls_attrs)
+ globs = globals().copy()
+ globs[Command.__name__] = command_cls
+
+ self.__env = Environment(globs, baked_args=baked_args)
def __getattr__(self, name):
return self.__env[name]
@@ -3523,9 +3534,6 @@ class SelfWrapper(ModuleType):
baked_args = self.__env.baked_args.copy()
baked_args.update(kwargs)
new_mod = self.__class__(self.__self_module, baked_args)
- # Update baked call args on the new Command class
- call_args, _ = new_mod.Command._extract_call_args(baked_args)
- new_mod.Command._call_args.update(call_args)
# inspect the line in the parent frame that calls and assigns the new sh
# variable, and get the name of the new variable we're assigning to.
diff --git a/test.py b/test.py
index <HASH>..<HASH> 100644
--- a/test.py
+++ b/test.py
@@ -3138,6 +3138,13 @@ class ExecutionContextTests(unittest.TestCase):
_sh.echo("-n", "TEST")
self.assertEqual("TEST", out.getvalue())
+ def test_command_with_baked_call_args(self):
+ # Test that sh.Command() knows about baked call args
+ import sh
+ _sh = sh(_ok_code=1)
+ self.assertEqual(sh.Command._call_args['ok_code'], 0)
+ self.assertEqual(_sh.Command._call_args['ok_code'], 1)
+
def test_importer_detects_module_name(self):
import sh
_sh = sh()
|
When wrapping th module, also copy the Command class. Make it aware of baked args
|
amoffat_sh
|
train
|
1a7aec124f741f7a35e8d4641e643951d5910b6e
|
diff --git a/safe/storage/vector.py b/safe/storage/vector.py
index <HASH>..<HASH> 100644
--- a/safe/storage/vector.py
+++ b/safe/storage/vector.py
@@ -828,6 +828,7 @@ class Vector(Layer):
# Write keywords if any
# write_keywords(self.keywords, base_name + '.keywords')
write_iso19115_metadata(filename, self.keywords)
+ self.keywords = read_iso19115_metadata(filename)
# FIXME (Ole): Maybe store style_info
|
Read keywords again after saving to a file.
|
inasafe_inasafe
|
train
|
8b51d8508c89446768bc53fe17503e858eb76265
|
diff --git a/loadbalancer/dnssrv/publisher.go b/loadbalancer/dnssrv/publisher.go
index <HASH>..<HASH> 100644
--- a/loadbalancer/dnssrv/publisher.go
+++ b/loadbalancer/dnssrv/publisher.go
@@ -13,12 +13,11 @@ import (
// Publisher yields endpoints taken from the named DNS SRV record. The name is
// resolved on a fixed schedule. Priorities and weights are ignored.
type Publisher struct {
- name string
- ttl time.Duration
- cache *loadbalancer.EndpointCache
- logger log.Logger
- endpoints chan []endpoint.Endpoint
- quit chan struct{}
+ name string
+ ttl time.Duration
+ cache *loadbalancer.EndpointCache
+ logger log.Logger
+ quit chan struct{}
}
// NewPublisher returns a DNS SRV publisher. The name is resolved
@@ -28,12 +27,11 @@ type Publisher struct {
// factory errors.
func NewPublisher(name string, ttl time.Duration, factory loadbalancer.Factory, logger log.Logger) *Publisher {
p := &Publisher{
- name: name,
- ttl: ttl,
- cache: loadbalancer.NewEndpointCache(factory, logger),
- logger: logger,
- endpoints: make(chan []endpoint.Endpoint),
- quit: make(chan struct{}),
+ name: name,
+ ttl: ttl,
+ cache: loadbalancer.NewEndpointCache(factory, logger),
+ logger: logger,
+ quit: make(chan struct{}),
}
instances, err := p.resolve()
@@ -58,8 +56,6 @@ func (p *Publisher) loop() {
defer t.Stop()
for {
select {
- case p.endpoints <- p.cache.Endpoints():
-
case <-t.C:
instances, err := p.resolve()
if err != nil {
@@ -76,12 +72,7 @@ func (p *Publisher) loop() {
// Endpoints implements the Publisher interface.
func (p *Publisher) Endpoints() ([]endpoint.Endpoint, error) {
- select {
- case endpoints := <-p.endpoints:
- return endpoints, nil
- case <-p.quit:
- return nil, loadbalancer.ErrPublisherStopped
- }
+ return p.cache.Endpoints(), nil
}
var (
diff --git a/loadbalancer/dnssrv/publisher_internal_test.go b/loadbalancer/dnssrv/publisher_internal_test.go
index <HASH>..<HASH> 100644
--- a/loadbalancer/dnssrv/publisher_internal_test.go
+++ b/loadbalancer/dnssrv/publisher_internal_test.go
@@ -123,27 +123,6 @@ func TestRefreshResolveError(t *testing.T) {
t.Skip("TODO")
}
-func TestErrPublisherStopped(t *testing.T) {
- var (
- name = "my-name"
- ttl = time.Second
- factory = func(string) (endpoint.Endpoint, loadbalancer.Closer, error) { return nil, nil, errors.New("kaboom") }
- logger = log.NewNopLogger()
- )
-
- oldLookup := lookupSRV
- defer func() { lookupSRV = oldLookup }()
- lookupSRV = mockLookupSRV([]*net.SRV{}, nil, nil)
-
- p := NewPublisher(name, ttl, factory, logger)
-
- p.Stop()
- _, have := p.Endpoints()
- if want := loadbalancer.ErrPublisherStopped; want != have {
- t.Fatalf("want %v, have %v", want, have)
- }
-}
-
func mockLookupSRV(addrs []*net.SRV, err error, count *uint64) func(service, proto, name string) (string, []*net.SRV, error) {
return func(service, proto, name string) (string, []*net.SRV, error) {
if count != nil {
|
loadbalancer/dnssrv: EndpointCache is safe
|
go-kit_kit
|
train
|
87b4dd0a2872b19b1e150c373946b4daa8b5c875
|
diff --git a/hazelcast-client/src/main/java/com/hazelcast/client/cache/impl/AbstractClientInternalCacheProxy.java b/hazelcast-client/src/main/java/com/hazelcast/client/cache/impl/AbstractClientInternalCacheProxy.java
index <HASH>..<HASH> 100644
--- a/hazelcast-client/src/main/java/com/hazelcast/client/cache/impl/AbstractClientInternalCacheProxy.java
+++ b/hazelcast-client/src/main/java/com/hazelcast/client/cache/impl/AbstractClientInternalCacheProxy.java
@@ -195,11 +195,11 @@ abstract class AbstractClientInternalCacheProxy<K, V> extends AbstractClientCach
NearCacheConfig nearCacheConfig = clientContext.getClientConfig().getNearCacheConfig(name);
if (nearCacheConfig != null) {
cacheOnUpdate = nearCacheConfig.getLocalUpdatePolicy() == NearCacheConfig.LocalUpdatePolicy.CACHE;
- NearCacheContext nearCacheContext =
- new NearCacheContext(
- nearCacheManager,
- clientContext.getSerializationService(),
- createNearCacheExecutor(clientContext.getExecutionService()));
+ NearCacheContext nearCacheContext = new NearCacheContext(
+ clientContext.getSerializationService(),
+ createNearCacheExecutor(clientContext.getExecutionService()),
+ nearCacheManager
+ );
nearCache = nearCacheManager.getOrCreateNearCache(nameWithPrefix, nearCacheConfig, nearCacheContext);
registerInvalidationListener();
}
diff --git a/hazelcast/src/main/java/com/hazelcast/cache/impl/nearcache/NearCacheContext.java b/hazelcast/src/main/java/com/hazelcast/cache/impl/nearcache/NearCacheContext.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/main/java/com/hazelcast/cache/impl/nearcache/NearCacheContext.java
+++ b/hazelcast/src/main/java/com/hazelcast/cache/impl/nearcache/NearCacheContext.java
@@ -30,19 +30,25 @@ public class NearCacheContext {
private NearCacheManager nearCacheManager;
- public NearCacheContext(NearCacheManager nearCacheManager,
- SerializationService serializationService,
+ public NearCacheContext(SerializationService serializationService,
NearCacheExecutor nearCacheExecutor) {
- this(nearCacheManager, serializationService, nearCacheExecutor, null);
+ this(serializationService, nearCacheExecutor, null, null);
}
- public NearCacheContext(NearCacheManager nearCacheManager,
- SerializationService serializationService,
+ public NearCacheContext(SerializationService serializationService,
NearCacheExecutor nearCacheExecutor,
+ NearCacheManager nearCacheManager) {
+ this(serializationService, nearCacheExecutor, nearCacheManager, null);
+ }
+
+ public NearCacheContext(SerializationService serializationService,
+ NearCacheExecutor nearCacheExecutor,
+ NearCacheManager nearCacheManager,
ClassLoader classLoader) {
this.serializationService = serializationService;
this.nearCacheExecutor = nearCacheExecutor;
this.classLoader = classLoader;
+
this.nearCacheManager = nearCacheManager;
}
diff --git a/hazelcast/src/main/java/com/hazelcast/map/impl/nearcache/NearCacheProvider.java b/hazelcast/src/main/java/com/hazelcast/map/impl/nearcache/NearCacheProvider.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/main/java/com/hazelcast/map/impl/nearcache/NearCacheProvider.java
+++ b/hazelcast/src/main/java/com/hazelcast/map/impl/nearcache/NearCacheProvider.java
@@ -78,9 +78,10 @@ public class NearCacheProvider {
public <K, V> NearCache<K, V> getOrCreateNearCache(String mapName) {
NearCacheConfig nearCacheConfig = getNearCacheConfig(mapName);
NearCacheContext nearCacheContext = new NearCacheContext(
- nearCacheManager,
nodeEngine.getSerializationService(),
- new MemberNearCacheExecutor(nodeEngine.getExecutionService()));
+ new MemberNearCacheExecutor(nodeEngine.getExecutionService()),
+ nearCacheManager
+ );
NearCache<K, V> nearCache = nearCacheManager.getOrCreateNearCache(mapName, nearCacheConfig, nearCacheContext);
diff --git a/hazelcast/src/test/java/com/hazelcast/cache/nearcache/CommonNearCacheTestSupport.java b/hazelcast/src/test/java/com/hazelcast/cache/nearcache/CommonNearCacheTestSupport.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/test/java/com/hazelcast/cache/nearcache/CommonNearCacheTestSupport.java
+++ b/hazelcast/src/test/java/com/hazelcast/cache/nearcache/CommonNearCacheTestSupport.java
@@ -42,9 +42,7 @@ public abstract class CommonNearCacheTestSupport extends HazelcastTestSupport {
protected NearCacheContext createNearCacheContext() {
final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorServices.add(scheduledExecutorService);
- // no need for a NearCacheManager, so we can pass null
return new NearCacheContext(
- null,
new DefaultSerializationServiceBuilder().build(),
createNearCacheExecutor());
}
|
Small cleanup of NearCacheContext to ease usage in different Near Cache scenarios.
|
hazelcast_hazelcast
|
train
|
a341d1c323cde966f8f29698a73d57382458d7aa
|
diff --git a/lib/gds_api/helpers.rb b/lib/gds_api/helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/gds_api/helpers.rb
+++ b/lib/gds_api/helpers.rb
@@ -25,11 +25,6 @@ module GdsApi
Object::const_defined?(:PANOPTICON_API_CREDENTIALS) ? PANOPTICON_API_CREDENTIALS : {}
end
- # This method is deprecated. Use content_api.artefact instead.
- def fetch_artefact(params)
- panopticon_api.artefact_for_slug(params[:slug]) || OpenStruct.new(section: 'missing', need_id: 'missing', kind: 'missing')
- end
-
def self.included(klass)
if klass.respond_to?(:helper_method)
klass.helper_method :publisher_api, :panopticon_api, :imminence_api, :content_api
|
Let's remove this deprecated method.
This will be released as a new version, so anything using this can be
refactored when upgrading.
|
alphagov_gds-api-adapters
|
train
|
626706899b16bbe7537baab01cce29b02c02148f
|
diff --git a/configs/prettier.config.js b/configs/prettier.config.js
index <HASH>..<HASH> 100644
--- a/configs/prettier.config.js
+++ b/configs/prettier.config.js
@@ -1,5 +1,6 @@
module.exports = {
arrowParens: 'avoid',
printWidth: 100,
- singleQuote: true
+ singleQuote: true,
+ trailingComma: 'none'
};
|
fix: do not add trailing comma during formatting
|
deftomat_opinionated
|
train
|
57e7197aa551eac9049d3eee75ba32ab1b58a6d5
|
diff --git a/lxd/network/driver_ovn.go b/lxd/network/driver_ovn.go
index <HASH>..<HASH> 100644
--- a/lxd/network/driver_ovn.go
+++ b/lxd/network/driver_ovn.go
@@ -205,6 +205,16 @@ func (n *ovn) Validate(config map[string]string) error {
return err
}
+ // Check that if IPv6 enabled then the network size must be at least a /64 as both RA and DHCPv6
+ // in OVN (as it generates addresses using EUI64) require at least a /64 subnet to operate.
+ _, ipv6Net, _ := net.ParseCIDR(config["ipv6.address"])
+ if ipv6Net != nil {
+ ones, _ := ipv6Net.Mask.Size()
+ if ones < 64 {
+ return fmt.Errorf("IPv6 subnet must be at least a /64")
+ }
+ }
+
// Load the project to get uplink network restrictions.
p, err := n.state.Cluster.GetProject(n.project)
if err != nil {
|
lxd/network/driver/ovn: Enforce that ipv6.address if specified is at least a /<I> subnet
OVN requires at least a /<I> for DHCP and SLAAC.
|
lxc_lxd
|
train
|
2e3f520664729ea078e1dddc569d5d50e9453c47
|
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -11,6 +11,7 @@
from datetime import datetime
import os
+import re
import sys
import metpy
@@ -89,6 +90,7 @@ autosummary_imported_members = True
# The encoding of source files.
# source_encoding = 'utf-8-sig'
+cur_date = datetime.utcnow()
# The master toctree document.
master_doc = 'index'
@@ -96,26 +98,28 @@ master_doc = 'index'
# General information about the project.
project = 'MetPy'
# noinspection PyShadowingBuiltins
-copyright = ('2008-2020, MetPy Developers. '
+copyright = (f'{cur_date:%Y}-2020, MetPy Developers. '
'Development supported by National Science Foundation grants '
- 'AGS-1344155, OAC-1740315, and AGS-1901712.')
+ 'AGS-1344155, OAC-1740315, and AGS-1901712')
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
-# The short X.Y version.
verinfo = metpy.__version__
-full_version = verinfo.split('+')[0]
-version = full_version.rsplit('.', 1)[0]
+parsed_version = re.search(r'(?P<full>(?P<base>\d+\.\d+)\.\d+\w*)', verinfo).groupdict()
+# The short X.Y version.
+version = parsed_version['base']
+if '+' in verinfo:
+ version += 'dev'
# The full version, including alpha/beta/rc tags.
-release = verinfo
+release = parsed_version['full']
-rst_prolog = '''
-.. |cite_version| replace:: {0}
-.. |cite_year| replace:: {1:%Y}
-.. |access_date| replace:: {1:%d %B %Y}
-'''.format(full_version, datetime.utcnow())
+rst_prolog = f'''
+.. |cite_version| replace:: {release}
+.. |cite_year| replace:: {cur_date:%Y}
+.. |access_date| replace:: {cur_date:%d %B %Y}
+'''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
|
DOCS: Cleanup conf.py a bit
Use f-strings and clean up version/release parsing code.
|
Unidata_MetPy
|
train
|
ba70a44fa2aa32bc222cd578e240b96c213e908b
|
diff --git a/server/src/com/thoughtworks/go/server/service/plugins/builder/ElasticAgentViewViewModelBuilder.java b/server/src/com/thoughtworks/go/server/service/plugins/builder/ElasticAgentViewViewModelBuilder.java
index <HASH>..<HASH> 100644
--- a/server/src/com/thoughtworks/go/server/service/plugins/builder/ElasticAgentViewViewModelBuilder.java
+++ b/server/src/com/thoughtworks/go/server/service/plugins/builder/ElasticAgentViewViewModelBuilder.java
@@ -26,6 +26,8 @@ import com.thoughtworks.go.server.ui.plugins.PluggableInstanceSettings;
import com.thoughtworks.go.server.ui.plugins.PluginConfiguration;
import com.thoughtworks.go.server.ui.plugins.PluginInfo;
import com.thoughtworks.go.server.ui.plugins.PluginView;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
@@ -33,6 +35,7 @@ import java.util.List;
import java.util.Map;
class ElasticAgentViewViewModelBuilder implements ViewModelBuilder {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ElasticAgentViewViewModelBuilder.class);
private final ElasticAgentPluginRegistry registry;
ElasticAgentViewViewModelBuilder(ElasticAgentPluginRegistry registry) {
@@ -44,8 +47,12 @@ class ElasticAgentViewViewModelBuilder implements ViewModelBuilder {
List<PluginInfo> pluginInfos = new ArrayList<>();
for (PluginDescriptor descriptor : registry.getPlugins()) {
- Image icon = registry.getIcon(descriptor.id());
- pluginInfos.add(new PluginInfo(descriptor, Constants.EXTENSION_NAME, null, null, icon));
+ try {
+ Image icon = registry.getIcon(descriptor.id());
+ pluginInfos.add(new PluginInfo(descriptor, Constants.EXTENSION_NAME, null, null, icon));
+ } catch (Exception e) {
+ LOGGER.error("Failed to load plugin info for {}", descriptor.id(), e);
+ }
}
return pluginInfos;
diff --git a/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/models/pipeline_configs/plugin_infos.js b/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/models/pipeline_configs/plugin_infos.js
index <HASH>..<HASH> 100644
--- a/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/models/pipeline_configs/plugin_infos.js
+++ b/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/models/pipeline_configs/plugin_infos.js
@@ -18,6 +18,11 @@ define(['mithril', 'lodash', 'string-plus', 'helpers/mrequest', 'models/shared/i
var PluginInfos = m.prop([]);
PluginInfos.init = function (type) {
+ return PluginInfos.all(type).then(PluginInfos);
+ };
+
+
+ PluginInfos.all = function (type) {
var unwrap = function (response) {
return response._embedded.plugin_info;
};
@@ -29,7 +34,7 @@ define(['mithril', 'lodash', 'string-plus', 'helpers/mrequest', 'models/shared/i
config: mrequest.xhrConfig.v1,
unwrapSuccess: unwrap,
type: PluginInfos.PluginInfo
- }).then(PluginInfos);
+ });
};
PluginInfos.findById = function (id) {
diff --git a/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/single_page_apps/elastic_profiles.js b/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/single_page_apps/elastic_profiles.js
index <HASH>..<HASH> 100644
--- a/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/single_page_apps/elastic_profiles.js
+++ b/server/webapp/WEB-INF/rails.new/app/assets/new_javascripts/single_page_apps/elastic_profiles.js
@@ -24,8 +24,17 @@ require([
$(function () {
$(document).foundation();
- m.sync([PluginInfos.init('elastic-agent')]).then(function () {
+ var onSuccess = function () {
m.mount($("#elastic-profiles").get(0), ElasticProfilesWidget);
- });
+ };
+
+ var onFailure = function(){
+ $("#elastic-profiles").html($('<div class="alert callout">')
+ .append('<h5>There was a problem fetching the elastic profiles</h5>')
+ .append('<p>Refresh <a href="javascript: window.location.reload()">this page</a> in some time, and if the problem persists, check the server logs.</p>')
+ );
+ };
+
+ m.sync([PluginInfos.init('elastic-agent')]).then(onSuccess, onFailure);
});
});
|
Fixed issue in listing down the elastic profiles
|
gocd_gocd
|
train
|
bf620a9e10153d10a9af45013dac6880e69e2f72
|
diff --git a/lib/rib/core/multiline.rb b/lib/rib/core/multiline.rb
index <HASH>..<HASH> 100644
--- a/lib/rib/core/multiline.rb
+++ b/lib/rib/core/multiline.rb
@@ -48,6 +48,7 @@ module Rib::Multiline
# mri and rubinius
"syntax error, unexpected \\$end" ,
# rubinius
+ "expecting keyword_end" ,
"expecting \\$end" ,
"expecting '.+'( or '.+')*" ,
"missing '.+' for '.+' started on line \\d+"].join('|'))
|
so here's the missing part for rubinius
|
godfat_rib
|
train
|
eb3dd53d20bbad7f36d14f5f1a9393967dee7275
|
diff --git a/spec/app/models/metasploit_data_models/search/visitor/relation_spec.rb b/spec/app/models/metasploit_data_models/search/visitor/relation_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/app/models/metasploit_data_models/search/visitor/relation_spec.rb
+++ b/spec/app/models/metasploit_data_models/search/visitor/relation_spec.rb
@@ -177,7 +177,8 @@ describe MetasploitDataModels::Search::Visitor::Relation do
:mdm_host,
name: non_matching_host_name,
os_flavor: non_matching_host_os_flavor,
- os_name: non_matching_host_os_name
+ os_name: non_matching_host_os_name,
+ os_sp: non_matching_host_os_sp
)
}
@@ -193,6 +194,10 @@ describe MetasploitDataModels::Search::Visitor::Relation do
'mdm_host_os_name_b'
}
+ let(:non_matching_host_os_sp) {
+ 'mdm_host_os_sp_b'
+ }
+
let(:non_matching_info) {
'mdm_service_info_c'
}
@@ -320,7 +325,8 @@ describe MetasploitDataModels::Search::Visitor::Relation do
:mdm_host,
name: matching_host_name,
os_flavor: matching_host_os_flavor,
- os_name: matching_host_os_name
+ os_name: matching_host_os_name,
+ os_sp: matching_host_os_sp
)
}
@@ -336,6 +342,10 @@ describe MetasploitDataModels::Search::Visitor::Relation do
'mdm_host_os_name_a'
}
+ let(:matching_host_os_sp) {
+ 'mdm_host_os_sp_a'
+ }
+
let(:matching_info) {
'mdm_service_info_a'
}
@@ -380,6 +390,10 @@ describe MetasploitDataModels::Search::Visitor::Relation do
attribute: :os_name
it_should_behave_like 'MetasploitDataModels::Search::Visitor::Relation#visit matching record',
+ association: :host,
+ attribute: :os_sp
+
+ it_should_behave_like 'MetasploitDataModels::Search::Visitor::Relation#visit matching record',
attribute: :info
it_should_behave_like 'MetasploitDataModels::Search::Visitor::Relation#visit matching record',
@@ -394,6 +408,7 @@ describe MetasploitDataModels::Search::Visitor::Relation do
host.name:#{matching_host_name}
host.os_flavor:#{matching_host_os_flavor}
host.os_name:#{matching_host_os_name}
+ host.os_sp:#{matching_host_os_sp}
name:#{matching_name}
port:#{matching_port}
proto:#{matching_proto}
|
Mdm::Service#host os_sp search
MSP-<I>
|
rapid7_metasploit_data_models
|
train
|
6dcd63a0517a067901b16609fada856527771288
|
diff --git a/examples/splitter/.bitbundler.js b/examples/splitter/.bitbundler.js
index <HASH>..<HASH> 100644
--- a/examples/splitter/.bitbundler.js
+++ b/examples/splitter/.bitbundler.js
@@ -6,8 +6,8 @@ module.exports = {
"bit-loader-js"
],
bundler: [
- ["bit-bundler-splitter", { name: "vendor", match: { path: /\/node_modules\// }, dest: "dest/vendor.js" }],
- ["bit-bundler-splitter", { name: "renderer", match: { path: /\/src\/renderer\// }, dest: "dest/renderer.js" }],
- ["bit-bundler-splitter", { name: "other.js", match: { fileName: "other.js" }, dest: "dest/other.js" }]
+ ["bit-bundler-splitter", { name: "vendor", dest: "dest/vendor.js", match: { path: /\/node_modules\// } }],
+ ["bit-bundler-splitter", { name: "renderer", dest: "dest/renderer.js", match: { path: /\/src\/renderer\// } }],
+ ["bit-bundler-splitter", { name: "other.js", dest: "dest/other.js", match: { fileName: "other.js" } }]
]
};
|
tweaked order of options in the splitter example
|
MiguelCastillo_bit-bundler
|
train
|
d22cc075e08bb89ffdca72e167b7212811488992
|
diff --git a/brozzler/browser.py b/brozzler/browser.py
index <HASH>..<HASH> 100644
--- a/brozzler/browser.py
+++ b/brozzler/browser.py
@@ -157,7 +157,10 @@ class WebsockReceiverThread(threading.Thread):
brozzler.thread_raise(self.calling_thread, BrowsingException)
def run(self):
- self.websock.run_forever()
+ # ping_timeout is used as the timeout for the call to select.select()
+ # in addition to its documented purpose, and must have a value to avoid
+ # hangs in certain situations
+ self.websock.run_forever(ping_timeout=0.5)
def _on_message(self, websock, message):
try:
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -32,7 +32,7 @@ def find_package_data(package):
setuptools.setup(
name='brozzler',
- version='1.1b9.dev173',
+ version='1.1b9.dev174',
description='Distributed web crawling with browsers',
url='https://github.com/internetarchive/brozzler',
author='Noah Levitt',
|
restore ping_timeout argument to WebSocketApp.run_forever to fix problem of leaking websocket receiver threads hanging forever on select()
|
internetarchive_brozzler
|
train
|
f81bfb7b86589d7f199a44013c0279077adc2d49
|
diff --git a/default_app/main.js b/default_app/main.js
index <HASH>..<HASH> 100644
--- a/default_app/main.js
+++ b/default_app/main.js
@@ -306,7 +306,6 @@ function startRepl () {
if (process.platform === 'win32') {
console.error('Electron REPL not currently supported on Windows')
process.exit(1)
- return
}
const repl = require('repl')
diff --git a/lib/browser/api/auto-updater/squirrel-update-win.js b/lib/browser/api/auto-updater/squirrel-update-win.js
index <HASH>..<HASH> 100644
--- a/lib/browser/api/auto-updater/squirrel-update-win.js
+++ b/lib/browser/api/auto-updater/squirrel-update-win.js
@@ -28,7 +28,7 @@ var spawnUpdate = function (args, detached, callback) {
// Process spawned, different args: Return with error
// No process spawned: Spawn new process
if (spawnedProcess && !isSameArgs(args)) {
- return callback('AutoUpdater process with arguments ' + args + ' is already running')
+ return callback(`AutoUpdater process with arguments ${args} is already running`)
} else if (!spawnedProcess) {
spawnedProcess = spawn(updateExe, args, {
detached: detached
@@ -68,7 +68,7 @@ var spawnUpdate = function (args, detached, callback) {
// Process terminated with error.
if (code !== 0) {
- return callback('Command failed: ' + (signal != null ? signal : code) + '\n' + stderr)
+ return callback(`Command failed: ${signal != null ? signal : code}\n${stderr}`)
}
// Success.
@@ -93,7 +93,7 @@ exports.checkForUpdate = function (updateURL, callback) {
json = stdout.trim().split('\n').pop()
update = (ref = JSON.parse(json)) != null ? (ref1 = ref.releasesToApply) != null ? typeof ref1.pop === 'function' ? ref1.pop() : void 0 : void 0 : void 0
} catch (jsonError) {
- return callback('Invalid result:\n' + stdout)
+ return callback(`Invalid result:\n${stdout}`)
}
return callback(null, update)
})
diff --git a/lib/browser/api/net.js b/lib/browser/api/net.js
index <HASH>..<HASH> 100644
--- a/lib/browser/api/net.js
+++ b/lib/browser/api/net.js
@@ -79,7 +79,6 @@ class IncomingMessage extends Readable {
this.shouldPush = true
this._pushInternalData()
}
-
}
URLRequest.prototype._emitRequestEvent = function (isAsync, ...rest) {
@@ -103,7 +102,6 @@ URLRequest.prototype._emitResponseEvent = function (isAsync, ...rest) {
}
class ClientRequest extends EventEmitter {
-
constructor (options, callback) {
super()
@@ -354,7 +352,6 @@ class ClientRequest extends EventEmitter {
abort () {
this.urlRequest.cancel()
}
-
}
function writeAfterEndNT (self, error, callback) {
diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js
index <HASH>..<HASH> 100644
--- a/lib/browser/api/web-contents.js
+++ b/lib/browser/api/web-contents.js
@@ -6,6 +6,7 @@ const {app, ipcMain, session, NavigationController} = electron
// session is not used here, the purpose is to make sure session is initalized
// before the webContents module.
+// eslint-disable-next-line
session
let nextId = 0
|
:wrench: Fix style issues
|
electron_electron
|
train
|
f86eba810808016552fada80fb668610e9e0b7e3
|
diff --git a/src/Auth/Importer.php b/src/Auth/Importer.php
index <HASH>..<HASH> 100644
--- a/src/Auth/Importer.php
+++ b/src/Auth/Importer.php
@@ -57,20 +57,22 @@ class Importer implements ImporterInterface
return;
}
- if (method_exists($model, 'trashed')) {
+ $query = $model->newQuery();
+
+ if ($query->getMacro('withTrashed')) {
// If the trashed method exists on our User model, then we must be
// using soft deletes. We need to make sure we include these
// results so we don't create duplicate user records.
- $model = $model->withTrashed();
+ $query->withTrashed();
}
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
- $model->where($key, $value);
+ $query->where($key, $value);
}
}
- return $model->first();
+ return $query->first();
}
/**
|
Fixed overwriting first user
- No new query object was created when calling methods upon the model,
so the first model was always returned.
- Closes #<I> & #<I>
|
Adldap2_Adldap2-Laravel
|
train
|
564999ad7b9fbdf759da9a87bc1cbfcd5bc0841c
|
diff --git a/spec/Configuration/Translations/TranslationsSpec.php b/spec/Configuration/Translations/TranslationsSpec.php
index <HASH>..<HASH> 100644
--- a/spec/Configuration/Translations/TranslationsSpec.php
+++ b/spec/Configuration/Translations/TranslationsSpec.php
@@ -31,16 +31,15 @@ class TranslationsSpec extends ObjectBehavior
$this->shouldHaveType('LIN3S\WPFoundation\Configuration\Translations\TranslationsInterface');
}
- function it_throws_exception_when_the_WPML_is_not_installed()
+ function it_trans_when_the_WPML_is_not_installed()
{
- $this->shouldThrow(new \Exception('This class needs WPML, please install it before using Translations class'))
- ->during('trans', ['dummy-key']);
+ $this->trans('dummy-key')->shouldReturn('dummy-key');
}
function it_trans_returns_translation()
{
include_once __DIR__ . '/../../../vendor/lin3s/wp-phpspec-brigde/src/Wpml.php';
- $this->trans('dummy-key')->shouldReturn('dummy-key');
+ $this->trans('dummy-key')->shouldReturn('translation of dummy-key');
}
}
diff --git a/src/Configuration/Translations/Translations.php b/src/Configuration/Translations/Translations.php
index <HASH>..<HASH> 100644
--- a/src/Configuration/Translations/Translations.php
+++ b/src/Configuration/Translations/Translations.php
@@ -34,7 +34,9 @@ class Translations implements TranslationsInterface
*/
public static function trans($key)
{
- self::isWpmlDefined();
+ if (false === function_exists('icl_t') || false === function_exists('icl_register_string')) {
+ return $key;
+ }
if (false === icl_t(false === self::domain(), $key)) {
icl_register_string(self::domain(), $key, $key);
@@ -53,16 +55,4 @@ class Translations implements TranslationsInterface
{
return defined('TRANSLATION_DOMAIN') ? TRANSLATION_DOMAIN : self::$domain;
}
-
- /**
- * Checks if the WMPL is available.
- *
- * @throws \Exception when the WPML is not installed.
- */
- private static function isWpmlDefined()
- {
- if (false === function_exists('icl_t') || false === function_exists('icl_register_string')) {
- throw new \Exception('This class needs WPML, please install it before using Translations class');
- }
- }
}
|
Removed exception when the WPML is not active
|
LIN3S_WPFoundation
|
train
|
46d6c43ebbfc5aad2682179590ce179f572b284d
|
diff --git a/shared/desktop/package.desktop.js b/shared/desktop/package.desktop.js
index <HASH>..<HASH> 100644
--- a/shared/desktop/package.desktop.js
+++ b/shared/desktop/package.desktop.js
@@ -119,7 +119,7 @@ function startPack() {
}
copySyncFolder('./dist', 'build/desktop/sourcemaps', ['.map'])
- copySyncFolder('./dist', 'build/desktop/dist', ['.js', '.ttf', '.png', '.html'])
+ copySyncFolder('./dist', 'build/desktop/dist', ['.js', '.ttf', '.otf', '.png', '.html'])
fs.removeSync(desktopPath('build/desktop/dist/fonts'))
del(desktopPath('release'))
|
add otf to bundles (#<I>)
|
keybase_client
|
train
|
5b7556b80910ae3abf0cc1985f45ccf07febea88
|
diff --git a/flink-end-to-end-tests/flink-end-to-end-tests-common/src/main/java/org/apache/flink/tests/util/flink/LocalStandaloneFlinkResource.java b/flink-end-to-end-tests/flink-end-to-end-tests-common/src/main/java/org/apache/flink/tests/util/flink/LocalStandaloneFlinkResource.java
index <HASH>..<HASH> 100644
--- a/flink-end-to-end-tests/flink-end-to-end-tests-common/src/main/java/org/apache/flink/tests/util/flink/LocalStandaloneFlinkResource.java
+++ b/flink-end-to-end-tests/flink-end-to-end-tests-common/src/main/java/org/apache/flink/tests/util/flink/LocalStandaloneFlinkResource.java
@@ -66,6 +66,7 @@ public class LocalStandaloneFlinkResource implements FlinkResource {
private FlinkDistribution distribution;
LocalStandaloneFlinkResource(Path distributionDirectory, @Nullable Path logBackupDirectory, FlinkResourceSetup setup) {
+ LOG.info("Using distribution {}.", distributionDirectory);
this.distributionDirectory = distributionDirectory;
this.logBackupDirectory = logBackupDirectory;
this.setup = setup;
|
[FLINK-<I>][tests] Log path of used distribution
|
apache_flink
|
train
|
eba14d1cdffbe770346fc41a4f66ba1d76d34bc4
|
diff --git a/asv/benchmark.py b/asv/benchmark.py
index <HASH>..<HASH> 100644
--- a/asv/benchmark.py
+++ b/asv/benchmark.py
@@ -916,7 +916,8 @@ def disc_benchmarks(root, ignore_import_errors=False):
(k, v) for k, v in module.__dict__.items()
if not k.startswith('_')
):
- if inspect.isclass(module_attr):
+ if (inspect.isclass(module_attr) and
+ not inspect.isabstract(module_attr)):
for name, class_attr in inspect.getmembers(module_attr):
if (inspect.isfunction(class_attr) or
inspect.ismethod(class_attr)):
|
FIX do not try to test abstract Benchmark classes
|
airspeed-velocity_asv
|
train
|
a43b49575b69488a98619c852c720b984f135ad1
|
diff --git a/baron/dumper.py b/baron/dumper.py
index <HASH>..<HASH> 100644
--- a/baron/dumper.py
+++ b/baron/dumper.py
@@ -6,7 +6,7 @@ def dumps(tree):
class Dumper(RenderWalker):
- def on_constant(self, constant, pos, key):
+ def on_leaf(self, constant, pos, key):
self.dump += constant
return self.CONTINUE
diff --git a/baron/finder.py b/baron/finder.py
index <HASH>..<HASH> 100644
--- a/baron/finder.py
+++ b/baron/finder.py
@@ -95,7 +95,7 @@ class PositionFinder(RenderWalker):
return self.stop
- def on_constant(self, constant, pos, key):
+ def on_leaf(self, constant, pos, key):
"""Determine if we're on the targetted node.
If the targetted column is reached, `stop` and `path_found` are
diff --git a/baron/render.py b/baron/render.py
index <HASH>..<HASH> 100644
--- a/baron/render.py
+++ b/baron/render.py
@@ -661,26 +661,26 @@ class RenderWalker:
def after_key(self, node, render_pos, render_key):
return self.CONTINUE
- def on_constant(self, node, render_pos, render_key):
+ def on_leaf(self, node, render_pos, render_key):
return self.CONTINUE
def before(self, key_type, item, position, render_key):
if key_type not in node_types:
raise NotImplemented("Unknown key type: %s" % key_type)
- return getattr(self, 'before_'+key_type)(item, position, render_key)
+ return getattr(self, 'before_'+key_type.replace("constant", "leaf"))(item, position, render_key)
def after(self, key_type, item, position, render_key):
if key_type not in node_types:
raise NotImplemented("Unknown key type: %s" % key_type)
- return getattr(self, 'after_'+key_type)(item, position, render_key)
+ return getattr(self, 'after_'+key_type.replace("constant", "leaf"))(item, position, render_key)
def walk(self, node):
stop = self.CONTINUE
for key_type, item, render_pos, render_key in render(node):
if key_type == 'constant':
- stop = self.on_constant(item, render_pos, render_key)
+ stop = self.on_leaf(item, render_pos, render_key)
else:
stop = self.before(key_type, item, render_pos, render_key)
if stop:
|
[mod] rename on_constant to on_leaf to match reality, not so cool way of doing this
|
PyCQA_baron
|
train
|
227d3d6c19c47c77567724e7e6d2af3101e56f3a
|
diff --git a/lib/specials.js b/lib/specials.js
index <HASH>..<HASH> 100644
--- a/lib/specials.js
+++ b/lib/specials.js
@@ -3,8 +3,6 @@ const intended = [
'ZEIT Inc.',
'CLI',
'API',
- 'Next.js',
- 'Node.js',
'HTTP',
'HTTPS',
'JSX',
@@ -19,7 +17,10 @@ const intended = [
'CSS',
'JS',
'HTML',
- 'WordPress'
+ 'WordPress',
+ 'JavaScript',
+ 'Next.js',
+ 'Node.js'
]
module.exports = intended
diff --git a/test/index.js b/test/index.js
index <HASH>..<HASH> 100644
--- a/test/index.js
+++ b/test/index.js
@@ -76,4 +76,4 @@ test("should not capitalize word in adjacent parens", t => {
from = "cat(s) can be a pain"
to = "Cat(s) can Be a Pain"
t.is(title(from), to)
-})
\ No newline at end of file
+})
|
Fixed tests (#<I>)
|
zeit_title
|
train
|
6d16b08a349c300413e3ced054890f17ff4efb08
|
diff --git a/src/Interfaces/Library.php b/src/Interfaces/Library.php
index <HASH>..<HASH> 100644
--- a/src/Interfaces/Library.php
+++ b/src/Interfaces/Library.php
@@ -143,10 +143,10 @@ interface Library
* be thrown when an attempt to create a query is made.
*
* @param string $table Table to join to
- * @param string $type Join type, default self::JOIN_INNER
+ * @param string $type Join type, default string("INNER JOIN")
* @return void
*/
- public function join(string $table, string $type = Builder::JOIN_INNER);
+ public function join(string $table, string $type = "INNER JOIN");
/**
* Left Join
|
fix default value for join method
Builder class of the sub-component must not be accessed from the
Database component
|
SlaxWeb_Database
|
train
|
8899d31870505e846c0efc66f746b26608b99bfe
|
diff --git a/lib/firehose/server/channel_subscription.rb b/lib/firehose/server/channel_subscription.rb
index <HASH>..<HASH> 100644
--- a/lib/firehose/server/channel_subscription.rb
+++ b/lib/firehose/server/channel_subscription.rb
@@ -76,16 +76,13 @@ module Firehose
@subscriber.unsubscribe self
end
-
- class Firehose::Server::ChannelSubscription
- def process_messages(messages)
- messages = messages.map do |m|
- m = m.dup
- on_message(m)
- m
- end
- @deferrable.succeed messages
+ def process_messages(messages)
+ messages = messages.map do |m|
+ m = m.dup
+ on_message(m)
+ m
end
+ @deferrable.succeed messages
end
private
|
Fix unnecessary code nesting for ChannelSubscription#process_messages
|
firehoseio_firehose
|
train
|
aef96874f2cfca66addc9ad29cabb7d2327559b9
|
diff --git a/lib/xcodeproj/project.rb b/lib/xcodeproj/project.rb
index <HASH>..<HASH> 100644
--- a/lib/xcodeproj/project.rb
+++ b/lib/xcodeproj/project.rb
@@ -79,7 +79,8 @@ module Xcodeproj
# @example Opening a project
# Project.new("path/to/Project.xcodeproj")
#
- def initialize(xcodeproj = nil, build_configurations = { 'Debug' => :debug, 'Release' => :release })
+ def initialize(xcodeproj = nil, build_configurations = nil)
+ build_configurations = { 'Debug' => :debug, 'Release' => :release }.merge(build_configurations)
@objects_by_uuid = {}
@generated_uuids = []
@available_uuids = []
|
Do not define default build configurations in the method signature
This will ensure they always get a Release and a Debug configuration and makes it so subclasses don’t need to repeat the default values.
|
CocoaPods_Xcodeproj
|
train
|
7ad1944187bff4393fd47fd2b786ef24bc268d98
|
diff --git a/id.go b/id.go
index <HASH>..<HASH> 100644
--- a/id.go
+++ b/id.go
@@ -78,6 +78,8 @@ var objectIDCounter = randInt()
// to NewObjectId function.
var machineID = readMachineID()
+var pid = os.Getpid()
+
// readMachineId generates machine id and puts it into the machineId global
// variable. If this function fails to get the hostname, it will cause
// a runtime error.
@@ -115,7 +117,6 @@ func New() ID {
id[5] = machineID[1]
id[6] = machineID[2]
// Pid, 2 bytes, specs don't specify endianness, but we use big endian.
- pid := os.Getpid()
id[7] = byte(pid >> 8)
id[8] = byte(pid)
// Increment, 3 bytes, big endian
diff --git a/id_test.go b/id_test.go
index <HASH>..<HASH> 100644
--- a/id_test.go
+++ b/id_test.go
@@ -123,3 +123,9 @@ func TestIDJSONUnmarshalingError(t *testing.T) {
err = json.Unmarshal([]byte(`{"ID":"TYjhW2D0huQoQS3kdk"}`), &v)
assert.EqualError(t, err, "invalid ID")
}
+
+func BenchmarkNew(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ New()
+ }
+}
|
Get pid only once (#6)
This increases the performance of New() by <I>%
|
rs_xid
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.