hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
af8574a55aff5653a323360fafa9e7a258ec79b5 | diff --git a/foolbox/attacks/adef_attack.py b/foolbox/attacks/adef_attack.py
index <HASH>..<HASH> 100644
--- a/foolbox/attacks/adef_attack.py
+++ b/foolbox/attacks/adef_attack.py
@@ -191,26 +191,6 @@ class ADefAttack(Attack):
.. [2]_ https://gitlab.math.ethz.ch/tandrig/ADef/tree/master
- Parameters
- ----------
- input_or_adv : `numpy.ndarray` or :class:`Adversarial`
- The original, unperturbed input as a `numpy.ndarray` or
- an :class:`Adversarial` instance.
- label : int
- The reference label of the original input. Must be passed
- if `a` is a `numpy.ndarray`, must not be passed if `a` is
- an :class:`Adversarial` instance.
- unpack : bool
- If true, returns the adversarial input, otherwise returns
- the Adversarial object.
- max_iter : int > 0
- Maximum number of iterations (default max_iter = 100).
- max_norm : float
- Maximum l2 norm of vector field (default max_norm = numpy.inf).
- smooth : float >= 0
- Width of the Gaussian kernel used for smoothing.
- (default is smooth = 0 for no smoothing).
-
"""
def __init__(self, model=None, criterion=Misclassification()):
@@ -219,8 +199,33 @@ class ADefAttack(Attack):
@call_decorator
def __call__(self, input_or_adv, unpack=True, max_iter=100,
- max_norm=np.inf, label=None, smooth=1.0):
-
+ max_norm=np.inf, label=None, smooth=1.0, subsample=10):
+
+ """Parameters
+ ----------
+ input_or_adv : `numpy.ndarray` or :class:`Adversarial`
+ The original, unperturbed input as a `numpy.ndarray` or
+ an :class:`Adversarial` instance.
+ label : int
+ The reference label of the original input. Must be passed
+ if `a` is a `numpy.ndarray`, must not be passed if `a` is
+ an :class:`Adversarial` instance.
+ unpack : bool
+ If true, returns the adversarial input, otherwise returns
+ the Adversarial object.
+ max_iter : int > 0
+ Maximum number of iterations (default max_iter = 100).
+ max_norm : float
+ Maximum l2 norm of vector field (default max_norm = numpy.inf).
+ smooth : float >= 0
+ Width of the Gaussian kernel used for smoothing.
+ (default is smooth = 0 for no smoothing).
+ subsample : int
+ Limit on the number of the most likely classes that should
+ be considered. A small value is usually sufficient and much
+ faster.
+
+ """
a = input_or_adv
del input_or_adv
del label
@@ -245,17 +250,23 @@ class ADefAttack(Attack):
# this, we could easily incorporate this case here. For a targeted
# attack, it is necessary to find the probability of this class and
# pass this index as the candidate (not the actual target).
+ pred, _ = a.predictions(perturbed)
+ pred_sorted = (-pred).argsort()
if targeted is False:
- ind_of_candidates = 1
+ # choose the top-k classes
+ logging.info('Only testing the top-{} classes'.format(subsample))
+ assert isinstance(subsample, int)
+ index_of_target_class, = pred_sorted[:subsample]
+ ind_of_candidates = index_of_target_class
+ # Include the correct label (index 0) in the list of targets.
+ # Remove duplicates and sort the label indices.
+ ind_of_candidates = np.unique(np.append(ind_of_candidates, 0))
else:
- pred, _ = a.predictions(perturbed)
- pred_sorted = (-pred).argsort()
index_of_target_class, = np.where(pred_sorted == target_class)
ind_of_candidates = index_of_target_class
+ ind_of_candidates = np.unique(
+ np.append(ind_of_candidates, original_label))
- # Include the correct label (index 0) in the list of targets.
- # Remove duplicates and sort the label indices.
- ind_of_candidates = np.unique(np.append(ind_of_candidates, 0))
# Remove negative entries.
ind_of_candidates = ind_of_candidates[ind_of_candidates >= 0] | included topk classes for the untargetted attack | bethgelab_foolbox | train |
9c70d6798b64b577f2f5f1094f732a9f0ce7842b | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -22,8 +22,8 @@ A highly efficient and modular mail delivery framework for
Python 2.6+ and 3.1+, formerly called TurboMail.""",
author="Alice Bevan-McGregor",
author_email="[email protected]",
- url="",
- download_url="",
+ url="https://github.com/marrow/marrow.mailer",
+ download_url="http://pypi.python.org/pypi/marrow.mailer",
license="MIT",
keywords="",
@@ -33,7 +33,7 @@ Python 2.6+ and 3.1+, formerly called TurboMail.""",
tests_require=["nose", "coverage"],
classifiers=[
- "Development Status :: 1 - Planning",
+ "Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License", | Added URLs and updated development status to beta. | marrow_mailer | train |
4ca36232c4e9835e688a89d15c184d5ed1404468 | diff --git a/src/Illuminate/Bus/Queueable.php b/src/Illuminate/Bus/Queueable.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Bus/Queueable.php
+++ b/src/Illuminate/Bus/Queueable.php
@@ -21,7 +21,7 @@ trait Queueable
/**
* The number of seconds before the job should be made available.
*
- * @var int|null
+ * @var \DateTime|int|null
*/
public $delay; | DateTime delay (#<I>) | laravel_framework | train |
6c62e38ceade749ae2e91d0e1475cb5953a7cab3 | diff --git a/tap/tests/test_plugin.py b/tap/tests/test_plugin.py
index <HASH>..<HASH> 100644
--- a/tap/tests/test_plugin.py
+++ b/tap/tests/test_plugin.py
@@ -56,8 +56,8 @@ class TestPlugin(unittest.TestCase):
self.assertTrue(
True, 'Pass because this Python does not support SkipTest.')
- @mock.patch('tap.plugin.sys')
- def test_bad_format_string(self, fake_sys):
+ @mock.patch('sys.exit')
+ def test_bad_format_string(self, fake_exit):
"""A bad format string exits the runner."""
options = FakeOptions()
options.tap_format = "Not gonna work {sort_desc}"
@@ -66,4 +66,4 @@ class TestPlugin(unittest.TestCase):
plugin._description(test)
- self.assertTrue(fake_sys.exit.called)
+ self.assertTrue(fake_exit.called)
diff --git a/tap/tests/test_runner.py b/tap/tests/test_runner.py
index <HASH>..<HASH> 100644
--- a/tap/tests/test_runner.py
+++ b/tap/tests/test_runner.py
@@ -47,8 +47,8 @@ class TestTAPTestRunner(unittest.TestCase):
TAPTestResult.FORMAT = previous_format
- @mock.patch('tap.runner.sys')
- def test_bad_format_string(self, fake_sys):
+ @mock.patch('sys.exit')
+ def test_bad_format_string(self, fake_exit):
"""A bad format string exits the runner."""
previous_format = TAPTestResult.FORMAT
bad_format = "Not gonna work {sort_desc}"
@@ -58,6 +58,6 @@ class TestTAPTestRunner(unittest.TestCase):
result._description(test)
- self.assertTrue(fake_sys.exit.called)
+ self.assertTrue(fake_exit.called)
TAPTestResult.FORMAT = previous_format | Tox does not like to mock tap.
Something strange happens when attempting to mock the tap package.
For some reason, it is mistaken as a module. I'm guessing it has
something to do with how nose imports the plugin. I'm not interested
enough to dig at the problem. | python-tap_tappy | train |
3c8dcf8cd66e279603f77b8d8157e74082086e6d | diff --git a/audio.go b/audio.go
index <HASH>..<HASH> 100644
--- a/audio.go
+++ b/audio.go
@@ -2,6 +2,13 @@ package audio
import "math"
+var (
+ // RootA or concert A is the reference frequency for A4.
+ // Modify this package variable if you need to change it to 435 (classical) or
+ // 415 (baroque). Methods refering to this root A note will use this variable.
+ RootA = 440.0
+)
+
// AvgInt averages the int values passed
func AvgInt(xs ...int) int {
var output int
diff --git a/demos/decimator/main.go b/demos/decimator/main.go
index <HASH>..<HASH> 100644
--- a/demos/decimator/main.go
+++ b/demos/decimator/main.go
@@ -27,12 +27,12 @@ func main() {
flag.Parse()
if *fileFlag == "" {
- freq := 440
+ freq := audio.RootA
fs := 44100
fmt.Printf("Going from %dHz to %dHz\n", fs, fs / *factorFlag)
// generate a wave sine
- osc := generator.NewOsc(generator.WaveSine, float64(freq), fs)
+ osc := generator.NewOsc(generator.WaveSine, freq, fs)
data := osc.Signal(fs * 4)
buf := audio.NewPCMFloatBuffer(data, audio.FormatMono4410016bBE)
// our osc generates values from -1 to 1, we need to go back to PCM scale
diff --git a/generator/cmd/main.go b/generator/cmd/main.go
index <HASH>..<HASH> 100644
--- a/generator/cmd/main.go
+++ b/generator/cmd/main.go
@@ -17,7 +17,7 @@ import (
)
var (
- freqFlag = flag.Int("freq", 440, "frequency to generate")
+ freqFlag = flag.Float64("freq", audio.RootA, "frequency to generate")
biteDepthFlag = flag.Int("biteDepth", 16, "bit size to use when generating the auid file")
durationFlag = flag.Int("duration", 4, "duration of the generated file")
formatFlag = flag.String("format", "wav", "the audio format of the output file")
diff --git a/generator/osc_test.go b/generator/osc_test.go
index <HASH>..<HASH> 100644
--- a/generator/osc_test.go
+++ b/generator/osc_test.go
@@ -1,9 +1,13 @@
package generator
-import "testing"
+import (
+ "testing"
+
+ "github.com/mattetti/audio"
+)
func TestOsc_Signal(t *testing.T) {
- osc := NewOsc(WaveSine, 440, 44100)
+ osc := NewOsc(WaveSine, audio.RootA, 44100)
if osc.CurrentPhaseAngle != 0 {
t.Fatalf("expected the current phase to be zero")
}
diff --git a/midi/note.go b/midi/note.go
index <HASH>..<HASH> 100644
--- a/midi/note.go
+++ b/midi/note.go
@@ -4,6 +4,8 @@ import (
"math"
"strconv"
"strings"
+
+ "github.com/mattetti/audio"
)
var Notes = []string{"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
@@ -44,12 +46,12 @@ func KeyInt(n string, octave int) int {
// KeyFreq returns the frequency for the given key/octave combo
// https://en.wikipedia.org/wiki/MIDI_Tuning_Standard#Frequency_values
func KeyFreq(n string, octave int) float64 {
- return 440.0 * math.Pow(2, (float64(KeyInt(n, octave)-69)/12))
+ return audio.RootA * math.Pow(2, (float64(KeyInt(n, octave)-69)/12))
}
// NoteToFreq returns the frequency of the passed midi note.
func NoteToFreq(note int) float64 {
- return 440.0 * math.Pow(2, (float64(note)-69.0)/12.0)
+ return audio.RootA * math.Pow(2, (float64(note)-69.0)/12.0)
}
// NoteToName converts a midi note value into its English name | set the root A value in the top package
so it can be changed in a single place. | mattetti_audio | train |
f0e0fa0effc4ae54aff059caeef9efcb2068356f | diff --git a/Otherfiles/notebook_check.py b/Otherfiles/notebook_check.py
index <HASH>..<HASH> 100644
--- a/Otherfiles/notebook_check.py
+++ b/Otherfiles/notebook_check.py
@@ -19,9 +19,9 @@ EXTENSION = ".ipynb"
if __name__ == "__main__":
tprint("PYCM","bulbhead")
tprint("Document","bulbhead")
- ep = ExecutePreprocessor(timeout=6000, kernel_name='python3')
print("Processing ...")
for index, notebook in enumerate(NOTEBOOKS_LIST):
+ ep = ExecutePreprocessor(timeout=6000, kernel_name='python3')
path = os.path.join("Document", notebook)
with open(path + EXTENSION) as f:
nb = nbformat.read(f, as_version=4, encoding='utf-8') | fix : minor edit in notebook_check script | sepandhaghighi_pycm | train |
c446f7cd30f39f56f2c0fbd290a831f8ee6ed1e8 | diff --git a/test/tests/delegateTest.js b/test/tests/delegateTest.js
index <HASH>..<HASH> 100644
--- a/test/tests/delegateTest.js
+++ b/test/tests/delegateTest.js
@@ -12,6 +12,7 @@ setupHelper.setUp = function() {
'<div id="container1">'
+ '<div id="delegate-test-clickable" class="delegate-test-clickable"></div>'
+ '<div id="another-delegate-test-clickable"><input id="js-input" /></div>'
+ + '<div id="custom-event"></div>'
+ '</div>'
+ '<div id="container2">'
+ '<div id="element-in-container2-test-clickable" class="delegate-test-clickable"></div>'
@@ -59,6 +60,13 @@ setupHelper.fireFormEvent = function (target, eventName) {
}
};
+setupHelper.fireCustomEvent = function(target, eventName) {
+ var ev = new Event(eventName, {
+ bubbles: true
+ });
+ target.dispatchEvent(ev);
+};
+
buster.testCase('Delegate', {
'setUp': function() {
setupHelper.setUp();
@@ -604,6 +612,25 @@ buster.testCase('Delegate', {
assert.calledOnce(bubbleSpy);
},
+ 'Custom events are supported': function() {
+ var delegate = new Delegate(document.body);
+ var spyOnContainer = this.spy();
+ var spyOnElement = this.spy();
+
+ delegate.on('foobar', '#container1', function(event) {
+ spyOnContainer();
+ });
+
+ delegate.on('foobar', '#custom-event', function(event) {
+ spyOnElement();
+ });
+
+ setupHelper.fireCustomEvent(document.getElementById("custom-event"), 'foobar');
+
+ assert.calledOnce(spyOnContainer);
+ assert.calledOnce(spyOnElement);
+ },
+
'tearDown': function() {
setupHelper.tearDown();
} | Added test to assert that custom events do work correctly (fixes #<I>) | Financial-Times_ftdomdelegate | train |
cedee4ce37db25d42d5f8946bee3ba3c52b2fa10 | diff --git a/txaws/testing/s3.py b/txaws/testing/s3.py
index <HASH>..<HASH> 100644
--- a/txaws/testing/s3.py
+++ b/txaws/testing/s3.py
@@ -109,7 +109,7 @@ class _MemoryS3Client(MemoryClient):
prefix = b""
if marker is None:
- keys_after = u""
+ keys_after = b""
else:
keys_after = marker | Consistently consider marker to be bytes | twisted_txaws | train |
ac48e583e9de55371faecec428b1c0ef56a1db57 | diff --git a/nosedjango/nosedjango.py b/nosedjango/nosedjango.py
index <HASH>..<HASH> 100644
--- a/nosedjango/nosedjango.py
+++ b/nosedjango/nosedjango.py
@@ -469,6 +469,9 @@ class SetupCacheTesting():
settings.CACHE_BACKEND = 'locmem://'
settings.DISABLE_QUERYSET_CACHE = True
+ from django.core.cache import cache
+ cache.clear()
+
def after(self):
pass | Made the cache testing plugin clear the cache between tests. | nosedjango_nosedjango | train |
ef3eefaeb41c7c3d71b8789b69c227cf02561653 | diff --git a/src/Illuminate/Hashing/BcryptHasher.php b/src/Illuminate/Hashing/BcryptHasher.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Hashing/BcryptHasher.php
+++ b/src/Illuminate/Hashing/BcryptHasher.php
@@ -62,14 +62,16 @@ class BcryptHasher implements HasherContract {
}
/**
- * Set the default crypt cost factor.
+ * Set the default passwork work factor.
*
* @param int $rounds
- * @return void
+ * @return $this
*/
public function setRounds($rounds)
{
$this->rounds = (int) $rounds;
+
+ return $this;
}
} | Cleaning up the setRounds method. | laravel_framework | train |
4a2a24c1bbdb96aa3d9f74e31d2fb53ef7d6421a | diff --git a/rpc/rpc_test.go b/rpc/rpc_test.go
index <HASH>..<HASH> 100644
--- a/rpc/rpc_test.go
+++ b/rpc/rpc_test.go
@@ -308,7 +308,7 @@ func (c customMethodCaller) Call(objId string, arg reflect.Value) (reflect.Value
if reflect.TypeOf(obj) != c.expectedType {
logger.Errorf("got the wrong type back, expected %s got %T", c.expectedType, obj)
}
- logger.Infof("calling: %T %v %#v", obj, obj, c.objMethod)
+ logger.Debugf("calling: %T %v %#v", obj, obj, c.objMethod)
return c.objMethod.Call(obj, arg)
}
@@ -317,7 +317,7 @@ func (cc *CustomMethodFinder) FindMethod(
) (
rpcreflect.MethodCaller, error,
) {
- logger.Infof("got to FindMethod: %q %d %q", rootMethodName, version, objMethodName)
+ logger.Debugf("got to FindMethod: %q %d %q", rootMethodName, version, objMethodName)
if rootMethodName != "MultiVersion" {
return nil, &rpcreflect.CallNotImplementedError{
RootMethod: rootMethodName,
@@ -348,7 +348,7 @@ func (cc *CustomMethodFinder) FindMethod(
Version: version,
}
}
- logger.Infof("found type: %s", goType)
+ logger.Debugf("found type: %s", goType)
objType := rpcreflect.ObjTypeOf(goType)
objMethod, err := objType.Method(objMethodName)
if err != nil {
diff --git a/rpc/rpcreflect/value.go b/rpc/rpcreflect/value.go
index <HASH>..<HASH> 100644
--- a/rpc/rpcreflect/value.go
+++ b/rpc/rpcreflect/value.go
@@ -126,8 +126,10 @@ func (caller methodCaller) ResultType() reflect.Type {
type MethodCaller interface {
// ParamsType holds the required type of the parameter to the object method.
ParamsType() reflect.Type
+
// ResultType holds the result type of the result of calling the object method.
ResultType() reflect.Type
+
// Call is actually placing a call to instantiate an given instance and
// call the method on that instance.
Call(objId string, arg reflect.Value) (reflect.Value, error)
diff --git a/rpc/server.go b/rpc/server.go
index <HASH>..<HASH> 100644
--- a/rpc/server.go
+++ b/rpc/server.go
@@ -110,8 +110,8 @@ type Conn struct {
// mutex guards the following values.
mutex sync.Mutex
- //methodFinder is used to lookup methods to serve RPC requests. May be
- //nil if nothing is being served.
+ // methodFinder is used to lookup methods to serve RPC requests. May be
+ // nil if nothing is being served.
methodFinder MethodFinder
// killer is the current object that we are serving if it implements
@@ -285,7 +285,7 @@ func (conn *Conn) serve(methodFinder MethodFinder, maybeKiller interface{}, tran
conn.transformErrors = transformErrors
}
-// noopTransform is used when transformErrors is not supplied to Serve
+// noopTransform is used when transformErrors is not supplied to Serve.
func noopTransform(err error) error {
return err
} | respond to Dimiter's review comments on formatting issues. | juju_juju | train |
2da4aaeb05d5849f915fa18ba8657bed786e4ef3 | diff --git a/Tests/Extension/TwigExtensionTest.php b/Tests/Extension/TwigExtensionTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Extension/TwigExtensionTest.php
+++ b/Tests/Extension/TwigExtensionTest.php
@@ -49,7 +49,7 @@ class TwigExtensionTest extends ExtensionTestCase
public function testTwigDiscoveryGetsMappingIterator()
{
$root = getcwd();
- $driver = new SimpleTwigDriver($root, ['cache' => '/tmp/mannequin-test']);
+ $driver = new SimpleTwigDriver($root, ['cache' => '/tmp/mannequin-test/twig']);
$driver->getTwig();
$inner = new \ArrayIterator([]);
$outer = new MappingCallbackIterator($inner, new TemplateNameMapper($root));
@@ -63,7 +63,7 @@ class TwigExtensionTest extends ExtensionTestCase
{
$iterator = new \ArrayIterator(['foo']);
$root = getcwd();
- $driver = new SimpleTwigDriver($root, ['cache' => '/tmp/mannequin-test']);
+ $driver = new SimpleTwigDriver($root, ['cache' => '/tmp/mannequin-test/twig']);
$driver->getTwig();
$outer = new MappingCallbackIterator($iterator, new TemplateNameMapper($root));
$discovery = new TwigDiscovery($driver, $outer);
diff --git a/TwigExtension.php b/TwigExtension.php
index <HASH>..<HASH> 100644
--- a/TwigExtension.php
+++ b/TwigExtension.php
@@ -46,7 +46,7 @@ class TwigExtension extends AbstractTwigExtension
{
if (!$this->driver) {
if (!isset($this->twigOptions['cache'])) {
- $this->twigOptions['cache'] = $this->mannequin->getCacheDir();
+ $this->twigOptions['cache'] = $this->mannequin->getCacheDir().'/twig';
}
$this->driver = new SimpleTwigDriver(
$this->twigRoot, | Move ui download and caching to the standard cache directory | LastCallMedia_Mannequin-Twig | train |
c736cd9a97741a0e8be359f32135499a3b71342b | diff --git a/pages/lib/pages/marketable_routes.rb b/pages/lib/pages/marketable_routes.rb
index <HASH>..<HASH> 100644
--- a/pages/lib/pages/marketable_routes.rb
+++ b/pages/lib/pages/marketable_routes.rb
@@ -1,6 +1,6 @@
# Determines whether marketable urls are in use.
if ::Refinery::Page.use_marketable_urls?
- ::Refinery::Application.routes.draw do
+ ::Refinery::Application.routes.append do
scope(:module => 'refinery') do
match '*path' => 'pages#show'
end
diff --git a/pages/lib/refinerycms-pages.rb b/pages/lib/refinerycms-pages.rb
index <HASH>..<HASH> 100644
--- a/pages/lib/refinerycms-pages.rb
+++ b/pages/lib/refinerycms-pages.rb
@@ -50,6 +50,7 @@ module Refinery
end
initializer 'add marketable routes' do |app|
+ require File.expand_path('../pages/marketable_routes.rb', __FILE__)
app.routes_reloader.paths << File.expand_path('../pages/marketable_routes.rb', __FILE__)
end | [marketable routes] Fix marketable routes issue really really this time??? Hell I don't know...works for me for now. | refinery_refinerycms | train |
f88c2150dd4095e8d53290daf250cfb2c778c041 | diff --git a/yarpcerrors/codes.go b/yarpcerrors/codes.go
index <HASH>..<HASH> 100644
--- a/yarpcerrors/codes.go
+++ b/yarpcerrors/codes.go
@@ -185,6 +185,9 @@ var (
// the most specific error code that applies. For example, prefer
// `OutOfRange` over `FailedPrecondition` if both codes apply.
// Similarly prefer `NotFound` or `AlreadyExists` over `FailedPrecondition`.
+//
+// These codes are meant to match gRPC status codes.
+// https://godoc.org/google.golang.org/grpc/codes#Code
type Code int
// String returns the the string representation of the Code. | Add documentation to yarpcerrors.Code to note that the Codes match gRPC status codes (#<I>) | yarpc_yarpc-go | train |
055909dbbc9db57305953a0cede09bde4bcf2243 | diff --git a/aframe.js b/aframe.js
index <HASH>..<HASH> 100644
--- a/aframe.js
+++ b/aframe.js
@@ -207,12 +207,10 @@ var aFrame = function(){
*
* @class
* @private
- * @todo determine if this can be done with an associative Array better
*/
var cache = {
/**
- * Array of responses
- * @private
+ * Array of URIs
*/
items : [],
@@ -222,34 +220,40 @@ var aFrame = function(){
ms : 0,
/**
- * Returns the cached response from the URI or false
+ * Returns the cached object {headers, response} of the URI or false
*
* @param uri {string} The URI/Identifier for the resource to retrieve from cache
- * @returns {mixed} Returns the URI response or false
+ * @param expire {boolean} [Optional] If 'false' the URI will not expire
+ * @returns {mixed} Returns the URI object {headers, response} or false
*/
- get : function(uri) {
+ get : function(uri, expire) {
try {
+ expire = (expire === false) ? false : true;
+
if (this.items[uri] === undefined) {
return false;
}
else {
if (this.items[uri]["headers"] !== undefined) {
if (((this.items[uri]["headers"].Pragma !== undefined)
- && (this.items[uri]["headers"].Pragma == "no-cache"))
+ && (this.items[uri]["headers"].Pragma == "no-cache")
+ && (expire))
|| ((this.items[uri]["headers"].Expires !== undefined)
- && (new Date(this.items[uri]["headers"].Expires) < new Date()))
+ && (new Date(this.items[uri]["headers"].Expires) < new Date())
+ && (expire))
|| ((this.ms > 0)
&& (this.items[uri]["headers"].Date !== undefined)
- && (new Date(this.items[uri]["headers"].Date).setMilliseconds(new Date(this.items[uri]["headers"].Date).getMilliseconds() + this.ms) > new Date()))) {
+ && (new Date(this.items[uri]["headers"].Date).setMilliseconds(new Date(this.items[uri]["headers"].Date).getMilliseconds() + this.ms) > new Date())
+ && (expire))) {
delete this.items[uri];
return false;
}
else {
- return this.items[uri].response;
+ return this.items[uri];
}
}
else {
- return this.items[uri].response;
+ return this.items[uri];
}
}
}
@@ -677,7 +681,8 @@ var aFrame = function(){
cache.set(uri, "response", xmlHttp.responseText);
}
- handler(xmlHttp.responseText);
+ uri = cache.get(uri, false);
+ handler(uri);
}
else {
throw label.error.serverError; | Completed the cache{} / client{} refactoring. Exposing an object from cache.get() with headers and response. | avoidwork_abaaso | train |
4e6ddb47375b3ed215d0dde8656f05ab2cd8bbe7 | diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -1,13 +1,13 @@
'use strict';
+const Path = require('path');
const Objection = require('objection');
const Knex = require('knex');
-const Path = require('path');
const Hoek = require('hoek');
const Joi = require('joi');
+const Items = require('items');
const Schema = require('./schema');
const Package = require('../package.json');
-const Items = require('items');
const internals = {};
@@ -17,12 +17,6 @@ exports.register = (server, options, next) => {
const rootState = internals.state(server.root);
- let userOptions = Hoek.shallow(options);
-
- if (options.models) {
- userOptions.models = options.models;
- }
-
if (!rootState.setup) {
rootState.collector = {
@@ -53,8 +47,8 @@ exports.register = (server, options, next) => {
rootCollector.teardownOnStop = options.teardownOnStop;
}
- userOptions = internals.registrationConfig(userOptions);
- server.root.schwifty(userOptions);
+ const config = internals.registrationConfig(options);
+ server.root.schwifty(config);
return next();
};
@@ -153,7 +147,7 @@ internals.schwifty = function (config) {
// the default is the root server's connection.
const knexGroup = {
models: [],
- knex: {}
+ knex: null
};
const state = internals.state(this);
@@ -268,6 +262,50 @@ internals.stop = function (server, next) {
exports.Model = class SchwiftyModel extends Objection.Model {
+ static get joiSchema() {}
+
+ // Caches schema, with and without optional keys
+ // Will create _schemaMemo and _optionalSchemaMemo properties
+ static getJoiSchema(patch) {
+
+ const schema = this._schemaMemo = this._schemaMemo || this.joiSchema;
+
+ if (patch) {
+ const patchSchema = this._patchSchemaMemo = this._patchSchemaMemo || internals.patchSchema(schema);
+ return patchSchema;
+ }
+
+ return schema;
+ }
+
+ // Will create _jsonAttributesMemo properties
+ static get jsonAttributes() {
+
+ if (this._jsonAttributesMemo) {
+ return this._jsonAttributesMemo;
+ }
+
+ const joiSchema = this.getJoiSchema();
+
+ if (!joiSchema) {
+ return null;
+ }
+
+ const schemaKeyDescs = joiSchema.describe().children || {};
+
+ const jsonAttributes = Object.keys(schemaKeyDescs).filter((field) => {
+
+ const type = schemaKeyDescs[field].type;
+
+ // These are the joi types we want to be parsed/serialized as json
+ return (type === 'array') || (type === 'object');
+ });
+
+ this._jsonAttributesMemo = jsonAttributes;
+
+ return jsonAttributes;
+ }
+
static parseJoiValidationError(validation) {
return validation.error.details;
@@ -278,7 +316,7 @@ exports.Model = class SchwiftyModel extends Objection.Model {
json = json || this.$parseJson(this.$toJson(true));
options = options || {};
- let joiSchema = this.constructor.schema;
+ let joiSchema = this.constructor.getJoiSchema(options.patch);
if (!joiSchema || options.skipValidation) {
return json;
@@ -301,3 +339,20 @@ exports.Model = class SchwiftyModel extends Objection.Model {
return json;
}
};
+
+internals.patchSchema = (schema) => {
+
+ if (!schema) {
+ return;
+ }
+
+ const keys = Object.keys(schema.describe().children || {});
+
+ // Make all keys optional, do not enforce defaults
+
+ if (keys.length) {
+ schema = schema.optionalKeys(keys);
+ }
+
+ return schema.options({ noDefaults: true });
+}; | For model, compute jsonAttributes and allow proper validation of patch()es. Closes #4, closes #5 | hapipal_schwifty | train |
826c884c50da2e45e1a1a3803c8f275a41e5ac32 | diff --git a/potsdb.py b/potsdb.py
index <HASH>..<HASH> 100644
--- a/potsdb.py
+++ b/potsdb.py
@@ -16,7 +16,7 @@ _valid_metric_chars = set(string.ascii_letters + string.digits + '-_./')
def _mksocket(host, port, q, done, parent_thread):
"""Returns a tcp socket to (host/port). Retries forever every 5 seconds if connection fails"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- while 1:
+ while parent_thread.is_alive():
try:
s.connect((host, port))
return s
diff --git a/test.py b/test.py
index <HASH>..<HASH> 100644
--- a/test.py
+++ b/test.py
@@ -42,13 +42,12 @@ def invalid_metric_test():
# Attempts to send 10 metrics the same, should only send 1
print sys._getframe().f_code.co_name
t = tsdb(HOST, port=PORT, daemon=False)
- t.log('test.metric2 roflcopter!', 1, cheese='blue')
- '''try:
+ try:
t.log('test.metric2 roflcopter!', 1, cheese='blue')
except AssertionError as ex:
print ex
else:
- raise Exception('should have raised AssertionError for invalid metric')'''
+ raise Exception('should have raised AssertionError for invalid metric')
if len(sys.argv) < 3:
print 'usage: %s host port' % sys.argv[0] | added check for parent thread == alive to _mksocket | orionvm_potsdb | train |
1534d31a045962469a75222c1cb71a237f7bf96a | diff --git a/public/js/plugins.js b/public/js/plugins.js
index <HASH>..<HASH> 100755
--- a/public/js/plugins.js
+++ b/public/js/plugins.js
@@ -9,6 +9,17 @@ window.log = function(){
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});
+/* Function that doesn't seem to exist in IE, and Ace was complaining about */
+if (!String.prototype.trimRight) {
+ /* based on http://blog.stevenlevithan.com/archives/faster-trim-javascript */
+ var trimBeginRegexp = /^\s\s*/;
+ var trimEndRegexp = /\s\s*$/;
+ String.prototype.trimRight = function () {
+ return String(this).replace(trimBeginRegexp, '');
+ };
+}
+
+
/* ace behaviour.js */
/* vim:ts=4:sts=4:sw=4: | Added function that doesn't seem to exist in IE, and Ace was complaining about (trimRight) | dmfrancisco_escrito | train |
3420f696442d8764a3d28f5144505cee9e5dd7ed | diff --git a/lib/boxr/events.rb b/lib/boxr/events.rb
index <HASH>..<HASH> 100644
--- a/lib/boxr/events.rb
+++ b/lib/boxr/events.rb
@@ -1,14 +1,14 @@
module Boxr
class Client
- def user_events(stream_position, stream_type: :all, limit: 100)
+ def user_events(stream_position, stream_type: :all, limit: 800)
query = {stream_position: stream_position, stream_type: stream_type, limit: limit}
events, response = get(EVENTS_URI, query: query)
Hashie::Mash.new({events: events["entries"], chunk_size: events["chunk_size"], next_stream_position: events["next_stream_position"]})
end
- def enterprise_events(created_after: nil, created_before: nil, stream_position: 0, event_type: nil, limit: 100)
+ def enterprise_events(created_after: nil, created_before: nil, stream_position: 0, event_type: nil, limit: 500)
events = []
loop do
event_response = get_enterprise_events(created_after, created_before, stream_position, event_type, limit)
@@ -20,7 +20,7 @@ module Boxr
Hashie::Mash.new({events: events, next_stream_position: stream_position})
end
- def enterprise_events_stream(initial_stream_position, event_type: nil, limit: 100, refresh_period: 5)
+ def enterprise_events_stream(initial_stream_position, event_type: nil, limit: 500, refresh_period: 300)
stream_position = initial_stream_position
loop do
response = enterprise_events(stream_position: stream_position, event_type: event_type, limit: limit) | updated defaults to better reflect best practices of event limit and refresh period | cburnette_boxr | train |
b257d11a26a8f423836392e51d9998cb1026be10 | diff --git a/app/models/agents/post_agent.rb b/app/models/agents/post_agent.rb
index <HASH>..<HASH> 100644
--- a/app/models/agents/post_agent.rb
+++ b/app/models/agents/post_agent.rb
@@ -70,9 +70,9 @@ module Agents
incoming_events.each do |event|
outgoing = interpolated(event.payload)['payload'].presence || {}
if interpolated['no_merge'].to_s == 'true'
- handle outgoing
+ handle outgoing, event.payload
else
- handle outgoing.merge(event.payload)
+ handle outgoing.merge(event.payload), event.payload
end
end
end
@@ -81,35 +81,35 @@ module Agents
handle interpolated['payload'].presence || {}
end
- def generate_uri(params = nil)
- uri = URI interpolated[:post_url]
+ def generate_uri(params = nil, payload = {})
+ uri = URI interpolated(payload)[:post_url]
uri.query = URI.encode_www_form(Hash[URI.decode_www_form(uri.query || '')].merge(params)) if params
uri
end
private
- def handle(data)
+ def handle(data, payload = {})
if method == 'post'
- post_data(data, Net::HTTP::Post)
+ post_data(data, payload, Net::HTTP::Post)
elsif method == 'put'
- post_data(data, Net::HTTP::Put)
+ post_data(data, payload, Net::HTTP::Put)
elsif method == 'delete'
- post_data(data, Net::HTTP::Delete)
+ post_data(data, payload, Net::HTTP::Delete)
elsif method == 'patch'
- post_data(data, Net::HTTP::Patch)
+ post_data(data, payload, Net::HTTP::Patch)
elsif method == 'get'
- get_data(data)
+ get_data(data, payload)
else
error "Invalid method '#{method}'"
end
end
- def post_data(data, request_type = Net::HTTP::Post)
- uri = generate_uri
+ def post_data(data, payload, request_type = Net::HTTP::Post)
+ uri = generate_uri(nil, payload)
req = request_type.new(uri.request_uri, headers)
- if interpolated['content_type'] == 'json'
+ if interpolated(payload)['content_type'] == 'json'
req.set_content_type('application/json', 'charset' => 'utf-8')
req.body = data.to_json
else
@@ -119,8 +119,8 @@ module Agents
Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == "https") { |http| http.request(req) }
end
- def get_data(data)
- uri = generate_uri(data)
+ def get_data(data, payload)
+ uri = generate_uri(data, payload)
req = Net::HTTP::Get.new(uri.request_uri, headers)
Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == "https") { |http| http.request(req) }
end
diff --git a/spec/models/agents/post_agent_spec.rb b/spec/models/agents/post_agent_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/agents/post_agent_spec.rb
+++ b/spec/models/agents/post_agent_spec.rb
@@ -28,8 +28,8 @@ describe Agents::PostAgent do
@requests = 0
@sent_requests = { Net::HTTP::Get => [], Net::HTTP::Post => [], Net::HTTP::Put => [], Net::HTTP::Delete => [], Net::HTTP::Patch => [] }
- stub.any_instance_of(Agents::PostAgent).post_data { |data, type| @requests += 1; @sent_requests[type] << data }
- stub.any_instance_of(Agents::PostAgent).get_data { |data| @requests += 1; @sent_requests[Net::HTTP::Get] << data }
+ stub.any_instance_of(Agents::PostAgent).post_data { |data, payload, type| @requests += 1; @sent_requests[type] << data }
+ stub.any_instance_of(Agents::PostAgent).get_data { |data, payload| @requests += 1; @sent_requests[Net::HTTP::Get] << data }
end
describe "making requests" do
@@ -225,7 +225,17 @@ describe Agents::PostAgent do
it "just returns the post_uri when no params are given" do
@checker.options['post_url'] = "http://example.com/a/path?existing_param=existing_value"
uri = @checker.generate_uri
+ uri.host.should == 'example.com'
+ uri.scheme.should == 'http'
uri.request_uri.should == "/a/path?existing_param=existing_value"
end
+
+ it "interpolates when receiving a payload" do
+ @checker.options['post_url'] = "https://{{ domain }}/{{ variable }}?existing_param=existing_value"
+ uri = @checker.generate_uri({ "some_param" => "some_value", "another_param" => "another_value" }, { 'domain' => 'google.com', 'variable' => 'a_variable' })
+ uri.request_uri.should == "/a_variable?existing_param=existing_value&some_param=some_value&another_param=another_value"
+ uri.host.should == 'google.com'
+ uri.scheme.should == 'https'
+ end
end
end
\ No newline at end of file | allow the PostAgent to accept interpolation in post_url | huginn_huginn | train |
944da5b98a381199bf5feda1718a053323dd1084 | diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py
index <HASH>..<HASH> 100644
--- a/_pytest/assertion/rewrite.py
+++ b/_pytest/assertion/rewrite.py
@@ -163,9 +163,9 @@ class AssertionRewritingHook(object):
self.session = session
del session
else:
- for marked in self._must_rewrite:
- if marked.startswith(name):
- return True
+ toplevel_name = name.split('.', 1)[0]
+ if toplevel_name in self._must_rewrite:
+ return True
return False
def mark_rewrite(self, *names):
diff --git a/_pytest/pytester.py b/_pytest/pytester.py
index <HASH>..<HASH> 100644
--- a/_pytest/pytester.py
+++ b/_pytest/pytester.py
@@ -16,6 +16,7 @@ from _pytest._code import Source
import py
import pytest
from _pytest.main import Session, EXIT_OK
+from _pytest.assertion.rewrite import AssertionRewritingHook
def pytest_addoption(parser):
@@ -685,8 +686,17 @@ class Testdir:
``pytest.main()`` instance should use.
:return: A :py:class:`HookRecorder` instance.
-
"""
+ # When running py.test inline any plugins active in the main
+ # test process are already imported. So this disables the
+ # warning which will trigger to say they can no longer be
+ # re-written, which is fine as they are already re-written.
+ orig_warn = AssertionRewritingHook._warn_already_imported
+ def revert():
+ AssertionRewritingHook._warn_already_imported = orig_warn
+ self.request.addfinalizer(revert)
+ AssertionRewritingHook._warn_already_imported = lambda *a: None
+
rec = []
class Collect:
def pytest_configure(x, config): | Avoid rewrite warning for inline runs
When running pytest inline/inprocess we plugins have already been
imported and re-writen, so avoid the warning. | pytest-dev_pytest | train |
2a44360735f6f4af0d6c65dfaaece9fec3004341 | diff --git a/scripts/audit.js b/scripts/audit.js
index <HASH>..<HASH> 100644
--- a/scripts/audit.js
+++ b/scripts/audit.js
@@ -26,7 +26,8 @@ if (args[0] === 'clean') {
const { error: yarnInstallError, status: yarnInstallStatus } = spawnSync('yarn', ['install', '--force'], {
cwd: process.cwd(),
- stdio: 'inherit'
+ stdio: 'inherit',
+ shell: true
})
if (yarnInstallError || yarnInstallStatus === 1) {
@@ -72,7 +73,8 @@ for (const ext of extensionsList) {
const { error: npmInstallError, status: npmInstallStatus } = spawnSync('npm', args, {
cwd: path.join(process.cwd(), 'packages', packagesInWorkspace.get(ext)),
- stdio: 'inherit'
+ stdio: 'inherit',
+ shell: true
})
console.log('\n===== dependencies install finished (logs above) =====')
@@ -89,7 +91,8 @@ for (const ext of extensionsList) {
const { error: auditError, stdout, status: auditStatus } = spawnSync('npm', ['audit', '--omit', 'dev'], {
cwd: path.join(process.cwd(), 'packages', packagesInWorkspace.get(ext)),
- stdio: 'pipe'
+ stdio: 'pipe',
+ shell: true
})
const output = stdout != null ? stdout.toString().trim() : ''
diff --git a/scripts/changed.js b/scripts/changed.js
index <HASH>..<HASH> 100644
--- a/scripts/changed.js
+++ b/scripts/changed.js
@@ -33,7 +33,8 @@ if (targetPkg != null && targetPkg !== '') {
console.log(`running ${commands.join(' ')}`)
const { stdout, stderr, error, status } = spawnSync(commands[0], commands.slice(1), {
- stdio: 'pipe'
+ stdio: 'pipe',
+ shell: true
})
if (error || status === 1) {
@@ -70,7 +71,8 @@ if (targetPkg != null && targetPkg !== '') {
console.log(`running ${commands.join(' ')}`)
const { stdout, stderr, error, status } = spawnSync(commands[0], commands.slice(1), {
- stdio: 'pipe'
+ stdio: 'pipe',
+ shell: true
})
if (error || status === 1) {
diff --git a/scripts/publish.js b/scripts/publish.js
index <HASH>..<HASH> 100644
--- a/scripts/publish.js
+++ b/scripts/publish.js
@@ -66,7 +66,8 @@ if (extraneousDeps.length > 0) {
const { error: yarnBuildError, status: yarnBuildStatus } = spawnSync(buildCommand[0], buildCommand.slice(1), {
cwd: process.cwd(),
- stdio: 'inherit'
+ stdio: 'inherit',
+ shell: true
})
if (yarnBuildError || yarnBuildStatus === 1) {
@@ -87,6 +88,7 @@ if (extraneousDeps.length > 0) {
const { error: yarnTestError, status: yarnTestStatus } = spawnSync(testCommand[0], testCommand.slice(1), {
cwd: process.cwd(),
+ shell: true,
stdio: 'inherit'
})
@@ -142,9 +144,11 @@ if (extraneousDeps.length > 0) {
console.log(`\nrunning ${installCommand.join(' ')} to normalize node_modules tree after version update`)
- const { error: yarnInstallError, status: yarnInstallStatus } = spawnSync(installCommand[0], installCommand.slice(1), {
+ const { error: yarnInstallError, status: yarnInstallStatus } =
+ (installCommand[0], installCommand.slice(1), {
cwd: process.cwd(),
- stdio: 'inherit'
+ stdio: 'inherit',
+ shell: true
})
if (yarnInstallError || yarnInstallStatus === 1) {
@@ -182,7 +186,8 @@ if (extraneousDeps.length > 0) {
const { error: publishError, status: publishStatus } = spawnSync(publishCommand[0], publishCommand.slice(1), {
cwd: path.join(process.cwd(), 'packages', targetPkgFoldername),
- stdio: 'inherit'
+ stdio: 'inherit',
+ shell: true
})
if (publishError || publishStatus === 1) { | use shell:true in scripts to make it working on win | jsreport_jsreport | train |
677e63aa5562fc2db5223d94744d1f884506f45e | diff --git a/dist/axios.js b/dist/axios.js
index <HASH>..<HASH> 100644
--- a/dist/axios.js
+++ b/dist/axios.js
@@ -1,3 +1,4 @@
+/* axios v0.7.0 | (c) 2015 by Matt Zabriskie */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
@@ -1007,4 +1008,4 @@ return /******/ (function(modules) { // webpackBootstrap
/******/ ])
});
;
-//# sourceMappingURL=axios.map
\ No newline at end of file
+//# sourceMappingURL=axios.map | Update axios.js | axios_axios | train |
7a0e54fb62bf513d34148f6c1f3e087fdebad4e4 | diff --git a/spec/plsql/procedure_spec.rb b/spec/plsql/procedure_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/plsql/procedure_spec.rb
+++ b/spec/plsql/procedure_spec.rb
@@ -2253,6 +2253,15 @@ describe "PLS_INTEGER/SIMPLE_INTEGER should be nullable" do
end
describe '#get_argument_metadata' do
+ before(:all) do
+ plsql.connect! CONNECTION_PARAMS
+ end
+
+ after(:all) do
+ plsql.logoff
+ end
+
+
before(:each) do
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION magic_number(p_num INTEGER #{defaulted_clause}) | Fixed failing tests - not connected. | rsim_ruby-plsql | train |
f634d1a0ca378033cc6714d08725e1cccd164242 | diff --git a/lib/slaw/extract/extractor.rb b/lib/slaw/extract/extractor.rb
index <HASH>..<HASH> 100644
--- a/lib/slaw/extract/extractor.rb
+++ b/lib/slaw/extract/extractor.rb
@@ -1,4 +1,5 @@
require 'open3'
+require 'tempfile'
module Slaw
module Extract
@@ -46,14 +47,23 @@ module Slaw
#
# @return [String] extracted text
def extract_from_pdf(filename)
- cmd = pdf_to_text_cmd(filename)
- logger.info("Executing: #{cmd}")
- stdout, status = Open3.capture2(*cmd)
+ retried = false
- if status == 0
- cleanup(stdout)
- else
- nil
+ while true
+ cmd = pdf_to_text_cmd(filename)
+ logger.info("Executing: #{cmd}")
+ stdout, status = Open3.capture2(*cmd)
+
+ case status.exitstatus
+ when 0
+ return cleanup(stdout)
+ when 3
+ return nil if retried
+ retried = true
+ self.remove_pdf_password(filename)
+ else
+ return nil
+ end
end
end
@@ -79,6 +89,20 @@ module Slaw
text
end
+ def remove_pdf_password(filename)
+ file = Tempfile.new('steno')
+ begin
+ logger.info("Trying to remove password from #{filename}")
+ cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=#{file.path} -c .setpdfwrite -f #{filename}".split(" ")
+ logger.info("Executing: #{cmd}")
+ Open3.capture2(*cmd)
+ FileUtils.move(file.path, filename)
+ ensure
+ file.close
+ file.unlink
+ end
+ end
+
# Get location of the pdftotext executable for all instances.
def self.pdftotext_path
@@pdftotext_path | Use gs to strip passwords from pdf | longhotsummer_slaw | train |
fcd28d9f29365e6c84280d7bec1cb0d438b57531 | diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java
index <HASH>..<HASH> 100644
--- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java
+++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/BufferingFlux.java
@@ -61,13 +61,16 @@ public class BufferingFlux {
.bufferUntil(line -> {
final int bytesLength = line.getBytes().length;
final long now = System.currentTimeMillis();
- final long last = lastTime.getAndSet(now);
+ // Update last time to now if this is the first time
+ lastTime.compareAndSet(0, now);
+ final long last = lastTime.get();
long diff;
if (last != 0L) {
diff = now - last;
if (diff > maxMillisecondsBetweenEmits && byteSize.get() > 0) {
// This creates a buffer, reset size
byteSize.set(bytesLength);
+ lastTime.compareAndSet(last, now);
return true;
}
}
@@ -82,6 +85,7 @@ public class BufferingFlux {
if (projectedBytes > maxByteArraySize) {
// This creates a buffer, reset size
byteSize.set(bytesLength);
+ lastTime.compareAndSet(last, now);
return true;
}
diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java
index <HASH>..<HASH> 100644
--- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java
+++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/BufferingFluxTest.java
@@ -15,13 +15,16 @@
*/
package io.micrometer.statsd.internal;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.time.Duration;
+import java.util.concurrent.atomic.AtomicBoolean;
@Disabled
class BufferingFluxTest {
@@ -78,4 +81,27 @@ class BufferingFluxTest {
.expectNext("fourteen bytes")
.verifyComplete();
}
+
+ /**
+ * Covers a situation where events were produced at a faster rate than the maxMillisecondsBetweenEmits, and a bug
+ * caused it to never emit the events until it reached the maxByteArraySize
+ */
+ @Test
+ void doNotBufferIndefinitely() throws InterruptedException {
+ // Produce a value at a more frequent interval than the maxMillisecondsBetweenEmits
+ final DirectProcessor<Void> end = DirectProcessor.create();
+ final Flux<String> source = Flux.interval(Duration.ofMillis(100))
+ .map(l -> l.toString());
+
+ final Flux<String> buffered = BufferingFlux.create(source, "\n", Integer.MAX_VALUE, 200);
+
+ // Record whether any value came through
+ final AtomicBoolean receivedValue = new AtomicBoolean(false);
+ buffered.subscribe(v -> receivedValue.set(true));
+
+ // There should be something emitted after 500ms
+ Thread.sleep(500);
+ assertTrue(receivedValue.get(), "No values emitted after 500ms");
+ end.onComplete();
+ }
}
\ No newline at end of file | Fix BufferingFlux to properly flush buffered values after maxMillisecondsBetweenEmits (#<I>)
* Added a test that shows an issue with the BufferingFlux when metrics are updated at a shorter interval than the maxMillisecondsBetweenEmits | micrometer-metrics_micrometer | train |
435c4dc1d778245ee412a9909e671308469fa109 | diff --git a/tests/SchemaTest.php b/tests/SchemaTest.php
index <HASH>..<HASH> 100644
--- a/tests/SchemaTest.php
+++ b/tests/SchemaTest.php
@@ -68,7 +68,7 @@ class SchemaTest extends TestCase
public function testValidateInvalidResources()
{
$this->assertValidationErrors(
- 'error loading descriptor from source "--invalid--": file_get_contents(--invalid--): failed to open stream: No such file or directory',
+ 'error loading descriptor from source "--invalid--": '.$this->getFileGetContentsErrorMessage("--invalid--"),
"--invalid--"
);
@@ -85,7 +85,7 @@ class SchemaTest extends TestCase
$this->fail("constructing from invalid descriptor should throw exception");
} catch (\frictionlessdata\tableschema\Exceptions\SchemaLoadException $e) {
$this->assertEquals(
- 'error loading descriptor from source "--invalid--": file_get_contents(--invalid--): failed to open stream: No such file or directory',
+ 'error loading descriptor from source "--invalid--": '.$this->getFileGetContentsErrorMessage("--invalid--"),
$e->getMessage()
);
}
@@ -137,7 +137,7 @@ class SchemaTest extends TestCase
],
[
"descriptor" => "foobar",
- "expected_errors" => 'error loading descriptor from source "foobar": file_get_contents(foobar): failed to open stream: No such file or directory'
+ "expected_errors" => 'error loading descriptor from source "foobar": '.$this->getFileGetContentsErrorMessage("foobar")
],
[
"descriptor" => (object)[
@@ -199,4 +199,14 @@ class SchemaTest extends TestCase
)
);
}
+
+ protected function getFileGetContentsErrorMessage($in)
+ {
+ try {
+ file_get_contents($in);
+ } catch (\Exception $e) {
+ return $e->getMessage();
+ }
+ throw new \Exception();
+ }
}
diff --git a/tests/TableTest.php b/tests/TableTest.php
index <HASH>..<HASH> 100644
--- a/tests/TableTest.php
+++ b/tests/TableTest.php
@@ -49,7 +49,7 @@ class TableTest extends TestCase
public function testLoadingFromInvalidSource()
{
$this->assertTableValidation(
- ['fopen(--invalid--): failed to open stream: No such file or directory'],
+ [$this->getFopenErrorMessage("--invalid--")],
"--invalid--", null
);
}
@@ -136,4 +136,14 @@ class TableTest extends TestCase
};
$this->assertEquals($expectedErrors, $actualErrors);
}
+
+ protected function getFopenErrorMessage($in)
+ {
+ try {
+ fopen($in, "r");
+ } catch (\Exception $e) {
+ return $e->getMessage();
+ }
+ throw new \Exception();
+ }
}
\ No newline at end of file | fix expected error messages to be platform independent | frictionlessdata_tableschema-php | train |
7ab504463ce881ff13cd4b3094692a2d438d5985 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,7 @@ Or install it yourself as:
In the metrics world there are two types of things: Gauges and Counters.
Gauges are time senstive and represent something at a specific point in
time. Counters keep track of things and should be increasing. Counters
-can be reset back to zero. You can combine counters and/or gauges to
+can be reset back to zero. MeteresYou can combine counters and/or gauges to
correlate data about your application.
Harness makes this process easily. Harness' primary goal it make it dead
diff --git a/lib/harness/counter.rb b/lib/harness/counter.rb
index <HASH>..<HASH> 100644
--- a/lib/harness/counter.rb
+++ b/lib/harness/counter.rb
@@ -25,7 +25,7 @@ module Harness
counter.value = Harness.redis.incr(counter.id).to_i
end
- Harness.redis.zadd "meters/#{counter.id}", counter.time.to_i, counter.value
+ Harness.redis.zadd "meters/#{counter.id}", counter.time.to_f, counter.value
counter
end
diff --git a/lib/harness/meter.rb b/lib/harness/meter.rb
index <HASH>..<HASH> 100644
--- a/lib/harness/meter.rb
+++ b/lib/harness/meter.rb
@@ -19,7 +19,7 @@ module Harness
end
def per(rate, base = Time.now)
- redis.zcount(key, base.to_i - rate, base.to_i)
+ redis.zcount(key, base.to_f - rate, base.to_f)
end
private | Use #to_f for better resolution | ahawkins_harness | train |
ef56d0a5351c86b987b3f729e562732890abe423 | diff --git a/image.go b/image.go
index <HASH>..<HASH> 100644
--- a/image.go
+++ b/image.go
@@ -496,7 +496,7 @@ func (i *Image) ColorModel() color.Model {
//
// At can't be called outside the main loop (ebiten.Run's updating function) starts (as of version 1.4.0-alpha).
func (i *Image) At(x, y int) color.Color {
- if atomic.LoadInt32(&isRunning) == 0 {
+ if atomic.LoadInt32(&isImageAvailable) == 0 {
panic("ebiten: (*Image).At is not available outside the main loop so far")
}
@@ -519,7 +519,7 @@ func (i *Image) At(x, y int) color.Color {
//
// If the image is disposed, Set does nothing.
func (img *Image) Set(x, y int, clr color.Color) {
- if atomic.LoadInt32(&isRunning) == 0 {
+ if atomic.LoadInt32(&isImageAvailable) == 0 {
panic("ebiten: (*Image).Set is not available outside the main loop so far")
}
diff --git a/internal/web/js.go b/internal/web/js.go
index <HASH>..<HASH> 100644
--- a/internal/web/js.go
+++ b/internal/web/js.go
@@ -22,10 +22,6 @@ import (
"syscall/js"
)
-func IsGopherJS() bool {
- return runtime.GOOS != "js"
-}
-
func IsBrowser() bool {
return true
}
diff --git a/internal/web/notjs.go b/internal/web/notjs.go
index <HASH>..<HASH> 100644
--- a/internal/web/notjs.go
+++ b/internal/web/notjs.go
@@ -16,10 +16,6 @@
package web
-func IsGopherJS() bool {
- return false
-}
-
func IsBrowser() bool {
return false
}
diff --git a/run.go b/run.go
index <HASH>..<HASH> 100644
--- a/run.go
+++ b/run.go
@@ -22,7 +22,6 @@ import (
"github.com/hajimehoshi/ebiten/internal/driver"
"github.com/hajimehoshi/ebiten/internal/graphicsdriver"
"github.com/hajimehoshi/ebiten/internal/uidriver"
- "github.com/hajimehoshi/ebiten/internal/web"
)
var _ = __EBITEN_REQUIRES_GO_VERSION_1_12_OR_LATER__
@@ -47,7 +46,7 @@ func CurrentFPS() float64 {
var (
isDrawingSkipped = int32(0)
currentMaxTPS = int32(DefaultTPS)
- isRunning = int32(0)
+ isImageAvailable = int32(0)
)
func setDrawingSkipped(skipped bool) {
@@ -133,12 +132,6 @@ func Run(f func(*Image) error, width, height int, scale float64, title string) e
c := newUIContext(f)
theUIContext.Store(c)
- atomic.StoreInt32(&isRunning, 1)
- // On GopherJS, run returns immediately.
- if !web.IsGopherJS() {
- defer atomic.StoreInt32(&isRunning, 0)
- }
-
if err := uidriver.Get().Run(width, height, scale, title, c, graphicsdriver.Get()); err != nil {
if err == driver.RegularTermination {
return nil
@@ -160,7 +153,6 @@ func RunWithoutMainLoop(f func(*Image) error, width, height int, scale float64,
c := newUIContext(f)
theUIContext.Store(c)
- atomic.StoreInt32(&isRunning, 1)
return uidriver.Get().RunWithoutMainLoop(width, height, scale, title, c, graphicsdriver.Get())
}
diff --git a/uicontext.go b/uicontext.go
index <HASH>..<HASH> 100644
--- a/uicontext.go
+++ b/uicontext.go
@@ -17,6 +17,7 @@ package ebiten
import (
"fmt"
"math"
+ "sync/atomic"
"github.com/hajimehoshi/ebiten/internal/clock"
"github.com/hajimehoshi/ebiten/internal/driver"
@@ -96,6 +97,10 @@ func (c *uiContext) Update(afterFrameUpdate func()) error {
if err := shareable.BeginFrame(); err != nil {
return err
}
+
+ // Images are available after shareable is initialized.
+ atomic.StoreInt32(&isImageAvailable, 1)
+
for i := 0; i < updateCount; i++ {
c.offscreen.Clear()
// Mipmap images should be disposed by fill. | Refactoring: isRunning -> isImageAvailable | hajimehoshi_ebiten | train |
816ef4e4dc5518acab9e97e799a86a3a960a4582 | diff --git a/cli.js b/cli.js
index <HASH>..<HASH> 100644
--- a/cli.js
+++ b/cli.js
@@ -14,7 +14,7 @@ lx.on('bulbonoff', function(b) {
});
lx.on('bulb', function(b) {
- console.log('New bulb found: ' + b.name);
+ console.log('New bulb found: ' + b.name + " : " + b.addr.toString("hex"));
});
lx.on('gateway', function(g) {
@@ -72,12 +72,16 @@ stdin.on('data', function (key) {
case 0x31: // 1
console.log("Lights on");
// lx.lightsOn('Bedroom Lamp'); // Can specify one bulb by name
- lx.lightsOn();
+ var b = lx.bulbs['d073d5014163'];
+ lx.lightsOn(b);
+// lx.lightsOn();
break;
case 0x32: // 2
console.log("Lights off");
- lx.lightsOff();
+ var b = lx.bulbs['d073d5014163'];
+ lx.lightsOff(b);
+// lx.lightsOff();
break;
case 0x33: // 3
diff --git a/lifx.js b/lifx.js
index <HASH>..<HASH> 100644
--- a/lifx.js
+++ b/lifx.js
@@ -80,8 +80,14 @@ Lifx.prototype._setupPacketListener = function() {
case 'panGateway':
// Got a notification of a gateway. Check if it's new, using valid UDP, and if it is then handle accordingly
if (pkt.payload.service == 1 && pkt.payload.port > 0) {
- var gw = {ip:rinfo.address, port:pkt.payload.port, site:pkt.preamble.site};
+ var gw = {ip:rinfo.address, port:pkt.payload.port, site:pkt.preamble.site,
+ service: pkt.payload.service,
+ protocol: pkt.preamble.protocol,
+ bulbAddress: pkt.preamble.bulbAddress.toString("hex")
+ };
+
if (!self.gateways[gw.ip]) {
+ console.log(JSON.stringify(gw));
self.gateways[gw.ip] = gw;
self.emit('gateway', gw);
}
@@ -134,27 +140,38 @@ Lifx.prototype.close = function() {
Lifx.prototype._sendToOneOrAll = function(command, bulb) {
var self = this;
- _(this.gateways).each(function(gw, ip) {
- var siteAddress = gw.site;
- siteAddress.copy(command, 16);
- if (typeof bulb == 'undefined') {
- self._sendPacket(gw.ip, gw.port, command);
+
+// var gw = this.gateways["192.168.0.103"];
+
+ var bulbAddress = null;
+
+ if (typeof bulb != 'undefined') {
+ // Overwrite the bulb address here
+ if (Buffer.isBuffer(bulb)) {
+ bulbAddress = bulb;
+ } else if (typeof bulb.addr != 'undefined') {
+ bulbAddress = bulb.addr;
} else {
- // Overwrite the bulb address here
- var target;
- if (Buffer.isBuffer(bulb)) {
- target = bulb;
- } else if (typeof bulb.addr != 'undefined') {
- target = bulb.addr;
- } else {
- // Check if it's a recognised bulb name
- if (!self.bulbs[bulb.addr.toString('hex')]) {
- throw "Unknown bulb: " + bulb;
- }
+ // Check if it's a hex string of a known bulb addr
+ var b = self.bulbs[bulb]
+ if (b) {
+ bulbAddress = b.addr;
+ }
+ else {
+ throw "Unknown bulb: " + bulb;
}
- target.copy(command, 8);
- self._sendPacket(gw.ip, gw.port, command);
}
+ console.log("bulb target addr: " + bulbAddress.toString("hex"));
+ bulbAddress.copy(command, 8);
+ }
+
+ _(this.gateways).each(function(gw, ip) {
+ var siteAddress = gw.site;
+ siteAddress.copy(command, 16);
+
+ console.log("command: " + command.toString("hex"));
+
+ self._sendPacket(gw.ip, gw.port, command);
});
};
diff --git a/packet.js b/packet.js
index <HASH>..<HASH> 100644
--- a/packet.js
+++ b/packet.js
@@ -81,7 +81,9 @@ packet.fromParams = function(p) {
break;
case 'protocol':
if (typeof p[f.name] == 'undefined') {
- datum = 0x3400;
+// datum = 0x5400;
+// datum = 0x3400;
+ datum = 0x1400;
} else {
datum = p[f.name];
} | Force protocol 0x<I> for now | magicmonkey_lifxjs | train |
2b23af1bd0d96c8309885a275dd586aa728c92fb | diff --git a/butterknife/src/main/java/butterknife/internal/TargetClass.java b/butterknife/src/main/java/butterknife/internal/TargetClass.java
index <HASH>..<HASH> 100644
--- a/butterknife/src/main/java/butterknife/internal/TargetClass.java
+++ b/butterknife/src/main/java/butterknife/internal/TargetClass.java
@@ -110,7 +110,13 @@ class TargetClass {
.append(" @Override public void onClick(View view) {\n")
.append(" target.").append(method.name).append("(");
if (method.type != null) {
- builder.append("(").append(method.type).append(") view");
+ // Only emit a cast if the type is not View.
+ if (!VIEW_TYPE.equals(method.type)) {
+ builder.append("(")
+ .append(method.type)
+ .append(") ");
+ }
+ builder.append("view");
}
builder.append(");\n")
.append(" }\n")
diff --git a/butterknife/src/test/java/butterknife/internal/OnClickTest.java b/butterknife/src/test/java/butterknife/internal/OnClickTest.java
index <HASH>..<HASH> 100644
--- a/butterknife/src/test/java/butterknife/internal/OnClickTest.java
+++ b/butterknife/src/test/java/butterknife/internal/OnClickTest.java
@@ -108,7 +108,7 @@ public class OnClickTest {
" }",
" view.setOnClickListener(new View.OnClickListener() {",
" @Override public void onClick(View view) {",
- " target.click1((android.view.View) view);",
+ " target.click1(view);",
" }",
" });",
" view = finder.findById(source, 2);", | Do no emit redudant cast to view inside of method click handler. | JakeWharton_butterknife | train |
74633211b463a8a816463e71064c286ea281f74f | diff --git a/lib/sync.js b/lib/sync.js
index <HASH>..<HASH> 100644
--- a/lib/sync.js
+++ b/lib/sync.js
@@ -92,9 +92,11 @@ Function.prototype.async = function(obj)
return fn.apply(obj, args);
}, cb)
}
- // Call synchronously
+ // Call synchronously in new fiber
else {
- return fn.apply(obj, args);
+ return Fiber(function(){
+ return fn.apply(obj, args);
+ }).run();
}
}
} | call async() function in new Fiber even if it is already in a Fiber (blocking issue) | ybogdanov_node-sync | train |
608cdb078174627b29bd1e17ece42433a72afd18 | diff --git a/src/sd_plot.py b/src/sd_plot.py
index <HASH>..<HASH> 100644
--- a/src/sd_plot.py
+++ b/src/sd_plot.py
@@ -11,7 +11,7 @@ import crtomo.grid as CRGrid
import matplotlib.pyplot as plt
import matplotlib
import math
-import edf.main.units as units
+import reda.main.units as units
import crtomo.mpl as mpl_style
diff --git a/src/td_plot.py b/src/td_plot.py
index <HASH>..<HASH> 100644
--- a/src/td_plot.py
+++ b/src/td_plot.py
@@ -41,7 +41,7 @@ import crtomo.grid as CRGrid
import matplotlib.pyplot as plt
import matplotlib
import math
-import edf.main.units as units
+import reda.main.units as units
import crtomo.mpl as mpl_style
import matplotlib as mpl
@@ -969,7 +969,7 @@ def create_hlammagplot(plotman, h, ratio, alpha, options):
cidv = plotman.parman.add_data(
np.log10(np.divide(np.power(10, h), np.power(10, ratio))))
loglin = 'log_rho'
-
+
cidr = plotman.parman.add_data(np.power(10, ratio))
plot_mag(cidh, ax[0], plotman, 'horizontal', loglin, alpha,
options.mag_vmin, options.mag_vmax,
@@ -1002,7 +1002,7 @@ def create_hlamphaplot(plotman, h, v, alpha, options):
plt.subplots_adjust(wspace=1, top=0.8)
cidh = plotman.parman.add_data(h)
cidv = plotman.parman.add_data(v)
-
+
cidr = plotman.parman.add_data(np.subtract(h, v))
plot_pha(cidh, ax[0], plotman, 'horizontal', alpha,
options.pha_vmin, options.pha_vmax, | fix some imports from edf to reda | geophysics-ubonn_crtomo_tools | train |
17ac25f6124a232e697dc60feb2cb440181e11fa | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,11 +5,14 @@ import sys
import codecs
import platform
from glob import glob
+import warnings
+import exceptions
from setuptools import setup
from setuptools import Extension
from setuptools.command.build_ext import build_ext
+
"""
this parameter is used to opt out numpy support in _jpype library
"""
@@ -19,6 +22,10 @@ if "--disable-numpy" in sys.argv:
else:
disabled_numpy = False
+class FeatureNotice(exceptions.Warning):
+ """ indicate notices about features """
+ pass
+
def read_utf8(*parts):
filename = os.path.join(os.path.dirname(__file__), *parts)
@@ -138,8 +145,13 @@ if not disabled_numpy:
platform_specific['define_macros'] = [('HAVE_NUMPY', 1)]
platform_specific['include_dirs'].append(numpy.get_include())
+ warnings.warn("Turned ON Numpy support for fast Java array access",
+ FeatureNotice)
except ImportError:
pass
+else:
+ warnings.warn("Turned OFF Numpy support for fast Java array access",
+ FeatureNotice)
jpypeLib = Extension(name='_jpype', **platform_specific) | [setup] inform user about feature being turned on/off (currently only numpy) | jpype-project_jpype | train |
f11f2fe2ab7e8149813b887543b84946da7c617f | diff --git a/gulpfile.babel.js b/gulpfile.babel.js
index <HASH>..<HASH> 100644
--- a/gulpfile.babel.js
+++ b/gulpfile.babel.js
@@ -93,7 +93,7 @@ gulp.task('copy:.htaccess', () =>
gulp.task('copy:index.html', (done) =>
sri.hash('node_modules/jquery/dist/jquery.min.js', (err, hash) => {
- if (err) throw err
+ if (err) throw err;
let version = pkg.devDependencies.jquery;
let modernizrVersion = pkg.devDependencies.modernizr;
@@ -183,14 +183,14 @@ gulp.task('archive', (done) => {
'build',
'archive:create_archive_dir',
'archive:zip',
- done)
+ done);
});
gulp.task('build', (done) => {
runSequence(
['clean', 'lint:js'],
'copy', 'modernizr',
- done)
+ done);
});
gulp.task('default', ['build']); | Fixed JSHint errors (#<I>) | h5bp_html5-boilerplate | train |
865807b155f981ad590c01690af69ed86d051155 | diff --git a/bundles/org.eclipse.orion.client.ui/web/css/images.css b/bundles/org.eclipse.orion.client.ui/web/css/images.css
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/css/images.css
+++ b/bundles/org.eclipse.orion.client.ui/web/css/images.css
@@ -18,6 +18,8 @@
vertical-align: middle;
}
+.core-sprite-progress{ background-image: url(../images/progress_running.gif); background-repeat: no-repeat; width: 16px; height: 16px; }
+
/* Individual sprites
* These classes are generated by a sprite builder. Do not edit manually.
* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=360041#c5 for instructions.
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer.js b/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer.js
+++ b/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer.js
@@ -418,6 +418,7 @@ exports.ExplorerRenderer = (function() {
this._init(options);
this._expandImageClass = "core-sprite-openarrow"; //$NON-NLS-0$
this._collapseImageClass = "core-sprite-closedarrow"; //$NON-NLS-0$
+ this._progressImageClass = "core-sprite-progress"; //$NON-NLS-0$
this._twistieSpriteClass = "modelDecorationSprite"; //$NON-NLS-0$
}
ExplorerRenderer.prototype = {
@@ -631,8 +632,10 @@ exports.ExplorerRenderer = (function() {
updateExpandVisuals: function(tableRow, isExpanded) {
var expandImage = lib.node(this.expandCollapseImageId(tableRow.id));
if (expandImage) {
- expandImage.classList.add(isExpanded ? this._expandImageClass : this._collapseImageClass);
- expandImage.classList.remove(isExpanded ? this._collapseImageClass : this._expandImageClass);
+ expandImage.classList.remove(this._expandImageClass);
+ expandImage.classList.remove(this._collapseImageClass);
+ expandImage.classList.remove(this._progressImageClass);
+ expandImage.classList.add(isExpanded === "progress" ? this._progressImageClass : isExpanded ? this._expandImageClass : this._collapseImageClass); //$NON-NLS-0$
}
},
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/webui/treetable.js b/bundles/org.eclipse.orion.client.ui/web/orion/webui/treetable.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/orion/webui/treetable.js
+++ b/bundles/org.eclipse.orion.client.ui/web/orion/webui/treetable.js
@@ -185,15 +185,17 @@ define(['i18n!orion/nls/messages', 'orion/webui/littlelib'], function(messages,
// If the row should be expanded
if (row && (forceExpand || row._expanded)) {
this._removeChildRows(parentId);
- this._renderer.updateExpandVisuals(row, true);
if(children){
row._expanded = true;
+ this._renderer.updateExpandVisuals(row, true);
this._generateChildren(children, row._depth+1, row); //$NON-NLS-0$
this._rowsChanged();
} else {
tree = this;
+ this._renderer.updateExpandVisuals(row, "progress"); //$NON-NLS-0$
children = this._treeModel.getChildren(row._item, function(children) {
if (tree.destroyed) { return; }
+ tree._renderer.updateExpandVisuals(row, true);
if (!row._expanded) {
row._expanded = true;
tree._generateChildren(children, row._depth+1, row); //$NON-NLS-0$
@@ -225,11 +227,9 @@ define(['i18n!orion/nls/messages', 'orion/webui/littlelib'], function(messages,
if (row) {
if (row._expanded) {
this.collapse(id);
- this._renderer.updateExpandVisuals(row, false);
}
else {
this.expand(id);
- this._renderer.updateExpandVisuals(row, true);
}
}
},
@@ -251,9 +251,10 @@ define(['i18n!orion/nls/messages', 'orion/webui/littlelib'], function(messages,
return;
}
var tree = this;
- this._renderer.updateExpandVisuals(row, true);
+ this._renderer.updateExpandVisuals(row, "progress"); //$NON-NLS-0$
this._treeModel.getChildren(row._item, function(children) {
if (tree.destroyed) { return; }
+ tree._renderer.updateExpandVisuals(row, true);
if (!row._expanded) {
row._expanded = true;
tree._generateChildren(children, row._depth+1, row); //$NON-NLS-0$ | Bug <I> - [Navigator]Expanding a folder needs progressing indication. | eclipse_orion.client | train |
223ec28965661e36da68476bf1cb50d5719e34a2 | diff --git a/Commands/ConfigTrait.php b/Commands/ConfigTrait.php
index <HASH>..<HASH> 100644
--- a/Commands/ConfigTrait.php
+++ b/Commands/ConfigTrait.php
@@ -26,7 +26,7 @@ trait ConfigTrait
->addOption('bootstrap', null, InputOption::VALUE_OPTIONAL, 'The class that will be used to bootstrap your application', 'PHPPM\Bootstraps\Symfony')
->addOption('php-cgi', null, InputOption::VALUE_OPTIONAL, 'Full path to the php-cgi executable', false);
}
-
+
protected function renderConfig(OutputInterface $output, array $config)
{
$table = new Table($output);
@@ -39,12 +39,29 @@ trait ConfigTrait
$table->render();
}
+ /**
+ * @return string|null
+ */
+ protected function getConfigPath()
+ {
+ $possiblePaths = [
+ $this->file,
+ sprintf('%s/%s', dirname($GLOBALS['argv'][0]), $this->file)
+ ];
+
+ foreach ($possiblePaths as $path) {
+ if (file_exists($path)) {
+ return realpath($path);
+ }
+ }
+ }
+
protected function loadConfig(InputInterface $input)
{
$config = [];
- if (file_exists($this->file)) {
- $content = file_get_contents($this->file);
+ if ($path = $this->getConfigPath()) {
+ $content = file_get_contents($path);
$config = json_decode($content, true);
}
diff --git a/Commands/StartCommand.php b/Commands/StartCommand.php
index <HASH>..<HASH> 100644
--- a/Commands/StartCommand.php
+++ b/Commands/StartCommand.php
@@ -35,13 +35,13 @@ class StartCommand extends Command
}
$config = $this->loadConfig($input);
- if (file_exists($this->file)) {
+ if ($path = $this->getConfigPath()) {
$modified = '';
- $fileConfig = json_decode(file_get_contents($this->file), true);
+ $fileConfig = json_decode(file_get_contents($path), true);
if (json_encode($fileConfig) !== json_encode($config)) {
$modified = ', modified by command arguments';
}
- $output->writeln(sprintf('<info>Read configuration %s%s.</info>', realpath($this->file), $modified));
+ $output->writeln(sprintf('<info>Read configuration %s%s.</info>', $path, $modified));
}
$output->writeln(sprintf('<info>%s</info>', getcwd())); | Added functionality back where it was possible to have ppm.json inside dependency.
Fixed #<I> | php-pm_php-pm | train |
fddaec1c624c057e6d34ca5dd5bf1598bbe724d4 | diff --git a/mzidplus.py b/mzidplus.py
index <HASH>..<HASH> 100755
--- a/mzidplus.py
+++ b/mzidplus.py
@@ -46,13 +46,12 @@ parser.add_argument('-c', dest='command', type=str,
'PSMs. Needs to be passed a lookup db with --dbfile,\n'
'which has to contain quant information, and\n'
'optionally --isobaric, --precursor, --rttol, --mztol,\n'
- '--spectracolumn changes the column where the spectra\n'
+ '--spectracol changes the column where the spectra\n'
'file names are in from the standard #SpecFile column.\n'
- 'proteingroup - Takes lookup SQLite result from \n'
- 'proteingrouplookup, uses it to output mzidtsv file with\n'
- 'protein groups. With flags --confidence-lvl, \n'
- '--confidence-col, --confidence-better, --fasta\n'
- '--dbfile\n',
+ 'proteingroup - Takes lookup SQLite result, uses it\n'
+ 'to output mzidtsv file with protein groups\n'
+ 'With flags --confidence-lvl, --confidence-col,\n'
+ '--confidence-better, --fasta, --dbfile, --spectracol\n',
required=True
)
parser.add_argument('-i', dest='infile', help='TSV table of mzIdentML',
@@ -102,7 +101,7 @@ parser.add_argument('--mztoltype', dest='mztoltype', help='Type of tolerance\n'
'to identifications in the PSM table. One of ppm, Da.',
type=lambda x: parser_value_in_list(parser, x, ['ppm',
'Da']))
-parser.add_argument('--spectracolumn', dest='speccol', help='Column number\n'
+parser.add_argument('--spectracol', dest='speccol', help='Column number\n'
'in which spectra file names are, in case some framework\n'
'has changed the file names. First column number is 1.',
type=int, required=False) | Some changes in mzidplus executable | glormph_msstitch | train |
5af1fa99c567f6747e38897334dfee360ffa9a31 | diff --git a/webpack.config.js b/webpack.config.js
index <HASH>..<HASH> 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -1,5 +1,5 @@
const path = require('path')
-const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
+const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
var NPM_RUN = process.env.npm_lifecycle_event | style(webpack.config): use single quotes | clappr_dash-shaka-playback | train |
ee2dd78b3dcd0560c8aecbb5ab51ac5860846d20 | diff --git a/modules/backend/widgets/Lists.php b/modules/backend/widgets/Lists.php
index <HASH>..<HASH> 100644
--- a/modules/backend/widgets/Lists.php
+++ b/modules/backend/widgets/Lists.php
@@ -921,6 +921,16 @@ class Lists extends WidgetBase
}
/**
+ * Common mistake, relation is not a valid list column.
+ * @deprecated Remove if year >= 2018
+ */
+ protected function evalRelationTypeValue($record, $column, $value)
+ {
+ traceLog(sprintf('Warning: List column type "relation" for class "%s" is not valid.', get_class($record)));
+ return $this->evalTextTypeValue($record, $column, $value);
+ }
+
+ /**
* Process as partial reference
*/
protected function evalPartialTypeValue($record, $column, $value) | Exception handling for type: relation
It would appear many plugins incorrectly use type: relation as a list column, when this does nothing. Previously it would fallback to the text type, now that invalid types fail hard, this adds a softer landing by spamming the trace log instead.
Refs #<I> | octobercms_october | train |
ed4acc940a229186288eaf201caad3ab6c47475d | diff --git a/carmen/cli.py b/carmen/cli.py
index <HASH>..<HASH> 100644
--- a/carmen/cli.py
+++ b/carmen/cli.py
@@ -62,7 +62,7 @@ def main():
resolvers.append(ProfileResolver())
resolver = LocationResolver(resolvers)
for line in args.locations_file:
- resolver.add_location(Location(**json.loads(line)))
+ resolver.add_location(Location(known=True, **json.loads(line)))
# Variables for statistics.
city_found = county_found = state_found = country_found = 0
has_place = has_coordinates = has_geo = has_profile_location = 0 | Set Location.known to True where appropriate | mdredze_carmen-python | train |
466cfa2df4d03dfd3af303679fb42f488680ba0f | diff --git a/bugwarrior/db.py b/bugwarrior/db.py
index <HASH>..<HASH> 100644
--- a/bugwarrior/db.py
+++ b/bugwarrior/db.py
@@ -242,6 +242,52 @@ def find_local_uuid(tw, keys, issue, legacy_matching=True):
)
+def merge_annotations(remote_issue, local_task):
+ """ Merge annotations from the local task into the remote issue dict
+
+ If there are new annotations in the remote issue that do not appears in the
+ local task, additionally return True signalling that the new remote
+ annotations should be synched to the db.
+ """
+
+ # Ensure that empty defaults are present
+ remote_issue['annotations'] = remote_issue.get('annotations', [])
+ local_task['annotations'] = local_task.get('annotations', [])
+
+ # Setup some shorthands
+ remote_annotations = [a for a in remote_issue['annotations']]
+ local_annotations = [a['description'] for a in local_task['annotations']]
+
+ # Do two things.
+ # * If a local does not appears in remote, then add it there so users can
+ # maintain their own list of locals.
+ # * If a remote does not appear in local, then return True
+
+ # Part 1
+ for local in local_annotations:
+ for remote in remote_annotations:
+ if get_annotation_hamming_distance(remote, local) == 0:
+ remote_issue['annotations'].append(local)
+ break
+
+ # Part 2
+ for remote in remote_annotations:
+ found = False
+ for local in local_annotations:
+ if get_annotation_hamming_distance(remote, local) == 0:
+ found = True
+ break
+
+ # Then we have a new remote annotation that should be synced locally.
+ if not found:
+ log.name('db').debug(
+ "%s not found in %r" % (remote, local_annotations))
+ return True
+
+ # Otherwise, we found all of our remotes in our local annotations.
+ return False
+
+
def synchronize(issue_generator, conf):
def _bool_option(section, option, default):
@@ -293,22 +339,11 @@ def synchronize(issue_generator, conf):
_, task = tw.get_task(uuid=existing_uuid)
task_copy = copy.deepcopy(task)
- # Handle merging annotations
- annotations_changed = False
- for annotation in [
- a['description'] for a in task.get('annotations', [])
- ]:
- if not 'annotations' in issue_dict:
- issue_dict['annotations'] = []
- found = False
- for new_annot in issue_dict['annotations']:
- if get_annotation_hamming_distance(
- new_annot, annotation
- ) == 0:
- found = True
- if not found:
- annotations_changed = True
- issue_dict['annotations'].append(annotation)
+
+ annotations_changed = merge_annotations(issue_dict, task)
+
+ if annotations_changed:
+ log.name('db').debug("%s annotations changed." % existing_uuid)
# Merging tags, too
for tag in task.get('tags', []): | Break out and fix "merge_annotations" | ralphbean_bugwarrior | train |
6264f51ba157479b0aa22b47bc670379ed385e36 | diff --git a/providers/peerconnection.unprivileged.js b/providers/peerconnection.unprivileged.js
index <HASH>..<HASH> 100644
--- a/providers/peerconnection.unprivileged.js
+++ b/providers/peerconnection.unprivileged.js
@@ -125,7 +125,10 @@ PeerConnection_unprivileged.prototype.makeAnswer = function() {
PeerConnection_unprivileged.prototype.onIdentity = function(msg) {
try {
- var m = JSON.parse(msg.data);
+ var m = msg.data;
+ if (typeof msg.data === "string") {
+ m = JSON.parse(msg.data);
+ }
if (m['candidate']) {
var candidate = new RTCIceCandidate(m);
this.connection.addIceCandidate(candidate); | messages weren't always getting serialized in transit | freedomjs_freedom | train |
09aacf7a80949a5c941dfafe8174d1c561e3e036 | diff --git a/lib/rspec/benchmark/timing_matcher.rb b/lib/rspec/benchmark/timing_matcher.rb
index <HASH>..<HASH> 100644
--- a/lib/rspec/benchmark/timing_matcher.rb
+++ b/lib/rspec/benchmark/timing_matcher.rb
@@ -24,7 +24,7 @@ module RSpec
return false unless block.is_a?(Proc)
@bench = ::Benchmark::Performance.new
@average, @stddev = @bench.run(@samples, &block)
- (@average - 3 * @stddev) <= @threshold
+ @average <= @threshold
end
def does_not_match?(block) | Remove error confidence from timing matcher. | piotrmurach_rspec-benchmark | train |
2484443aa84c0e0e2e88a401cefc8062f54a0374 | diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -350,9 +350,7 @@ module ActiveRecord
# Initialize an empty model object from +attributes+.
# +attributes+ should be an attributes object, and unlike the
# `initialize` method, no assignment calls are made per attribute.
- #
- # :nodoc:
- def init_with_attributes(attributes, new_record = false)
+ def init_with_attributes(attributes, new_record = false) # :nodoc:
init_internals
@new_record = new_record | Bring ActiveRecord::Core's API document back [ci skip]
If exist `:nodoc:` before method define, it affects all subsequent
method definitions. | rails_rails | train |
c770578d4eac6fb403f0bdc5ef95cb0caac07ed4 | diff --git a/build/rpm.rb b/build/rpm.rb
index <HASH>..<HASH> 100644
--- a/build/rpm.rb
+++ b/build/rpm.rb
@@ -58,7 +58,7 @@ namespace :package do
test_setup
create_tarball(@verbosity)
# Add a single -v for some feedback
- noisy_system(*(%w{./rpm/release/build.rb --single} + @build_verbosity))
+ noisy_system(*(%w{./rpm/release/build.rb --single --stage-dir=pkg} + @build_verbosity))
end
desc "Build a Yum repository for the current release" | Change the staging directory to "pkg" for the package:rpm rake task. | phusion_passenger | train |
310b4a69d9defeb91f141583b3a8fcccc7301daa | diff --git a/spec/dummy/app/controllers/application_controller.rb b/spec/dummy/app/controllers/application_controller.rb
index <HASH>..<HASH> 100644
--- a/spec/dummy/app/controllers/application_controller.rb
+++ b/spec/dummy/app/controllers/application_controller.rb
@@ -2,16 +2,4 @@ class ApplicationController < ActionController::Base
include RailsJwtAuth::WardenHelper
protect_from_forgery with: :exception
-
- rescue_from ActionController::ParameterMissing do |exception|
- render json: {exception.param => 'is required'}, status: 422
- end
-
- rescue_from ActiveRecord::RecordNotFound do
- render json: {}, status: 404
- end
-
- rescue_from Mongoid::Errors::DocumentNotFound do
- render json: {}, status: 404
- end
end | Rescues removed from dummy. | rjurado01_rails_jwt_auth | train |
5283ec938a5f2663126061e3f43bc85c0ded3af1 | diff --git a/pkg/option/config.go b/pkg/option/config.go
index <HASH>..<HASH> 100644
--- a/pkg/option/config.go
+++ b/pkg/option/config.go
@@ -1230,7 +1230,7 @@ type DaemonConfig struct {
RunDir string // Cilium runtime directory
NAT46Prefix *net.IPNet // NAT46 IPv6 Prefix
Devices []string // bpf_host device
- DirectRoutingDevice string // Direct routing device (used only by NodePort BPF)
+ DirectRoutingDevice string // Direct routing device (used by BPF NodePort and BPF Host Routing)
LBDevInheritIPAddr string // Device which IP addr used by bpf_host devices
EnableXDPPrefilter bool // Enable XDP-based prefiltering
DevicePreFilter string // Prefilter device
@@ -2328,6 +2328,15 @@ func (c *DaemonConfig) K8sLeasesFallbackDiscoveryEnabled() bool {
return c.K8sEnableAPIDiscovery
}
+// DirectRoutingDeviceRequired return whether the Direct Routing Device is needed under
+// the current configuration.
+func (c *DaemonConfig) DirectRoutingDeviceRequired() bool {
+ // BPF NodePort and BPF Host Routing are using the direct routing device now.
+ // When tunneling is enabled, node-to-node redirection will be done by tunneling.
+ BPFHostRoutingEnabled := !c.EnableHostLegacyRouting
+ return (c.EnableNodePort || BPFHostRoutingEnabled) && !c.TunnelingEnabled()
+}
+
// EnableK8sLeasesFallbackDiscovery enables using direct API probing as a fallback to check
// for the support of Leases when discovering API groups is not possible.
func (c *DaemonConfig) EnableK8sLeasesFallbackDiscovery() { | datapath: Introduce DirectRoutingDeviceRequired helper
The Direct Routing Device is currently used by BPF Host
Routing and BPF Node Port. With both features, we don't
need it for tunneling mode. The DirectRoutingDeviceRequired
helper function checks the above conditions and returns if
the Direct Routing Device is required for the given
configuration.
Upcoming commits will fix several places that use Direct
Routing Device without tunneling or BPF Host Routing in
an account using DirectRoutingDeviceRequired. | cilium_cilium | train |
96ba8cd595ac47706416013f42730f77f04bf2cc | diff --git a/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java b/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java
index <HASH>..<HASH> 100644
--- a/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java
+++ b/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java
@@ -346,7 +346,7 @@ public class DiscoveryClient implements EurekaClient {
}
}
- if(backupRegistryInstance == null) {
+ if (backupRegistryInstance == null) {
logger.warn("Using default backup registry implementation which does not do anything.");
backupRegistryInstance = new NotImplementedRegistryImpl();
}
@@ -400,11 +400,21 @@ public class DiscoveryClient implements EurekaClient {
heartbeatExecutor = new ThreadPoolExecutor(
1, clientConfig.getHeartbeatExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
- new SynchronousQueue<Runnable>()); // use direct handoff
+ new SynchronousQueue<Runnable>(),
+ new ThreadFactoryBuilder()
+ .setNameFormat("DiscoveryClient-HeartbeatExecutor-%d")
+ .setDaemon(true)
+ .build()
+ ); // use direct handoff
cacheRefreshExecutor = new ThreadPoolExecutor(
1, clientConfig.getCacheRefreshExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
- new SynchronousQueue<Runnable>()); // use direct handoff
+ new SynchronousQueue<Runnable>(),
+ new ThreadFactoryBuilder()
+ .setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d")
+ .setDaemon(true)
+ .build()
+ ); // use direct handoff
fetchRegistryGeneration = new AtomicLong(0);
@@ -1391,7 +1401,7 @@ public class DiscoveryClient implements EurekaClient {
if (lastRedirectUrl != null) {
try {
ClientResponse clientResponse = makeRemoteCall(action, lastRedirectUrl);
- if(clientResponse == null) {
+ if (clientResponse == null) {
return null;
}
int status = clientResponse.getStatus();
@@ -1448,7 +1458,7 @@ public class DiscoveryClient implements EurekaClient {
URI targetUrl = new URI(serviceUrl);
for (int followRedirectCount = 0; followRedirectCount < MAX_FOLLOWED_REDIRECTS; followRedirectCount++) {
ClientResponse clientResponse = makeRemoteCall(action, targetUrl.toString());
- if(clientResponse == null) {
+ if (clientResponse == null) {
return null;
}
if (clientResponse.getStatus() != 302) { | Thread pools in eureka-client create non-daemon threads | Netflix_eureka | train |
6397a7f5e82d24b0929aee1a5ecc4b7de5c78e96 | diff --git a/views/js/controller/creator/main.js b/views/js/controller/creator/main.js
index <HASH>..<HASH> 100755
--- a/views/js/controller/creator/main.js
+++ b/views/js/controller/creator/main.js
@@ -212,8 +212,10 @@ define([
//"post-render it" to initialize the widget
var widget = item.postRender(_.clone(configProperties));
- _.each(item.getElements('include'), function(xinclude){
- xincludeRenderer.render(xinclude.data('widget'), config.properties.baseUrl);
+ _.each(item.getComposingElements(), function(element){
+ if(element.qtiClass === 'include'){
+ xincludeRenderer.render(element.data('widget'), config.properties.baseUrl);
+ }
});
editor.initGui(widget, configProperties); | render xinclude in all composing elements of the item | oat-sa_extension-tao-itemqti | train |
46c1378f345c8290fa34fc7f756ef6fafa8e2aa8 | diff --git a/lucid/modelzoo/aligned_activations.py b/lucid/modelzoo/aligned_activations.py
index <HASH>..<HASH> 100644
--- a/lucid/modelzoo/aligned_activations.py
+++ b/lucid/modelzoo/aligned_activations.py
@@ -32,6 +32,5 @@ def get_aligned_activations(layer):
PATH_TEMPLATE.format(sanitize(layer.model_class.name), sanitize(layer.name), page)
for page in range(NUMBER_OF_PAGES)
]
- print(activation_paths)
activations = [load(path) for path in activation_paths]
return np.vstack(activations) | Remove stray print statement O_o | tensorflow_lucid | train |
d2ce5a01a47debb9739e287c8a4ca43d77c2dad6 | diff --git a/lib/mpv/mpv.js b/lib/mpv/mpv.js
index <HASH>..<HASH> 100644
--- a/lib/mpv/mpv.js
+++ b/lib/mpv/mpv.js
@@ -87,62 +87,78 @@ mpv.prototype = Object.assign({
})
);
}
+ else{
+ // socket to observe the command
+ const observeSocket = net.Socket();
+ observeSocket.connect({path: this.options.socket}, () =>{
+ // send the command to mpv
+ return this.socket.command('loadfile', options ? [file, mode].concat(util.formatOptions(options)) : [file, mode])
+ .then(() => {
+ // get the playlist size
+ return this.getPlaylistSize();
+ })
+ .then((playlistSize) => {
+ // if the mode is append resolve the promise because nothing
+ // will be output by the mpv player
+ // checking whether this file can be played or not is done when
+ // the file is played
+ if(mode === 'append'){
+ observeSocket.destroy();
+ return resolve();
+ }
+ // if the mode is append-play and there are already songs in the playlist
+ // resolve the promise since nothing will be output
+ if(mode === 'append-play' && playlistSize > 1){
+ observeSocket.destroy();
+ return resolve();
+ }
- // socket to observe the command
- let observeSocket = net.Socket();
- observeSocket.connect({path: this.options.socket}, () =>{
- // send the command to mpv
- this.socket.command('loadfile', options ? [file, mode].concat(util.formatOptions(options)) : [file, mode]);
-
- // if the mode is append resolve the promise because nothing
- // will be output by the mpv player
- // checking whether this file can be played or not is done when
- // the file is played
- if(mode === 'append'){
- return resolve();
- }
-
- // timeout
- let timeout = 0;
- // check if the file was started
- let started = false;
-
- observeSocket.on('data', (data) => {
- // increase timeout
- timeout += 1;
- // parse the messages from the socket
- let messages = data.toString('utf-8').split('\n');
- // check every message
- messages.forEach((message) => {
- // ignore empty messages
- if(message.length > 0){
- message = JSON.parse(message);
- if('event' in message){
- if(message.event === 'start-file'){
- started = true;
- }
- // when the file has successfully been loaded resolve the promise
- else if(message.event === 'file-loaded' && started){
- observeSocket.destroy();
- // resolve the promise
- resolve();
- }
- // when the track has changed we don't need a seek event
- else if (message.event === 'end-file' && started){
- observeSocket.destroy();
- reject(this.errorHandler.errorMessage(0, caller, [file]));
+ // timeout
+ let timeout = 0;
+ // check if the file was started
+ let started = false;
+
+ observeSocket.on('data', (data) => {
+ // increase timeout
+ timeout += 1;
+ // parse the messages from the socket
+ const messages = data.toString('utf-8').split('\n');
+ // check every message
+ messages.forEach((message) => {
+ // ignore empty messages
+ if(message.length > 0){
+ message = JSON.parse(message);
+ if('event' in message){
+ if(message.event === 'start-file'){
+ started = true;
+ }
+ // when the file has successfully been loaded resolve the promise
+ else if(message.event === 'file-loaded' && started){
+ observeSocket.destroy();
+ // resolve the promise
+ return resolve();
+ }
+ // when the track has changed we don't need a seek event
+ else if (message.event === 'end-file' && started){
+ observeSocket.destroy();
+ return reject(this.errorHandler.errorMessage(0, caller, [file]));
+ }
+ }
}
+ });
+ // reject the promise if it took to long until the playback-restart happens
+ // to prevent having sockets listening forever
+ if(timeout > 10){
+ observeSocket.destroy();
+ return reject(this.errorHandler.errorMessage(5, caller, [file]));
}
- }
+ });
+
});
- // reject the promise if it took to long until the playback-restart happens
- // to prevent having sockets listening forever
- if(timeout > 10){
- observeSocket.destroy();
- reject(this.errorHandler.errorMessage(5, caller, [file]));
- }
});
- });
+
+ }
+
});
}, | Fixed a bug with load() and append()
If the mode was set to 'append-play' and the track was not the only one in the playlist the promise did not resolve. This is fixed | 00SteinsGate00_Node-MPV | train |
1ea5f990e54d8feee7f2e821f070765145eafd71 | diff --git a/src/audio_metadata/formats/mp3.py b/src/audio_metadata/formats/mp3.py
index <HASH>..<HASH> 100644
--- a/src/audio_metadata/formats/mp3.py
+++ b/src/audio_metadata/formats/mp3.py
@@ -508,7 +508,7 @@ class MP3StreamInfo(StreamInfo):
if frame._xing:
break
data.seek(frame._start + frame._size, os.SEEK_SET)
- except InvalidFrame:
+ except (InvalidFrame, bitstruct.Error):
data.seek(1, os.SEEK_CUR)
break
else: | Catch bitstruct.error when trying to load MPEG frames
Prevents failures when trying to detect false positives. | thebigmunch_audio-metadata | train |
90eeb8902853e46417596e7c5aedf2d7b4f26232 | diff --git a/cyipopt/utils.py b/cyipopt/utils.py
index <HASH>..<HASH> 100644
--- a/cyipopt/utils.py
+++ b/cyipopt/utils.py
@@ -10,9 +10,6 @@ from functools import wraps
from ipopt_wrapper import Problem
-__all__ = ["problem"]
-
-
def deprecated_warning(new_name):
"""Decorator that issues a FutureWarning for deprecated functionality. | Remove __all__ as empty | matthias-k_cyipopt | train |
a425ca934f00b3064fc58ae90e0214ed905c33d5 | diff --git a/shared/util_linux.go b/shared/util_linux.go
index <HASH>..<HASH> 100644
--- a/shared/util_linux.go
+++ b/shared/util_linux.go
@@ -453,7 +453,7 @@ func Major(dev uint64) int {
}
func Minor(dev uint64) int {
- return int((dev & 0xff) | ((dev >> 12) & (0xfff00)))
+ return int((dev & 0xff) | ((dev >> 12) & (0xffffff00)))
}
func GetFileStat(p string) (uid int, gid int, major int, minor int, | Take all <I> bits of minor device number | lxc_lxd | train |
6a2f22f10d79b035627491611b501dd110b4b70f | diff --git a/lib/flipper/spec/shared_adapter_specs.rb b/lib/flipper/spec/shared_adapter_specs.rb
index <HASH>..<HASH> 100644
--- a/lib/flipper/spec/shared_adapter_specs.rb
+++ b/lib/flipper/spec/shared_adapter_specs.rb
@@ -259,12 +259,9 @@ RSpec.shared_examples_for 'a flipper adapter' do
expect(subject.add(flipper[:search])).to eq(true)
result = subject.get_multi([flipper[:stats], flipper[:search], flipper[:other]])
-
expect(result).to be_instance_of(Hash)
- stats = result["stats"]
- search = result["search"]
- other = result["other"]
+ stats, search, other = result.values
expect(stats).to eq(default_config.merge(boolean: "true"))
expect(search).to eq(default_config)
expect(other).to eq(default_config)
diff --git a/lib/flipper/test/shared_adapter_test.rb b/lib/flipper/test/shared_adapter_test.rb
index <HASH>..<HASH> 100644
--- a/lib/flipper/test/shared_adapter_test.rb
+++ b/lib/flipper/test/shared_adapter_test.rb
@@ -238,10 +238,8 @@ module Flipper
result = @adapter.get_multi([@flipper[:stats], @flipper[:search], @flipper[:other]])
assert_instance_of Hash, result
- stats = result["stats"]
- search = result["search"]
- other = result["other"]
+ stats, search, other = result.values
assert_equal @default_config.merge(boolean: "true"), stats
assert_equal @default_config, search
assert_equal @default_config, other | Minor tweaks to shared specs/tests | jnunemaker_flipper | train |
0b8659f448843b9b421d3bff56dc40c369988628 | diff --git a/src/main/java/org/fit/layout/cssbox/BoxNode.java b/src/main/java/org/fit/layout/cssbox/BoxNode.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/fit/layout/cssbox/BoxNode.java
+++ b/src/main/java/org/fit/layout/cssbox/BoxNode.java
@@ -1039,6 +1039,16 @@ public class BoxNode extends DefaultTreeNode<org.fit.layout.model.Box> implement
}
}
+ @Override
+ public String getOwnText()
+ {
+ final Box box = getBox();
+ if (box instanceof TextBox)
+ return ((TextBox) box).getText();
+ else
+ return null;
+ }
+
//==================================================================================
@Override
@@ -1333,4 +1343,18 @@ public class BoxNode extends DefaultTreeNode<org.fit.layout.model.Box> implement
return null;
}
+ @Override
+ public Rectangular getSubstringBounds(int startPos, int endPos)
+ {
+ final String t = getOwnText();
+ if (t != null)
+ {
+ Rectangular ret = new Rectangular(getContentBounds());
+ //TODO use the text box here
+ return ret;
+ }
+ else
+ return null;
+ }
+
} | New substring bounds API in Box | FitLayout_layout-cssbox | train |
c2696bdcec45e4f5d0d53848e9d91582da6485dc | diff --git a/lib/synvert/core/rewriter.rb b/lib/synvert/core/rewriter.rb
index <HASH>..<HASH> 100644
--- a/lib/synvert/core/rewriter.rb
+++ b/lib/synvert/core/rewriter.rb
@@ -163,7 +163,7 @@ module Synvert::Core
# Process the rewriter.
# It will call the block.
def process
- instance_eval &@block
+ instance_eval(&@block)
end
# Process rewriter with sandbox mode.
diff --git a/lib/synvert/core/rewriter/condition.rb b/lib/synvert/core/rewriter/condition.rb
index <HASH>..<HASH> 100644
--- a/lib/synvert/core/rewriter/condition.rb
+++ b/lib/synvert/core/rewriter/condition.rb
@@ -17,7 +17,7 @@ module Synvert::Core
# If condition matches, run the block code.
def process
- @instance.instance_eval &@block if match?
+ @instance.instance_eval(&@block) if match?
end
end
end
diff --git a/lib/synvert/core/rewriter/instance.rb b/lib/synvert/core/rewriter/instance.rb
index <HASH>..<HASH> 100644
--- a/lib/synvert/core/rewriter/instance.rb
+++ b/lib/synvert/core/rewriter/instance.rb
@@ -101,7 +101,7 @@ module Synvert::Core
process_with_node ast do
begin
- instance_eval &@block
+ instance_eval(&@block)
rescue NoMethodError
puts @current_node.debug_info
raise
diff --git a/lib/synvert/core/rewriter/scope/goto_scope.rb b/lib/synvert/core/rewriter/scope/goto_scope.rb
index <HASH>..<HASH> 100644
--- a/lib/synvert/core/rewriter/scope/goto_scope.rb
+++ b/lib/synvert/core/rewriter/scope/goto_scope.rb
@@ -21,7 +21,7 @@ module Synvert::Core
child_node = current_node.send @child_node_name
@instance.process_with_other_node child_node do
- @instance.instance_eval &@block
+ @instance.instance_eval(&@block)
end
end
end
diff --git a/lib/synvert/core/rewriter/scope/within_scope.rb b/lib/synvert/core/rewriter/scope/within_scope.rb
index <HASH>..<HASH> 100644
--- a/lib/synvert/core/rewriter/scope/within_scope.rb
+++ b/lib/synvert/core/rewriter/scope/within_scope.rb
@@ -26,7 +26,7 @@ module Synvert::Core
@instance.process_with_node current_node do
matching_nodes.each do |matching_node|
@instance.process_with_node matching_node do
- @instance.instance_eval &@block
+ @instance.instance_eval(&@block)
end
end
end | Auto corrected by following Lint Ruby Lint/AmbiguousOperator | xinminlabs_synvert-core | train |
67c1d79c5c2b56ac48758340b7c79eec5983e274 | diff --git a/extensions/tags/js/admin/src/components/EditTagModal.js b/extensions/tags/js/admin/src/components/EditTagModal.js
index <HASH>..<HASH> 100644
--- a/extensions/tags/js/admin/src/components/EditTagModal.js
+++ b/extensions/tags/js/admin/src/components/EditTagModal.js
@@ -9,8 +9,8 @@ import tagLabel from 'flarum/tags/helpers/tagLabel';
* to create or edit a tag.
*/
export default class EditTagModal extends Modal {
- constructor(...args) {
- super(...args);
+ init() {
+ super.init();
this.tag = this.props.tag || app.store.createRecord('tags');
diff --git a/extensions/tags/js/forum/src/components/TagDiscussionModal.js b/extensions/tags/js/forum/src/components/TagDiscussionModal.js
index <HASH>..<HASH> 100644
--- a/extensions/tags/js/forum/src/components/TagDiscussionModal.js
+++ b/extensions/tags/js/forum/src/components/TagDiscussionModal.js
@@ -10,8 +10,8 @@ import tagIcon from 'flarum/tags/helpers/tagIcon';
import sortTags from 'flarum/tags/utils/sortTags';
export default class TagDiscussionModal extends Modal {
- constructor(...args) {
- super(...args);
+ init() {
+ super.init();
this.tags = sortTags(app.store.all('tags').filter(tag => tag.canStartDiscussion()));
diff --git a/extensions/tags/js/forum/src/components/TagsPage.js b/extensions/tags/js/forum/src/components/TagsPage.js
index <HASH>..<HASH> 100644
--- a/extensions/tags/js/forum/src/components/TagsPage.js
+++ b/extensions/tags/js/forum/src/components/TagsPage.js
@@ -7,9 +7,7 @@ import tagLabel from 'flarum/tags/helpers/tagLabel';
import sortTags from 'flarum/tags/utils/sortTags';
export default class TagsPage extends Component {
- constructor(...args) {
- super(...args);
-
+ init() {
this.tags = sortTags(app.store.all('tags').filter(tag => !tag.parent()));
app.current = this; | Initialise component state in init() instead of constructor | flarum_core | train |
e2cdbf1ec74576f3a3dd88149050871a66b1d8f4 | diff --git a/sqlite.js b/sqlite.js
index <HASH>..<HASH> 100644
--- a/sqlite.js
+++ b/sqlite.js
@@ -57,8 +57,10 @@ DatabaseSync.prototype.query = function (sql, bindings, callback) {
function SQLTransactionSync(db, txCallback, errCallback, successCallback) {
this.database = db;
this.executeSql = function(sqlStatement, arguments, callback) {
- // TODO: Somehow SQL errors are being eaten
- return db.query(sqlStatement, arguments, callback)[0];
+ var result = db.query(sqlStatement, arguments, callback)[0];
+ result.rows = {item: function (index) { return result[index]; },
+ length: result.length};
+ return result;
}
db.query("BEGIN TRANSACTION");
diff --git a/test.js b/test.js
index <HASH>..<HASH> 100644
--- a/test.js
+++ b/test.js
@@ -6,6 +6,14 @@ var sqlite = require("./sqlite");
posix.unlink('test.db');
+function asserteq(v1, v2) {
+ if (v1 != v2) {
+ sys.puts(sys.inspect(v1));
+ sys.puts(sys.inspect(v2));
+ }
+ process.assert(v1 == v2);
+}
+
var db = sqlite.openDatabaseSync('test.db');
db.query("CREATE TABLE egg (a,y,e)");
@@ -37,13 +45,20 @@ db.query("SELECT e FROM egg WHERE a = ?", [5], function (rows) {
});
+
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE tex (t,e,x)");
- tx.executeSql("INSERT INTO tex (t,e,x) VALUES (?,?,?)", ["this","is","SQL"]);
+ var i = tx.executeSql("INSERT INTO tex (t,e,x) VALUES (?,?,?)",
+ ["this","is","Sparta"]);
+ asserteq(i.rowsAffected, 1);
+ var s = tx.executeSql("SELECT * FROM tex");
+ asserteq(s.rows.length, 1);
+ asserteq(s.rows.item(0).t, "this");
+ asserteq(s.rows.item(0).e, "is");
+ asserteq(s.rows.item(0).x, "Sparta");
});
-
db.query("CREATE TABLE test (x,y,z)", function () {
db.query("INSERT INTO test (x,y) VALUES (?,?)", [5,10]);
db.query("INSERT INTO test (x,y,z) VALUES ($x, $y, $z)", {$x:1, $y:2, $z:3}); | Better conformance to HTML5 for transaction() | mapbox_node-sqlite3 | train |
e98c4b910440d3bf9028686fa86b41710aca924c | diff --git a/test/com/google/javascript/jscomp/ControlStructureCheckTest.java b/test/com/google/javascript/jscomp/ControlStructureCheckTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/ControlStructureCheckTest.java
+++ b/test/com/google/javascript/jscomp/ControlStructureCheckTest.java
@@ -104,6 +104,19 @@ public class ControlStructureCheckTest extends CompilerTestCase {
"with(a){}");
}
+ public void testUseOfWith3() {
+ testSame(
+ "function f(expr, context) {\n" +
+ " try {\n" +
+ " /** @suppress{with} */ with (context) {\n" +
+ " return eval('[' + expr + '][0]');\n" +
+ " }\n" +
+ " } catch (e) {\n" +
+ " return null;\n" +
+ " }\n" +
+ "};\n");
+ }
+
private void assertNoError(String js) {
testSame(js);
}
diff --git a/test/com/google/javascript/jscomp/TypeCheckTest.java b/test/com/google/javascript/jscomp/TypeCheckTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/TypeCheckTest.java
+++ b/test/com/google/javascript/jscomp/TypeCheckTest.java
@@ -5046,6 +5046,15 @@ public class TypeCheckTest extends CompilerTypeTestCase {
"Property indexOf never defined on String.prototype.toLowerCase");
}
+ public void testIssue380() throws Exception {
+ testTypes(
+ "/** @type { function(string): {innerHTML: string} } */" +
+ "document.getElementById;" +
+ "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" +
+ "list.push('?');\n" +
+ "document.getElementById('node').innerHTML = list.toString();");
+ }
+
/**
* Tests that the || operator is type checked correctly, that is of
* the type of the first argument or of the second argument. See
diff --git a/test/com/google/javascript/jscomp/parsing/ParserTest.java b/test/com/google/javascript/jscomp/parsing/ParserTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/parsing/ParserTest.java
+++ b/test/com/google/javascript/jscomp/parsing/ParserTest.java
@@ -467,6 +467,14 @@ public class ParserTest extends BaseJSTypeTestCase {
assertNull(varNode.getJSDocInfo());
}
+ public void testJSDocAttachment16() {
+ Node exprCall =
+ parse("/** @private */ x(); function f() {};").getFirstChild();
+ assertEquals(Token.EXPR_RESULT, exprCall.getType());
+ assertNull(exprCall.getNext().getJSDocInfo());
+ assertNotNull(exprCall.getFirstChild().getJSDocInfo());
+ }
+
public void testIncorrectJSDocDoesNotAlterJSParsing1() throws Exception {
assertNodeEquality(
parse("var a = [1,2]"), | Verify some tests that have been fixed by rhino changes.
Fixes issue <I>
Fixes issue <I>
R=johnlenz
DELTA=<I> (<I> added, 0 deleted, 0 changed)
Revision created by MOE tool push_codebase.
MOE_MIGRATION=<I>
git-svn-id: <URL> | google_closure-compiler | train |
af7956e1903ccabcf93a2c0b4a8babd92509f8dc | diff --git a/src/main/java/net/dv8tion/jda/internal/requests/restaction/MessageActionImpl.java b/src/main/java/net/dv8tion/jda/internal/requests/restaction/MessageActionImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/internal/requests/restaction/MessageActionImpl.java
+++ b/src/main/java/net/dv8tion/jda/internal/requests/restaction/MessageActionImpl.java
@@ -522,7 +522,7 @@ public class MessageActionImpl extends RestActionImpl<Message> implements Messag
if (override)
{
if (embeds == null)
- obj.putNull("embeds");
+ obj.put("embeds", DataArray.empty());
else
obj.put("embeds", DataArray.fromCollection(embeds));
if (content.length() == 0)
@@ -534,7 +534,7 @@ public class MessageActionImpl extends RestActionImpl<Message> implements Messag
else
obj.put("nonce", nonce);
if (components == null)
- obj.putNull("components");
+ obj.put("components", DataArray.empty());
else
obj.put("components", DataArray.fromCollection(components));
if (retainedAttachments != null) | Attempt a fix for overriding messages | DV8FromTheWorld_JDA | train |
5458e5e0d6aa0bc4b71cafcb529fcb24839b198f | diff --git a/lib/web/web.go b/lib/web/web.go
index <HASH>..<HASH> 100644
--- a/lib/web/web.go
+++ b/lib/web/web.go
@@ -1045,22 +1045,18 @@ func (m *Handler) siteSessionStreamGet(w http.ResponseWriter, r *http.Request, p
var writer io.Writer = w
for _, acceptedEnc := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
if strings.TrimSpace(acceptedEnc) == "gzip" {
- gzipper, err := gzip.NewWriterLevel(w, gzip.BestCompression)
- if err != nil {
- onError(trace.Wrap(err))
- return
- }
+ gzipper := gzip.NewWriter(w)
writer = gzipper
defer gzipper.Close()
w.Header().Set("Content-Encoding", "gzip")
}
}
+ w.Header().Set("Content-Type", "application/octet-stream")
_, err = writer.Write(bytes)
if err != nil {
onError(trace.Wrap(err))
return
}
- w.Header().Set("Content-Type", "application/octet-stream")
}
type eventsListGetResponse struct { | Properly set content-type for gzipped responses
Fixes #<I> | gravitational_teleport | train |
1b8650a027769263780d2ada4e783d906a246434 | diff --git a/lib/travis/cli/command.rb b/lib/travis/cli/command.rb
index <HASH>..<HASH> 100644
--- a/lib/travis/cli/command.rb
+++ b/lib/travis/cli/command.rb
@@ -149,8 +149,8 @@ module Travis
data = data.gsub(/<\[\[/, '<%=').gsub(/\]\]>/, '%>')
end
- def template(file)
- File.read(file).split('__END__', 2)[1].strip
+ def template(*args)
+ File.read(*args).split('__END__', 2)[1].strip
end
def color(line, style)
diff --git a/lib/travis/cli/encrypt.rb b/lib/travis/cli/encrypt.rb
index <HASH>..<HASH> 100644
--- a/lib/travis/cli/encrypt.rb
+++ b/lib/travis/cli/encrypt.rb
@@ -69,5 +69,5 @@ Please add the following to your <[[ color('.travis.yml', :info) ]]> file:
%s
-Pro Tip<[[ "™" unless Travis::CLI.windows? ]]>: You can add it automatically by running with <[[ color('--add', :info) ]]>.
+Pro Tip: You can add it automatically by running with <[[ color('--add', :info) ]]>.
diff --git a/travis.gemspec b/travis.gemspec
index <HASH>..<HASH> 100644
--- a/travis.gemspec
+++ b/travis.gemspec
@@ -13,18 +13,24 @@ Gem::Specification.new do |s|
s.authors = [
"Konstantin Haase",
"Henrik Hodne",
- "Adrien Brault",
+ "Max Barnash",
"Mario Visic",
- "Piotr Sarnacki"
+ "Adrien Brault",
+ "Piotr Sarnacki",
+ "Justin Lambert",
+ "Laurent Petit"
]
# generated from git shortlog -sne
s.email = [
"[email protected]",
"[email protected]",
+ "[email protected]",
"[email protected]",
- "[email protected]",
- "[email protected]"
+ "[email protected]",
+ "[email protected]",
+ "[email protected]",
+ "[email protected]"
]
# generated from git ls-files | remove unicode, to much hassle | travis-ci_travis.rb | train |
19a56d55a5e24430820ed552dacb76c2e9a7a68a | diff --git a/xunit/crypto.py b/xunit/crypto.py
index <HASH>..<HASH> 100644
--- a/xunit/crypto.py
+++ b/xunit/crypto.py
@@ -13,7 +13,7 @@ import unittest2
# Python patterns, scenario unit-testing
from python_patterns.unittest.scenario import ScenarioMeta, ScenarioTest
-from bitcoin.crypto import merkle
+from bitcoin.crypto import *
# ===----------------------------------------------------------------------=== | Switch to import-all, since we need to make sure that the API endpoints are are using are in fact caught by a wildcard import. | maaku_python-bitcoin | train |
f70d518dd8afd2780a2bc7655c13f452f01c14e6 | diff --git a/spec/unit/tracker/duration_tracker_spec.rb b/spec/unit/tracker/duration_tracker_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/tracker/duration_tracker_spec.rb
+++ b/spec/unit/tracker/duration_tracker_spec.rb
@@ -107,7 +107,7 @@ describe RequestLogAnalyzer::Tracker::Duration do
it "should generate a YAML output" do
@tracker.update(request(:category => 'a', :duration => 0.2))
@tracker.update(request(:category => 'b', :duration => 0.2))
- @tracker.to_yaml_object.should eql({"a"=>{:hits=>1, :min=>0.2, :mean=>0.2, :max=>0.2, :sum_of_squares=>0.0, :sum=>0.2}, "b"=>{:hits=>1, :min=>0.2, :mean=>0.2, :max=>0.2, :sum_of_squares=>0.0, :sum=>0.2}})
+ @tracker.to_yaml_object.should == {"a"=>{:hits=>1, :min=>0.2, :mean=>0.2, :max=>0.2, :sum_of_squares=>0.0, :sum=>0.2}, "b"=>{:hits=>1, :min=>0.2, :mean=>0.2, :max=>0.2, :sum_of_squares=>0.0, :sum=>0.2}}
end
end
end
diff --git a/spec/unit/tracker/frequency_tracker_spec.rb b/spec/unit/tracker/frequency_tracker_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/tracker/frequency_tracker_spec.rb
+++ b/spec/unit/tracker/frequency_tracker_spec.rb
@@ -78,6 +78,6 @@ describe RequestLogAnalyzer::Tracker::Frequency, 'reporting' do
it "should generate a YAML output" do
@tracker.update(request(:category => 'a', :blah => 0.2))
@tracker.update(request(:category => 'b', :blah => 0.2))
- @tracker.to_yaml_object.should eql({"a"=>1, "b"=>1})
+ @tracker.to_yaml_object.should == { "a" => 1, "b" => 1 }
end
end
\ No newline at end of file
diff --git a/spec/unit/tracker/hourly_spread_spec.rb b/spec/unit/tracker/hourly_spread_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/tracker/hourly_spread_spec.rb
+++ b/spec/unit/tracker/hourly_spread_spec.rb
@@ -74,6 +74,6 @@ describe RequestLogAnalyzer::Tracker::HourlySpread, 'reporting' do
@tracker.update(request(:timestamp => 20090101000000))
@tracker.update(request(:timestamp => 20090103000000))
@tracker.update(request(:timestamp => 20090103010000))
- @tracker.to_yaml_object.should eql({"22:00 - 23:00"=>0, "9:00 - 10:00"=>0, "7:00 - 8:00"=>0, "2:00 - 3:00"=>0, "12:00 - 13:00"=>0, "11:00 - 12:00"=>0, "16:00 - 17:00"=>0, "15:00 - 16:00"=>0, "19:00 - 20:00"=>0, "3:00 - 4:00"=>0, "21:00 - 22:00"=>0, "20:00 - 21:00"=>0, "14:00 - 15:00"=>0, "13:00 - 14:00"=>0, "4:00 - 5:00"=>0, "10:00 - 11:00"=>0, "18:00 - 19:00"=>0, "17:00 - 18:00"=>0, "8:00 - 9:00"=>0, "6:00 - 7:00"=>0, "5:00 - 6:00"=>0, "1:00 - 2:00"=>1, "0:00 - 1:00"=>3, "23:00 - 24:00"=>0})
+ @tracker.to_yaml_object.should == {"22:00 - 23:00"=>0, "9:00 - 10:00"=>0, "7:00 - 8:00"=>0, "2:00 - 3:00"=>0, "12:00 - 13:00"=>0, "11:00 - 12:00"=>0, "16:00 - 17:00"=>0, "15:00 - 16:00"=>0, "19:00 - 20:00"=>0, "3:00 - 4:00"=>0, "21:00 - 22:00"=>0, "20:00 - 21:00"=>0, "14:00 - 15:00"=>0, "13:00 - 14:00"=>0, "4:00 - 5:00"=>0, "10:00 - 11:00"=>0, "18:00 - 19:00"=>0, "17:00 - 18:00"=>0, "8:00 - 9:00"=>0, "6:00 - 7:00"=>0, "5:00 - 6:00"=>0, "1:00 - 2:00"=>1, "0:00 - 1:00"=>3, "23:00 - 24:00"=>0}
end
end
\ No newline at end of file
diff --git a/spec/unit/tracker/timespan_tracker_spec.rb b/spec/unit/tracker/timespan_tracker_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/tracker/timespan_tracker_spec.rb
+++ b/spec/unit/tracker/timespan_tracker_spec.rb
@@ -67,7 +67,7 @@ describe RequestLogAnalyzer::Tracker::Timespan, 'reporting' do
@tracker.update(request(:category => 'a', :timestamp => 20090102000000))
@tracker.update(request(:category => 'a', :timestamp => 20090101000000))
@tracker.update(request(:category => 'a', :timestamp => 20090103000000))
- @tracker.to_yaml_object.should eql({ :first => DateTime.parse('20090101000000'), :last => DateTime.parse('20090103000000')})
+ @tracker.to_yaml_object.should == { :first => DateTime.parse('20090101000000'), :last => DateTime.parse('20090103000000')}
end
end
\ No newline at end of file | Fixed #to_yaml_objects specs to use == comparison instead of eql? | wvanbergen_request-log-analyzer | train |
9de9b88212cc5340eba580c9f4c06c80fc2f0705 | diff --git a/lib/tic-tac-toe/game.rb b/lib/tic-tac-toe/game.rb
index <HASH>..<HASH> 100755
--- a/lib/tic-tac-toe/game.rb
+++ b/lib/tic-tac-toe/game.rb
@@ -15,9 +15,7 @@ module TicTacToe
def run
setup_game
- loop do
- main_game_loop
- end
+ main_game_loop
if @game_type.play_again?
new_game
@@ -42,8 +40,12 @@ module TicTacToe
end
def main_game_loop
- [:get_move_from_user!, :get_move_from_computer!].each do |command|
- @game_type.send(command)
+ loop do
+ @game_type.get_move_from_user!
+ @game_type.update_board
+ break if game_over?
+
+ get_move_from_computer!
@game_type.update_board
break if game_over?
end
diff --git a/test/game_test.rb b/test/game_test.rb
index <HASH>..<HASH> 100644
--- a/test/game_test.rb
+++ b/test/game_test.rb
@@ -4,15 +4,17 @@ class GameTest < MiniTest::Unit::TestCase
def setup
@game = TicTacToe::Game.new
@game.instance_variable_set("@computer_letter", "x")
- end
-
- def test_main_game_loop_doesnt_raise_error
+
# Mock out user move from user
game_type = @game.instance_variable_get("@game_type")
- def game_type.get_move_from_user!
- @game.method(:get_move_from_computer!)
- end
+ def game_type.get_move_from_user!; end
+ # Mock out output
+ def game_type.update_board; end
+ def game_type.display_text(text); end
+ def @game.update_board; end
+ end
+ def test_main_game_loop_doesnt_raise_error
success = true
begin
@game.send(:main_game_loop) | Passing tests. Fixed main_game_loop | ekosz_Erics-Tic-Tac-Toe | train |
d8f425962cfc1402bbaca5bf7adba4437963b896 | diff --git a/audio/audio.go b/audio/audio.go
index <HASH>..<HASH> 100644
--- a/audio/audio.go
+++ b/audio/audio.go
@@ -287,12 +287,18 @@ func BytesReadSeekCloser(b []uint8) ReadSeekCloser {
return &bytesReadSeekCloser{reader: bytes.NewReader(b)}
}
+type readingResult struct {
+ data []uint8
+ err error
+}
+
// Player is an audio player which has one stream.
type Player struct {
players *players
src ReadSeekCloser
sampleRate int
- readingCh chan error
+ readingCh chan readingResult
+ seekCh chan int64
buf []uint8
pos int64
@@ -320,6 +326,7 @@ func NewPlayer(context *Context, src ReadSeekCloser) (*Player, error) {
players: context.players,
src: src,
sampleRate: context.sampleRate,
+ seekCh: make(chan int64, 1),
buf: []uint8{},
volume: 1,
}
@@ -369,28 +376,38 @@ func (p *Player) Close() error {
func (p *Player) readToBuffer(length int) (int, error) {
if p.readingCh == nil {
- p.readingCh = make(chan error)
+ p.readingCh = make(chan readingResult)
go func() {
defer close(p.readingCh)
- bb := make([]uint8, length)
+ b := make([]uint8, length)
p.srcM.Lock()
- n, err := p.src.Read(bb)
+ n, err := p.src.Read(b)
p.srcM.Unlock()
if err != nil {
- p.readingCh <- err
+ p.readingCh <- readingResult{
+ err: err,
+ }
return
}
- if 0 < n {
- p.m.Lock()
- p.buf = append(p.buf, bb[:n]...)
- p.m.Unlock()
+ p.readingCh <- readingResult{
+ data: b[:n],
}
}()
}
select {
- case err := <-p.readingCh:
+ case pos := <-p.seekCh:
+ p.buf = []uint8{}
+ p.pos = pos
+ return 0, nil
+ case r := <-p.readingCh:
+ if r.err != nil {
+ return 0, r.err
+ }
+ if len(r.data) > 0 {
+ p.buf = append(p.buf, r.data...)
+ }
p.readingCh = nil
- return len(p.buf), err
+ return len(p.buf), nil
case <-time.After(15 * time.Millisecond):
return length, nil
}
@@ -416,10 +433,8 @@ func (p *Player) proceed(length int) {
if p.readingCh != nil {
return
}
- p.m.Lock()
p.buf = p.buf[length:]
p.pos += int64(length)
- p.m.Unlock()
}
// Play plays the stream.
@@ -462,10 +477,7 @@ func (p *Player) Seek(offset time.Duration) error {
if err != nil {
return err
}
- p.m.Lock()
- p.buf = []uint8{}
- p.pos = pos
- p.m.Unlock()
+ p.seekCh <- pos
return nil
} | audio: Bug fix: players' buffer can be empty when seeking before proceeding (#<I>) | hajimehoshi_ebiten | train |
1003fb4869a60d09322f7abf00b5846d8e41f6c8 | diff --git a/Worker.php b/Worker.php
index <HASH>..<HASH> 100644
--- a/Worker.php
+++ b/Worker.php
@@ -811,7 +811,7 @@ class Worker
*
* @throws Exception
*/
- protected static function resetStd()
+ public static function resetStd()
{
if (!self::$daemonize) {
return; | Allow Log rotation by making the redirection public | walkor_Workerman | train |
9cda57fa372a0a596fff0301672fe6c7215720e0 | diff --git a/tests/base.py b/tests/base.py
index <HASH>..<HASH> 100644
--- a/tests/base.py
+++ b/tests/base.py
@@ -14,9 +14,6 @@ from django_registration import signals
from django_registration.forms import RegistrationForm
-User = get_user_model()
-
-
# django-registration needs to test that signals are sent at
# registration and activation. Django -- as of 2.1 -- does not have a
# test assertion built in to test whether a signal was or was not
@@ -176,6 +173,7 @@ class WorkflowTestCase(RegistrationTestCase):
self.assertTrue(resp.context["form"].has_error("password2"))
def test_registration_signal(self):
+ User = get_user_model()
with self.assertSignalSent(signals.user_registered) as cm:
self.client.post(
reverse("django_registration_register"), data=self.valid_data | Clean up another stray User reference in tests.base. | ubernostrum_django-registration | train |
32b119b77fe06eeaaaac84d06960384623763619 | diff --git a/elasticsearch_dsl/document.py b/elasticsearch_dsl/document.py
index <HASH>..<HASH> 100644
--- a/elasticsearch_dsl/document.py
+++ b/elasticsearch_dsl/document.py
@@ -120,6 +120,13 @@ class DocType(ObjectBase):
return getattr(self.meta, name[1:])
return super(DocType, self).__getattr__(name)
+ def __repr__(self):
+ return '%s(%s)' % (
+ self.__class__.__name__,
+ ', '.join('%s=%r' % (key, getattr(self.meta, key)) for key in
+ ('index', 'doc_type', 'id') if key in self.meta)
+ )
+
def __setattr__(self, name, value):
if name.startswith('_') and name[1:] in META_FIELDS:
return setattr(self.meta, name[1:], value)
diff --git a/elasticsearch_dsl/result.py b/elasticsearch_dsl/result.py
index <HASH>..<HASH> 100644
--- a/elasticsearch_dsl/result.py
+++ b/elasticsearch_dsl/result.py
@@ -80,5 +80,8 @@ class Result(AttrDict):
return super(Result, self).__dir__() + ['meta']
def __repr__(self):
- return u('<Result(%s/%s/%s): %s>') % (
- self.meta.index, self.meta.doc_type, self.meta.id, super(Result, self).__repr__())
+ return '<Result(%s): %s>' % (
+ '/'.join(getattr(self.meta, key) for key in
+ ('index', 'doc_type', 'id') if key in self.meta),
+ super(Result, self).__repr__()
+ )
diff --git a/test_elasticsearch_dsl/test_integration/test_search.py b/test_elasticsearch_dsl/test_integration/test_search.py
index <HASH>..<HASH> 100644
--- a/test_elasticsearch_dsl/test_integration/test_search.py
+++ b/test_elasticsearch_dsl/test_integration/test_search.py
@@ -23,6 +23,14 @@ class Commit(DocType):
parent = MetaField(type='repos')
def test_inner_hits_are_wrapped_in_response(data_client):
+ s = Search(index='git', doc_type='commits')[0:1].query('has_parent', type='repos', inner_hits={}, query=Q('match_all'))
+ response = s.execute()
+
+ commit = response.hits[0]
+ assert isinstance(commit.meta.inner_hits.repos, response.__class__)
+ assert repr(commit.meta.inner_hits.repos[0]).startswith("<Result(git/repos/elasticsearch-dsl-py): ")
+
+def test_inner_hits_are_wrapped_in_doc_type(data_client):
i = Index('git')
i.doc_type(Repository)
i.doc_type(Commit)
@@ -32,6 +40,8 @@ def test_inner_hits_are_wrapped_in_response(data_client):
commit = response.hits[0]
assert isinstance(commit.meta.inner_hits.repos, response.__class__)
assert isinstance(commit.meta.inner_hits.repos[0], Repository)
+ assert "Repository(index='git', doc_type='repos', id='elasticsearch-dsl-py')" == repr(commit.meta.inner_hits.repos[0])
+
def test_suggest_can_be_run_separately(data_client):
s = Search() | Fix repr for DocType and Result | elastic_elasticsearch-dsl-py | train |
4d703c51dc8c7de76fbd2b2f9f00d53e44a58418 | diff --git a/cdm/src/main/java/ucar/nc2/Group.java b/cdm/src/main/java/ucar/nc2/Group.java
index <HASH>..<HASH> 100644
--- a/cdm/src/main/java/ucar/nc2/Group.java
+++ b/cdm/src/main/java/ucar/nc2/Group.java
@@ -506,7 +506,7 @@ public class Group extends CDMNode {
if (immutable) throw new IllegalStateException("Cant modify");
if (findDimensionLocal(d.getShortName()) != null)
- throw new IllegalArgumentException("Variable name (" + d.getShortName() + ") must be unique within Group " + getShortName());
+ throw new IllegalArgumentException("Dimension name (" + d.getShortName() + ") must be unique within Group " + getShortName());
dimensions.add(d);
d.setGroup(this);
@@ -532,7 +532,7 @@ public class Group extends CDMNode {
if (immutable) throw new IllegalStateException("Cant modify");
if (findGroup(g.getShortName()) != null)
- throw new IllegalArgumentException("Variable name (" + g.getShortName() + ") must be unique within Group " + getShortName());
+ throw new IllegalArgumentException("Group name (" + g.getShortName() + ") must be unique within Group " + getShortName());
groups.add(g);
g.setParentGroup(this); // groups are a tree - only one parent
diff --git a/grib/src/main/java/ucar/nc2/grib/grib1/Grib1Iosp.java b/grib/src/main/java/ucar/nc2/grib/grib1/Grib1Iosp.java
index <HASH>..<HASH> 100644
--- a/grib/src/main/java/ucar/nc2/grib/grib1/Grib1Iosp.java
+++ b/grib/src/main/java/ucar/nc2/grib/grib1/Grib1Iosp.java
@@ -172,10 +172,10 @@ public class Grib1Iosp extends GribIosp {
String name = (pos > 0) ? f.getName().substring(0, pos) : f.getName();
if (isTimePartitioned) {
- timePartition = Grib1TimePartitionBuilder.createFromIndex(name, f.getParentFile(), raf, logger);
+ timePartition = Grib1TimePartitionBuilder.createFromIndex(name, null, raf, logger);
gribCollection = timePartition;
} else {
- gribCollection = Grib1CollectionBuilder.createFromIndex(name, f.getParentFile(), raf, gribConfig, logger);
+ gribCollection = Grib1CollectionBuilder.createFromIndex(name, null, raf, gribConfig, logger);
}
cust = Grib1Customizer.factory(gribCollection.getCenter(), gribCollection.getSubcenter(), gribCollection.getLocal(), tables);
diff --git a/grib/src/main/java/ucar/nc2/grib/grib2/Grib2Iosp.java b/grib/src/main/java/ucar/nc2/grib/grib2/Grib2Iosp.java
index <HASH>..<HASH> 100644
--- a/grib/src/main/java/ucar/nc2/grib/grib2/Grib2Iosp.java
+++ b/grib/src/main/java/ucar/nc2/grib/grib2/Grib2Iosp.java
@@ -347,10 +347,10 @@ public class Grib2Iosp extends GribIosp {
String name = (pos > 0) ? f.getName().substring(0, pos) : f.getName();
if (isTimePartitioned) {
- timePartition = Grib2TimePartitionBuilder.createFromIndex(name, f.getParentFile(), raf, logger);
+ timePartition = Grib2TimePartitionBuilder.createFromIndex(name, null, raf, logger);
gribCollection = timePartition;
} else {
- gribCollection = Grib2CollectionBuilder.createFromIndex(name, f.getParentFile(), raf, gribConfig, logger);
+ gribCollection = Grib2CollectionBuilder.createFromIndex(name, null, raf, gribConfig, logger);
}
cust = Grib2Customizer.factory(gribCollection.getCenter(), gribCollection.getSubcenter(), gribCollection.getMaster(), gribCollection.getLocal()); | allow GRIB index files to be in different directory than data | Unidata_thredds | train |
3b2a729f0bb1723f50ad2ffc819bbcd18626130e | diff --git a/lib/machinist.rb b/lib/machinist.rb
index <HASH>..<HASH> 100644
--- a/lib/machinist.rb
+++ b/lib/machinist.rb
@@ -17,7 +17,7 @@ module Machinist
lathe.instance_eval(&named_blueprint) if named_blueprint
klass = object.class
while klass
- lathe.instance_eval(&klass.blueprint) if klass.blueprint
+ lathe.instance_eval(&klass.blueprint) if klass.respond_to?(:blueprint) && klass.blueprint
klass = klass.superclass
end
end | Made sure ActiveRecord#make works even if machinist/object isn't loaded. | notahat_machinist | train |
fcb5ea431f6cf04a88e5ced4d1f2b0242e306d33 | diff --git a/tcontainer/bytepool.go b/tcontainer/bytepool.go
index <HASH>..<HASH> 100644
--- a/tcontainer/bytepool.go
+++ b/tcontainer/bytepool.go
@@ -99,18 +99,17 @@ func (b *BytePool) Get(size int) []byte {
return []byte{}
}
- slab, normalized := b.getSlab(size)
+ slab := b.getSlab(size)
if slab == nil {
return make([]byte, size) // ### return, oversized ###
}
select {
case buffer := <-slab:
- return b.withFinalizer(buffer[:size]) // ### return, cached ###
+ return buffer[:size] // ### return, cached ###
default:
- buffer := make([]byte, normalized)
- return b.withFinalizer(buffer[:size]) // ### return, new chunk ###
+ return make([]byte, size) // ### return, empty pool ###
}
}
@@ -123,27 +122,27 @@ func newSlabsList(numSlabs int, numChunks int, chunkSize int) slabsList {
}
}
-func (b *BytePool) getSlab(size int) (slab, int) {
+func (b *BytePool) getSlab(size int) slab {
switch {
case size <= tinyChunkMax:
- return b.tiny.fetch(size)
+ return b.tiny.fetch(size, b)
case size <= smallChunkMax:
- return b.small.fetch(size)
+ return b.small.fetch(size, b)
case size <= mediumChunkMax:
- return b.medium.fetch(size)
+ return b.medium.fetch(size, b)
case size <= largeChunkMax:
- return b.large.fetch(size)
+ return b.large.fetch(size, b)
default:
- return nil, size // ### return, too large ###
+ return nil // ### return, too large ###
}
}
-func (s *slabsList) fetch(size int) (slab, int) {
+func (s *slabsList) fetch(size int, b *BytePool) slab {
slabIdx := size / (s.chunkSize + 1)
chunks := s.slabs[slabIdx]
@@ -154,24 +153,28 @@ func (s *slabsList) fetch(size int) (slab, int) {
if chunks = s.slabs[slabIdx]; chunks == nil {
chunks = make(slab, s.numChunks)
+ chunkSize := (slabIdx + 1) * s.chunkSize
+
+ // Prepopulate slab
+ for i := 0; i < s.numChunks; i++ {
+ buffer := make([]byte, chunkSize)
+ runtime.SetFinalizer(&buffer, b.put)
+ chunks <- buffer
+ }
+
s.slabs[slabIdx] = chunks
}
}
- return chunks, (slabIdx + 1) * s.chunkSize
+ return chunks
}
func (b *BytePool) put(buffer *[]byte) {
- slab, _ := b.getSlab(cap(*buffer))
+ slab := b.getSlab(cap(*buffer))
select {
case slab <- *buffer:
- // store, pool has capacity
+ runtime.SetFinalizer(buffer, b.put)
default:
// discard, pool is full
}
}
-
-func (b *BytePool) withFinalizer(buffer []byte) []byte {
- runtime.SetFinalizer(&buffer, b.put)
- return buffer
-}
diff --git a/tcontainer/bytepool_test.go b/tcontainer/bytepool_test.go
index <HASH>..<HASH> 100644
--- a/tcontainer/bytepool_test.go
+++ b/tcontainer/bytepool_test.go
@@ -73,7 +73,7 @@ func allocateWaste(pool *BytePool, expect ttesting.Expect) {
func TestBytePoolRecycle(t *testing.T) {
expect := ttesting.NewExpect(t)
- pool := NewBytePool()
+ pool := NewBytePoolWithSize(1, 1, 1, 1)
expect.Nil(pool.tiny.slabs[0])
allocateWaste(&pool, expect)
@@ -86,4 +86,9 @@ func TestBytePoolRecycle(t *testing.T) {
})
expect.Equal(1, len(pool.tiny.slabs[0]))
+
+ data := pool.Get(32)
+ for i := 0; i < 32; i++ {
+ expect.Equal(byte(i), data[i])
+ }
} | BytePool now preallocates to move the cost of runtime.SetFinalizer to the GC | trivago_tgo | train |
74ae5b4f8b1ba773a4add7fc479760376ba890cf | diff --git a/CHANGES.txt b/CHANGES.txt
index <HASH>..<HASH> 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,3 +1,7 @@
+pypet 0.1b.10
+
+* New `v_crun_` property simply returning ``'run_ALL'`` if ``v_crun`` is ``None``.
+
pypet 0.1b.9
* BUG FIX: Fixed backwards compatibility
diff --git a/pypet/naturalnaming.py b/pypet/naturalnaming.py
index <HASH>..<HASH> 100644
--- a/pypet/naturalnaming.py
+++ b/pypet/naturalnaming.py
@@ -2260,7 +2260,7 @@ class NaturalNamingInterface(HasLogger):
crun = self._root_instance._crun
- if crun != pypetconstants.RUN_NAME_DUMMY and run_pos == -1:
+ if crun is not None and run_pos == -1:
# If we count the wildcard we have to perform the search twice,
# one with a run name and one with the dummy:
with self._disable_logger:
diff --git a/pypet/tests/hdf5_storage_test.py b/pypet/tests/hdf5_storage_test.py
index <HASH>..<HASH> 100644
--- a/pypet/tests/hdf5_storage_test.py
+++ b/pypet/tests/hdf5_storage_test.py
@@ -1823,12 +1823,13 @@ class ResultSortTest(TrajectoryComparator):
nameset = set((x.v_name for x in traj.f_iter_nodes(predicate=(idx,))))
self.assertTrue('run_%08d' % (idx+1) not in nameset)
self.assertTrue('run_%08d' % idx in nameset)
-
+ self.assertTrue(traj.v_crun == run_name)
self.assertTrue(newtraj.z==traj.x*traj.y,' z != x*y: %s != %s * %s' %
(str(newtraj.z),str(traj.x),str(traj.y)))
self.assertTrue(traj.v_idx == -1)
- self.assertTrue(traj.v_as_run == pypetconstants.RUN_NAME_DUMMY)
+ self.assertTrue(traj.v_crun is None)
+ self.assertTrue(traj.v_crun_ == pypetconstants.RUN_NAME_DUMMY)
self.assertTrue(newtraj.v_idx == idx)
diff --git a/pypet/trajectory.py b/pypet/trajectory.py
index <HASH>..<HASH> 100644
--- a/pypet/trajectory.py
+++ b/pypet/trajectory.py
@@ -458,6 +458,13 @@ class Trajectory(DerivedParameterGroup, ResultGroup, ParameterGroup, ConfigGroup
self.v_crun = run_name
@property
+ def v_crun_(self):
+ """"
+ Similar to ``v_crun`` but returns ``'run_ALL'`` if ``v_crun`` is ``None``.
+ """
+ return self.v_crun if self.v_crun is not None else pypetconstants.RUN_NAME_DUMMY
+
+ @property
def v_crun(self):
"""Run name if you want to access the trajectory as a single run.
@@ -469,8 +476,6 @@ class Trajectory(DerivedParameterGroup, ResultGroup, ParameterGroup, ConfigGroup
:func:`~pypet.trajectory.Trajectory.f_set_crun:`.
Set to `None` to make the trajectory to turn everything back to default.
- Note that if setting to `None`, the property will actually be reset
- to ``'run_ALL'``.
"""
return self._crun | undid changes; but new ``v_crun_`` property. | SmokinCaterpillar_pypet | train |
9ca17c022258c874d4eaf1c99a08a0354b8acf0e | diff --git a/symfit/core/fit.py b/symfit/core/fit.py
index <HASH>..<HASH> 100644
--- a/symfit/core/fit.py
+++ b/symfit/core/fit.py
@@ -1422,10 +1422,9 @@ class Fit(HasCovarianceMatrix):
:return: FitResults instance
"""
minimizer_ans = self.minimizer.execute(**minimize_options)
- cov_matrix = self.covariance_matrix(
+ minimizer_ans.covariance_matrix = self.covariance_matrix(
dict(zip(self.model.params, minimizer_ans._popt))
)
- minimizer_ans.covariance_matrix = cov_matrix
# Overwrite the DummyModel with the current model
minimizer_ans.model = self.model
return minimizer_ans
diff --git a/symfit/core/fit_results.py b/symfit/core/fit_results.py
index <HASH>..<HASH> 100644
--- a/symfit/core/fit_results.py
+++ b/symfit/core/fit_results.py
@@ -27,7 +27,8 @@ class FitResults(object):
:param model: :class:`~symfit.core.fit.Model` that was fit to.
:param popt: best fit parameters, same ordering as in model.params.
:param covariance_matrix: covariance matrix.
- :param minimizer_output: Raw output as given by the minimizer.
+ :param minimizer_output: ``dict`` with the raw output as given by the
+ minimizer.
:param minimizer: Minimizer instance used.
:param objective: Objective function which was optimized.
""" | Processed @pckroon's last suggestions. | tBuLi_symfit | train |
93e37f8ba24f65c497637225c99739e465822408 | diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -168,33 +168,10 @@ HtmlDiffer.prototype.isEqual = function (html1, html2, options) {
return (diff.length === 1 && !diff[0].added && !diff[0].removed);
};
-/**
- * @deprecated
- * @param {String} html1
- * @param {String} html2
- */
-function bemDiff(html1, html2) {
- console.warn('WARNING! You use deprecated method \'bemDiff\'!'.bold.red);
-
- var logger = require('./diff-logger'),
- options = {
- ignoreHtmlAttrs: ['id', 'for'],
- compareHtmlAttrsAsJSON: ['data-bem', 'onclick', 'ondblclick']
- },
- loggerOptions = {
- showCharacters: 40
- },
- htmlDiffer = new HtmlDiff(options);
-
- logger.log(htmlDiffer.diff(html1, html2), loggerOptions);
-}
-
var htmlDiffer = new HtmlDiffer();
module.exports = {
HtmlDiffer: HtmlDiffer,
diffHtml: htmlDiffer.diffHtml.bind(htmlDiffer),
- isEqual: htmlDiffer.isEqual.bind(htmlDiffer),
-
- bemDiff: bemDiff
+ isEqual: htmlDiffer.isEqual.bind(htmlDiffer)
}; | Get rid of deprecated method 'bemDiff' | bem_html-differ | train |
47093d53724fdad3b1b9f569a8a11877b6a4cf40 | diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -42,7 +42,6 @@
},
"dependencies": {
"abort-controller": "^3.0.0",
- "async-iterator-all": "^1.0.0",
"async-iterator-to-pull-stream": "^1.3.0",
"bignumber.js": "^9.0.0",
"bl": "^4.0.0",
@@ -60,6 +59,7 @@
"ipld-dag-pb": "^0.18.1",
"ipld-raw": "^4.0.0",
"is-ipfs": "~0.6.1",
+ "it-all": "^1.0.1",
"it-glob": "0.0.7",
"it-tar": "^1.1.1",
"it-to-stream": "^0.1.1",
diff --git a/src/add/index.js b/src/add/index.js
index <HASH>..<HASH> 100644
--- a/src/add/index.js
+++ b/src/add/index.js
@@ -29,6 +29,8 @@ module.exports = configure(({ ky }) => {
if (options.trickle != null) searchParams.set('trickle', options.trickle)
if (options.wrapWithDirectory != null) searchParams.set('wrap-with-directory', options.wrapWithDirectory)
if (options.preload != null) searchParams.set('preload', options.preload)
+ if (options.fileImportConcurrency != null) searchParams.set('file-import-concurrency', options.fileImportConcurrency)
+ if (options.blockWriteConcurrency != null) searchParams.set('block-write-concurrency', options.blockWriteConcurrency)
const res = await ky.post('add', {
timeout: options.timeout,
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -11,7 +11,7 @@ const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const nodeify = require('promise-nodeify')
const callbackify = require('callbackify')
-const all = require('async-iterator-all')
+const all = require('it-all')
const toPullStream = require('async-iterator-to-pull-stream')
const toStream = require('it-to-stream')
const BufferList = require('bl/BufferList')
diff --git a/src/lib/converters.js b/src/lib/converters.js
index <HASH>..<HASH> 100644
--- a/src/lib/converters.js
+++ b/src/lib/converters.js
@@ -1,7 +1,7 @@
'use strict'
const toPull = require('async-iterator-to-pull-stream')
-const all = require('async-iterator-all')
+const all = require('it-all')
const toStream = require('it-to-stream')
const { Buffer } = require('buffer') | feat: expose import concurrency controls (#<I>) | ipfs_js-ipfs-http-client | train |
b07b34208675055e90a74de55e468101e265f89e | diff --git a/js/src/util/sanitizer.js b/js/src/util/sanitizer.js
index <HASH>..<HASH> 100644
--- a/js/src/util/sanitizer.js
+++ b/js/src/util/sanitizer.js
@@ -37,7 +37,7 @@ const allowedAttribute = (attr, allowedAttributeList) => {
if (allowedAttributeList.indexOf(attrName) !== -1) {
if (uriAttrs.indexOf(attrName) !== -1) {
- return SAFE_URL_PATTERN.test(attr.nodeValue) || DATA_URL_PATTERN.test(attr.nodeValue)
+ return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
}
return true
@@ -47,7 +47,7 @@ const allowedAttribute = (attr, allowedAttributeList) => {
// Check if a regular expression validates the attribute.
for (let i = 0, len = regExp.length; i < len; i++) {
- if (regExp[i].test(attrName)) {
+ if (attrName.match(regExp[i])) {
return true
}
} | Partially Revert "Use regex.test() when we want to check for a Boolean. (#<I>)" (#<I>)
This partially reverts commit 9c2b9ac<I>d4abb5ec8b<I>de<I>d5f3a. | twbs_bootstrap | train |
26a7c5cccb8466a7e0e644ba6f9e0b258c023519 | diff --git a/App.php b/App.php
index <HASH>..<HASH> 100644
--- a/App.php
+++ b/App.php
@@ -475,8 +475,6 @@ class App implements IEventSubject, LoggerAwareInterface {
public function run($environment = 'production') {
$this->environment = $environment;
- // Error handling
-
// Throw exceptions instead of fatal errors on class not found
spl_autoload_register(function($class) {
throw new InvalidClassException(tr('Class not found: %1', $class));
@@ -484,7 +482,20 @@ class App implements IEventSubject, LoggerAwareInterface {
// Set exception handler
set_exception_handler(array($this, 'handleError'));
+
+ // Set timezone (required by file logger)
+ if (!isset($this->config['i18n']['timeZone'])) {
+ $defaultTimeZone = 'UTC';
+ try {
+ $defaultTimeZone = @date_default_timezone_get();
+ }
+ catch (\ErrorException $e) { }
+ $this->config['i18n']['timeZone'] = $defaultTimeZone;
+ }
+ if (!date_default_timezone_set($this->config['i18n']['timeZone']))
+ date_default_timezone_set('UTC');
+ // Set up the default file loger
if ($this->logger instanceof Logger) {
try {
$this->logger->addHandler(new FileHandler(
diff --git a/Boot.php b/Boot.php
index <HASH>..<HASH> 100644
--- a/Boot.php
+++ b/Boot.php
@@ -76,20 +76,9 @@ class Boot extends Module {
'showReference' => true
)
);
-
- if (!isset($this->config['core']['timeZone'])) {
- $defaultTimeZone = 'UTC';
- try {
- $defaultTimeZone = @date_default_timezone_get();
- }
- catch (\ErrorException $e) { }
- $this->config['core']['timeZone'] = $defaultTimeZone;
- }
- if (!date_default_timezone_set($this->config['core']['timeZone']))
- date_default_timezone_set('UTC');
- if (isset($this->config['core']['language']))
- I18n::setLanguage($this->config['core']['language']);
+ if (isset($this->config['i18n']['language']))
+ I18n::setLanguage($this->config['i18n']['language']);
I18n::loadFrom($this->p('Core', 'languages'));
diff --git a/I18n.php b/I18n.php
index <HASH>..<HASH> 100644
--- a/I18n.php
+++ b/I18n.php
@@ -76,15 +76,6 @@ class I18n {
self::load($localization, $extend);
return true;
}
-
- /**
- * Get language code of current language.
- * @return string A language code, e.g. 'en', 'en-GB', 'da-DK', etc.
- * @deprecated
- */
- public static function getLanguageCode() {
- return self::$language;
- }
/**
* Translate a string. | Set time zone before enabling file logger. | jivoo_core | train |
3f639562941d06dffa85ca1841ab10fb07fd684e | diff --git a/src/Transaction.php b/src/Transaction.php
index <HASH>..<HASH> 100644
--- a/src/Transaction.php
+++ b/src/Transaction.php
@@ -8,63 +8,6 @@ use pxgamer\Arionum\Transaction\Version;
final class Transaction
{
- /**
- * @deprecated
- *
- * @see Version::STANDARD
- *
- * The transaction version for sending to an address.
- */
- public const VERSION_STANDARD = Version::STANDARD;
- /**
- * @deprecated
- *
- * @see Version::ALIAS_SEND
- *
- * The transaction version for sending to an alias.
- */
- public const VERSION_ALIAS_SEND = Version::ALIAS_SEND;
- /**
- * @deprecated
- *
- * @see Version::ALIAS_SET
- *
- * The transaction version for setting an alias.
- */
- public const VERSION_ALIAS_SET = Version::ALIAS_SET;
- /**
- * @deprecated
- *
- * @see Version::MASTERNODE_CREATE
- *
- * The transaction version for creating a masternode.
- */
- public const VERSION_MASTERNODE_CREATE = Version::MASTERNODE_CREATE;
- /**
- * @deprecated
- *
- * @see Version::MASTERNODE_PAUSE
- *
- * The transaction version for pausing a masternode.
- */
- public const VERSION_MASTERNODE_PAUSE = Version::MASTERNODE_PAUSE;
- /**
- * @deprecated
- *
- * @see Version::MASTERNODE_RESUME
- *
- * The transaction version for resuming a masternode.
- */
- public const VERSION_MASTERNODE_RESUME = Version::MASTERNODE_RESUME;
- /**
- * @deprecated
- *
- * @see Version::MASTERNODE_RELEASE
- *
- * The transaction version for releasing a masternode.
- */
- public const VERSION_MASTERNODE_RELEASE = Version::MASTERNODE_RELEASE;
-
/** The default value for masternode commands. */
public const VALUE_MASTERNODE_COMMAND = 0.00000001;
/** The default fee for masternode commands. */ | Remove deprecated Transaction class constants | pxgamer_arionum-php | train |
72812572d32a3ab6e790826a28e660f73e73199d | diff --git a/shared/actions/chat.js b/shared/actions/chat.js
index <HASH>..<HASH> 100644
--- a/shared/actions/chat.js
+++ b/shared/actions/chat.js
@@ -884,7 +884,7 @@ function * _loadInbox (action: ?LoadInbox): SagaGenerator<any, any> {
chatInboxConversation: takeFromChannelMap(loadInboxChanMap, 'chat.1.chatUi.chatInboxConversation'),
chatInboxFailed: takeFromChannelMap(loadInboxChanMap, 'chat.1.chatUi.chatInboxFailed'),
finished: takeFromChannelMap(loadInboxChanMap, 'finished'),
- timeout: call(delay, 10000),
+ timeout: call(delay, 30000),
})
if (incoming.chatInboxConversation) { | Bump inbox timeout to <I>s | keybase_client | train |
dde93d104963116541e70f2ecb4cb070a94fae02 | diff --git a/pkg/cmd/util/editor/editor.go b/pkg/cmd/util/editor/editor.go
index <HASH>..<HASH> 100644
--- a/pkg/cmd/util/editor/editor.go
+++ b/pkg/cmd/util/editor/editor.go
@@ -97,7 +97,7 @@ func (e Editor) Launch(path string) error {
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
glog.V(5).Infof("Opening file with editor %v", args)
- if err := withSafeTTYAndInterrupts(os.Stdin, cmd.Run); err != nil {
+ if err := withSafeTTYAndInterrupts(cmd.Run); err != nil {
if err, ok := err.(*exec.Error); ok {
if err.Err == exec.ErrNotFound {
return fmt.Errorf("unable to launch the editor %q", strings.Join(e.Args, " "))
@@ -134,27 +134,32 @@ func (e Editor) LaunchTempFile(dir, prefix string, r io.Reader) ([]byte, string,
// state has been stored, and then on any error or termination attempts to
// restore the terminal state to its prior behavior. It also eats signals
// for the duration of the function.
-func withSafeTTYAndInterrupts(r io.Reader, fn func() error) error {
+func withSafeTTYAndInterrupts(fn func() error) error {
ch := make(chan os.Signal, 1)
signal.Notify(ch, childSignals...)
defer signal.Stop(ch)
- if file, ok := r.(*os.File); ok {
- inFd := file.Fd()
- if term.IsTerminal(inFd) {
- state, err := term.SaveState(inFd)
- if err != nil {
- return err
- }
- go func() {
- if _, ok := <-ch; !ok {
- return
- }
- term.RestoreTerminal(inFd, state)
- }()
- defer term.RestoreTerminal(inFd, state)
- return fn()
+ inFd := os.Stdin.Fd()
+ if !term.IsTerminal(inFd) {
+ if f, err := os.Open("/dev/tty"); err == nil {
+ defer f.Close()
+ inFd = f.Fd()
}
}
+
+ if term.IsTerminal(inFd) {
+ state, err := term.SaveState(inFd)
+ if err != nil {
+ return err
+ }
+ go func() {
+ if _, ok := <-ch; !ok {
+ return
+ }
+ term.RestoreTerminal(inFd, state)
+ }()
+ defer term.RestoreTerminal(inFd, state)
+ return fn()
+ }
return fn()
} | Check /dev/tty if STDIN is not a tty
Should allow piping input streams to edit. | openshift_origin | train |
88e874da0fbc5e14318296fc6443ae4161a1e5cb | diff --git a/modules/DOMHistory.js b/modules/DOMHistory.js
index <HASH>..<HASH> 100644
--- a/modules/DOMHistory.js
+++ b/modules/DOMHistory.js
@@ -24,9 +24,13 @@ class DOMHistory extends History {
this.scrollHistory = {};
}
+ getScrollKey(path, query, key) {
+ return key || this.makePath(path, query);
+ }
+
createLocation(path, query, navigationType, key) {
- var fullPath = this.makePath(path, query);
- var scrollPosition = this.scrollHistory[fullPath];
+ var scrollKey = this.getScrollKey(path, query, key);
+ var scrollPosition = this.scrollHistory[scrollKey];
return new Location(path, query, navigationType, key, scrollPosition);
}
@@ -39,10 +43,10 @@ class DOMHistory extends History {
}
recordScrollPosition() {
- var renderedLocation = this.state.location;
- var renderedFullPath = this.makePath(renderedLocation.path, renderedLocation.query);
+ var location = this.state.location;
+ var scrollKey = this.getScrollKey(location.path, location.query, location.key);
- this.scrollHistory[renderedFullPath] = this.props.getScrollPosition();
+ this.scrollHistory[scrollKey] = this.props.getScrollPosition();
}
} | Use location.key for storing scroll position when available | taion_rrtr | train |
8f45eae1b308f2ae9bf062643c79a366b19f680e | diff --git a/host/fei4/register.py b/host/fei4/register.py
index <HASH>..<HASH> 100644
--- a/host/fei4/register.py
+++ b/host/fei4/register.py
@@ -4,6 +4,9 @@ import re
import os
import numpy as np
import itertools
+from collections import OrderedDict
+import hashlib
+import copy
from utils.utils import string_is_binary, flatten_iterable, iterable, str2bool
@@ -185,6 +188,7 @@ class FEI4Register(object):
self.chip_id = 8 # This 4-bit field always exists and is the chip ID. The three least significant bits define the chip address and are compared with the geographical address of the chip (selected via wire bonding), while the most significant one, if set, means that the command is broadcasted to all FE chips receiving the data stream.
self.chip_flavor = None
self.chip_flavors = ['fei4a', 'fei4b']
+ self.config_state = OrderedDict()
self.load_configuration_file(self.configuration_file)
@@ -965,14 +969,100 @@ class FEI4Register(object):
# print bv.length()
return bv1 + bv0
- def save_config_state(self):
- pass
+ def create_restore_point(self, name=None):
+ '''Creating a configuration restore point.
- def restore_config_state(self):
- pass
+ Parameters
+ ----------
+ name : str
+ Name of the restore point. If not given, a md5 hash will be generated.
+ '''
+ md5 = hashlib.md5()
+ if name is None:
+ md5.update(self.global_registers)
+ md5.update(self.pixel_registers)
+ name = md5.digest()
+ self.config_state[name] = (copy.deepcopy(self.global_registers), copy.deepcopy(self.pixel_registers))
+
+ def restore(self, name=None, keep=False, last=True):
+ '''Restoring a configuration restore point.
+
+ Parameters
+ ----------
+ name : str
+ Name of the restore point. If not given, a md5 hash will be generated.
+ keep : bool
+ Keeping restore point for later use.
+ last : bool
+ If name is not given, the latest restore point will be taken.
+ '''
+ if name is None:
+ if keep:
+ key = next(reversed(self.config_state) if last else iter(self.config_state))
+ self.global_registers, self.pixel_registers = self.config_state[key]
+ else:
+ self.global_registers, self.pixel_registers = copy.deepcopy(self.config_state.popitem(last=last))
+ else:
+ self.global_registers, self.pixel_registers = copy.deepcopy(self.config_state[name])
+ if not keep:
+ del self.config_state[name]
+
+ def clear_restore_points(self, name=None):
+ '''Deleting all/a configuration restore points/point.
+
+ Parameters
+ ----------
+ name : str
+ Name of the restore point to be deleted. If not given, all restore points will be deleted.
+ '''
+ if name is None:
+ self.config_state.clear()
+ else:
+ del self.config_state[name]
+
+ @property
+ def can_restore(self):
+ '''Any restore point existing?
+
+ Parameters
+ ----------
+ none
+
+ Returns
+ -------
+ True if restore points are existing, else false.
+ '''
+ if self.config_state:
+ return True
+ else:
+ return False
- def clear(self):
- pass
+ def has_changed(self, name=None, last=True):
+ '''Compare existing restore point to current configuration.
- def can_undo(self):
- pass
+ Parameters
+ ----------
+ name : str
+ Name of the restore point. If name is not given, the first/last restore point will be taken depending on last.
+ last : bool
+ If name is not given, the latest restore point will be taken.
+
+ Returns
+ -------
+ True if configuration is identical, else false.
+ '''
+ if name is None:
+ key = next(reversed(self.config_state) if last else iter(self.config_state))
+ global_registers, pixel_registers = self.config_state[key]
+ else:
+ global_registers, pixel_registers = self.config_state[name]
+ md5_state = hashlib.md5()
+ md5_state.update(global_registers)
+ md5_state.update(pixel_registers)
+ md5_curr = hashlib.md5()
+ md5_curr.update(self.global_registers)
+ md5_curr.update(self.pixel_registers)
+ if md5_state.digest() != md5_curr.digest():
+ return False
+ else:
+ return True | ENH: added possibility to set configuration restore points | SiLab-Bonn_pyBAR | train |
a1a8de1336271cf92a30a59c610fe792da66a2c5 | diff --git a/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/tests/xunit/CxxXunitSensor.java b/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/tests/xunit/CxxXunitSensor.java
index <HASH>..<HASH> 100644
--- a/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/tests/xunit/CxxXunitSensor.java
+++ b/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/tests/xunit/CxxXunitSensor.java
@@ -164,7 +164,7 @@ public class CxxXunitSensor extends CxxReportSensor {
.withValue(testsCount)
.save();
} catch(Exception ex) {
- LOG.error("Cannot save measure Test : '{}', ignoring measure", ex.getMessage());
+ LOG.error("Cannot save measure TESTS : '{}', ignoring measure", ex.getMessage());
if (!settings.getBoolean(CxxPlugin.ERROR_RECOVERY_KEY)) {
LOG.info("Recovery is disabled, failing analysis.");
throw ex;
@@ -179,7 +179,7 @@ public class CxxXunitSensor extends CxxReportSensor {
.withValue(testsErrors)
.save();
} catch(Exception ex) {
- LOG.error("Cannot save measure Test : '{}', ignoring measure", ex.getMessage());
+ LOG.error("Cannot save measure TEST_ERRORS : '{}', ignoring measure", ex.getMessage());
if (!settings.getBoolean(CxxPlugin.ERROR_RECOVERY_KEY)) {
LOG.info("Recovery is disabled, failing analysis.");
throw ex;
@@ -194,7 +194,7 @@ public class CxxXunitSensor extends CxxReportSensor {
.withValue(testsFailures)
.save();
} catch(Exception ex) {
- LOG.error("Cannot save measure Test : '{}', ignoring measure", ex.getMessage());
+ LOG.error("Cannot save measure TEST_FAILURES : '{}', ignoring measure", ex.getMessage());
if (!settings.getBoolean(CxxPlugin.ERROR_RECOVERY_KEY)) {
LOG.info("Recovery is disabled, failing analysis.");
throw ex;
@@ -209,7 +209,7 @@ public class CxxXunitSensor extends CxxReportSensor {
.withValue(testsSkipped)
.save();
} catch(Exception ex) {
- LOG.error("Cannot save measure Test : '{}', ignoring measure", ex.getMessage());
+ LOG.error("Cannot save measure SKIPPED_TESTS : '{}', ignoring measure", ex.getMessage());
if (!settings.getBoolean(CxxPlugin.ERROR_RECOVERY_KEY)) {
LOG.info("Recovery is disabled, failing analysis.");
throw ex;
@@ -224,7 +224,7 @@ public class CxxXunitSensor extends CxxReportSensor {
.withValue(ParsingUtils.scaleValue(successDensity))
.save();
} catch(Exception ex) {
- LOG.error("Cannot save measure Test : '{}', ignoring measure", ex.getMessage());
+ LOG.error("Cannot save measure TEST_SUCCESS_DENSITY : '{}', ignoring measure", ex.getMessage());
if (!settings.getBoolean(CxxPlugin.ERROR_RECOVERY_KEY)) {
LOG.info("Recovery is disabled, failing analysis.");
throw ex;
@@ -239,7 +239,7 @@ public class CxxXunitSensor extends CxxReportSensor {
.withValue(testsTime)
.save();
} catch(Exception ex) {
- LOG.error("Cannot save measure Test : '{}', ignoring measure", ex.getMessage());
+ LOG.error("Cannot save measure TEST_EXECUTION_TIME : '{}', ignoring measure", ex.getMessage());
if (!settings.getBoolean(CxxPlugin.ERROR_RECOVERY_KEY)) {
LOG.info("Recovery is disabled, failing analysis.");
throw ex; | ignore measures for tests that can be saved because they have been added already | SonarOpenCommunity_sonar-cxx | train |
7ed4b0ec498c33461d68071ebceaab1096c35c77 | diff --git a/AdvancedHTMLParser/Tags.py b/AdvancedHTMLParser/Tags.py
index <HASH>..<HASH> 100644
--- a/AdvancedHTMLParser/Tags.py
+++ b/AdvancedHTMLParser/Tags.py
@@ -76,6 +76,15 @@ class AdvancedTag(object):
except AttributeError:
raise AttributeError('Cannot set property %s. Use setAttribute?' %(name,))
+ def cloneNode(self):
+ '''
+ cloneNode - Clone this node (tag name and attributes). Does not clone children.
+
+ Tags will be equal according to isTagEqual method, but will contain a different internal
+ unique id such tag origTag != origTag.cloneNode() , as is the case in JS DOM.
+ '''
+ return self.__class__(self.tagName, self.getAttributesList(), self.isSelfClosing)
+
def appendText(self, text):
'''
appendText - append some inner text
@@ -287,6 +296,15 @@ class AdvancedTag(object):
return TagCollection(self.children)
@property
+ def childElementCount(self):
+ '''
+ childElementCount - Returns the number of direct children to this node
+
+ @return <int> - The number of direct children to this node
+ '''
+ return len(self.children)
+
+ @property
def parentElement(self):
'''
parentElement - get the parent element
diff --git a/tests/AdvancedHTMLParserTests/test_Building.py b/tests/AdvancedHTMLParserTests/test_Building.py
index <HASH>..<HASH> 100755
--- a/tests/AdvancedHTMLParserTests/test_Building.py
+++ b/tests/AdvancedHTMLParserTests/test_Building.py
@@ -65,6 +65,8 @@ class TestBuilding(object):
assert len(itemsEm.children) == 2 , 'Expected two children'
+ assert itemsEm.childElementCount == 2 , 'Expected childElementCount to equal 2'
+
newItem = AdvancedTag('div')
newItem.setAttributes( {
'name' : 'item',
diff --git a/tests/AdvancedHTMLParserTests/test_Compare.py b/tests/AdvancedHTMLParserTests/test_Compare.py
index <HASH>..<HASH> 100755
--- a/tests/AdvancedHTMLParserTests/test_Compare.py
+++ b/tests/AdvancedHTMLParserTests/test_Compare.py
@@ -170,6 +170,25 @@ class TestCompare(object):
assert child1.isTagEqual(child1Copy) is False, "Expected same tag name same attribute names but different value to return isTagEqual as False"
+ def test_cloneNode(self):
+ parser = AdvancedHTMLParser()
+ parser.parseStr('''
+ <div id="hello" class="classX classY" cheese="cheddar" > <span>Child</span><span>Other Child</span> </div>
+ ''')
+
+ helloEm = parser.getElementById('hello')
+
+ helloClone = helloEm.cloneNode()
+
+ for attributeName in ('id', 'class', 'cheese'):
+ helloEmValue = helloEm.getAttribute(attributeName, None)
+ helloCloneValue = helloClone.getAttribute(attributeName, None)
+ assert helloEmValue == helloCloneValue, 'Expected cloneNode to return an exact copy, got different %s. %s != %s' %(attributeName, repr(helloEmValue), repr(helloCloneValue))
+
+ assert helloEm.childElementCount == 2 , 'Expected original helloEm to retain two direct children'
+ assert helloClone.childElementCount == 0 , 'Expected clone to NOT copy children'
+
+
if __name__ == '__main__':
pipe = subprocess.Popen('GoodTests.py "%s"' %(sys.argv[0],), shell=True).wait() | Implement cloneNode method, to return a copy of the node but not children (and not copy of uid). Also, implement childElementCount property of a tag, as found in JS DOM. | kata198_AdvancedHTMLParser | train |
d39a33f9210fca9ceddddbdd10dd122654763400 | diff --git a/client.go b/client.go
index <HASH>..<HASH> 100644
--- a/client.go
+++ b/client.go
@@ -231,6 +231,8 @@ func newClient(
) (*client, error) {
if tlsConf == nil {
tlsConf = &tls.Config{}
+ } else {
+ tlsConf = tlsConf.Clone()
}
if tlsConf.ServerName == "" {
sni := host | clone TLS conf in newClient (#<I>)
Fixes #<I> | lucas-clemente_quic-go | train |
a1824cb1de627976a54141ba38025a37cdd5b2bd | diff --git a/library/src/main/java/hotchemi/android/rate/AppRate.java b/library/src/main/java/hotchemi/android/rate/AppRate.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/hotchemi/android/rate/AppRate.java
+++ b/library/src/main/java/hotchemi/android/rate/AppRate.java
@@ -204,6 +204,11 @@ public class AppRate {
return this;
}
+ public AppRate setDialogStyle(int resourceId) {
+ options.setDialogStyle(resourceId);
+ return this;
+ }
+
public void monitor() {
if (isFirstLaunch(context)) {
setInstallDate(context);
diff --git a/library/src/main/java/hotchemi/android/rate/DialogOptions.java b/library/src/main/java/hotchemi/android/rate/DialogOptions.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/hotchemi/android/rate/DialogOptions.java
+++ b/library/src/main/java/hotchemi/android/rate/DialogOptions.java
@@ -27,6 +27,8 @@ final class DialogOptions {
private int textNegativeResId = R.string.rate_dialog_no;
+ private int dialogStyleResId = 0;
+
private String titleText = null;
private String messageText = null;
@@ -77,7 +79,7 @@ final class DialogOptions {
return storeType;
}
- public void setStoreType( StoreType appstore ) {
+ public void setStoreType(StoreType appstore) {
storeType = appstore;
}
@@ -191,4 +193,12 @@ final class DialogOptions {
public void setNegativeText(String negativeText) {
this.negativeText = negativeText;
}
+
+ public void setDialogStyle(int dialogStyleResId) {
+ this.dialogStyleResId = dialogStyleResId;
+ }
+
+ public int getDialogStyleResId() {
+ return this.dialogStyleResId;
+ }
}
diff --git a/library/src/main/java/hotchemi/android/rate/Utils.java b/library/src/main/java/hotchemi/android/rate/Utils.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/hotchemi/android/rate/Utils.java
+++ b/library/src/main/java/hotchemi/android/rate/Utils.java
@@ -18,16 +18,18 @@ final class Utils {
return Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1;
}
- static int getDialogTheme() {
- return isLollipop() ? R.style.CustomLollipopDialogStyle : 0;
+ static int getDialogTheme(int defaultStyle) {
+ // TODO: CustomLollipopDialogStyle parent could be switched to AppCompat
+ return defaultStyle == 0 && isLollipop() ? R.style.CustomLollipopDialogStyle : defaultStyle;
}
@SuppressLint("NewApi")
- static AlertDialog.Builder getDialogBuilder(Context context) {
+ static AlertDialog.Builder getDialogBuilder(Context context, int defaultStyle) {
if (underHoneyComb()) {
+ // TODO: verify need for this with support.v7.app.AlertDialog
return new AlertDialog.Builder(context);
} else {
- return new AlertDialog.Builder(context, getDialogTheme());
+ return new AlertDialog.Builder(context, getDialogTheme(defaultStyle));
}
} | Added dialog custom theme
Based on pending PR @swellner | hotchemi_Android-Rate | train |
eeab2b0aad39cff0de1deccf6cdaba2ad04c9a24 | diff --git a/src/Raygun4php/RaygunClient.php b/src/Raygun4php/RaygunClient.php
index <HASH>..<HASH> 100644
--- a/src/Raygun4php/RaygunClient.php
+++ b/src/Raygun4php/RaygunClient.php
@@ -176,11 +176,13 @@ class RaygunClient
/**
* Stores the current user of the calling application. This will be added to any messages sent
* by this provider. It is used in the dashboard to provide unique user tracking.
- * If it is an email address, the user's Gravatar can be displayed. This method is optional,
- * if it is not used a random identifier will be assigned to the current user.
*
- * @param string $user A username, email address or other identifier for the current user
- * of the calling application.
+ * @param string|int $user String or numeric type, identifier for the current user, a username, email address or other unique identifier
+ * @param string $firstName
+ * @param string $fullName
+ * @param string $email
+ * @param boolean $isAnonymous
+ * @param string $uuid
*/
public function SetUser(
$user = null, | udpate set user comment to include parameters | MindscapeHQ_raygun4php | train |
e654d8768cfeaee21e7046964502dfcdf1093dbc | diff --git a/src/Place/ReadModel/Relations/Doctrine/DBALRepository.php b/src/Place/ReadModel/Relations/Doctrine/DBALRepository.php
index <HASH>..<HASH> 100644
--- a/src/Place/ReadModel/Relations/Doctrine/DBALRepository.php
+++ b/src/Place/ReadModel/Relations/Doctrine/DBALRepository.php
@@ -54,24 +54,29 @@ class DBALRepository implements RepositoryInterface
{
$q = $this->connection->createQueryBuilder();
$q
- ->select('event')
+ ->select('place')
->from($this->tableName)
->where('organizer = ?')
->setParameter(0, $organizerId);
$results = $q->execute();
- $events = array();
+ $places = array();
while ($id = $results->fetchColumn(0)) {
- $events[] = $id;
+ $places[] = $id;
}
- return $events;
+ return $places;
}
- public function removeRelations($eventId)
+ public function removeRelations($placeId)
{
- // @todo implement this for non-drupal.
+ $q = $this->connection->createQueryBuilder();
+ $q->delete($this->tableName)
+ ->where('place = ?')
+ ->setParameter(0, $placeId);
+
+ $q->execute();
}
/**
@@ -93,17 +98,17 @@ class DBALRepository implements RepositoryInterface
$table = $schema->createTable($this->tableName);
$table->addColumn(
- 'organizer',
+ 'place',
'string',
- array('length' => 32, 'notnull' => false)
+ array('length' => 36, 'notnull' => false)
);
$table->addColumn(
- 'place',
+ 'organizer',
'string',
- array('length' => 32, 'notnull' => false)
+ array('length' => 36, 'notnull' => false)
);
- $table->setPrimaryKey(array('event'));
+ $table->setPrimaryKey(array('place'));
return $table;
} | III-<I> Implemented DBAL repository for relations of places. | cultuurnet_udb3-php | train |
02f98e08450bd7f0bba61de6d7b75cd6969388e8 | diff --git a/counterfeiter_test.go b/counterfeiter_test.go
index <HASH>..<HASH> 100644
--- a/counterfeiter_test.go
+++ b/counterfeiter_test.go
@@ -83,6 +83,15 @@ var _ = Describe("A Fake generated by counterfeiter", func() {
Expect(arg1).To(ConsistOf(byte(1)))
})
+ It("records a nil slice argument as a nil", func() {
+ var buffer []byte = nil
+
+ fake.DoASlice(buffer)
+
+ arg1 := fake.DoASliceArgsForCall(0)
+ Expect(arg1).To(BeNil())
+ })
+
It("records an array argument as a copy", func() {
buffer := [4]byte{1, 2, 3, 4}
diff --git a/generator/generator.go b/generator/generator.go
index <HASH>..<HASH> 100644
--- a/generator/generator.go
+++ b/generator/generator.go
@@ -187,32 +187,48 @@ func (gen CodeGenerator) stubbedMethodImplementation(method *ast.Field) *ast.Fun
if tArray, ok := t.(*ast.ArrayType); ok && tArray.Len == nil {
copyName := name + "Copy"
bodyStatements = append(bodyStatements,
- &ast.AssignStmt{
- Tok: token.DEFINE,
- Lhs: []ast.Expr{
- ast.NewIdent(copyName),
+ &ast.DeclStmt{
+ Decl: &ast.GenDecl{
+ Tok: token.VAR,
+ Specs: []ast.Spec{
+ &ast.ValueSpec{
+ Names: []*ast.Ident{ast.NewIdent(copyName)},
+ Type: t,
+ },
+ },
},
- Rhs: []ast.Expr{
- &ast.CallExpr{
- Fun: ast.NewIdent("make"),
- Args: []ast.Expr{
- t,
+ },
+ &ast.IfStmt{
+ Cond: nilCheck(ast.NewIdent(name)),
+ Body: &ast.BlockStmt{List: []ast.Stmt{
+ &ast.AssignStmt{
+ Tok: token.ASSIGN,
+ Lhs: []ast.Expr{
+ ast.NewIdent(copyName),
+ },
+ Rhs: []ast.Expr{
&ast.CallExpr{
- Fun: ast.NewIdent("len"),
- Args: []ast.Expr{ast.NewIdent(name)},
+ Fun: ast.NewIdent("make"),
+ Args: []ast.Expr{
+ t,
+ &ast.CallExpr{
+ Fun: ast.NewIdent("len"),
+ Args: []ast.Expr{ast.NewIdent(name)},
+ },
+ },
},
},
},
- },
- },
- &ast.ExprStmt{
- X: &ast.CallExpr{
- Fun: ast.NewIdent("copy"),
- Args: []ast.Expr{
- ast.NewIdent(copyName),
- ast.NewIdent(name),
+ &ast.ExprStmt{
+ X: &ast.CallExpr{
+ Fun: ast.NewIdent("copy"),
+ Args: []ast.Expr{
+ ast.NewIdent(copyName),
+ ast.NewIdent(name),
+ },
+ },
},
- },
+ }},
})
paramValuesToRecord = append(paramValuesToRecord, ast.NewIdent(copyName))
} else {
diff --git a/generator/generator_test.go b/generator/generator_test.go
index <HASH>..<HASH> 100644
--- a/generator/generator_test.go
+++ b/generator/generator_test.go
@@ -119,8 +119,11 @@ func (fake *FakeSomething) DoNothingCallCount() int {
}
func (fake *FakeSomething) DoASlice(arg1 []byte) {
- arg1Copy := make([]byte, len(arg1))
- copy(arg1Copy, arg1)
+ var arg1Copy []byte
+ if arg1 != nil {
+ arg1Copy = make([]byte, len(arg1))
+ copy(arg1Copy, arg1)
+ }
fake.doASliceMutex.Lock()
fake.doASliceArgsForCall = append(fake.doASliceArgsForCall, struct {
arg1 []byte | Record a nil slice as nil (fixes #<I>) | maxbrunsfeld_counterfeiter | train |
25e822253e3953408a715f7055c2f15d40ca6e0d | diff --git a/qiskit/wrapper/jupyter/jupyter_magics.py b/qiskit/wrapper/jupyter/jupyter_magics.py
index <HASH>..<HASH> 100644
--- a/qiskit/wrapper/jupyter/jupyter_magics.py
+++ b/qiskit/wrapper/jupyter/jupyter_magics.py
@@ -81,6 +81,7 @@ class StatusMagic(Magics):
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
+ status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(args.interval)
job_status = job_var.status() | immediately set job status value (#<I>) | Qiskit_qiskit-terra | train |
fea31914767042d0d42800ab82dc29b3e76a6a2b | diff --git a/addon/hint/javascript-hint.js b/addon/hint/javascript-hint.js
index <HASH>..<HASH> 100644
--- a/addon/hint/javascript-hint.js
+++ b/addon/hint/javascript-hint.js
@@ -108,7 +108,8 @@
if (obj.type && obj.type.indexOf("variable") === 0) {
if (options && options.additionalContext)
base = options.additionalContext[obj.string];
- base = base || window[obj.string];
+ if (!options || options.useGlobalScope !== false)
+ base = base || window[obj.string];
} else if (obj.type == "string") {
base = "";
} else if (obj.type == "atom") {
@@ -128,7 +129,8 @@
// (reading into JS mode internals to get at the local and global variables)
for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
- gatherCompletions(window);
+ if (!options || options.useGlobalScope !== false)
+ gatherCompletions(window);
forEach(keywords, maybeAdd);
}
return found; | [javascript-hint addon] Support an option that disables use of the current global scope | codemirror_CodeMirror | train |
6be70860f87ddfbb097c9a9af1991fed8d087b42 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -53,6 +53,11 @@ if sys.version_info[0:2] == (2, 6):
import os_setup
from os_setup import shell, shell_check, import_setuptools
+if sys.version_info[0] == 2:
+ from xmlrpclib import Fault
+else:
+ from xmlrpc.client import Fault
+
_VERBOSE = True
def package_version(filename, varname):
@@ -497,7 +502,20 @@ def main():
if sys.version_info[0:2] == (2, 6):
args['install_requires'].append('ordereddict')
- setup(**args)
+ # The following retry logic attempts to handle the frequent xmlrpc
+ # errors that recently (9/2016) have shown up with Pypi.
+ tries = 2
+ while True:
+ tries -= 1
+ try:
+ setup(**args)
+ except Fault as exc:
+ if tries == 0:
+ raise
+ else:
+ break
+ print("Warning: Retrying setup() because %s was raised: %s"\
+ (exc.__class__.__name__, exc))
if 'install' in sys.argv or 'develop' in sys.argv:
build_moftab(_VERBOSE) | Added retry in setup script for pypi xmlrpc failures. | pywbem_pywbem | train |
f1b1a43a68af3ff5abf3bd617f42bf3f0ba4c036 | diff --git a/contrib/agent/src/test/java/io/opencensus/contrib/agent/bootstrap/ContextManagerTest.java b/contrib/agent/src/test/java/io/opencensus/contrib/agent/bootstrap/ContextManagerTest.java
index <HASH>..<HASH> 100644
--- a/contrib/agent/src/test/java/io/opencensus/contrib/agent/bootstrap/ContextManagerTest.java
+++ b/contrib/agent/src/test/java/io/opencensus/contrib/agent/bootstrap/ContextManagerTest.java
@@ -13,7 +13,11 @@
package io.opencensus.contrib.agent.bootstrap;
+import static org.mockito.Mockito.mock;
+
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -25,16 +29,28 @@ import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ContextManagerTest {
- @Mock
- private ContextStrategy mockContextStrategy;
+ private static final ContextStrategy mockContextStrategy;
+
+ static {
+ mockContextStrategy = mock(ContextStrategy.class);
+ ContextManager.setContextStrategy(mockContextStrategy);
+ }
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
@Mock
private Runnable runnable;
@Test
- public void setContextStrategy() {
+ public void setContextStrategy_already_initialized() {
+ exception.expect(IllegalStateException.class);
+
ContextManager.setContextStrategy(mockContextStrategy);
+ }
+ @Test
+ public void wrapInCurrentContext() {
ContextManager.wrapInCurrentContext(runnable);
Mockito.verify(mockContextStrategy).wrapInCurrentContext(runnable); | Also test double initialization. While there, moved the initialization of ContextManager to the static initializer, otherwise the execution of test methods would matter. | census-instrumentation_opencensus-java | train |
b3350159b02909257962c166014604f71a3669d1 | diff --git a/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index <HASH>..<HASH> 100644
--- a/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -9684,7 +9684,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* the line count is passed as the second argument.
*
* @param self a String
- * @param firstLine the count of the first line
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure (arg 1 is line, optional arg 2 is line number)
* @return the last value returned by the closure
* @throws java.io.IOException if an error occurs
@@ -9718,12 +9718,29 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
}
/**
+ * Iterates through this file line by line. Each line is passed to the
+ * given 1 or 2 arg closure. The file is read using a reader which
+ * is closed before this method returns.
+ *
+ * @param self a File
+ * @param charset opens the file with a specified charset
+ * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1)
+ * @throws IOException if an IOException occurs.
+ * @return the last value returned by the closure
+ * @see #eachLine(java.io.File, int, groovy.lang.Closure)
+ * @since 1.5.5
+ */
+ public static Object eachLine(File self, String charset, Closure closure) throws IOException {
+ return eachLine(self, charset, 1, closure);
+ }
+
+ /**
* Iterates through this file line by line. Each line is passed
* to the given 1 or 2 arg closure. The file is read using a reader
* which is closed before this method returns.
*
* @param self a File
- * @param firstLine the count of the first line
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure (arg 1 is line, optional arg 2 is line number)
* @throws IOException if an IOException occurs.
* @return the last value returned by the closure
@@ -9735,6 +9752,24 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
}
/**
+ * Iterates through this file line by line. Each line is passed
+ * to the given 1 or 2 arg closure. The file is read using a reader
+ * which is closed before this method returns.
+ *
+ * @param self a File
+ * @param charset opens the file with a specified charset
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
+ * @param closure a closure (arg 1 is line, optional arg 2 is line number)
+ * @throws IOException if an IOException occurs.
+ * @return the last value returned by the closure
+ * @see #eachLine(java.io.Reader, int, groovy.lang.Closure)
+ * @since 1.5.7
+ */
+ public static Object eachLine(File self, String charset, int firstLine, Closure closure) throws IOException {
+ return eachLine(newReader(self, charset), firstLine, closure);
+ }
+
+ /**
* Iterates through this stream reading with the provided charset, passing each line to the
* given 1 or 2 arg closure. The stream is closed before this method returns.
*
@@ -9756,7 +9791,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
*
* @param stream a stream
* @param charset opens the stream with a specified charset
- * @param firstLine the count of the first line
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure (arg 1 is line, optional arg 2 is line number)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
@@ -9787,7 +9822,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* The stream is closed before this method returns.
*
* @param stream a stream
- * @param firstLine the count of the first line
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure (arg 1 is line, optional arg 2 is line number)
* @throws IOException if an IOException occurs.
* @return the last value returned by the closure
@@ -9818,7 +9853,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* line to the given 1 or 2 arg closure. The stream is closed before this method returns.
*
* @param url a URL to open and read
- * @param firstLine the count of the first line
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure to apply on each line (arg 1 is line, optional arg 2 is line number)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
@@ -9851,7 +9886,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
*
* @param url a URL to open and read
* @param charset opens the stream with a specified charset
- * @param firstLine the count of the first line
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure to apply on each line (arg 1 is line, optional arg 2 is line number)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
@@ -9883,7 +9918,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* as the second argument. The Reader is closed before this method returns.
*
* @param self a Reader, closed after the method returns
- * @param firstLine the count of the first line
+ * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure which will be passed each line (or for 2 arg closures the line and line count)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs. | GROOVY-<I>: DGM: missing eachLine(File, String, Closure) with charset (patch by Merlyn Albery-Speyer)
git-svn-id: <URL> | groovy_groovy-core | train |
04aca5667d7ed5e8acba857a800eb294464fd501 | diff --git a/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php b/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php
+++ b/lib/Doctrine/ODM/MongoDB/Persisters/DocumentPersister.php
@@ -1042,6 +1042,10 @@ class DocumentPersister
// No further processing for fields without a targetDocument mapping
if ( ! isset($mapping['targetDocument'])) {
+ if ($nextObjectProperty) {
+ $fieldName .= '.'.$nextObjectProperty;
+ }
+
return array($fieldName, $value);
}
@@ -1049,6 +1053,10 @@ class DocumentPersister
// No further processing for unmapped targetDocument fields
if ( ! $targetClass->hasField($objectProperty)) {
+ if ($nextObjectProperty) {
+ $fieldName .= '.'.$nextObjectProperty;
+ }
+
return array($fieldName, $value);
}
diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php
+++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php
@@ -78,6 +78,30 @@ class DocumentPersisterTest extends \Doctrine\ODM\MongoDB\Tests\BaseTest
$this->assertEquals('b', $documents[0]->name);
$this->assertCount(1, $documents);
}
+
+ /**
+ * @dataProvider getTestPrepareQueryOrNewObjData
+ */
+ public function testPrepareFieldName($fieldName, $expected)
+ {
+ $this->assertEquals($expected, $this->documentPersister->prepareFieldName($fieldName));
+ }
+
+ public function getTestPrepareQueryOrNewObjData()
+ {
+ return array(
+ array('name', 'dbName'),
+ array('association', 'associationName'),
+ array('association.id', 'associationName._id'),
+ array('association.nested', 'associationName.nestedName'),
+ array('association.nested.$id', 'associationName.nestedName.$id'),
+ array('association.nested._id', 'associationName.nestedName._id'),
+ array('association.nested.id', 'associationName.nestedName._id'),
+ array('association.nested.association.nested.$id', 'associationName.nestedName.associationName.nestedName.$id'),
+ array('association.nested.association.nested.id', 'associationName.nestedName.associationName.nestedName._id'),
+ array('association.nested.association.nested.firstName', 'associationName.nestedName.associationName.nestedName.firstName'),
+ );
+ }
}
/** @ODM\Document */
@@ -88,4 +112,68 @@ class DocumentPersisterTestDocument
/** @ODM\String(name="dbName") */
public $name;
+
+ /**
+ * @ODM\EmbedOne(
+ * targetDocument="Doctrine\ODM\MongoDB\Tests\Functional\AbstractDocumentPersisterTestDocumentAssociation",
+ * discriminatorField="type",
+ * discriminatorMap={
+ * "reference"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentReference",
+ * "embed"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentEmbed"
+ * },
+ * name="associationName"
+ * )
+ */
+ public $association;
+}
+
+/**
+ * @ODM\EmbeddedDocument
+ * @ODM\InheritanceType("SINGLE_COLLECTION")
+ * @ODM\DiscriminatorField(fieldName="type")
+ * @ODM\DiscriminatorMap({
+ * "reference"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentReference",
+ * "embed"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentEmbed"
+ * })
+ */
+abstract class AbstractDocumentPersisterTestDocumentAssociation
+{
+ /** @ODM\Id */
+ public $id;
+
+ /** @ODM\EmbedOne(name="nestedName") */
+ public $nested;
+
+ /**
+ * @ODM\EmbedOne(
+ * targetDocument="Doctrine\ODM\MongoDB\Tests\Functional\AbstractDocumentPersisterTestDocumentAssociation",
+ * discriminatorField="type",
+ * discriminatorMap={
+ * "reference"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentReference",
+ * "embed"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentEmbed"
+ * },
+ * name="associationName"
+ * )
+ */
+ public $association;
+}
+
+/** @ODM\EmbeddedDocument */
+class DocumentPersisterTestDocumentReference extends AbstractDocumentPersisterTestDocumentAssociation
+{
+ /** @ODM\Id */
+ public $id;
+
+ /** @ODM\ReferenceOne(name="nestedName") */
+ public $nested;
+}
+
+/** @ODM\EmbeddedDocument */
+class DocumentPersisterTestDocumentEmbed extends AbstractDocumentPersisterTestDocumentAssociation
+{
+ /** @ODM\Id */
+ public $id;
+
+ /** @ODM\EmbedOne(name="nestedName") */
+ public $nested;
} | Fix issue with nested reference queries not being prepared properly. | Briareos_mongodb-odm | train |
46a6385a33a6b9163c0637384b233815467bfdc1 | diff --git a/Swat/javascript/swat-disclosure.js b/Swat/javascript/swat-disclosure.js
index <HASH>..<HASH> 100644
--- a/Swat/javascript/swat-disclosure.js
+++ b/Swat/javascript/swat-disclosure.js
@@ -8,7 +8,7 @@ function toggleDisclosureWidget(id) {
img.alt = 'open';
} else {
div.className = 'swat-disclosure-container-opened';
- img.src = 'swat/images/disclosure-opened.png';
+ img.src = 'swat/images/disclosure-open.png';
img.alt = 'close';
}
} | Updated SwatDisclosure javascript for renamed open triangle graphic.
svn commit r<I> | silverorange_swat | train |
ad6d945991392a575a0218e708813c98cceea065 | diff --git a/js/liqui.js b/js/liqui.js
index <HASH>..<HASH> 100644
--- a/js/liqui.js
+++ b/js/liqui.js
@@ -291,11 +291,13 @@ module.exports = class liqui extends Exchange {
symbol = market['symbol'];
let amount = trade['amount'];
let type = 'market';
+ let takerOrMaker = 'taker';
// this is filled by fetchMyTrades() only
let isYourOrder = this.safeValue (trade, 'is_your_order');
- if (isYourOrder)
+ if (isYourOrder) {
type = 'limit';
- let takerOrMaker = (type == 'market') ? 'taker' : 'maker'; // warning: a limit order isn't always a maker
+ takerOrMaker = 'maker';
+ }
let fee = this.calculateFee (symbol, type, side, amount, price, takerOrMaker);
return {
'id': id, | explicit flow to liqui fees #<I> | ccxt_ccxt | train |
Subsets and Splits