hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
a164de623b94e5cf7b19d014e7c8eb389693a98f
|
diff --git a/salt/cloud/clouds/nova.py b/salt/cloud/clouds/nova.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/clouds/nova.py
+++ b/salt/cloud/clouds/nova.py
@@ -820,12 +820,12 @@ def volume_create(name, size=100, snapshot=None, voltype=None, **kwargs):
Create block storage device
'''
conn = get_conn()
- return conn.volume_create(
- name,
- size,
- snapshot,
- voltype
- )
+ create_kwargs = {'name': name,
+ 'size': size,
+ 'snapshot': snapshot,
+ 'voltype': voltype}
+ create_kwargs['availability_zone'] = kwargs.get('availability_zone', None)
+ return conn.volume_create(**create_kwargs)
def volume_delete(name, **kwargs):
diff --git a/salt/utils/openstack/nova.py b/salt/utils/openstack/nova.py
index <HASH>..<HASH> 100644
--- a/salt/utils/openstack/nova.py
+++ b/salt/utils/openstack/nova.py
@@ -293,7 +293,8 @@ class SaltNova(object):
return volume
- def volume_create(self, name, size=100, snapshot=None, voltype=None):
+ def volume_create(self, name, size=100, snapshot=None, voltype=None,
+ availability_zone=None):
'''
Create a block device
'''
@@ -302,7 +303,8 @@ class SaltNova(object):
size=size,
display_name=name,
volume_type=voltype,
- snapshot_id=snapshot
+ snapshot_id=snapshot,
+ availability_zone=availability_zone
)
return self._volume_get(response.id)
|
added availability_zones to nova cloud
|
saltstack_salt
|
train
|
aea9511b2d4192761b3c0b13810e59977a7c13f7
|
diff --git a/src/EventExport/FileWriter/CSVFileWriter.php b/src/EventExport/FileWriter/CSVFileWriter.php
index <HASH>..<HASH> 100644
--- a/src/EventExport/FileWriter/CSVFileWriter.php
+++ b/src/EventExport/FileWriter/CSVFileWriter.php
@@ -116,8 +116,9 @@ class CSVFileWriter implements FileWriterInterface
{
return [
'id' => [ 'name' => 'id', 'include' => function ($event) {
- $eventId = $event->{'@id'};
- var_dump('id: ' . $eventId);
+ $eventUri = $event->{'@id'};
+ $uriParts = explode('/',$eventUri);
+ $eventId = array_pop($uriParts);
return $eventId;
}, 'property' => 'id' ],
'name' => [ 'name' => 'titel', 'include' => function ($event) {
|
III-<I>: Pop event IDs from URL when Exporting as CSV
|
cultuurnet_udb3-php
|
train
|
6a98a65efc69e8b49195faff9b5e455dc45f29aa
|
diff --git a/alot/command.py b/alot/command.py
index <HASH>..<HASH> 100644
--- a/alot/command.py
+++ b/alot/command.py
@@ -546,4 +546,13 @@ class BounceMailCommand(Command):
mail = msg.get_email()
del(mail['To'])
ui.apply_command(ComposeCommand(mail=mail))
+
+### taglist
+class TaglistSelectCommand(Command):
+ def apply(self, ui):
+ tagstring = ui.current_buffer.get_selected_tag()
+ cmd = SearchCommand(query='tag:%s' % tagstring)
+ ui.apply_command(cmd)
+
+
import envelope
diff --git a/alot/commandfactory.py b/alot/commandfactory.py
index <HASH>..<HASH> 100644
--- a/alot/commandfactory.py
+++ b/alot/commandfactory.py
@@ -59,6 +59,9 @@ COMMANDS = {
'reply': (command.ReplyCommand, {}),
'groupreply': (command.ReplyCommand, {'groupreply': True}),
'bounce': (command.BounceMailCommand, {}),
+
+ # taglist
+ 'select': (command.TaglistSelectCommand, {}),
}
@@ -112,7 +115,7 @@ ALLOWED_COMMANDS = {
'retagprompt'] + globalcomands,
'envelope': ['send', 'reedit', 'to', 'subject'] + globalcomands,
'bufferlist': ['openfocussed', 'closefocussed'] + globalcomands,
- 'taglist': globalcomands,
+ 'taglist': ['select'] + globalcomands,
'thread': ['toggletag', 'reply', 'groupreply', 'bounce'] + globalcomands,
}
@@ -147,7 +150,7 @@ def interpret_commandline(cmdline, mode):
'openfocussed', 'closefocussed', 'bnext', 'bprevious',
'retag', 'refresh', 'bufferlist', 'refineprompt', 'reply',
'groupreply', 'bounce', 'openthread', 'send', 'reedit',
- 'retagprompt']:
+ 'select', 'retagprompt']:
return commandfactory(cmd)
else:
return None
diff --git a/alot/settings.py b/alot/settings.py
index <HASH>..<HASH> 100644
--- a/alot/settings.py
+++ b/alot/settings.py
@@ -319,8 +319,7 @@ MAPPING = {
'g': ('groupreply', ''),
},
'taglist': {
- # 'enter': ('search', {'query': (lambda: 'tag:' +
- # self.get_selected_tag())}),
+ 'enter': ('select', ''),
},
'envelope': {
'y': ('send', ''),
|
select in taglist works again. issue #<I>
|
pazz_alot
|
train
|
89fdd9796d501b444fe79d086d81e92b93446355
|
diff --git a/ocrd_utils/ocrd_utils/__init__.py b/ocrd_utils/ocrd_utils/__init__.py
index <HASH>..<HASH> 100644
--- a/ocrd_utils/ocrd_utils/__init__.py
+++ b/ocrd_utils/ocrd_utils/__init__.py
@@ -423,7 +423,7 @@ def get_local_filename(url, start=None):
url = url[len('file://'):]
# Goobi/Kitodo produces those, they are always absolute
if url.startswith('file:/'):
- url = url[len('file:'):]
+ raise Exception("Invalid (java) URL: %s" % url)
if start:
if not url.startswith(start):
raise Exception("Cannot remove prefix %s from url %s" % (start, url))
@@ -477,7 +477,7 @@ def is_local_filename(url):
"""
Whether a url is a local filename.
"""
- return url.startswith('file:/') or not('://' in url)
+ return url.startswith('file://') or not('://' in url)
def is_string(val):
"""
diff --git a/ocrd_validators/ocrd_validators/workspace_validator.py b/ocrd_validators/ocrd_validators/workspace_validator.py
index <HASH>..<HASH> 100644
--- a/ocrd_validators/ocrd_validators/workspace_validator.py
+++ b/ocrd_validators/ocrd_validators/workspace_validator.py
@@ -194,7 +194,7 @@ class WorkspaceValidator():
self.report.add_error("File '%s' does not manifest any physical page." % f.ID)
if 'url' not in self.skip and f.url and ':/' in f.url:
if re.match(r'^file:/[^/]', f.url):
- self.report.add_warning("File '%s' has an invalid (Java-specific) file URL '%s'" % (f.ID, f.url))
+ self.report.add_error("File '%s' has an invalid (Java-specific) file URL '%s'" % (f.ID, f.url))
scheme = f.url[0:f.url.index(':')]
if scheme not in ('http', 'https', 'file'):
self.report.add_warning("File '%s' has non-HTTP, non-file URL '%s'" % (f.ID, f.url))
diff --git a/tests/test_utils.py b/tests/test_utils.py
index <HASH>..<HASH> 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -152,7 +152,8 @@ class TestUtils(TestCase):
def test_local_filename(self):
self.assertEqual(get_local_filename('/foo/bar'), '/foo/bar')
self.assertEqual(get_local_filename('file:///foo/bar'), '/foo/bar')
- self.assertEqual(get_local_filename('file:/foo/bar'), '/foo/bar')
+ with self.assertRaisesRegex(Exception, "Invalid.* URL"):
+ self.assertEqual(get_local_filename('file:/foo/bar'), '/foo/bar')
self.assertEqual(get_local_filename('/foo/bar', '/foo/'), 'bar')
self.assertEqual(get_local_filename('/foo/bar', '/foo'), 'bar')
self.assertEqual(get_local_filename('foo/bar', 'foo'), 'bar')
diff --git a/tests/validator/test_workspace_validator.py b/tests/validator/test_workspace_validator.py
index <HASH>..<HASH> 100644
--- a/tests/validator/test_workspace_validator.py
+++ b/tests/validator/test_workspace_validator.py
@@ -88,13 +88,8 @@ class TestWorkspaceValidator(TestCase):
f = workspace.mets.add_file('OCR-D-GT-PAGE', ID='file2', mimetype='image/png', pageId='page2', url='nothttp://unusual.scheme')
f._el.set('GROUPID', 'donotuse') # pylint: disable=protected-access
workspace.save_mets()
- report = WorkspaceValidator.validate(self.resolver, join(tempdir, 'mets.xml'), skip=['pixel_density'])
- self.assertEqual(len(report.errors), 0)
- self.assertEqual(len(report.warnings), 2)
- self.assertIn("Java-specific", report.warnings[0])
- self.assertIn("non-HTTP", report.warnings[1])
- self.assertEqual(len(report.notices), 1)
- self.assertIn("has GROUPID attribute", report.notices[0])
+ with self.assertRaisesRegex(Exception, "Invalid.* URL"):
+ WorkspaceValidator.validate(self.resolver, join(tempdir, 'mets.xml'), skip=['pixel_density'])
def test_validate_pixel_no_download(self):
imgpath = assets.path_to('kant_aufklaerung_1784-binarized/data/OCR-D-IMG-BIN/BIN_0020.png')
|
raise exceptions for pseudo-file URL (file:/path instead of file://path)
|
OCR-D_core
|
train
|
aabc7a11734b3f5e645dd1b9c68a470c36b678ec
|
diff --git a/src/Rapid/Model/Support/HasAttributesTrait.php b/src/Rapid/Model/Support/HasAttributesTrait.php
index <HASH>..<HASH> 100644
--- a/src/Rapid/Model/Support/HasAttributesTrait.php
+++ b/src/Rapid/Model/Support/HasAttributesTrait.php
@@ -42,8 +42,6 @@ trait HasAttributesTrait
foreach ($attributes as $key => $value) {
if ($this->isFillable($key)) {
$this->setAttribute($key, $value);
- } else {
- throw new MassAssignmentException(sprintf("Unexpected attribute '%s' for class %s", $key, $class));
}
}
|
Remove exception thrown for Rapid fields not in SDK Models
|
eWAYPayment_eway-rapid-php
|
train
|
e7a0370621aead1b9069e88a994af4b5e8bca25a
|
diff --git a/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java b/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java
index <HASH>..<HASH> 100644
--- a/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java
+++ b/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java
@@ -21,6 +21,7 @@ public class SlidingTimeWindowReservoir implements Reservoir {
private final long window;
private final AtomicLong lastTick;
private final AtomicLong count;
+ private final long startTick;
/**
* Creates a new {@link SlidingTimeWindowReservoir} with the given window of time.
@@ -40,10 +41,11 @@ public class SlidingTimeWindowReservoir implements Reservoir {
* @param clock the {@link Clock} to use
*/
public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) {
+ this.startTick = clock.getTick();
this.clock = clock;
this.measurements = new ConcurrentSkipListMap<>();
this.window = windowUnit.toNanos(window) * COLLISION_BUFFER;
- this.lastTick = new AtomicLong(clock.getTick() * COLLISION_BUFFER);
+ this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER);
this.count = new AtomicLong();
}
@@ -70,7 +72,7 @@ public class SlidingTimeWindowReservoir implements Reservoir {
private long getTick() {
for ( ;; ) {
final long oldTick = lastTick.get();
- final long tick = clock.getTick() * COLLISION_BUFFER;
+ final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER;
// ensure the tick is strictly incrementing even if there are duplicate ticks
final long newTick = tick - oldTick > 0 ? tick : oldTick + 1;
if (lastTick.compareAndSet(oldTick, newTick)) {
diff --git a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java
index <HASH>..<HASH> 100644
--- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java
+++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java
@@ -28,6 +28,8 @@ public class SlidingTimeWindowReservoirTest {
@Test
public void boundsMeasurementsToATimeWindow() {
final Clock clock = mock(Clock.class);
+ when(clock.getTick()).thenReturn(0L);
+
final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(10, NANOSECONDS, clock);
when(clock.getTick()).thenReturn(0L);
@@ -61,14 +63,15 @@ public class SlidingTimeWindowReservoirTest {
for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) {
//logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, updatesPerTick);
- // Set the clock to overflow in (2*window+1)ns
final ManualClock clock = new ManualClock();
- clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick());
- assertThat(clock.getTick() * 256).isGreaterThan(0);
// Create the reservoir
final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(window, NANOSECONDS, clock);
+ // Set the clock to overflow in (2*window+1)ns
+ clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick());
+ assertThat(clock.getTick() * 256).isGreaterThan(0);
+
int updatesAfterThreshold = 0;
while (true) {
// Update the reservoir
|
Improve tick overflow handling in SlidingTimeWindowReservoir (#<I>)
|
dropwizard_metrics
|
train
|
3449394c5f3609a63cfba1b720ddda86c4769b50
|
diff --git a/lib/mongoid/persistence_context.rb b/lib/mongoid/persistence_context.rb
index <HASH>..<HASH> 100644
--- a/lib/mongoid/persistence_context.rb
+++ b/lib/mongoid/persistence_context.rb
@@ -107,6 +107,10 @@ module Mongoid
#
# @since 6.0.0
def client
+ client_options = send(:client_options)
+ if client_options[:read].is_a?(Symbol)
+ client_options = client_options.merge(read: {mode: client_options[:read]})
+ end
@client ||= (client = Clients.with_name(client_name)
client = client.use(database_name) if database_name_option
client.with(client_options))
@@ -208,7 +212,7 @@ module Mongoid
if context = get(object)
context.client.close unless (context.cluster.equal?(cluster) || cluster.nil?)
end
- ensure
+ ensure
Thread.current["[mongoid][#{object.object_id}]:context"] = nil
end
end
diff --git a/spec/mongoid/clients/options_spec.rb b/spec/mongoid/clients/options_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mongoid/clients/options_spec.rb
+++ b/spec/mongoid/clients/options_spec.rb
@@ -188,25 +188,40 @@ describe Mongoid::Clients::Options do
context 'when returning a criteria' do
- let(:context_and_criteria) do
- collection = nil
- cxt = TestModel.with(read: :secondary) do |klass|
- collection = klass.all.collection
- klass.persistence_context
+ shared_context 'applies secondary read preference' do
+
+ let(:context_and_criteria) do
+ collection = nil
+ cxt = TestModel.with(read_secondary_option) do |klass|
+ collection = klass.all.collection
+ klass.persistence_context
+ end
+ [ cxt, collection ]
end
- [ cxt, collection ]
- end
- let(:persistence_context) do
- context_and_criteria[0]
+ let(:persistence_context) do
+ context_and_criteria[0]
+ end
+
+ let(:client) do
+ context_and_criteria[1].client
+ end
+
+ it 'applies the options to the criteria client' do
+ expect(client.options['read']).to eq('mode' => :secondary)
+ end
end
- let(:client) do
- context_and_criteria[1].client
+ context 'read: :secondary shorthand' do
+ let(:read_secondary_option) { {read: :secondary} }
+
+ it_behaves_like 'applies secondary read preference'
end
- it 'applies the options to the criteria client' do
- expect(client.options['read']).to eq(:secondary)
+ context 'read: {mode: :secondary}' do
+ let(:read_secondary_option) { {read: {mode: :secondary}} }
+
+ it_behaves_like 'applies secondary read preference'
end
end
|
Fix read preference passing to ruby driver
|
mongodb_mongoid
|
train
|
ca124569ce6c928b5bf4bfafa8097dcc45ba12a5
|
diff --git a/lib/cache-serializers.js b/lib/cache-serializers.js
index <HASH>..<HASH> 100644
--- a/lib/cache-serializers.js
+++ b/lib/cache-serializers.js
@@ -78,7 +78,12 @@ LevelDbSerializer.prototype.write = function(moduleOps) {
}
for (var i = 0; i < ops.length; i++) {
- ops.type = 'put';
+ if (ops[i].value === null) {
+ ops[i].type = 'delete';
+ }
+ else {
+ ops[i].type = 'put';
+ }
}
var cachePath = this.path;
|
Set batch op type in leveldb serializer
Let items get deleted from the db when its value would be null.
|
mzgoddard_hard-source-webpack-plugin
|
train
|
6554e5ac3d0eccfcca338ae9c1da6db9ec86fdf5
|
diff --git a/salt/modules/virt.py b/salt/modules/virt.py
index <HASH>..<HASH> 100644
--- a/salt/modules/virt.py
+++ b/salt/modules/virt.py
@@ -75,7 +75,6 @@ The calls not using the libvirt connection setup are:
# Special Thanks to Michael Dehann, many of the concepts, and a few structures
# of his in the virt func module have been used
-# Import python libs
import base64
import copy
@@ -91,10 +90,7 @@ import time
from xml.etree import ElementTree
from xml.sax import saxutils
-# Import third party libs
import jinja2.exceptions
-
-# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
@@ -2616,8 +2612,8 @@ def update(
data = {k: v for k, v in locals().items() if bool(v)}
if boot_dev:
data["boot_dev"] = {i + 1: dev for i, dev in enumerate(boot_dev.split())}
- need_update = need_update or salt.utils.xmlutil.change_xml(
- desc, data, params_mapping
+ need_update = (
+ salt.utils.xmlutil.change_xml(desc, data, params_mapping) or need_update
)
# Update the XML definition with the new disks and diff changes
diff --git a/tests/unit/modules/test_virt.py b/tests/unit/modules/test_virt.py
index <HASH>..<HASH> 100644
--- a/tests/unit/modules/test_virt.py
+++ b/tests/unit/modules/test_virt.py
@@ -4,7 +4,6 @@ virt execution module unit tests
# pylint: disable=3rd-party-module-not-gated
-# Import python libs
import datetime
import os
@@ -15,16 +14,12 @@ import salt.config
import salt.modules.config as config
import salt.modules.virt as virt
import salt.syspaths
-
-# Import salt libs
import salt.utils.yaml
from salt._compat import ElementTree as ET
from salt.exceptions import CommandExecutionError, SaltInvocationError
# pylint: disable=import-error
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
-
-# Import Salt Testing libs
from tests.support.helpers import dedent
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
@@ -1858,6 +1853,24 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin):
virt.update("my_vm"),
)
+ # mem + cpu case
+ define_mock.reset_mock()
+ domain_mock.setMemoryFlags.return_value = 0
+ domain_mock.setVcpusFlags.return_value = 0
+ self.assertEqual(
+ {
+ "definition": True,
+ "disk": {"attached": [], "detached": [], "updated": []},
+ "interface": {"attached": [], "detached": []},
+ "mem": True,
+ "cpu": True,
+ },
+ virt.update("my_vm", mem=2048, cpu=2),
+ )
+ setxml = ET.fromstring(define_mock.call_args[0][0])
+ self.assertEqual("2", setxml.find("vcpu").text)
+ self.assertEqual("2048", setxml.find("memory").text)
+
# Same parameters passed than in default virt.defined state case
self.assertEqual(
{
|
Fix virt update when cpu and memory are changed
If CPU is changed, the memory change would be short circuited. This is a
regression introduced by PR #<I>
|
saltstack_salt
|
train
|
f8a7bf86548dc106e9ed431f4b95edaaf077c0ff
|
diff --git a/util_test.go b/util_test.go
index <HASH>..<HASH> 100644
--- a/util_test.go
+++ b/util_test.go
@@ -5,6 +5,7 @@ import (
"bytes"
"flag"
"fmt"
+ "io"
"math/rand"
"net/textproto"
"strings"
@@ -13,31 +14,78 @@ import (
var compareWithStd = flag.Bool("std", false, "compare with standard library implementation (if exists)")
+var readLineCases = []struct {
+ label string
+ in string
+ line []byte
+ err error
+ bufSize int
+}{
+ {
+ label: "simple",
+ in: "hello, world!",
+ line: []byte("hello, world!"),
+ err: io.EOF,
+ bufSize: 1024,
+ },
+ {
+ label: "simple",
+ in: "hello, world!\r\n",
+ line: []byte("hello, world!"),
+ bufSize: 1024,
+ },
+ {
+ label: "simple",
+ in: "hello, world!\n",
+ line: []byte("hello, world!"),
+ bufSize: 1024,
+ },
+ {
+ // The case where "\r\n" straddles the buffer.
+ label: "straddle",
+ in: "hello, world!!!\r\n...",
+ line: []byte("hello, world!!!"),
+ bufSize: 16,
+ },
+ {
+ label: "chunked",
+ in: "hello, world! this is a long long line!",
+ line: []byte("hello, world! this is a long long line!"),
+ err: io.EOF,
+ bufSize: 16,
+ },
+ {
+ label: "chunked",
+ in: "hello, world! this is a long long line!\r\n",
+ line: []byte("hello, world! this is a long long line!"),
+ bufSize: 16,
+ },
+}
+
func TestReadLine(t *testing.T) {
- for _, test := range []struct {
- label string
- in string
- bufSize int
- }{
- {
- label: "simple",
- in: "hello, world!",
- bufSize: 1024,
- },
- {
- label: "chunked",
- in: "hello, world! this is a long long line!",
- bufSize: 16,
- },
- } {
+ for _, test := range readLineCases {
t.Run(test.label, func(t *testing.T) {
br := bufio.NewReaderSize(strings.NewReader(test.in), test.bufSize)
bts, err := readLine(br)
- if err != nil {
- t.Errorf("unexpected error: %s", err)
+ if err != test.err {
+ t.Errorf("unexpected error: %v; want %v", err, test.err)
+ }
+ if act, exp := bts, test.line; !bytes.Equal(act, exp) {
+ t.Errorf("readLine() result is %#q; want %#q", act, exp)
}
- if act, exp := string(bts), test.in; act != exp {
- t.Errorf("readLine() returned %#q; want %#q", act, exp)
+ })
+ }
+}
+
+func BenchmarkReadLine(b *testing.B) {
+ for _, test := range readLineCases {
+ sr := strings.NewReader(test.in)
+ br := bufio.NewReaderSize(sr, test.bufSize)
+ b.Run(test.label, func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _, _ = readLine(br)
+ sr.Reset(test.in)
+ br.Reset(sr)
}
})
}
|
util: readLine more tests and benchmarks
|
gobwas_ws
|
train
|
f80c32ba96c066ad6e5ae15533072c9acb475f89
|
diff --git a/app/helpers/admin/configuration_helper.rb b/app/helpers/admin/configuration_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/admin/configuration_helper.rb
+++ b/app/helpers/admin/configuration_helper.rb
@@ -20,7 +20,7 @@ module Admin::ConfigurationHelper
html << content_tag(:span, value, :id => domkey, :class => options[:class])
end
html << content_tag(:span, " #{t("units.#{setting.units}")}", :class => 'units') if setting.units
- html << content_tag(:span, " #{t('warning')}: #{[setting.errors.on(:value)].flatten.first}", :class => 'warning') if setting.errors.on(:value)
+ html << content_tag(:span, " #{t('warning')}: #{[setting.errors.get(:value)].flatten.first}", :class => 'warning') if setting.errors.get(:value)
html
end
diff --git a/lib/string_extensions/string_extensions.rb b/lib/string_extensions/string_extensions.rb
index <HASH>..<HASH> 100644
--- a/lib/string_extensions/string_extensions.rb
+++ b/lib/string_extensions/string_extensions.rb
@@ -6,7 +6,7 @@ class String
end
def titlecase
- self.gsub(/((?:^|\s)[a-z])/) { $1.upcase }
+ self.gsub(/((?:^|\s)[a-z])/) { $1.to_s.upcase }
end
def to_name(last_part = '')
|
Added to_s to force nil to string if necessary (Thanks Wuest!). Also fixed deprecated .on method to .get method! I DID THAT ALL BY MYSELF WOOOO! :D resolves #<I>
|
pgharts_trusty-cms
|
train
|
2f90b38273c43e9dda01b8abcb68784463b1542b
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,5 @@
from setuptools import setup
-with open('README.rst') as f:
- readme = f.read()
with open('LICENSE') as f:
license = f.read()
@@ -10,7 +8,6 @@ setup(
name='pybotvac',
version='0.0.1',
description='Python package for controlling Neato pybotvac Connected vacuum robot',
- long_description=readme,
author='Stian Askeland',
author_email='stianaske@gmail.com',
url='https://github.com/stianaske/pybotvac',
|
Update setup.py
Removed reference to README.rst.
|
stianaske_pybotvac
|
train
|
a6036d57a54780a24271d9ce776b2f109d5966c1
|
diff --git a/engine_api.md b/engine_api.md
index <HASH>..<HASH> 100644
--- a/engine_api.md
+++ b/engine_api.md
@@ -103,17 +103,6 @@ Response:
The requested result as a blob of text. If the desired `export_type` is not supported, an HTTP 404 error is returned.
-#### GET /v1/calc/:calc_id/log
-
-Get the full calculation log for the given `calc_id`.
-
-Parameters: None
-
-Response:
-
-The requested log as a JSON list of rows
-
-
#### GET /v1/calc/:calc_id/log/:start:[:stop]
Get a slice of the calculation log for the given `calc_id`, from `start`
diff --git a/openquake/server/v1/calc_urls.py b/openquake/server/v1/calc_urls.py
index <HASH>..<HASH> 100644
--- a/openquake/server/v1/calc_urls.py
+++ b/openquake/server/v1/calc_urls.py
@@ -7,8 +7,7 @@ urlpatterns = patterns(
url(r'^(\d+)$', 'calc_info'),
url(r'^(\d+)/results$', 'calc_results'),
url(r'^(\d+)/log/size$', 'get_log_size'),
- url(r'^(\d+)/log/(\d+):(\d*)$', 'get_log_slice'),
- url(r'^(\d+)/log$', 'get_log'),
+ url(r'^(\d+)/log/(\d*):(\d*)$', 'get_log_slice'),
url(r'^result/(\d+)$', 'get_result'),
url(r'^run$', 'run_calc'),
)
diff --git a/openquake/server/views.py b/openquake/server/views.py
index <HASH>..<HASH> 100644
--- a/openquake/server/views.py
+++ b/openquake/server/views.py
@@ -1,4 +1,3 @@
-import zipfile
import shutil
import json
import logging
@@ -185,6 +184,7 @@ def get_log_slice(request, calc_id, start, stop):
"""
Get a slice of the calculation log as a JSON list of rows
"""
+ start = start or 0
stop = stop or None
try:
rows = oqe_models.Log.objects.filter(job_id=calc_id)[start:stop]
@@ -207,13 +207,6 @@ def get_log_size(request, calc_id):
return HttpResponse(content=json.dumps(response_data), content_type=JSON)
-def get_log(request, calc_id):
- """
- Get the full log of the calculation as a JSON list of rows
- """
- return get_log_slice(request, calc_id, 0, None)
-
-
@csrf_exempt
@cross_domain_ajax
@require_http_methods(['POST'])
|
Removed get_log since get_log_slice does everything
Former-commit-id: <I>c<I>d<I>ac<I>c<I>eab<I>c<I>b<I>f
|
gem_oq-engine
|
train
|
5b557316263440ecb6d7eef5fc34a217a05d1f0d
|
diff --git a/tests/test_client.py b/tests/test_client.py
index <HASH>..<HASH> 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -6,6 +6,7 @@ import random
import unittest
from io import StringIO
from xml.etree import ElementTree
+import random
from pysolr import (NESTED_DOC_KEY, Results, Solr, SolrError, clean_xml_string,
force_bytes, force_unicode, json, safe_urlencode, sanitize,
|
delete(): improved multiple-id code and tests
Received all feedback as of PR#<I> comment:
<<URL>
|
django-haystack_pysolr
|
train
|
7f7faa2dfecbe674e8a76a695efee997cd7edf5d
|
diff --git a/src/js/common/parser.js b/src/js/common/parser.js
index <HASH>..<HASH> 100644
--- a/src/js/common/parser.js
+++ b/src/js/common/parser.js
@@ -177,7 +177,8 @@ gpii.schema.parser.lookupDescription = function (that, schemaKey, schemaFieldPat
*/
gpii.schema.parser.updateSchemas = function (that) {
var promises = [];
- fluid.each(that.model.schemas, function (schemaContent, schemaKey) {
+ fluid.each(
+ that.model.schemas, function (schemaContent, schemaKey) {
if (!that.dereferencedSchemas[schemaKey]) {
promises.push(gpii.schema.parser.dereference(that, schemaKey));
}
@@ -186,7 +187,7 @@ gpii.schema.parser.updateSchemas = function (that) {
if (promises.length > 0) {
fluid.promise.sequence(promises).then(function () {
that.events.onSchemasUpdated.fire(that);
- });
+ }, fluid.fail);
}
};
diff --git a/src/js/common/validate.js b/src/js/common/validate.js
index <HASH>..<HASH> 100644
--- a/src/js/common/validate.js
+++ b/src/js/common/validate.js
@@ -104,13 +104,13 @@ gpii.schema.validator.sanitizeValidationErrors = function (that, schemaKey, erro
// If we have a parser, we will evolve the output if possible, and use that to replace every raw message for
// the same field.
//
- if (that.parser) {
+ //if (that.parser) {
var evolvedMessage = that.parser.lookupDescription(schemaKey, path);
if (evolvedMessage) {
errorMessage = evolvedMessage;
overwriteExisting = true;
}
- }
+ //}
gpii.schema.validator.saveToPath(path, errorMessage, sanitizedErrors, overwriteExisting);
});
@@ -324,11 +324,7 @@ fluid.defaults("gpii.schema.validator", {
excludeSource: "init",
args: ["{that}"]
}
- }
-});
-
-// Convenience grade to add a parser to any validator, with the same schemas, etc. configured.
-fluid.defaults("gpii.schema.validator.hasParser", {
+ },
components: {
parser: {
type: "gpii.schema.parser",
@@ -340,4 +336,5 @@ fluid.defaults("gpii.schema.validator.hasParser", {
}
}
}
-});
\ No newline at end of file
+});
+
diff --git a/src/js/server/schemaMiddleware.js b/src/js/server/schemaMiddleware.js
index <HASH>..<HASH> 100644
--- a/src/js/server/schemaMiddleware.js
+++ b/src/js/server/schemaMiddleware.js
@@ -126,13 +126,4 @@ fluid.defaults("gpii.schema.middleware", {
}
}
-});
-
-fluid.defaults("gpii.schema.middleware.hasParser", {
- gradeNames: ["gpii.schema.middleware"],
- components: {
- validator: {
- type: "gpii.schema.validator.server.hasParser"
- }
- }
-});
+});
\ No newline at end of file
diff --git a/src/js/server/validate.js b/src/js/server/validate.js
index <HASH>..<HASH> 100644
--- a/src/js/server/validate.js
+++ b/src/js/server/validate.js
@@ -49,9 +49,16 @@ fluid.defaults("gpii.schema.validator.server", {
funcName: "gpii.schema.validator.server.init",
args: ["{that}"]
}
+ },
+ components: {
+ parser: {
+ type: "gpii.schema.parser",
+ options: {
+ schemaDir: "{gpii.schema.validator}.options.schemaDir",
+ model: {
+ schemas: "{gpii.schema.validator}.model.schemas"
+ }
+ }
+ }
}
-});
-
-fluid.defaults("gpii.schema.validator.server.hasParser", {
- gradeNames: ["gpii.schema.validator.hasParser", "gpii.schema.validator.server"]
});
\ No newline at end of file
diff --git a/tests/js/parser-server-tests.js b/tests/js/parser-server-tests.js
index <HASH>..<HASH> 100644
--- a/tests/js/parser-server-tests.js
+++ b/tests/js/parser-server-tests.js
@@ -126,7 +126,7 @@ fluid.defaults("gpii.schema.parser.tests.server.environment", {
options: {
components: {
validator: {
- type: "gpii.schema.validator.server.hasParser",
+ type: "gpii.schema.validator.server",
options: {
schemaDir: schemaDir,
components: {
diff --git a/tests/js/validate-server-tests.js b/tests/js/validate-server-tests.js
index <HASH>..<HASH> 100644
--- a/tests/js/validate-server-tests.js
+++ b/tests/js/validate-server-tests.js
@@ -14,7 +14,7 @@ var schemaDir = path.resolve(__dirname, "../schemas");
jqUnit.module("Unit tests for validation component...");
-var testValidator = gpii.schema.validator.server.hasParser({
+var testValidator = gpii.schema.validator.server({
gradeNames: ["gpii.schema.tests.validator"],
schemaDir: schemaDir,
listeners: {
|
GPII-<I>: Collapsed `hasParser` grades into defaults and removed check for parser existence.
|
GPII_gpii-json-schema
|
train
|
fc85092f22ecc0e4866196bb531bf4fddd39a404
|
diff --git a/seleniumhelpers/seleniumhelpers.py b/seleniumhelpers/seleniumhelpers.py
index <HASH>..<HASH> 100644
--- a/seleniumhelpers/seleniumhelpers.py
+++ b/seleniumhelpers/seleniumhelpers.py
@@ -166,13 +166,22 @@ class SeleniumTestCase(LiveServerTestCase):
def waitForText(self, text,
timeout=get_default_timeout(),
- msg='Could not find text "{text}"'):
+ msg='Could not find text "{text}"',
+ within=None):
"""
- Wait for ``text`` to appear in ``selenium.page_source``.
+ Wait for ``text`` to appear in ``selenium.page_source`` or from the text of an element.
+ :param within: The element to find text within (uses within.text). If
+ this is not specified, we get text from ``selenium.page_source``.
:param timeout: Fail unless the ``text`` appears in ``selenium.page_source`` before ``timeout`` seconds has passed.
"""
- self.waitFor(self.selenium, lambda selenium: text in selenium.page_source, timeout,
+ def check(s):
+ text = None
+ if within:
+ return text in within.text
+ else:
+ return text in self.page_source
+ self.waitFor(self.selenium, lambda s: check, timeout,
msg=msg.format(text=text))
def waitForTitle(self, title,
|
Added ``within`` to ``SeleniumTestCase.waitForText()``.
|
espenak_django_seleniumhelpers
|
train
|
e4d29a69127ba488ae49bdd21a2c06c8f5216baf
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -57,7 +57,7 @@ setuptools.setup(
author_email='geguileo@redhat.com',
url='https://github.com/akrog/cinderlib',
packages=setuptools.find_packages(exclude=['tmp', 'tests*']),
- include_package_data=True,
+ include_package_data=False,
install_requires=requirements,
extras_requires=extras,
license="Apache Software License 2.0",
|
Don't include package data for now
|
Akrog_cinderlib
|
train
|
47817488c8ae921e8e56cb9fbcfdde126eb24ace
|
diff --git a/marshmallow_jsonapi/schema.py b/marshmallow_jsonapi/schema.py
index <HASH>..<HASH> 100644
--- a/marshmallow_jsonapi/schema.py
+++ b/marshmallow_jsonapi/schema.py
@@ -106,7 +106,7 @@ class Schema(ma.Schema):
{
'detail': '`data` object must include `type` key.',
'source': {
- 'pointer': '/data'
+ 'pointer': '/data'
}
}
])
|
Fix a small overindentation.
|
marshmallow-code_marshmallow-jsonapi
|
train
|
698eeb37978b8200b79fac91056c3ccee248b9ce
|
diff --git a/ipdata/cli.py b/ipdata/cli.py
index <HASH>..<HASH> 100644
--- a/ipdata/cli.py
+++ b/ipdata/cli.py
@@ -141,16 +141,15 @@ def batch(ctx, ip_list, output, output_format, fields):
result_context['writer'] = csv.writer(output)
def print_result(res):
- result_context['writer'].writerow([res[k] for k in extract_fields])
+ for result in res['responses']:
+ result_context['writer'].writerow([result[k] for k in extract_fields])
def finish():
pass
elif output_format == 'JSON':
- result_context['results'] = []
-
def print_result(res):
- result_context['results'].append(res)
+ result_context['results'] = res['responses']
def finish():
json.dump(result_context, fp=output)
@@ -159,10 +158,13 @@ def batch(ctx, ip_list, output, output_format, fields):
print(f'Unsupported format: {output_format}', file=stderr)
return
- for ip in ip_list:
- ip = ip.strip()
- if len(ip) > 0:
- print_result(get_ip_info(ctx.obj['api-key'], ip=ip.strip(), fields=extract_fields))
+ ip_data = IPData(get_and_check_api_key(ctx.obj['api-key']))
+ res = ip_data.bulk_lookup(
+ list(
+ filter(lambda ip: len(ip) > 0,
+ [ip.strip() for ip in ip_list])
+ ), extract_fields)
+ print_result(res)
finish()
|
Use IPData bulk_lookup for batch command
|
ipdata_python
|
train
|
d81b05e701e688d26f17f4918a3f6ff6a6a21509
|
diff --git a/index.php b/index.php
index <HASH>..<HASH> 100644
--- a/index.php
+++ b/index.php
@@ -74,8 +74,11 @@
} else {
$currlang = current_language();
$langs = get_list_of_languages();
- $langlabel = get_accesshide(get_string('language'));
- $langmenu = popup_form($CFG->wwwroot .'/index.php?lang=', $langs, 'chooselang', $currlang, '', '', '', true, 'self', $langlabel);
+
+ $select = moodle_select::make_popup_form($CFG->wwwroot .'/index.php', 'lang', $langs, 'chooselang', $currlang);
+ $select->nothinglabel = false;
+ $select->set_label(get_accesshide(get_string('language')));
+ $langmenu = $OUTPUT->select($select);
}
$PAGE->set_other_editing_capability('moodle/course:manageactivities');
$PAGE->set_url('');
diff --git a/lib/blocklib.php b/lib/blocklib.php
index <HASH>..<HASH> 100644
--- a/lib/blocklib.php
+++ b/lib/blocklib.php
@@ -1337,7 +1337,7 @@ function matching_page_type_patterns($pagetype) {
* cannot add any blocks here.
*/
function block_add_block_ui($page, $output) {
- global $CFG;
+ global $CFG, $OUTPUT;
if (!$page->user_is_editing() || !$page->user_can_edit_blocks()) {
return null;
}
@@ -1361,9 +1361,11 @@ function block_add_block_ui($page, $output) {
}
asort($menu, SORT_LOCALE_STRING);
- // TODO convert to $OUTPUT.
- $actionurl = $page->url->out_action() . '&bui_addblock=';
- $bc->content = popup_form($actionurl, $menu, 'add_block', '', get_string('adddots'), '', '', true);
+ $actionurl = $page->url->out_action();
+ $select = moodle_select::make_popup_form($actionurl, 'bui_addblock', $menu, 'add_block');
+ $select->nothinglabel = get_string('adddots');
+
+ $bc->content = $OUTPUT->select($select);
return $bc;
}
diff --git a/lib/grouplib.php b/lib/grouplib.php
index <HASH>..<HASH> 100644
--- a/lib/grouplib.php
+++ b/lib/grouplib.php
@@ -412,7 +412,7 @@ function groups_get_activity_groupmode($cm, $course=null) {
* @return mixed void or string depending on $return param
*/
function groups_print_course_menu($course, $urlroot, $return=false) {
- global $CFG, $USER, $SESSION;
+ global $CFG, $USER, $SESSION, $OUTPUT;
if (!$groupmode = $course->groupmode) {
if ($return) {
@@ -480,7 +480,10 @@ function groups_print_course_menu($course, $urlroot, $return=false) {
$groupname = reset($groupsmenu);
$output = $grouplabel.': '.$groupname;
} else {
- $output = popup_form($urlroot.'&group=', $groupsmenu, 'selectgroup', $activegroup, '', '', '', true, 'self', $grouplabel);
+ $select = moodle_select::make_popup_form($urlroot, 'group', $groupsmenu, 'selectgroup', $activegroup);
+ $select->nothinglabel = false;
+ $select->set_label($grouplabel);
+ $output = $OUTPUT->select($select);
}
$output = '<div class="groupselector">'.$output.'</div>';
@@ -511,7 +514,7 @@ function groups_print_course_menu($course, $urlroot, $return=false) {
* @return mixed void or string depending on $return param
*/
function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
- global $CFG, $USER, $SESSION;
+ global $CFG, $USER, $SESSION, $OUTPUT;
// groupings are ignored when not enabled
if (empty($CFG->enablegroupings)) {
@@ -585,7 +588,10 @@ function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallpartic
$groupname = reset($groupsmenu);
$output = $grouplabel.': '.$groupname;
} else {
- $output = popup_form($urlroot.'&group=', $groupsmenu, 'selectgroup', $activegroup, '', '', '', true, 'self', $grouplabel);
+ $select = moodle_select::make_popup_form($urlroot, 'group', $groupsmenu, 'selectgroup', $activegroup);
+ $select->nothinglabel = false;
+ $select->set_label($grouplabel);
+ $output = $OUTPUT->select($select);
}
$output = '<div class="groupselector">'.$output.'</div>';
diff --git a/my/index.php b/my/index.php
index <HASH>..<HASH> 100644
--- a/my/index.php
+++ b/my/index.php
@@ -50,9 +50,10 @@
} else {
$currlang = current_language();
$langs = get_list_of_languages();
- $langlabel = get_accesshide(get_string('language'));
- $langmenu = popup_form($CFG->wwwroot . '/my/index.php?lang=', $langs,
- 'chooselang', $currlang, '', '', '', true, 'self', $langlabel);
+ $select = moodle_select::make_popup_form($CFG->wwwroot .'/my/index.php', 'lang', $langs, 'chooselang', $currlang);
+ $select->nothinglabel = false;
+ $select->set_label(get_accesshide(get_string('language')));
+ $langmenu = $OUTPUT->select($select);
}
print_header($strmymoodle, $header, $navigation, '', '', true, $button, $loggedinas . $langmenu);
|
MDL-<I> Converted calls to popup_form()
|
moodle_moodle
|
train
|
1ef95afb5e95ad6f071eff33031c860ff95cb765
|
diff --git a/CHANGES.txt b/CHANGES.txt
index <HASH>..<HASH> 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,7 +1,7 @@
Changelog
==========
-bleeding
+1.0.0
-----
- Added Mocking API
- Added a bunch of tests
diff --git a/describe/value/mixins.py b/describe/value/mixins.py
index <HASH>..<HASH> 100644
--- a/describe/value/mixins.py
+++ b/describe/value/mixins.py
@@ -1,3 +1,7 @@
+"""Provides the extensive feature set for the Value objects. It can be assumed that all are
+mixed into the ValueInternals object.
+"""
+
from properties import Properties
from decorators import VerifyDecorator, DeferredDecorator
from ..tracebacks import get_current_stack, get_stack
@@ -43,6 +47,7 @@ class BuiltinFunctionsMixin(BuiltinFunctionsMixin):
class StringMixin(object):
"""String specific methods."""
def requires_string(self):
+ """Internal. Enforces the provided type to be a string."""
prev_stack = get_current_stack()[1]
self.requires(type(self.value) == str,
"Value(%(value)r).%(method)s %(should)s be type str, but was type %(actual)s.",
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@ setup(
# The runner hasn't been extensively tested.
install_requires=[
'nose',
- 'mock'
+ 'mock',
],
entry_points = {
'nose.plugins.0.10': ['describe = describe.nose_plugin:SpecPlugin'],
|
Set version to <I> (alpha?) and added some documentation.
|
jeffh_describe
|
train
|
785b3e7a575f26f3c33e3369d8a75fb131f90584
|
diff --git a/cmd/geth/main.go b/cmd/geth/main.go
index <HASH>..<HASH> 100644
--- a/cmd/geth/main.go
+++ b/cmd/geth/main.go
@@ -42,6 +42,8 @@ import (
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/metrics"
+ "github.com/ethereum/go-ethereum/params"
+ "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc/codec"
"github.com/ethereum/go-ethereum/rpc/comms"
"github.com/mattn/go-colorable"
@@ -49,11 +51,14 @@ import (
)
const (
- ClientIdentifier = "Geth"
- Version = "1.0.1"
+ ClientIdentifier = "Geth "
+ VersionMajor = 1
+ VersionMinor = 0
+ VersionPatch = 1
)
var (
+ Version = fmt.Sprintf("%d.%d.%d", VersionMajor, VersionMinor, VersionPatch)
gitCommit string // set via linker flagg
nodeNameVersion string
app *cli.App
@@ -346,6 +351,27 @@ func main() {
}
}
+func makeDefaultExtra() []byte {
+ var clientInfo = struct {
+ Version uint
+ Name string
+ GoVersion string
+ Os string
+ }{uint(VersionMajor<<16 | VersionMinor<<8 | VersionPatch), ClientIdentifier, runtime.Version(), runtime.GOOS}
+ extra, err := rlp.EncodeToBytes(clientInfo)
+ if err != nil {
+ glog.V(logger.Warn).Infoln("error setting canonical miner information:", err)
+ }
+
+ if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
+ glog.V(logger.Warn).Infoln("error setting canonical miner information: extra exceeds", params.MaximumExtraDataSize)
+ glog.V(logger.Debug).Infof("extra: %x\n", extra)
+ return nil
+ }
+
+ return extra
+}
+
func run(ctx *cli.Context) {
utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))
if ctx.GlobalBool(utils.OlympicFlag.Name) {
@@ -353,6 +379,8 @@ func run(ctx *cli.Context) {
}
cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
+ cfg.ExtraData = makeDefaultExtra()
+
ethereum, err := eth.New(cfg)
if err != nil {
utils.Fatalf("%v", err)
diff --git a/eth/backend.go b/eth/backend.go
index <HASH>..<HASH> 100644
--- a/eth/backend.go
+++ b/eth/backend.go
@@ -45,7 +45,6 @@ import (
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover"
"github.com/ethereum/go-ethereum/p2p/nat"
- "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/whisper"
)
@@ -92,6 +91,7 @@ type Config struct {
NatSpec bool
AutoDAG bool
PowTest bool
+ ExtraData []byte
MaxPeers int
MaxPendingPeers int
@@ -378,12 +378,7 @@ func New(config *Config) (*Ethereum, error) {
eth.miner = miner.New(eth, eth.EventMux(), eth.pow)
eth.miner.SetGasPrice(config.GasPrice)
-
- extra := config.Name
- if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
- extra = extra[:params.MaximumExtraDataSize.Uint64()]
- }
- eth.miner.SetExtra([]byte(extra))
+ eth.miner.SetExtra(config.ExtraData)
if config.Shh {
eth.whisper = whisper.New()
|
cmd/geth, eth: added canonical extra data
Implemented canonical extra data according to
<URL>
|
ethereum_go-ethereum
|
train
|
01a2fe05bdc5533bf99b14703ebfd03149ac4b5e
|
diff --git a/quart/serving.py b/quart/serving.py
index <HASH>..<HASH> 100644
--- a/quart/serving.py
+++ b/quart/serving.py
@@ -188,7 +188,7 @@ class H2Server(HTTPProtocol):
loop: asyncio.AbstractEventLoop,
transport: asyncio.BaseTransport,
) -> None:
- super().__init__(app, loop, transport, 'quart-h11')
+ super().__init__(app, loop, transport, 'quart-h2')
self.connection = h2.connection.H2Connection(
h2.config.H2Configuration(client_side=False, header_encoding='utf-8'),
)
diff --git a/tests/test_serving.py b/tests/test_serving.py
index <HASH>..<HASH> 100644
--- a/tests/test_serving.py
+++ b/tests/test_serving.py
@@ -3,14 +3,49 @@ from unittest.mock import Mock
import h11
import h2
+import pytest
+from quart import Quart, ResponseReturnValue
from quart.serving import H11Server, H2Server, Server
-from quart.wrappers import CIMultiDict
BASIC_H11_HEADERS = [('Host', 'quart')]
BASIC_H2_HEADERS = [
(':authority', 'quart'), (':path', '/'), (':scheme', 'https'), (':method', 'GET'),
]
+BASIC_DATA = 'index'
+
+
+class MockTransport:
+
+ def __init__(self) -> None:
+ self.data = bytearray()
+ self.closed = asyncio.Event()
+ self.updated = asyncio.Event()
+
+ def get_extra_info(self, _: str) -> tuple:
+ return ('127.0.0.1',)
+
+ def write(self, data: bytes) -> None:
+ self.data.extend(data)
+ self.updated.set()
+
+ def close(self) -> None:
+ self.closed.set()
+
+ def clear(self) -> None:
+ self.data = bytearray()
+ self.updated.clear()
+
+
+@pytest.fixture()
+def serving_app() -> Quart:
+ app = Quart(__name__)
+
+ @app.route('/')
+ async def index() -> ResponseReturnValue:
+ return BASIC_DATA, 202, {'X-Test': 'Test'}
+
+ return app
def test_server() -> None:
@@ -26,23 +61,53 @@ def test_server() -> None:
assert isinstance(server._http_server, H11Server)
-def test_h11server(event_loop: asyncio.AbstractEventLoop) -> None:
- server = H11Server(Mock(), event_loop, Mock())
- server.handle_request = Mock() # type: ignore
+@pytest.mark.asyncio
+async def test_h11server(serving_app: Quart, event_loop: asyncio.AbstractEventLoop) -> None:
+ transport = MockTransport()
+ server = H11Server(serving_app, event_loop, transport) # type: ignore
connection = h11.Connection(h11.CLIENT)
server.data_received(
connection.send(h11.Request(method='GET', target='/', headers=BASIC_H11_HEADERS)),
)
server.data_received(connection.send(h11.EndOfMessage()))
- server.handle_request.assert_called_once_with(0, 'GET', '/', CIMultiDict(BASIC_H11_HEADERS))
+ await transport.closed.wait()
+ connection.receive_data(transport.data)
+ response_data = b''
+ while True:
+ event = connection.next_event()
+ if isinstance(event, h11.Response):
+ assert event.status_code == 202
+ assert (b'server', b'quart-h11') in event.headers
+ assert (b'x-test', b'Test') in event.headers
+ elif isinstance(event, h11.Data):
+ response_data += event.data
+ else:
+ break
+ assert response_data.decode() == BASIC_DATA
-def test_h2server(event_loop: asyncio.AbstractEventLoop) -> None:
- server = H2Server(Mock(), event_loop, Mock())
- server.handle_request = Mock() # type: ignore
+@pytest.mark.asyncio
+async def test_h2server(serving_app: Quart, event_loop: asyncio.AbstractEventLoop) -> None:
+ transport = MockTransport()
+ server = H2Server(serving_app, event_loop, transport) # type: ignore
connection = h2.connection.H2Connection()
connection.initiate_connection()
server.data_received(connection.data_to_send())
connection.send_headers(1, BASIC_H2_HEADERS, end_stream=True)
server.data_received(connection.data_to_send())
- server.handle_request.assert_called_once_with(1, 'GET', '/', CIMultiDict(BASIC_H2_HEADERS))
+ response_data = b''
+ connection_open = True
+ while connection_open:
+ await transport.updated.wait()
+ events = connection.receive_data(transport.data)
+ transport.clear()
+ for event in events:
+ if isinstance(event, h2.events.ResponseReceived):
+ assert (b':status', b'202') in event.headers
+ assert (b'server', b'quart-h2') in event.headers
+ assert (b'x-test', b'Test') in event.headers
+ elif isinstance(event, h2.events.DataReceived):
+ response_data += event.data
+ elif isinstance(event, (h2.events.StreamEnded, h2.events.ConnectionTerminated)):
+ connection_open = False
+ assert response_data.decode() == BASIC_DATA
|
Improve the serving tests
This now actual checks the returned data is sane, and includes aspects
that should have been set during the serving stage (i.e. server). It
also fixes a bug in the server header for h2 connections.
|
pgjones_quart
|
train
|
7f0309fc457836107adad59106668a12154eca65
|
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/SinkTransformationTranslator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/SinkTransformationTranslator.java
index <HASH>..<HASH> 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/SinkTransformationTranslator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/SinkTransformationTranslator.java
@@ -110,13 +110,11 @@ public class SinkTransformationTranslator<Input, Output>
}
private void expand() {
- // Reset the environment parallelism temporarily to configure the sub topology
- // parallelism
- executionEnvironment.setParallelism(ExecutionConfig.PARALLELISM_DEFAULT);
final int sizeBefore = executionEnvironment.getTransformations().size();
DataStream<T> prewritten = inputStream;
+
if (sink instanceof WithPreWriteTopology) {
prewritten =
adjustTransformations(
@@ -135,9 +133,6 @@ public class SinkTransformationTranslator<Input, Output>
new SinkWriterOperatorFactory<>(sink)));
}
- // Restore the previous parallelism of the environment before transforming
- executionEnvironment.setParallelism(environmentParallelism);
-
final List<Transformation<?>> sinkTransformations =
executionEnvironment
.getTransformations()
@@ -176,6 +171,7 @@ public class SinkTransformationTranslator<Input, Output>
precommitted,
((WithPreCommitTopology<T, CommT>) sink)::addPreCommitTopology);
}
+
DataStream<CommittableMessage<CommT>> committed =
adjustTransformations(
precommitted,
@@ -184,6 +180,7 @@ public class SinkTransformationTranslator<Input, Output>
COMMITTER_NAME,
typeInformation,
new CommitterOperatorFactory<>(committingSink)));
+
if (sink instanceof WithPostCommitTopology) {
DataStream<CommittableMessage<CommT>> postcommitted = addFailOverRegion(committed);
adjustTransformations(
@@ -207,13 +204,34 @@ public class SinkTransformationTranslator<Input, Output>
StreamExchangeMode.BATCH));
}
+ /**
+ * Since user may set specific parallelism on sub topologies, we have to pay attention to
+ * the priority of parallelism at different levels, i.e. sub topologies customized
+ * parallelism > sinkTransformation customized parallelism > environment customized
+ * parallelism. In order to satisfy this rule and keep these customized parallelism values,
+ * the environment parallelism will be set to be {@link ExecutionConfig#PARALLELISM_DEFAULT}
+ * before adjusting transformations. SubTransformations, constructed after that, will have
+ * either the default value or customized value. In this way, any customized value will be
+ * discriminated from the default value and, for any subTransformation with the default
+ * parallelism value, we will then be able to let it inherit the parallelism value from the
+ * previous sinkTransformation. After adjustment of transformations is closed, the
+ * environment parallelism will be restored back to its original value to keep the
+ * customized parallelism value at environment level.
+ */
private <I, R> R adjustTransformations(
DataStream<I> inputStream, Function<DataStream<I>, R> action) {
+
+ // Reset the environment parallelism temporarily before adjusting transformations,
+ // we can therefore be aware of any customized parallelism of the sub topology
+ // set by users during the adjustment.
+ executionEnvironment.setParallelism(ExecutionConfig.PARALLELISM_DEFAULT);
+
int numTransformsBefore = executionEnvironment.getTransformations().size();
R result = action.apply(inputStream);
List<Transformation<?>> transformations = executionEnvironment.getTransformations();
List<Transformation<?>> expandedTransformations =
transformations.subList(numTransformsBefore, transformations.size());
+
for (Transformation<?> subTransformation : expandedTransformations) {
// Skip overwriting the parallelism for the global committer
if (subTransformation.getName() == null
@@ -224,40 +242,59 @@ public class SinkTransformationTranslator<Input, Output>
.GLOBAL_COMMITTER_TRANSFORMATION_NAME)) {
subTransformation.setParallelism(transformation.getParallelism());
}
+
concatUid(
subTransformation,
Transformation::getUid,
Transformation::setUid,
subTransformation.getName());
+
concatProperty(
subTransformation,
Transformation::getCoLocationGroupKey,
Transformation::setCoLocationGroupKey);
+
concatProperty(subTransformation, Transformation::getName, Transformation::setName);
+
concatProperty(
subTransformation,
Transformation::getDescription,
Transformation::setDescription);
+
Optional<SlotSharingGroup> ssg = transformation.getSlotSharingGroup();
+
if (ssg.isPresent() && !subTransformation.getSlotSharingGroup().isPresent()) {
subTransformation.setSlotSharingGroup(ssg.get());
}
+
+ // remember that the environment parallelism has been set to be default
+ // at the beginning. SubTransformations, whose parallelism has been
+ // customized, will skip this part. The customized parallelism value set by user
+ // will therefore be kept.
if (subTransformation.getParallelism() == ExecutionConfig.PARALLELISM_DEFAULT) {
- // The parallelism of the transformation is by default the env parallelism, or
- // it is overwritten by the user.
+ // In this case, the subTransformation does not contain any customized
+ // parallelism value and will therefore inherit the parallelism value
+ // from the sinkTransformation.
subTransformation.setParallelism(transformation.getParallelism());
}
+
if (subTransformation.getMaxParallelism() < 0
&& transformation.getMaxParallelism() > 0) {
subTransformation.setMaxParallelism(transformation.getMaxParallelism());
}
+
if (transformation.getChainingStrategy() == null
|| !(subTransformation instanceof PhysicalTransformation)) {
continue;
}
+
((PhysicalTransformation<?>) subTransformation)
.setChainingStrategy(transformation.getChainingStrategy());
}
+
+ // Restore the previous parallelism of the environment before adjusting transformations
+ executionEnvironment.setParallelism(environmentParallelism);
+
return result;
}
|
[hotfix][datastream] move the change and restore of env parallelism into the adjusTransformations method.
|
apache_flink
|
train
|
cfa54c7b249835858bfb99271d54a190f008468e
|
diff --git a/src/main/groovy/lang/Script.java b/src/main/groovy/lang/Script.java
index <HASH>..<HASH> 100644
--- a/src/main/groovy/lang/Script.java
+++ b/src/main/groovy/lang/Script.java
@@ -53,17 +53,7 @@ package groovy.lang;
* @version $Revision$
*/
public abstract class Script extends GroovyObjectSupport {
- private ScriptContext bindings;
-
- public Script() {
- this(new ScriptContext());
- }
-
- /** @todo temporary hack until constructor type checking is better */
- public Script(Object object) {
- ScriptContext bindings = (ScriptContext) object;
- this.bindings = bindings;
- }
+ private ScriptContext bindings = new ScriptContext();
public ScriptContext getBindings() {
return bindings;
@@ -78,7 +68,7 @@ public abstract class Script extends GroovyObjectSupport {
}
public void setProperty(String property, Object newValue) {
- bindings.setVariable(property, newValue);
+ bindings.setVariable(property, newValue);
}
/**
diff --git a/src/main/org/codehaus/groovy/runtime/InvokerHelper.java b/src/main/org/codehaus/groovy/runtime/InvokerHelper.java
index <HASH>..<HASH> 100644
--- a/src/main/org/codehaus/groovy/runtime/InvokerHelper.java
+++ b/src/main/org/codehaus/groovy/runtime/InvokerHelper.java
@@ -53,6 +53,7 @@ import groovy.lang.ScriptContext;
import groovy.lang.Tuple;
import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -283,8 +284,11 @@ public class InvokerHelper {
public static Script createScript(Class scriptClass, ScriptContext context) {
try {
- Constructor constructor = scriptClass.getConstructor(new Class[] { ScriptContext.class });
- return (Script) constructor.newInstance(new Object[] { context });
+ Constructor constructor = scriptClass.getConstructor(new Class[] {});
+ Script script = (Script) constructor.newInstance(new Object[] {});
+ Method setBindings = script.getClass().getMethod("setBindings", new Class[] { ScriptContext.class });
+ setBindings.invoke(script, new Object[] { context });
+ return script;
}
catch (Exception e) {
throw new InvokerException(
|
Remove the script context from the constructor so the lifecycle is consistent for Scripts.
git-svn-id: <URL>
|
groovy_groovy-core
|
train
|
ee939f75a88ec3c2b162bc6bc68ff2cd4e050d89
|
diff --git a/pyhocon/config_parser.py b/pyhocon/config_parser.py
index <HASH>..<HASH> 100644
--- a/pyhocon/config_parser.py
+++ b/pyhocon/config_parser.py
@@ -194,7 +194,7 @@ class ConfigParser(object):
comment = (Literal('#') | Literal('//')) - SkipTo(eol)
comment_eol = Suppress(Optional(eol_comma) + comment)
comment_no_comma_eol = (comment | eol).suppress()
- number_expr = Regex('[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE]\d+)?(?=[ \t]*([\$\}\],#\n\r]|//))',
+ number_expr = Regex('[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE]\d+)?(?=$|[ \t]*([\$\}\],#\n\r]|//))',
re.DOTALL).setParseAction(convert_number)
# multi line string using """
@@ -207,7 +207,7 @@ class ConfigParser(object):
# line1 \
# line2 \
# so a backslash precedes the \n
- unquoted_string = Regex(r'(\\[ \t]*[\r\n]|[^\[\{\n\r\]\}#,=\$])+?(?=(\$|[ \t]*(//|[\}\],#\n\r])))',
+ unquoted_string = Regex(r'(\\[ \t]*[\r\n]|[^\[\{\n\r\]\}#,=\$])+?(?=($|\$|[ \t]*(//|[\}\],#\n\r])))',
re.DOTALL).setParseAction(unescape_string)
substitution_expr = Regex('[ \t]*\$\{[^\}]+\}[ \t]*').setParseAction(create_substitution)
string_expr = multiline_string | quoted_string | unquoted_string
diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py
index <HASH>..<HASH> 100644
--- a/tests/test_config_parser.py
+++ b/tests/test_config_parser.py
@@ -515,20 +515,26 @@ class TestConfigParser(object):
'cluster-size': 6
}
- def test_dos_chars(self):
- config = ConfigFactory.parse_string(
- """
- app.heap_size = 128\r
- app.java_opts = [\r
- -Xms${app.heap_size}m\r
- -Xmx${app.heap_size}m\r
- ]\r
- foo = bar\r
- """
- )
-
+ def test_dos_chars_with_unquoted_string_noeol(self):
+ config = ConfigFactory.parse_string("foo = bar")
assert config['foo'] == 'bar'
+ def test_dos_chars_with_quoted_string_noeol(self):
+ config = ConfigFactory.parse_string('foo = "5"')
+ assert config['foo'] == '5'
+
+ def test_dos_chars_with_triple_quoted_string_noeol(self):
+ config = ConfigFactory.parse_string('foo = """5"""')
+ assert config['foo'] == '5'
+
+ def test_dos_chars_with_int_noeol(self):
+ config = ConfigFactory.parse_string("foo = 5")
+ assert config['foo'] == 5
+
+ def test_dos_chars_with_float_noeol(self):
+ config = ConfigFactory.parse_string("foo = 5.0")
+ assert config['foo'] == 5.0
+
def test_list_substitutions(self):
config = ConfigFactory.parse_string(
"""
|
fixed parsing of last line when no eol
|
chimpler_pyhocon
|
train
|
381f68d0e53f07e11a52f1c1b617c63584b8b839
|
diff --git a/app/models/chat/message.rb b/app/models/chat/message.rb
index <HASH>..<HASH> 100644
--- a/app/models/chat/message.rb
+++ b/app/models/chat/message.rb
@@ -14,6 +14,8 @@ class Chat::Message < ApplicationRecord
before_save :remove_extra_new_line
before_save :execute_dot_command
+ validates :text, presence: true, unless: :image?
+
after_create_commit do
Chat::MessageRelayJob.send(Chat.perform_method.to_sym, id)
Chat::NotificationRelayJob.send(Chat.perform_method.to_sym, self)
|
Dont allow empty messages to get created
|
npezza93_chat
|
train
|
22f47bdd7d36f25a567414dde81c70098a1d2bd8
|
diff --git a/test/definitions/eventTest.js b/test/definitions/eventTest.js
index <HASH>..<HASH> 100644
--- a/test/definitions/eventTest.js
+++ b/test/definitions/eventTest.js
@@ -110,7 +110,7 @@ describe('event definition', function () {
it('it should work as expected', function (done) {
var evtObj = { my: 'event', with: { deep: 'value' } };
- var aggregateObj = {};
+ var aggregateObj = { get: function () {}, has: function () {} };
var evtFn = function (evt, aggregateModel) {
expect(evt).to.eql(evtObj);
|
test definitionBase and eventTest
|
adrai_node-cqrs-domain
|
train
|
8de6ea9623cb03fefee421c9598a9c4e077116e8
|
diff --git a/lib/Daemon_WorkerThread.class.php b/lib/Daemon_WorkerThread.class.php
index <HASH>..<HASH> 100644
--- a/lib/Daemon_WorkerThread.class.php
+++ b/lib/Daemon_WorkerThread.class.php
@@ -353,7 +353,7 @@ class Daemon_WorkerThread extends Thread
$this->setStatus(3);
if ($hard) {exit(0);}
$reloadReady = $this->appInstancesReloadReady();
- Daemon::log('[WORKER '.$this->pid.'] reloadReady = '.Daemon::var_dump($reloadReady));
+ if (Daemon::$settings['logevents']) {Daemon::log('[WORKER '.$this->pid.'] reloadReady = '.Daemon::var_dump($reloadReady));}
foreach ($this->queue as $r)
{
if ($r instanceof stdClass) {continue;}
diff --git a/lib/Request.class.php b/lib/Request.class.php
index <HASH>..<HASH> 100644
--- a/lib/Request.class.php
+++ b/lib/Request.class.php
@@ -184,7 +184,12 @@ class Request
*/
public function call()
{
- if ($this->state === 0) {return 1;}
+ if ($this->state === 0)
+ {
+ $this->state = 1;
+ $this->finish();
+ return 1;
+ }
if ($this->attrs->params_done)
{
if (isset($this->appInstance->passphrase))
|
Class Request: fixed bug related with finish() inside of init().
Daemon_WorkerThread: trivial change of debug-message.
|
kakserpom_phpdaemon
|
train
|
2dc31ce3b680568fb58be8ee065c91441dbd5042
|
diff --git a/src/playground/playground.go b/src/playground/playground.go
index <HASH>..<HASH> 100644
--- a/src/playground/playground.go
+++ b/src/playground/playground.go
@@ -46,7 +46,7 @@ func main() {
return dirs[name], nil
},
OpenFile: func(name string) (io.ReadCloser, error) {
- if name == "/input.go" {
+ if name == "/prog.go" {
return ioutil.NopCloser(strings.NewReader(scope.GetString("code"))), nil
}
@@ -74,7 +74,7 @@ func main() {
Package: &build.Package{
Name: "main",
ImportPath: "main",
- GoFiles: []string{"input.go"},
+ GoFiles: []string{"prog.go"},
},
}
@@ -82,12 +82,14 @@ func main() {
err := t.BuildPackage(pkg)
if err != nil {
if list, isList := err.(translator.ErrorList); isList {
+ output := make([]interface{}, 0)
for _, entry := range list {
- println(entry.Error())
+ output = append(output, &OutputLine{"err", entry.Error()})
}
+ scope.Set("output", output)
return
}
- println(err.Error())
+ scope.Set("output", []interface{}{&OutputLine{"err", err.Error()}})
return
}
|
playground: Compile time errors shown in output.
|
gopherjs_gopherjs
|
train
|
df6312b6c9c4bc520f8f98a83ee6cedee9539968
|
diff --git a/yadlt/core/model.py b/yadlt/core/model.py
index <HASH>..<HASH> 100644
--- a/yadlt/core/model.py
+++ b/yadlt/core/model.py
@@ -85,8 +85,8 @@ class Model(object):
with the same name of this model is restored from disk
to continue training.
"""
- self.tf_merged_summaries = tf.merge_all_summaries()
- init_op = tf.initialize_all_variables()
+ self.tf_merged_summaries = tf.summary.merge_all()
+ init_op = tf.global_variables_initializer()
self.tf_saver = tf.train.Saver()
self.tf_session.run(init_op)
@@ -105,7 +105,7 @@ class Model(object):
run_dir = os.path.join(self.tf_summary_dir, 'run' + str(run_id))
print('Tensorboard logs dir for this run is %s' % (run_dir))
- self.tf_summary_writer = tf.train.SummaryWriter(
+ self.tf_summary_writer = tf.summary.FileWriter(
run_dir, self.tf_session.graph)
def _initialize_training_parameters(
@@ -279,7 +279,7 @@ class Model(object):
if cost is not None:
self.cost = cost + regterm if regterm is not None else cost
- tf.scalar_summary(self.loss_func, self.cost)
+ tf.summary.scalar(self.loss_func, self.cost)
else:
self.cost = None
|
Updated tf summaries to latest version (<I>rc0)
|
blackecho_Deep-Learning-TensorFlow
|
train
|
2b531923da53878ba06ec68df9803aec68e6ec9d
|
diff --git a/app/models/resource_import_file.rb b/app/models/resource_import_file.rb
index <HASH>..<HASH> 100644
--- a/app/models/resource_import_file.rb
+++ b/app/models/resource_import_file.rb
@@ -65,12 +65,12 @@ class ResourceImportFile < ActiveRecord::Base
rows = open_import_file(create_import_temp_file(resource_import))
row_num = 1
- field = rows.first
- if [field['manifestation_id'], field['manifestation_identifier'], field['isbn'], field['original_title']].reject{|f|
- f.to_s.strip == ''
- }.empty?
- raise "You should specify isbn or original_title in the first line"
- end
+ #field = rows.first
+ #if [field['manifestation_id'], field['manifestation_identifier'], field['isbn'], field['original_title']].reject{|f|
+ # f.to_s.strip == ''
+ #}.empty?
+ # raise "You should specify isbn or original_title in the first line"
+ #end
rows.each do |row|
row_num += 1
|
disabled header check next-l/enju_leaf#<I>
|
next-l_enju_biblio
|
train
|
d3cf181e74d609c8f5439c98cbdd0ac8a9b599a9
|
diff --git a/coap/coap-request.js b/coap/coap-request.js
index <HASH>..<HASH> 100644
--- a/coap/coap-request.js
+++ b/coap/coap-request.js
@@ -79,7 +79,7 @@ module.exports = function(RED) {
});
onPayloadDecoded(payload);
} else if (res.headers['Content-Format'] === 'application/cbor') {
- cbor.decode(data, _onCborDecode);
+ cbor.decodeAll(data, _onCborDecode);
} else if (res.headers['Content-Format'] === 'application/link-format') {
payload = linkFormat.parse( data.toString() );
node.send({
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -3,7 +3,7 @@
"version": "0.1.0",
"description": "CoAP support in Node-RED",
"dependencies": {
- "cbor": "0.3.10",
+ "cbor": "^1.0.4",
"coap": "^0.16.0",
"h5.linkformat": "0.0.0"
},
diff --git a/test/coap-request_spec.js b/test/coap-request_spec.js
index <HASH>..<HASH> 100644
--- a/test/coap-request_spec.js
+++ b/test/coap-request_spec.js
@@ -380,11 +380,11 @@ describe('CoapRequestNode', function() {
format: 'application/cbor',
message: { thisIs: 'CBOR' },
decode: function (buf) { return new Promise( function (resolve, reject) {
- cbor.decode(buf,function (error, value) {
+ cbor.decodeFirst(buf,function (error, value) {
if ( error ) {
reject(error);
} else {
- resolve(value[0]);
+ resolve(value);
}
});
}); }
|
Update dependency: `cbor`
|
reederz_node-red-contrib-coap
|
train
|
fffd7a412b2dff644c87280d03122869978dfba2
|
diff --git a/flip.go b/flip.go
index <HASH>..<HASH> 100644
--- a/flip.go
+++ b/flip.go
@@ -21,6 +21,12 @@ const (
// GopherEmoticon is the gopher emoticon used to do a gopher flip
GopherEmoticon = "ʕ╯◔ϖ◔ʔ╯︵"
+
+ // AngryEmoticon is an angry emoticon used to angrily flip the table
+ AngryEmoticon = "(ノಠ益ಠ)ノ︵"
+
+ // SparklyEmoticon is a very sparkly emoticon used to flip the table
+ SparklyEmoticon = "(ノ◕ヮ◕)ノ*:・゚✧*:・゚✧ "
)
var (
@@ -30,10 +36,18 @@ var (
// Gopher is the gopher table flipper func
Gopher = Func(GopherEmoticon)
+ // Angry is the angry table flipper func
+ Angry = Func(AngryEmoticon)
+
+ // Sparkly is the sparkly table flipper func
+ Sparkly = Func(SparklyEmoticon)
+
// Flippers is a map of named flipper funcs
Flippers = map[string]func(string) string{
- "table": Table,
- "gopher": Gopher,
+ "table": Table,
+ "gopher": Gopher,
+ "angry": Angry,
+ "sparkly": Sparkly,
}
)
diff --git a/flip_test.go b/flip_test.go
index <HASH>..<HASH> 100644
--- a/flip_test.go
+++ b/flip_test.go
@@ -9,6 +9,8 @@ var flippersTests = []struct {
}{
{"table", "foo", "(╯°□°)╯︵ooɟ"},
{"gopher", "bar", "ʕ╯◔ϖ◔ʔ╯︵ɹɐq"},
+ {"angry", "baz", "(ノಠ益ಠ)ノ︵zɐq"},
+ {"sparkly", "qux", "(ノ◕ヮ◕)ノ*:・゚✧*:・゚✧ xnb"},
}
func TestFlippers(t *testing.T) {
|
Added the angry and sparkly emoticons
|
peterhellberg_flip
|
train
|
1fe681b6b7d454fe295bb3fdb852a67d8d0feb98
|
diff --git a/PageTool/User/User.tool.php b/PageTool/User/User.tool.php
index <HASH>..<HASH> 100644
--- a/PageTool/User/User.tool.php
+++ b/PageTool/User/User.tool.php
@@ -1,6 +1,13 @@
<?php
class User_PageTool extends PageTool {
- public function go($api, $dom, $template, $tool) {}
+ public function go($api, $dom, $template, $tool) {
+ if(empty($_COOKIE["PhpGt_Track"])) {
+ $anonId = $this->generateSalt();
+ $expires = strtotime("+2 weeks");
+ setcookie("PhpGt_Track", $anonId, $expires);
+ }
+ return $_COOKIE["PhpGt_Track"];
+ }
/**
* Checks the current session for authentication data. This may be
@@ -162,9 +169,10 @@ class User_PageTool extends PageTool {
}
private function deleteCookies() {
- setcookie("PhpGt_Login[0]", "deleted", time());
- setcookie("PhpGt_Login[1]", "deleted", time());
- setcookie("PhpGt_Login[2]", "deleted", time());
+ unset($_COOKIE["PhpGt_Login"]);
+ setcookie("PhpGt_Login[0]", "deleted", 0);
+ setcookie("PhpGt_Login[1]", "deleted", 0);
+ setcookie("PhpGt_Login[2]", "deleted", 0);
}
private function generateSalt() {
|
User tool updated to use an anonymous tracking cookie - allows extended sessions without authentication
|
PhpGt_WebEngine
|
train
|
5b49959934750e3cfd186c85fe8f5a4bcffc253b
|
diff --git a/tests/test_sdist.py b/tests/test_sdist.py
index <HASH>..<HASH> 100644
--- a/tests/test_sdist.py
+++ b/tests/test_sdist.py
@@ -351,6 +351,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
# filling data_files by pointing files in package_data
dist.package_data = {'somecode': ['*.txt']}
self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
+ cmd.formats = ['gztar']
cmd.ensure_finalized()
cmd.run()
|
Issue #<I>: Fix distutils sdist test on Windows.
Patch by Jeremy Kloth.
|
pypa_setuptools
|
train
|
50d4ce6ae436e57d087e57631735a9631c6922d7
|
diff --git a/docs/source/conf.py b/docs/source/conf.py
index <HASH>..<HASH> 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -11,8 +11,13 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
-import sys, os
-sys.path.insert(1, '..')
+import sys
+import os
+
+_prj_root = os.path.dirname(__file__)
+_prj_root = os.path.relpath(os.path.join('..', '..'), _prj_root)
+_prj_root = os.path.abspath(_prj_root)
+sys.path.insert(1, _prj_root)
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
@@ -42,16 +47,16 @@ master_doc = 'index'
# General information about the project.
project = u'AdvancedHTTPServer'
-copyright = u'2014, Spencer McIntyre'
+copyright = u'2015, Spencer McIntyre'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
-version = '0.3'
+version = '0.4'
# The full version, including alpha/beta/rc tags.
-release = '0.3'
+release = '0.4'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
|
Make some updates to the sphinx conf file
|
zeroSteiner_AdvancedHTTPServer
|
train
|
a4a083913d5016fed503818897a14251c923bac4
|
diff --git a/cherrypy/test/test_config_server.py b/cherrypy/test/test_config_server.py
index <HASH>..<HASH> 100644
--- a/cherrypy/test/test_config_server.py
+++ b/cherrypy/test/test_config_server.py
@@ -5,7 +5,9 @@ test.prefer_parent_path()
import os, sys
localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+import socket
import StringIO
+import time
import cherrypy
@@ -43,6 +45,7 @@ def setup_server():
'server.socket_port': 9876,
'server.max_request_body_size': 200,
'server.max_request_header_size': 500,
+ 'server.socket_timeout': 0.5,
# Test explicit server.instance
'server.2.instance': 'cherrypy._cpwsgi_server.CPWSGIServer',
@@ -121,6 +124,42 @@ Content-Type: text/plain
("Content-Length", len(b))]
self.getPage('/upload', h, "POST", b)
self.assertStatus(413)
+
+ def test_socket_timeout(self):
+ if cherrypy.server.protocol_version != "HTTP/1.1":
+ print "skipped ",
+ return
+
+ self.PROTOCOL = "HTTP/1.1"
+
+ # Put request 1
+ self.persistent = True
+ conn = self.HTTP_CONN
+ conn.putrequest("GET", "/", skip_host=True)
+ conn.putheader("Host", self.HOST)
+ conn.endheaders()
+ response = conn.response_class(conn.sock, method="GET")
+ response.begin()
+ body = response.read()
+ self.assertEqual(response.status, 200)
+
+ time.sleep(cherrypy.server.socket_timeout)
+
+ # Put next request
+ try:
+ conn._output('GET /hello HTTP/1.1')
+ conn._output("Host: %s" % self.HOST)
+ conn._send_output()
+ response = conn.response_class(conn.sock, method="GET")
+ response.begin()
+ body = response.read()
+ self.assertEqual(response.status, 200)
+ except socket.error:
+ pass
+ else:
+ self.fail("Socket did not time out as it should have.")
+
+ conn.close()
|
Added a test for socket_timeout.
|
cherrypy_cheroot
|
train
|
b2dc389d4ce722cb499b87f2f607a68342a62e48
|
diff --git a/tests/lib/screenshot-testing/support/page-renderer.js b/tests/lib/screenshot-testing/support/page-renderer.js
index <HASH>..<HASH> 100644
--- a/tests/lib/screenshot-testing/support/page-renderer.js
+++ b/tests/lib/screenshot-testing/support/page-renderer.js
@@ -242,6 +242,11 @@ PageRenderer.prototype.capture = function (outputPath, callback, selector) {
element.each(function (index, node) {
var rect = node.getBoundingClientRect();
+ if (!rect.width || !rect.height) {
+ // element is not visible
+ return;
+ }
+
if (null === clipRect.left || rect.left < clipRect.left) {
clipRect.left = rect.left;
}
@@ -272,6 +277,13 @@ PageRenderer.prototype.capture = function (outputPath, callback, selector) {
throw new Error("Error while detecting element clipRect " + selector + ": " + result.message);
}
+ if (null === result.left
+ || null === result.top
+ || null === result.bottom
+ || null === result.right) {
+ throw new Error("Element(s) " + selector + " found but none is visible");
+ }
+
page.clipRect = result;
}
|
when detecting the clipRect ignore elements that are not visible and trigger an error if no element is visible
|
matomo-org_matomo
|
train
|
be6432ee4c2a22ddbe2cfc884235caf09039278f
|
diff --git a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php
+++ b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php
@@ -162,8 +162,8 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp
try {
$reflectionProperty = new \ReflectionProperty($class, $property);
$type = $reflectionProperty->getType();
- if (null !== $type) {
- return $this->extractFromReflectionType($type, $reflectionProperty->getDeclaringClass());
+ if (null !== $type && $types = $this->extractFromReflectionType($type, $reflectionProperty->getDeclaringClass())) {
+ return $types;
}
} catch (\ReflectionException $e) {
// noop
diff --git a/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php b/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php
+++ b/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php
@@ -239,6 +239,7 @@ class ReflectionExtractorTest extends TestCase
['string', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Stringable'), new Type(Type::BUILTIN_TYPE_STRING)]],
['payload', null],
['data', null],
+ ['mixedProperty', null],
];
}
diff --git a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php80Dummy.php b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php80Dummy.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php80Dummy.php
+++ b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php80Dummy.php
@@ -4,6 +4,8 @@ namespace Symfony\Component\PropertyInfo\Tests\Fixtures;
class Php80Dummy
{
+ public mixed $mixedProperty;
+
public function getFoo(): array|null
{
}
|
fix extracting mixed type-hinted property types
|
symfony_symfony
|
train
|
f83c0c880627b4d309df251d410aef67a4992040
|
diff --git a/core-bundle/src/Resources/contao/drivers/DC_Table.php b/core-bundle/src/Resources/contao/drivers/DC_Table.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/drivers/DC_Table.php
+++ b/core-bundle/src/Resources/contao/drivers/DC_Table.php
@@ -3607,7 +3607,7 @@ class DC_Table extends DataContainer implements \listable, \editable
}
}
- $breadcrumb = (isset($GLOBALS['TL_DCA'][$table]['list']['sorting']['breadcrumb']) ? $GLOBALS['TL_DCA'][$table]['list']['sorting']['breadcrumb'] : '');
+ $breadcrumb = ($GLOBALS['TL_DCA'][$table]['list']['sorting']['breadcrumb'] ?? '');
// Return if there are no records
if ($tree == '' && Input::get('act') != 'paste')
diff --git a/core-bundle/src/Resources/contao/library/Contao/Email.php b/core-bundle/src/Resources/contao/library/Contao/Email.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/library/Contao/Email.php
+++ b/core-bundle/src/Resources/contao/library/Contao/Email.php
@@ -68,7 +68,7 @@ class Email
* E-mail priority
* @var integer
*/
- protected $intPriority = null;
+ protected $intPriority;
/**
* E-mail subject
diff --git a/core-bundle/tests/Functional/app/config/security.yml b/core-bundle/tests/Functional/app/config/security.yml
index <HASH>..<HASH> 100644
--- a/core-bundle/tests/Functional/app/config/security.yml
+++ b/core-bundle/tests/Functional/app/config/security.yml
@@ -38,6 +38,8 @@ security:
two_factor:
auth_form_path: contao_backend_login
check_path: contao_backend_two_factor
+ default_target_path: contao_backend
+ success_handler: contao.security.authentication_success_handler
auth_code_parameter_name: verify
logout:
@@ -63,6 +65,13 @@ security:
remember_me: true
use_forward: true
+ two_factor:
+ auth_form_path: contao_frontend_two_factor
+ check_path: contao_frontend_two_factor
+ default_target_path: contao_root
+ success_handler: contao.security.authentication_success_handler
+ auth_code_parameter_name: verify
+
remember_me:
secret: '%secret%'
remember_me_parameter: autologin
@@ -78,3 +87,5 @@ security:
- { path: ^/contao/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/contao/logout$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/contao(/|$), roles: ROLE_USER }
+ - { path: ^/_contao/two-factor$, roles: [IS_AUTHENTICATED_2FA_IN_PROGRESS, ROLE_MEMBER] }
+ - { path: ^/, roles: [IS_AUTHENTICATED_2FA_IN_PROGRESS, IS_AUTHENTICATED_ANONYMOUSLY] }
|
Update the security.yml file and run the CS fixer
|
contao_contao
|
train
|
e0f5f277363a692c75d75709da98ecbf327ee680
|
diff --git a/lang/en_utf8/install.php b/lang/en_utf8/install.php
index <HASH>..<HASH> 100644
--- a/lang/en_utf8/install.php
+++ b/lang/en_utf8/install.php
@@ -86,24 +86,26 @@ $string['databasesettingssub_mssql'] = '<b>Type:</b> SQL*Server<br />
<b>User:</b> your database username<br />
<b>Password:</b> your database password<br />
<b>Tables Prefix:</b> prefix to use for all table names (mandatory)';
-$string['databasesettingssub_odbc_mssql'] = '<b>Type:</b> SQL*Server (over ODBC) <b>Experimental!</b><br />
+$string['databasesettingssub_odbc_mssql'] = '<b>Type:</b> SQL*Server (over ODBC) <b><font color=\"red\">Experimental! (not for use in production)</font></b><br />
<b>Host:</b> given name of the DSN in the ODBC control panel<br />
<b>Name:</b> database name, eg moodle<br />
<b>User:</b> your database username<br />
<b>Password:</b> your database password<br />
<b>Tables Prefix:</b> prefix to use for all table names (mandatory)';
$string['databasesettingssub_oci8po'] = '<b>Type:</b> Oracle<br />
- <b>Host:</b> not used, can be left blank<br />
+ <b>Host:</b> not used, must be left blank<br />
<b>Name:</b> given name of the tnsnames.ora connection<br />
<b>User:</b> your database username<br />
<b>Password:</b> your database password<br />
- <b>Tables Prefix:</b> prefix to use for all table names (mandatory, 2cc max)';
+ <b>Tables Prefix:</b> prefix to use for all table names (mandatory, 2cc. max)';
$string['dataroot'] = 'Data Directory';
$string['datarooterror'] = 'The \'Data Directory\' you specified could not be found or created. Either correct the path or create that directory manually.';
$string['dbconnectionerror'] = 'We could not connect to the database you specified. Please check your database settings.';
$string['dbcreationerror'] = 'Database creation error. Could not create the given database name with the settings provided';
$string['dbwrongencoding'] = 'The selected database is running under one non-recommended encoding ($a). It would be better to use one Unicode (UTF-8) encoded database instead. Anyway, you can bypass this test by selecting the \"Skip DB Encoding Test\" check below, but you could experience problems in the future.';
-$string['dbwrongprefix'] = 'You must follow prefix rules as explained above.';
+$string['dbwronghostserver'] = 'You must follow \"Host\" rules as explained above.';
+$string['dbwrongnlslang'] = 'The NLS_LANG environment variable in your web server must use the AL32UTF8 charset. See PHP documentation about how to configure OCI8 properly.';
+$string['dbwrongprefix'] = 'You must follow \"Tables Prefix\" rules as explained above.';
$string['dbhost'] = 'Host Server';
$string['dbpass'] = 'Password';
$string['dbprefix'] = 'Tables prefix';
@@ -223,10 +225,14 @@ $string['memorylimithelp'] = '<p>The PHP memory limit for your server is current
(you will see errors when you look at pages) so you\'ll have to remove the .htaccess file.</p></li>
</ol>';
$string['mssql'] = 'SQL*Server (mssql)';
+$string['mssqlextensionisnotpresentinphp'] = 'PHP has not been properly configured with the MSSQL extension so that it can communicate with SQL*Server. Please check your php.ini file or recompile PHP.';
$string['mysql'] = 'MySQL (mysql)';
$string['mysqlextensionisnotpresentinphp'] = 'PHP has not been properly configured with the MySQL extension so that it can communicate with MySQL. Please check your php.ini file or recompile PHP.';
$string['oci8po'] = 'Oracle (oci8po)';
+$string['ociextensionisnotpresentinphp'] = 'PHP has not been properly configured with the OCI8 extension so that it can communicate with Oracle. Please check your php.ini file or recompile PHP.';
+$string['odbcextensionisnotpresentinphp'] = 'PHP has not been properly configured with the ODBC extension so that it can communicate with SQL*Server. Please check your php.ini file or recompile PHP.';
$string['odbc_mssql'] = 'SQL*Server over ODBC (odbc_mssql)';
+$string['pgsqlextensionisnotpresentinphp'] = 'PHP has not been properly configured with the PGSQL extension so that it can communicate with PostgreSQL. Please check your php.ini file or recompile PHP.';
$string['postgres7'] = 'PostgreSQL (postgres7)';
$string['pass'] = 'Pass';
$string['phpversion'] = 'PHP version';
|
Some more strings added to the installer to make it more resposible.
Merged from MOODLE_<I>_STABLE
|
moodle_moodle
|
train
|
a2f1e8d4faaea09456091c788c9f4b94525107c1
|
diff --git a/examples/items.php b/examples/items.php
index <HASH>..<HASH> 100644
--- a/examples/items.php
+++ b/examples/items.php
@@ -107,6 +107,10 @@ $item->fields = array(
new PodioImageItemField('image-field'),
);
+// Or you can use add_field and remove_field methods to add/remove fields one at a time:
+$item->add_field(new PodioNumberItemField('number-field')); // Field object must have a field_id or an external_id
+$item->remove_field('number-field'); // Remove by field_id or external_id
+
// Notice how the external_id of the fields is being passed as the first argument to the constructor? When you create new instances of any of the Podio objects you can send three things to the constructor:
// 1. An associative array of properties. Like we did above when creating the item.
diff --git a/lib/Podio.php b/lib/Podio.php
index <HASH>..<HASH> 100644
--- a/lib/Podio.php
+++ b/lib/Podio.php
@@ -101,7 +101,7 @@ class Podio {
}
if (!is_array($attributes) && !is_object($attributes)) {
- throw new Exception('Attributes must be an array');
+ throw new PodioDataIntegrityError('Attributes must be an array');
}
switch ($method) {
diff --git a/lib/PodioError.php b/lib/PodioError.php
index <HASH>..<HASH> 100644
--- a/lib/PodioError.php
+++ b/lib/PodioError.php
@@ -37,3 +37,5 @@ class PodioRateLimitError extends PodioError {}
class PodioServerError extends PodioError {}
class PodioUnavailableError extends PodioError {}
class PodioMissingRelationshipError extends PodioError {}
+
+class PodioDataIntegrityError extends Exception {}
diff --git a/lib/PodioObject.php b/lib/PodioObject.php
index <HASH>..<HASH> 100644
--- a/lib/PodioObject.php
+++ b/lib/PodioObject.php
@@ -137,7 +137,7 @@ class PodioObject {
}
return true;
}
- throw new Exception("Attribute cannot be assigned. Property '{$name}' doesn't exist.");
+ throw new PodioDataIntegrityError("Attribute cannot be assigned. Property '{$name}' doesn't exist.");
}
public static function listing($response_or_attributes) {
diff --git a/models/PodioSuperApp.php b/models/PodioSuperApp.php
index <HASH>..<HASH> 100644
--- a/models/PodioSuperApp.php
+++ b/models/PodioSuperApp.php
@@ -20,6 +20,28 @@ class PodioSuperApp extends PodioObject {
}
/**
+ * Adds a field. Will replace any current field with the same ID
+ */
+ public function add_field($field) {
+ if (!$field->id && !$field->external_id) {
+ throw new PodioDataIntegrityError('Field must have id or external_id set.');
+ }
+ $this->remove_field($field->id ? $field->id : $field->external_id);
+
+ $this->fields = array_merge($this->fields, array($field));
+
+ }
+
+ /**
+ * Removes a field.
+ */
+ public function remove_field($field_id_or_external_id) {
+ $this->fields = array_filter($this->fields, function($field) use ($field_id_or_external_id) {
+ return !($field->id == $field_id_or_external_id || $field->external_id == $field_id_or_external_id);
+ });
+ }
+
+ /**
* Returns all fields of the given type on this item
*/
public function fields_of_type($type) {
|
Add convenience methods for adding and removing fields on items and apps.
|
podio-community_podio-php
|
train
|
615668848ff42a48ea08c34ab50a8f61ca74f4c3
|
diff --git a/dciclient/v1/api/file.py b/dciclient/v1/api/file.py
index <HASH>..<HASH> 100644
--- a/dciclient/v1/api/file.py
+++ b/dciclient/v1/api/file.py
@@ -17,6 +17,8 @@
from dciclient.v1.api import base
from dciclient.v1 import utils
+import os
+
RESOURCE = 'files'
TABLE_HEADERS = ['id', 'name', 'mime', 'md5', 'jobstate_id',
@@ -35,6 +37,22 @@ def create(context, name, content, mime='text/plain',
return context.session.post(uri, headers=headers, data=content)
+def create_with_stream(context, name, file_path, mime='text/plain',
+ jobstate_id=None, md5=None, job_id=None):
+ headers = {'DCI-NAME': name,
+ 'DCI-MIME': mime,
+ 'DCI-JOBSTATE-ID': jobstate_id,
+ 'DCI-MD5': md5,
+ 'DCI-JOB-ID': job_id}
+ headers = utils.sanitize_kwargs(**headers)
+ uri = '%s/%s' % (context.dci_cs_api, RESOURCE)
+
+ if not os.path.exists(file_path):
+ raise FileErrorException()
+ with open(file_path, 'rb') as f:
+ return context.session.post(uri, headers=headers, data=f)
+
+
def get(context, id, where=None, embed=None):
return base.get(context, RESOURCE, id=id, where=where, embed=embed)
@@ -51,3 +69,8 @@ def content(context, id):
uri = '%s/%s/%s/content' % (context.dci_cs_api, RESOURCE, id)
r = context.session.get(uri)
return r
+
+
+class FileErrorException(Exception):
+ def __init__(self, *args, **kwargs):
+ super(FileErrorException, self).__init__(self, *args, **kwargs)
|
Upload files with streaming.
Change-Id: Ic9e4e<I>e9ae4c<I>c2fa<I>dc1fc<I>c<I>
|
redhat-cip_python-dciclient
|
train
|
1572735824103e2fa74c103be10ed2995da1723e
|
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3246,6 +3246,22 @@ class TestDataFrame(unittest.TestCase, CheckIndexing,
rs = df.to_records(convert_datetime64=False)
self.assert_(rs['index'][0] == df.index.values[0])
+ def test_to_records_with_Mapping_type(self):
+ import email
+ from email.parser import Parser
+ import collections
+
+ collections.Mapping.register(email.message.Message)
+
+ headers = Parser().parsestr('From: <user@example.com>\n'
+ 'To: <someone_else@example.com>\n'
+ 'Subject: Test message\n'
+ '\n'
+ 'Body would go here\n')
+
+ frame = DataFrame.from_records([headers])
+ all( x in frame for x in ['Type','Subject','From'])
+
def test_from_records_to_records(self):
# from numpy documentation
arr = np.zeros((2,), dtype=('i4,f4,a10'))
|
TST: df.from_records should accept values deriving from ABC collection.Mapping
|
pandas-dev_pandas
|
train
|
468d38118e2a0970806ed6e6a4377dd77d669f04
|
diff --git a/src/ResourceUri.php b/src/ResourceUri.php
index <HASH>..<HASH> 100644
--- a/src/ResourceUri.php
+++ b/src/ResourceUri.php
@@ -185,6 +185,21 @@ final class ResourceUri
return self::fromProtocolAndResource($this->protocol, $this->resource . '/' . ltrim($childRelativePath, '/'));
}
+ public function getPath()
+ {
+ $resource = $this;
+
+ while ($resource->hasChainedResource()) {
+ $resource = $resource->getChainedResource();
+ }
+
+ if (false === $position = strrpos($resource->getResource(), '/')) {
+ return '';
+ }
+
+ return substr($resource->getResource(), $position + 1);
+ }
+
/**
* @return string
*/
diff --git a/src/functions.php b/src/functions.php
index <HASH>..<HASH> 100644
--- a/src/functions.php
+++ b/src/functions.php
@@ -9,7 +9,6 @@
* file that was distributed with this source code.
*/
-
/**
* @param string|\Alchemy\Resource\ResourceUri $uri A valid resource URI instance or string.
* @return \Alchemy\Resource\ResourceUri
diff --git a/tests/Tests/ResourceUriTest.php b/tests/Tests/ResourceUriTest.php
index <HASH>..<HASH> 100644
--- a/tests/Tests/ResourceUriTest.php
+++ b/tests/Tests/ResourceUriTest.php
@@ -229,4 +229,25 @@ class ResourceUriTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('root://uri/child', (string) ResourceUri::fromString('root://uri')->child('child'));
$this->assertEquals('root://uri/child', (string) ResourceUri::fromString('root://uri')->child('/child'));
}
+
+ public function testGetPathReturnsEmptyStringForPathlessResources()
+ {
+ $uri = ResourceUri::fromString('mock://path-less');
+
+ $this->assertEquals('', $uri->getPath());
+ }
+
+ public function testGetPathReturnsRelativePath()
+ {
+ $uri = ResourceUri::fromString('mock://resource')->child('path');
+
+ $this->assertEquals('path', $uri->getPath());
+ }
+
+ public function testGetPathFromChainedResourceReturnsRelativePath()
+ {
+ $uri = ResourceUri::fromString('mock://resource')->child('path')->chain('chained');
+
+ $this->assertEquals('path', $uri->getPath());
+ }
}
|
Add method to extract relative path from resource URIs
|
alchemy-fr_resource-component
|
train
|
87b195be6e15f07f1fdf65b04a705a8e29c18103
|
diff --git a/plugins/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/util/TypeReferences.java b/plugins/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/util/TypeReferences.java
index <HASH>..<HASH> 100644
--- a/plugins/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/util/TypeReferences.java
+++ b/plugins/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/util/TypeReferences.java
@@ -79,9 +79,11 @@ public class TypeReferences {
return rawType;
} else if (reference instanceof JvmGenericArrayTypeReference) {
JvmArrayType type = ((JvmGenericArrayTypeReference) reference).getType();
- JvmTypeReference componentType = type.getComponentType();
- JvmComponentType rawComponentType = (JvmComponentType) getRawType(componentType);
- return rawComponentType.getArrayType();
+ JvmTypeReference componentTypeReference = type.getComponentType();
+ JvmType rawComponentType = getRawType(componentTypeReference);
+ if (rawComponentType instanceof JvmComponentType && !rawComponentType.eIsProxy())
+ return ((JvmComponentType) rawComponentType).getArrayType();
+ return null;
} else if (reference instanceof JvmWildcardTypeReference) {
List<JvmTypeConstraint> constraints = ((JvmWildcardTypeReference) reference).getConstraints();
// TODO handle multiple upper bounds
|
[xbase][typereferences] Fix: Don't cast without instance of check - the element may be a proxy
|
eclipse_xtext-extras
|
train
|
d06cc81b05a156657695d6e822a9651d3fa91963
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index <HASH>..<HASH> 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -4,6 +4,7 @@
* better diagnostics for API mode install failure [kleisauke]
* revise docs [int-ua]
+* better reference tracking for new_from_memory [aspadm]
## Version 2.1.12 (17 Feb 2020)
diff --git a/pyvips/vimage.py b/pyvips/vimage.py
index <HASH>..<HASH> 100644
--- a/pyvips/vimage.py
+++ b/pyvips/vimage.py
@@ -158,8 +158,10 @@ class Image(pyvips.VipsObject):
def __init__(self, pointer):
# a list of other objects which this object depends on and which need
- # to be kept alive ... we can't use a set, since bytearrays are
- # unhashable
+ # to be kept alive
+ # we can't use a set because set elements are unique under "==", and
+ # Python checks memoryview equality with hash functions, not pointer
+ # equality
self._references = []
# logger.debug('Image.__init__: pointer = %s', pointer)
super(Image, self).__init__(pointer)
diff --git a/pyvips/voperation.py b/pyvips/voperation.py
index <HASH>..<HASH> 100644
--- a/pyvips/voperation.py
+++ b/pyvips/voperation.py
@@ -243,14 +243,25 @@ class Operation(pyvips.VipsObject):
logger.debug('VipsOperation.call: match_image = %s', match_image)
- # collect a list of all input references here ... we can't use a set,
- # unfortunately, because bytearrays are unhashable
+ # collect a list of all input references here
+ # we can't use a set because set elements are unique under "==", and
+ # Python checks memoryview equality with hash functions, not pointer
+ # equality
references = []
+ # does a list contain an element using "is" (pointer equality) to test
+ # equality ... we can't use "in" since that uses "==", which means
+ # hash equality
+ def contains(array, x):
+ for y in array:
+ if x is y:
+ return True
+ return False
+
def add_reference(x):
if isinstance(x, pyvips.Image):
for i in x._references:
- if i not in references:
+ if not contains(references, i):
references.append(i)
return False
@@ -285,7 +296,7 @@ class Operation(pyvips.VipsObject):
# attach all input refs to output x
def set_reference(x):
if isinstance(x, pyvips.Image):
- x._references += references
+ x._references.append(references)
return False
# fetch required output args (plus modified input images)
|
better reference tracking in new_from_memory
We were using "in" to check for repeats of memoryview objects, but "in"
uses "==", and "==" on memoryview compares hashes. This means that
different pointers are equal if they point to equal bytes.
This patch swaps "in" for a loop testing equality with "is" (pointer
equality). It should speed up pyvips operations on large memoryviews
too, since hashes will no longer be calculated.
Thanks aspadm
See <URL>
|
libvips_pyvips
|
train
|
e0ed49f86418be31875ed8523e2a137f704c1fce
|
diff --git a/structr/structr-core/src/main/java/org/structr/common/ImageHelper.java b/structr/structr-core/src/main/java/org/structr/common/ImageHelper.java
index <HASH>..<HASH> 100644
--- a/structr/structr-core/src/main/java/org/structr/common/ImageHelper.java
+++ b/structr/structr-core/src/main/java/org/structr/common/ImageHelper.java
@@ -113,6 +113,8 @@ public abstract class ImageHelper {
Image newImage = createNodeCommand.execute(props);
FileHelper.writeToFile(newImage, imageData);
+ newImage.setChecksum(FileHelper.getChecksum(newImage));
+ newImage.setSize(FileHelper.getSize(newImage));
return newImage;
diff --git a/structr/structr-core/src/main/java/org/structr/core/entity/File.java b/structr/structr-core/src/main/java/org/structr/core/entity/File.java
index <HASH>..<HASH> 100644
--- a/structr/structr-core/src/main/java/org/structr/core/entity/File.java
+++ b/structr/structr-core/src/main/java/org/structr/core/entity/File.java
@@ -113,7 +113,7 @@ public class File extends AbstractNode implements Linkable {
} catch (FrameworkException ex) {
- logger.log(Level.SEVERE, "Could not set checksum", ex);
+ logger.log(Level.SEVERE, "Could not set checksum and size", ex);
}
@@ -129,7 +129,7 @@ public class File extends AbstractNode implements Linkable {
} catch (FrameworkException ex) {
- logger.log(Level.SEVERE, "Could not set checksum", ex);
+ logger.log(Level.SEVERE, "Could not set checksum and size", ex);
}
|
set checksum and size at creation time
|
structr_structr
|
train
|
30f6a08d959e32ef8b09429d0970c23b39ac58d5
|
diff --git a/Gruntfile.js b/Gruntfile.js
index <HASH>..<HASH> 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -1,26 +1,35 @@
module.exports = function(grunt) {
+
"use strict";
+
grunt.initConfig({
+
pkg: grunt.file.readJSON('package.json'),
- copy: {
- main:{
- files: [{ src: ['javascript/src/eventsource.js'], dest: 'eventsource.js'}]
+
+ 'string-replace': {
+ dist: {
+ options: {
+ replacements: [
+ {pattern: /{{VERSION}}/g, replacement: '<%= pkg.version %>'}
+ ]
+ },
+ files: {
+ 'dist/eventsource.js': ['javascript/src/eventsource.js']
+ }
}
},
+
uglify: {
- options: {
- preserveComments: "some",
- compress: {
- drop_console: true
+ dist: {
+ files: {
+ 'dist/eventsource.min.js': ['dist/eventsource.js']
+ }
}
- },
- build: {
- src: 'javascript/src/eventsource.js',
- dest: 'eventsource.min.js'
- }
- }
- });
- grunt.loadNpmTasks('grunt-contrib-copy');
+ },
+
+
+ });
+ grunt.loadNpmTasks('grunt-string-replace');
grunt.loadNpmTasks('grunt-contrib-uglify');
- grunt.registerTask('default', ['copy','uglify']);
+ grunt.registerTask('default', ['string-replace', 'uglify']);
};
diff --git a/javascript/src/eventsource.js b/javascript/src/eventsource.js
index <HASH>..<HASH> 100644
--- a/javascript/src/eventsource.js
+++ b/javascript/src/eventsource.js
@@ -1,3 +1,8 @@
+/*
+ * EventSource polyfill version {{VERSION}}
+ * Supported by sc AmvTek srl
+ * :email: devel@amvtek.com
+ */
;(function (global) {
if (global.EventSource && !global._eventSourceImportPrefix){
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "eventsource-polyfill",
- "version": "0.9.1",
+ "version": "0.9.3",
"description": "A polyfill for http://www.w3.org/TR/eventsource/",
"main": "javascript/src/eventsource.js",
"directories": {
@@ -28,7 +28,7 @@
"homepage": "https://github.com/amvtek/EventSource",
"devDependencies": {
"grunt": "^0.4.5",
- "grunt-contrib-copy": "^0.7.0",
- "grunt-contrib-uglify": "^0.6.0"
+ "grunt-contrib-uglify": "^0.6.0",
+ "grunt-string-replace": "^1.0.0"
}
}
|
Improved release packaging, & added template for release version to show in distributed sources...
|
amvtek_EventSource
|
train
|
288d3bd55d9727b6bcb76b84070d28cb09908ec1
|
diff --git a/spec/features/examples/facebook_api_spec.rb b/spec/features/examples/facebook_api_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/features/examples/facebook_api_spec.rb
+++ b/spec/features/examples/facebook_api_spec.rb
@@ -1,7 +1,8 @@
require 'spec_helper'
require 'base64'
-describe 'Facebook API example', type: :feature, js: true do
+# FIXME: Looks like Facebook API changed recently and this test fails consistently now -RS 2018-03-05
+xdescribe 'Facebook API example', type: :feature, js: true do
before do
proxy.stub('https://www.facebook.com:443/dialog/oauth').and_return(proc do |params, _, _|
# mock a signed request from facebook. the JS api never verifies the
|
Removing failing feature spec or now
|
oesmith_puffing-billy
|
train
|
a6d8cd30cadf0c9a2de6d90f4e16d2eb594fe92c
|
diff --git a/nago/extensions/__init__.py b/nago/extensions/__init__.py
index <HASH>..<HASH> 100644
--- a/nago/extensions/__init__.py
+++ b/nago/extensions/__init__.py
@@ -1,9 +1,3 @@
-from nago.core import nago_access, get_node
-import nago.core
-import inspect
-import os
-import json
-
""" Extensions module for Nago
All actual domain and check-specific logic of Nago should live as an extension.
@@ -14,6 +8,14 @@ made available to the message bus.
Take a look at facts.py for an example of a simple extension.
"""
+from nago.core import nago_access, get_node
+import nago.core
+import inspect
+import os
+import json
+import time
+
+
__localaccess__ = object() # If you are working locally on this machine, you can proof it with this
__loaded_extensions = {} # Extensions are loaded here with the load() method
@@ -103,12 +105,19 @@ def call_method(token, extension_name, method_name, json_data=None, *args, **kwa
result['current_access'] = node.get('access')
return result
+ # If a special argument called json_data, we decode the json and treat it
+ # As json encoded arguments
if json_data:
- kwargs = kwargs.copy()
data = json.loads(json_data)
for k,v in data.items():
kwargs[k] = v
+ if 'about_me' in kwargs:
+ about_me = kwargs.pop('about_me')
+ node.update_info('node_info', about_me)
+ # Log when node last connected
+ now = time.time()
+ node.update_info('last_connect', now)
return method(*args, **kwargs)
|
extension api now stores metadata from clients
|
opinkerfi_nago
|
train
|
68e96f50d8d65bd164ee2e47be9a0663899b4476
|
diff --git a/resources/lang/de-DE/cachet.php b/resources/lang/de-DE/cachet.php
index <HASH>..<HASH> 100644
--- a/resources/lang/de-DE/cachet.php
+++ b/resources/lang/de-DE/cachet.php
@@ -33,6 +33,7 @@ return [
'scheduled' => 'Geplante Wartungen',
'scheduled_at' => ', geplant :timestamp',
'posted' => 'Veröffentlicht :timestamp',
+ 'posted_at' => 'Posted at :timestamp',
'status' => [
1 => 'Untersuchungen laufen',
2 => 'Identifiziert',
@@ -75,7 +76,7 @@ return [
// Subscriber
'subscriber' => [
'subscribe' => 'Abonnieren Sie um die neuesten Updates zu erhalten.',
- 'unsubscribe' => 'Deabonnieren unter :link',
+ 'unsubscribe' => 'Unter :link abbestellen',
'button' => 'Abonnieren',
'manage' => [
'no_subscriptions' => 'Du hast im Augenblick alle Updates abonniert.',
|
New translations cachet.php (German)
|
CachetHQ_Cachet
|
train
|
9b528439d882766668e7d7aa923e39e57918aa85
|
diff --git a/csg/core.py b/csg/core.py
index <HASH>..<HASH> 100644
--- a/csg/core.py
+++ b/csg/core.py
@@ -323,9 +323,9 @@ class CSG(object):
polygons = []
def appendVertex(vertices, theta, phi):
d = Vector(
- math.cos(theta) * math.sin(phi),
- math.cos(phi),
- math.sin(theta) * math.sin(phi))
+ center[0] + r * math.cos(theta) * math.sin(phi),
+ center[1] + r * math.cos(phi),
+ center[2] + r * math.sin(theta) * math.sin(phi))
vertices.append(Vertex(c.plus(d.times(r)), d))
dTheta = math.pi * 2.0 / float(slices)
diff --git a/test/test_csg.py b/test/test_csg.py
index <HASH>..<HASH> 100644
--- a/test/test_csg.py
+++ b/test/test_csg.py
@@ -55,8 +55,8 @@ class TestCSG(unittest.TestCase):
def test_sphere_union(self):
# this test currently fails
- a = CSG.sphere(center=(0., 0., 0.), radius=1.0, slices=16, stacks=8)
- b = CSG.sphere(center=(1., 0., 0.), radius=1.0, slices=16, stacks=8)
+ a = CSG.sphere(center=(0., 0., 0.), radius=1.0, slices=64, stacks=32)
+ b = CSG.sphere(center=(1.99, 0., 0.), radius=1.0, slices=64, stacks=32)
c = a + b
a.saveVTK('test_sphere_union_a.vtk')
b.saveVTK('test_sphere_union_b.vtk')
|
fixed the offset and radius problem when creating a sphere
|
timknip_pycsg
|
train
|
46a121d3d9059be5956bd1022c8fdca084c0119d
|
diff --git a/src/Command/SelfUpdateCommand.php b/src/Command/SelfUpdateCommand.php
index <HASH>..<HASH> 100755
--- a/src/Command/SelfUpdateCommand.php
+++ b/src/Command/SelfUpdateCommand.php
@@ -25,27 +25,6 @@ class SelfUpdateCommand extends Command
{
/**
- * @var Updater
- */
- private $updater;
-
- /**
- * SelfUpdateCommand constructor.
- *
- * @param null $name
- */
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->updater = new Updater(null, false, Updater::STRATEGY_GITHUB);
- /** @var GithubStrategy $strategy */
- $strategy = $this->updater->getStrategy();
- $strategy->setPackageName('TYPO3/Surf');
- $strategy->setPharName('surf.phar');
- }
-
- /**
* @return bool
*/
public function isEnabled()
@@ -85,6 +64,12 @@ class SelfUpdateCommand extends Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
+ $updater = new Updater(null, false, Updater::STRATEGY_GITHUB);
+ /** @var GithubStrategy $strategy */
+ $strategy = $updater->getStrategy();
+ $strategy->setPackageName('TYPO3/Surf');
+ $strategy->setPharName('surf.phar');
+
$io = new SymfonyStyle($input, $output);
$stability = $input->getOption('stability');
@@ -93,36 +78,36 @@ class SelfUpdateCommand extends Command
$stability = GithubStrategy::UNSTABLE;
}
/** @var GithubStrategy $strategy */
- $strategy = $this->updater->getStrategy();
+ $strategy = $updater->getStrategy();
$strategy->setCurrentLocalVersion($this->getApplication()->getVersion());
$strategy->setStability($stability);
if ($input->getOption('check')) {
- $result = $this->updater->hasUpdate();
+ $result = $updater->hasUpdate();
if ($result) {
$output->writeln(sprintf(
'The %s build available remotely is: %s',
$strategy->getStability() === GithubStrategy::ANY ? 'latest' : 'current ' . $strategy->getStability(),
- $this->updater->getNewVersion()
+ $updater->getNewVersion()
));
- } elseif (false === $this->updater->getNewVersion()) {
+ } elseif (false === $updater->getNewVersion()) {
$output->writeln('There are no new builds available.');
} else {
$output->writeln(sprintf('You have the current %s build installed.', $strategy->getStability()));
}
} elseif ($input->getOption('rollback')) {
- $result = $this->updater->rollback();
+ $result = $updater->rollback();
$result ? $output->writeln('Success!') : $output->writeln('Failure!');
} else {
- $result = $this->updater->update();
+ $result = $updater->update();
if ($result) {
$io->success(
sprintf(
'Your %s has been updated from "%s" to "%s".',
$this->getLocalPharName(),
- $this->updater->getOldVersion(),
- $this->updater->getNewVersion()
+ $updater->getOldVersion(),
+ $updater->getNewVersion()
)
);
} else {
|
[HOTFIX] Move instantiation of Updater to execute method
Resolve #<I>
|
TYPO3_Surf
|
train
|
feabdf08aa7535ef0b2e2f863cdd0c665dcb52ad
|
diff --git a/src/Service/MelisWebPackService.php b/src/Service/MelisWebPackService.php
index <HASH>..<HASH> 100644
--- a/src/Service/MelisWebPackService.php
+++ b/src/Service/MelisWebPackService.php
@@ -240,7 +240,7 @@ class MelisWebPackService implements ServiceLocatorAwareInterface
// remove params on URL
$file = preg_replace('/\?(.+?)*/', '', $file);
-
+ $exists = file_exists($file) === true ? '// exists' : '// file does not exists';
$syntax .= "\t'$file', ". PHP_EOL;
}
|
added checker if the file exists
|
melisplatform_melis-asset-manager
|
train
|
c145a0a2cdbe990e5d64a8bd7e15db95d12af058
|
diff --git a/molotov/quickstart/loadtest.py b/molotov/quickstart/loadtest.py
index <HASH>..<HASH> 100644
--- a/molotov/quickstart/loadtest.py
+++ b/molotov/quickstart/loadtest.py
@@ -8,7 +8,7 @@ from molotov import scenario, setup, global_setup, teardown, global_teardown
_API = 'http://localhost:8080'
-@global_setup
+@global_setup()
def test_starts(args):
""" This functions is called before anything starts.
@@ -30,7 +30,7 @@ async def worker_starts(worker_id, args):
return {'headers': headers}
-@teardown
+@teardown()
def worker_ends(worker_id):
""" This functions is called when the worker is done.
@@ -39,7 +39,7 @@ def worker_ends(worker_id):
pass
-@global_teardown
+@global_teardown()
def test_ends():
""" This functions is called when everything is done.
diff --git a/molotov/tests/test_quickstart.py b/molotov/tests/test_quickstart.py
index <HASH>..<HASH> 100644
--- a/molotov/tests/test_quickstart.py
+++ b/molotov/tests/test_quickstart.py
@@ -3,16 +3,18 @@ import unittest
import shutil
import os
-from molotov import quickstart, __version__
+from molotov import quickstart, __version__, run
from molotov.tests.support import set_args
class TestQuickStart(unittest.TestCase):
def setUp(self):
+ self._curdir = os.getcwd()
self.tempdir = tempfile.mkdtemp()
self._answers = ['y', 'welp', self.tempdir]
def tearDown(self):
+ os.chdir(self._curdir)
shutil.rmtree(self.tempdir)
def _input(self, text):
@@ -49,3 +51,20 @@ class TestQuickStart(unittest.TestCase):
raise AssertionError()
except SystemExit:
pass
+
+ def test_codeworks(self):
+ quickstart._input = self._input
+
+ with set_args('molostart'):
+ quickstart.main()
+
+ result = os.listdir(self.tempdir)
+ result.sort()
+ self.assertEqual(result, ['Makefile', 'loadtest.py', 'molotov.json'])
+
+ os.chdir(self.tempdir)
+ with set_args('molotov', '-cxv', '--max-runs', '1'):
+ try:
+ run.main()
+ except SystemExit:
+ pass
|
Make sure the generated code works - fixes #<I>
|
loads_molotov
|
train
|
932b057f4de960d8b42826a214d37dd9dffc9852
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -85,7 +85,7 @@
"webpack-isomorphic-tools": "^0.8.5"
},
"devDependencies": {
- "autoprefixer-loader": "^2.0.0",
+ "autoprefixer-loader": "^3.1.0",
"babel-core": "^5.8.22",
"babel-eslint": "^4.0.10",
"babel-loader": "5.3.2",
diff --git a/src/api/routes/updateWidget.js b/src/api/routes/updateWidget.js
index <HASH>..<HASH> 100644
--- a/src/api/routes/updateWidget.js
+++ b/src/api/routes/updateWidget.js
@@ -9,6 +9,11 @@ export default function updateWidget(req) {
} else {
const widgets = getWidgets(req);
const widget = req.body;
+ if (widget.color === 'Green') {
+ reject({
+ color: 'We do not accept green widgets' // example server-side validation error
+ });
+ }
if (widget.id) {
widgets[widget.id - 1] = widget; // id is 1-based. please don't code like this in production! :-)
}
diff --git a/src/components/WidgetForm.js b/src/components/WidgetForm.js
index <HASH>..<HASH> 100755
--- a/src/components/WidgetForm.js
+++ b/src/components/WidgetForm.js
@@ -72,7 +72,13 @@ export default class WidgetForm extends Component {
<i className="fa fa-ban"/> Cancel
</button>
<button className="btn btn-success"
- onClick={handleSubmit(() => save(values))}
+ onClick={handleSubmit(() => save(values)
+ .catch(x => {
+ if (x && typeof x.error === 'object') {
+ return Promise.reject(x.error);
+ }
+ })
+ )}
disabled={pristine || invalid || submitting}>
<i className={'fa ' + (submitting ? 'fa-cog fa-spin' : 'fa-cloud')}/> Save
</button>
diff --git a/src/ducks/widgets.js b/src/ducks/widgets.js
index <HASH>..<HASH> 100644
--- a/src/ducks/widgets.js
+++ b/src/ducks/widgets.js
@@ -70,13 +70,13 @@ export default function reducer(state = initialState, action = {}) {
}
};
case SAVE_FAIL:
- return {
+ return typeof action.error === 'string' ? {
...state,
saveError: {
...state.saveError,
[action.id]: action.error
}
- };
+ } : state;
default:
return state;
}
|
upgraded autoprefixer-loader, upgraded to redux-form <I>
|
bdefore_universal-redux
|
train
|
5f27a37aa2f8f64dd43787a34d94a7e006ebfa98
|
diff --git a/ballet/eng/category_encoders.py b/ballet/eng/category_encoders.py
index <HASH>..<HASH> 100644
--- a/ballet/eng/category_encoders.py
+++ b/ballet/eng/category_encoders.py
@@ -18,3 +18,24 @@ try:
from category_encoders import WOEEncoder
except ImportError:
pass
+
+
+__all__ = (
+ 'BackwardDifferenceEncoder',
+ 'BaseNEncoder',
+ 'BinaryEncoder',
+ 'CatBoostEncoder',
+ 'CountEncoder',
+ 'GLMMEncoder',
+ 'HashingEncoder',
+ 'HelmertEncoder',
+ 'JamesSteinEncoder',
+ 'LeaveOneOutEncoder',
+ 'MEstimateEncoder',
+ 'OneHotEncoder',
+ 'OrdinalEncoder',
+ 'PolynomialEncoder',
+ 'SumEncoder',
+ 'TargetEncoder',
+ 'WOEEncoder',
+)
diff --git a/ballet/eng/feature_engine.py b/ballet/eng/feature_engine.py
index <HASH>..<HASH> 100644
--- a/ballet/eng/feature_engine.py
+++ b/ballet/eng/feature_engine.py
@@ -25,3 +25,31 @@ try:
from feature_engine.variable_transformers import YeoJohnsonTransformer
except ImportError:
pass
+
+
+__all__ = ()
+ 'AddMissingIndicator',
+ 'ArbitraryNumberImputer',
+ 'ArbitraryOutlierCapper',
+ 'BoxCoxTransformer',
+ 'CategoricalVariableImputer',
+ 'CountFrequencyCategoricalEncoder',
+ 'DecisionTreeDiscretiser',
+ 'EndTailImputer',
+ 'EqualFrequencyDiscretiser',
+ 'EqualWidthDiscretiser',
+ 'LogTransformer',
+ 'MeanCategoricalEncoder',
+ 'MeanMedianImputer',
+ 'OneHotCategoricalEncoder',
+ 'OrdinalCategoricalEncoder',
+ 'OutlierTrimmer',
+ 'PowerTransformer',
+ 'RandomSampleImputer',
+ 'RareLabelCategoricalEncoder',
+ 'ReciprocalTransformer',
+ 'UserInputDIscretiser',
+ 'Winsorizer',
+ 'WoERatioCategoricalEncoder',
+ 'YeoJohnsonTransformer',
+)
diff --git a/ballet/eng/featuretools.py b/ballet/eng/featuretools.py
index <HASH>..<HASH> 100644
--- a/ballet/eng/featuretools.py
+++ b/ballet/eng/featuretools.py
@@ -2,3 +2,8 @@ try:
from featuretools.wrappers import DFSTransformer
except ImportError:
pass
+
+
+__all__ = (
+ 'DFSTransformer',
+)
diff --git a/ballet/eng/skits.py b/ballet/eng/skits.py
index <HASH>..<HASH> 100644
--- a/ballet/eng/skits.py
+++ b/ballet/eng/skits.py
@@ -5,10 +5,23 @@ try:
from skits.feature_extraction import RollingMeanTransformer
from skits.feature_extraction import TrendTransformer
from skits.feature_extraction import FourierTransformer
-
from skits.preprocessing import ReversibleImputer
from skits.preprocessing import DifferenceTransformer
from skits.preprocessing import LogTransformer
from skits.preprocessing import HorizonTransformer
except ImportError:
pass
+
+
+__all__ = (
+ 'AutoregressiveTransformer',
+ 'DifferenceTransformer',
+ 'FourierTransformer',
+ 'HorizonTransformer',
+ 'IntegratedTransformer',
+ 'LogTransformer',
+ 'ReversibleImputer',
+ 'RollingMeanTransformer',
+ 'SeasonalTransformer',
+ 'TrendTransformer',
+)
diff --git a/ballet/eng/sklearn.py b/ballet/eng/sklearn.py
index <HASH>..<HASH> 100644
--- a/ballet/eng/sklearn.py
+++ b/ballet/eng/sklearn.py
@@ -21,3 +21,26 @@ try:
from sklearn.impute import IterativeImputer
except ImportError:
pass
+
+
+__all__ = (
+ 'Binarizer',
+ 'FunctionTransformer',
+ 'GaussianRandomProjection',
+ 'IterativeImputer',
+ 'KBinsDiscretizer',
+ 'KNNImputer'
+ 'MaxAbsScaler',
+ 'MinMaxScaler',
+ 'MissingIndicator',
+ 'Normalizer',
+ 'OneHotEncoder',
+ 'OrdinalEncoder',
+ 'PolynomialFeatures',
+ 'PowerTransformer',
+ 'QuantileTransformer',
+ 'RobustScaler',
+ 'SimpleImputer',
+ 'SparseRandomProjection',
+ 'StandardScaler',
+)
diff --git a/ballet/eng/sklearn_pandas.py b/ballet/eng/sklearn_pandas.py
index <HASH>..<HASH> 100644
--- a/ballet/eng/sklearn_pandas.py
+++ b/ballet/eng/sklearn_pandas.py
@@ -2,3 +2,8 @@ try:
from sklearn_pandas.transformers import NumericalTransformer
except ImportError:
pass
+
+
+__all__ = (
+ 'NumericalTransformer',
+)
diff --git a/ballet/eng/tsfresh.py b/ballet/eng/tsfresh.py
index <HASH>..<HASH> 100644
--- a/ballet/eng/tsfresh.py
+++ b/ballet/eng/tsfresh.py
@@ -2,3 +2,9 @@ try:
from tsfresh.transformers import FeatureAugmenter
except ImportError:
pass
+
+
+
+__all__ = (
+ 'FeatureAugmenter',
+)
|
Set __all__ for re-exported libraries
|
HDI-Project_ballet
|
train
|
a8981c1e082f993d9700264242c471a4182d3b96
|
diff --git a/django_tablib/fields.py b/django_tablib/fields.py
index <HASH>..<HASH> 100644
--- a/django_tablib/fields.py
+++ b/django_tablib/fields.py
@@ -1,4 +1,4 @@
class Field(object):
def __init__(self, attribute=None, header=None):
self.attribute = attribute
- self.header = header or self.attribute
+ self.header = header
|
Don't set Field.header to the attribute if no header is specified.
|
joshourisman_django-tablib
|
train
|
a7b3f1b65081325f739ea7f50c2b621cce5f9a06
|
diff --git a/spyderlib/widgets/status.py b/spyderlib/widgets/status.py
index <HASH>..<HASH> 100644
--- a/spyderlib/widgets/status.py
+++ b/spyderlib/widgets/status.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright © 2012 Pierre Raybaut
+# Copyright © 2009- The Spyder Development Team
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
@@ -184,7 +184,7 @@ class CursorPositionStatus(StatusBarWidget):
def test():
from spyderlib.qt.QtGui import QMainWindow
from spyderlib.utils.qthelpers import qapplication
- app = qapplication()
+ app = qapplication(test_time=5)
win = QMainWindow()
win.setWindowTitle("Status widgets test")
win.resize(900, 300)
@@ -196,6 +196,7 @@ def test():
swidgets.append(swidget)
win.show()
app.exec_()
-
+
+
if __name__ == "__main__":
test()
|
Testing: Fix widgets/status tests
|
spyder-ide_spyder
|
train
|
70495a83b1b4c62866865d7336e3731103630780
|
diff --git a/src/kba/pipeline/test_dedup.py b/src/kba/pipeline/test_dedup.py
index <HASH>..<HASH> 100644
--- a/src/kba/pipeline/test_dedup.py
+++ b/src/kba/pipeline/test_dedup.py
@@ -108,7 +108,8 @@ def test_dedup_production_config():
print 'removed %d near-exact duplicates' % num_dups
assert num_dups == 3
-@pytest.mark.xfail # pylint: disable=E1101 ## until we get v0_3_0 data into _test_data.py
+## until we get v0_3_0 data into _test_data.py
+@pytest.mark.xfail # pylint: disable=E1101
def test_dedup_chunk_counts():
path = os.path.dirname(__file__)
config = yaml.load(open(os.path.join(path, 'test_dedup_chunk_counts.yaml')))
|
fixing more pylint
|
trec-kba_streamcorpus-pipeline
|
train
|
8aa770fab6ac19993bb4b05637dd1f57b28c5810
|
diff --git a/composite_rsr_plot.py b/composite_rsr_plot.py
index <HASH>..<HASH> 100644
--- a/composite_rsr_plot.py
+++ b/composite_rsr_plot.py
@@ -34,8 +34,7 @@ import numpy as np
def plot_band(plt_in, band_name, spec_response, pltname=None):
- """Do the plotting of one band
- """
+ """Do the plotting of one band"""
detectors = spec_response[band_name].keys()
# for det in detectors:
@@ -58,9 +57,11 @@ def plot_band(plt_in, band_name, spec_response, pltname=None):
return plt_in
-if __name__ == "__main__":
+
+def get_arguments():
+ """Get the command line arguments"""
+
import argparse
- import sys
parser = argparse.ArgumentParser(
description='Plot spectral responses for a set of satellite imagers')
@@ -96,9 +97,15 @@ if __name__ == "__main__":
help="The wavelength range for the plot",
default=[None, None], type=float)
+ return parser.parse_args()
+
+if __name__ == "__main__":
+ import sys
+
+ args = get_arguments()
+
LOG = get_logger(__name__)
- args = parser.parse_args()
platform_names = args.platform_name
sensors = args.sensor
minimum_response = args.minimum_response
diff --git a/pyspectral/__init__.py b/pyspectral/__init__.py
index <HASH>..<HASH> 100644
--- a/pyspectral/__init__.py
+++ b/pyspectral/__init__.py
@@ -26,14 +26,13 @@
from pyspectral.version import __version__
import logging
import os
-
-LOG = logging.getLogger(__name__)
-
#from six.moves import configparser
import yaml
from collections import Mapping
-
import pkg_resources
+
+LOG = logging.getLogger(__name__)
+
BUILTIN_CONFIG_FILE = pkg_resources.resource_filename(__name__,
os.path.join('etc', 'pyspectral.yaml'))
diff --git a/pyspectral/rsr_reader.py b/pyspectral/rsr_reader.py
index <HASH>..<HASH> 100644
--- a/pyspectral/rsr_reader.py
+++ b/pyspectral/rsr_reader.py
@@ -92,9 +92,7 @@ class RelativeSpectralResponse(object):
self.load()
def _check_instrument(self):
- """Check and try correct instrument name if needed"""
-
- # Try fix instrument naming
+ """Check and try fix instrument name if needed"""
instr = INSTRUMENTS.get(self.platform_name, self.instrument)
if instr != self.instrument:
self.instrument = instr
@@ -105,15 +103,14 @@ class RelativeSpectralResponse(object):
def _get_filename(self):
"""Get the rsr filname from platform and instrument names, and download if not
- available
- """
+ available.
+ """
self.filename = expanduser(
os.path.join(self.rsr_dir, 'rsr_{0}_{1}.h5'.format(self.instrument,
self.platform_name)))
LOG.debug('Filename: %s', str(self.filename))
-
if not os.path.exists(self.filename) or not os.path.isfile(self.filename):
# Try download from the internet!
LOG.warning("No rsr file %s on disk", self.filename)
diff --git a/pyspectral/utils.py b/pyspectral/utils.py
index <HASH>..<HASH> 100644
--- a/pyspectral/utils.py
+++ b/pyspectral/utils.py
@@ -344,8 +344,7 @@ def logging_on(level=logging.WARNING):
class NullHandler(logging.Handler):
- """Empty handler.
- """
+ """Empty handler"""
def emit(self, record):
"""Record a message.
diff --git a/pyspectral/viirs_rsr.py b/pyspectral/viirs_rsr.py
index <HASH>..<HASH> 100644
--- a/pyspectral/viirs_rsr.py
+++ b/pyspectral/viirs_rsr.py
@@ -109,8 +109,6 @@ class ViirsRSR(object):
"""Container for the (S-NPP/JPSS) VIIRS RSR data"""
def __init__(self, bandname, platform_name):
- """Init"""
-
self.platform_name = platform_name
self.bandname = bandname
self.filename = None
@@ -128,7 +126,6 @@ class ViirsRSR(object):
def _get_bandfilenames(self, **options):
"""Get filename for each band"""
-
conf = options[self.platform_name + '-viirs']
rootdir = conf['rootdir']
|
Improve code style (following Codacy)
|
pytroll_pyspectral
|
train
|
8373fc49fdd7d17831990f2d7dd3afc9b894c5e4
|
diff --git a/tests/Subscriber/RedirectTest.php b/tests/Subscriber/RedirectTest.php
index <HASH>..<HASH> 100644
--- a/tests/Subscriber/RedirectTest.php
+++ b/tests/Subscriber/RedirectTest.php
@@ -24,7 +24,14 @@ class RedirectTest extends \PHPUnit_Framework_TestCase
$client->getEmitter()->attach($history);
$client->getEmitter()->attach($mock);
- $response = $client->get('/foo');
+ $request = $client->createRequest('GET', '/foo');
+ // Ensure "end" is called only once
+ $called = 0;
+ $request->getEmitter()->on('end', function () use (&$called) {
+ $called++;
+ });
+ $response = $client->send($request);
+
$this->assertEquals(200, $response->getStatusCode());
$this->assertContains('/redirect2', $response->getEffectiveUrl());
@@ -37,6 +44,8 @@ class RedirectTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('GET', $requests[1]->getMethod());
$this->assertEquals('/redirect2', $requests[2]->getPath());
$this->assertEquals('GET', $requests[2]->getMethod());
+
+ $this->assertEquals(1, $called);
}
/**
|
Ensuring redirect "end" is called only onect
|
guzzle_guzzle
|
train
|
a7b24e705e4acdf3bffefe6fb885d10e3e29d956
|
diff --git a/atrcopy/parsers.py b/atrcopy/parsers.py
index <HASH>..<HASH> 100644
--- a/atrcopy/parsers.py
+++ b/atrcopy/parsers.py
@@ -21,9 +21,11 @@ class SegmentParser(object):
self.image = None
self.segments = []
self.strict = strict
- self.parse(segment_data)
+ self.segment_data = segment_data
+ self.parse()
- def parse(self, r):
+ def parse(self):
+ r = self.segment_data
self.segments.append(DefaultSegment(r, 0))
try:
self.image = self.get_image(r)
@@ -51,8 +53,8 @@ class SegmentParser(object):
class DefaultSegmentParser(SegmentParser):
menu_name = "Raw Data"
- def parse(self, r):
- self.segments = [DefaultSegment(r, 0)]
+ def parse(self):
+ self.segments = [DefaultSegment(self.segment_data, 0)]
class KBootSegmentParser(SegmentParser):
|
SegmentParser now stores ref to segment data so it can reparse without having to pass that in again
|
robmcmullen_atrcopy
|
train
|
9d8cfce7ef34664b445527cc0be592f3dfc1d873
|
diff --git a/blockstack_client/user.py b/blockstack_client/user.py
index <HASH>..<HASH> 100644
--- a/blockstack_client/user.py
+++ b/blockstack_client/user.py
@@ -353,7 +353,9 @@ def user_zonefile_data_pubkey(user_zonefile, key_prefix='pubkey:data:'):
Return None if not defined
Raise if there are multiple ones.
"""
- assert is_user_zonefile(user_zonefile)
+ if not is_user_zonefile(user_zonefile):
+ log.debug("invalid zone file")
+ return None
if 'txt' not in user_zonefile:
return None
@@ -504,7 +506,9 @@ def put_immutable_data_zonefile(user_zonefile, data_id, data_hash, data_url=None
Return False otherwise.
"""
- assert is_user_zonefile(user_zonefile)
+ if not is_user_zonefile(user_zonefile):
+ log.debug("Invalid zone file structure")
+ return False
data_hash = str(data_hash)
assert scripts.is_valid_hash(data_hash)
@@ -631,7 +635,9 @@ def has_immutable_data_id(user_zonefile, data_id):
Return True if so
Return False if not
"""
- assert is_user_zonefile(user_zonefile)
+ if not is_user_zonefile(user_zonefile):
+ log.debug("Not a valid zone file")
+ return False
if 'txt' not in user_zonefile:
return False
|
it's okay if we don't have a user zone file when searching through it; just return None in these cases.
|
blockstack_blockstack-core
|
train
|
8b3f88ff8ef216867feed614ba463b9d7cc828df
|
diff --git a/tests/sockjs_app.js b/tests/sockjs_app.js
index <HASH>..<HASH> 100644
--- a/tests/sockjs_app.js
+++ b/tests/sockjs_app.js
@@ -5,7 +5,7 @@ exports.install = function(config, server) {
sjs_echo.on('open', function(conn){
console.log(' [+] echo open ' + conn);
conn.on('close', function(e) {
- console.log(' [-] echo close ' + conn, e);
+ console.log(' [-] echo close ' + conn);
});
conn.on('message', function(e) {
var d = JSON.stringify(e.data);
@@ -21,7 +21,7 @@ exports.install = function(config, server) {
console.log(' [+] clos open ' + conn);
conn.close(3000, "Go away!");
conn.on('close', function(e) {
- console.log(' [-] clos close ' + conn, e);
+ console.log(' [-] clos close ' + conn);
});
});
@@ -36,7 +36,7 @@ exports.install = function(config, server) {
tref = setTimeout(schedule, 1000);
conn.on('close', function(e) {
clearTimeout(tref);
- console.log(' [-] ticker close ' + conn, e);
+ console.log(' [-] ticker close ' + conn);
});
});
@@ -47,7 +47,7 @@ exports.install = function(config, server) {
broadcast[conn.id] = conn;
conn.on('close', function(e) {
delete broadcast[conn.id];
- console.log(' [-] broadcast close' + conn, e);
+ console.log(' [-] broadcast close' + conn);
});
conn.on('message', function(e) {
console.log(' [-] broadcast message', e);
@@ -61,7 +61,7 @@ exports.install = function(config, server) {
sjs_amplify.on('open', function(conn){
console.log(' [+] amp open ' + conn);
conn.on('close', function(e) {
- console.log(' [-] amp close ' + conn, e);
+ console.log(' [-] amp close ' + conn);
});
conn.on('message', function(e) {
var n = Math.floor(Number(e.data));
|
Be less verbose during tests.
|
sockjs_sockjs-client
|
train
|
5aa48facaf77d8fb6919c960659dfa41f3f1ad78
|
diff --git a/fabfile.py b/fabfile.py
index <HASH>..<HASH> 100644
--- a/fabfile.py
+++ b/fabfile.py
@@ -2,7 +2,13 @@ import os
from fabric.api import *
+def clean():
+ current_dir = os.path.dirname(__file__)
+ local("find %s -name '*.pyc' -exec rm -f {} \;" % current_dir)
+ local("rm -rf %s/build" % current_dir)
+
def unit():
+ clean()
current_dir = os.path.dirname(__file__)
command = " ".join(["PYTHONPATH=$PYTHONPATH:%s/videolog" % current_dir,
"nosetests", "-s", "--verbose", "--with-coverage",
|
Add task clean() to remove *.pyc files
|
rcmachado_pyvideolog
|
train
|
da970a263abed444da7ca1c6b1c0f4700d3171d1
|
diff --git a/client/mc.go b/client/mc.go
index <HASH>..<HASH> 100644
--- a/client/mc.go
+++ b/client/mc.go
@@ -46,6 +46,16 @@ func (client *Client) Send(req gomemcached.MCRequest) (rv gomemcached.MCResponse
return
}
+// Send a request, but do not wait for a response.
+func (client *Client) Transmit(req gomemcached.MCRequest) {
+ transmitRequest(client.writer, req)
+}
+
+// Receive a response
+func (client *Client) Receive() gomemcached.MCResponse {
+ return client.getResponse()
+}
+
// Get the value for a key.
func (client *Client) Get(vb uint16, key string) gomemcached.MCResponse {
var req gomemcached.MCRequest
|
Commands for sending and receiving requests.
|
dustin_gomemcached
|
train
|
ad2a9b6e71182e7f48291dc629e05aee85c5624c
|
diff --git a/zotero.py b/zotero.py
index <HASH>..<HASH> 100644
--- a/zotero.py
+++ b/zotero.py
@@ -17,7 +17,29 @@ import urllib
import urllib2
import feedparser
import xml.etree.ElementTree as xml
-import traceback
+
+
+
+# Define some exceptions
+class PyZoteroError(Exception):
+ """ Generic parent exception
+ """
+ pass
+
+
+
+class ParamNotPassed(PyZoteroError):
+ """ Raised if a parameter which is required isn't passed
+ """
+ pass
+
+
+
+class CallDoesNotExist(PyZoteroError):
+ """ Raised if the specified API call doesn't exist
+ """
+ pass
+
def open_file(to_read):
@@ -83,7 +105,6 @@ def collections_data(fp_object):
collections = []
collection_key = [k['zapi_key'] for k in fp_object.entries]
collection_title = [t['title'] for t in fp_object.entries]
- # TODO recurse through subcollections if they're present
collection_sub = [s['zapi_numcollections'] for s in fp_object.entries]
for index, content in enumerate(collection_key):
collection_data = {}
@@ -165,8 +186,7 @@ class Zotero(object):
"""
# Add request parameter(s) if required
if request not in self.api_methods:
- # TODO raise an error
- pass
+ raise CallDoesNotExist
if request_params:
try:
request_params['u'] = self.user_id
@@ -174,14 +194,14 @@ class Zotero(object):
self.api_methods[request].format(**request_params))
except KeyError:
print 'There\'s a request parameter missing:'
- raise
+ raise ParamNotPassed
# Otherwise, just add the user ID
else:
try:
request = self.api_methods[request].format(u = self.user_id)
except KeyError:
print 'There\'s a request parameter missing:'
- raise
+ raise ParamNotPassed
# Add URL parameters if they're passed
if url_params:
url_params['key'] = self.user_key
|
Defining some exception handlers
|
urschrei_pyzotero
|
train
|
8325e0546ff0c09ed679c667d0669bbf3bfdbd63
|
diff --git a/test_copier.py b/test_copier.py
index <HASH>..<HASH> 100644
--- a/test_copier.py
+++ b/test_copier.py
@@ -61,5 +61,16 @@ def test_copy_dir(reporter):
file_list = [{test_dir: "copier-directory"}]
copier.copy_files(file_list)
copier.copy_files(file_list) # not called the second time
+ eq_(reporter.call_count, 1)
+ shutil.rmtree(test_dir)
+
+
+@patch("moban.reporter.report_copying")
+def test_copy_dir_recusively(reporter):
+ test_dir = "/tmp/copy-a-directory"
+ copier = Copier([os.path.join("tests", "fixtures")])
+ file_list = [{test_dir: "copier-directory/**"}]
+ copier.copy_files(file_list)
+ copier.copy_files(file_list) # not called the second time
eq_(reporter.call_count, 2)
shutil.rmtree(test_dir)
|
:sparkles: allow copy a directory without its subdirectories. #<I>
|
moremoban_moban-handlebars
|
train
|
abe0db0bc7d6ecef0c2f232f8bde89aa7ec6c6f6
|
diff --git a/web.go b/web.go
index <HASH>..<HASH> 100644
--- a/web.go
+++ b/web.go
@@ -254,9 +254,12 @@ func SetStaticDir(dir string) {
func SetStaticRoute(route string) {
cr, err := regexp.Compile(route)
- if err != nil {
+ switch {
+ case err != nil:
log.Stderrf("Error in static route regex %q\n", route)
- } else {
+ case cr.NumberOfSubexpressions() != 1:
+ log.Stderrf("Static route %q must have exactly one subexpression\n", route)
+ default:
staticRoute = cr
}
}
|
Ensure only one subexpression in static route.
|
hoisie_web
|
train
|
075a112e5a3a1c1a2468e72f9c5f28ea7752090e
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -67,7 +67,7 @@ setup(
'bokeh.server.models', 'bokeh.server.views',
'bokeh.server.test', 'bokeh.specialmodels',
'bokeh.sampledata', 'bokeh.vendor',
- 'bokeh.test'],
+ 'bokeh.tests'],
package_data = {'bokeh' : package_data_dirs},
author = 'Continuum Analytics',
author_email = 'info@continuum.io',
|
Corrected minor typo in setup.py
|
bokeh_bokeh
|
train
|
4e2e32cd2133b0b5e136ac3c343b1b6e317880ad
|
diff --git a/firefly/src/main/java/com/firefly/Version.java b/firefly/src/main/java/com/firefly/Version.java
index <HASH>..<HASH> 100644
--- a/firefly/src/main/java/com/firefly/Version.java
+++ b/firefly/src/main/java/com/firefly/Version.java
@@ -4,5 +4,5 @@ package com.firefly;
* @author Pengtao Qiu
*/
public interface Version {
- String value = "4.0.21";
+ String value = "4.0.22";
}
|
[chore]: update version to <I>
|
hypercube1024_firefly
|
train
|
d86891cf814697a1d213062117d8c2659725cb63
|
diff --git a/lib/workers/repository/updates/generate.js b/lib/workers/repository/updates/generate.js
index <HASH>..<HASH> 100644
--- a/lib/workers/repository/updates/generate.js
+++ b/lib/workers/repository/updates/generate.js
@@ -49,9 +49,6 @@ function generateBranchConfig(branchUpgrades) {
upgrade.baseBranches && upgrade.baseBranches.length > 1
? ' ({{baseBranch}})'
: '';
- // Compile a few times to allow for nested handlebars templates
- upgrade.prTitle = handlebars.compile(upgrade.prTitle)(upgrade);
- upgrade.prTitle = handlebars.compile(upgrade.prTitle)(upgrade);
upgrade.prTitle = handlebars.compile(upgrade.prTitle)(upgrade);
if (upgrade.semanticCommits) {
logger.debug('Upgrade has semantic commits enabled');
@@ -61,6 +58,8 @@ function generateBranchConfig(branchUpgrades) {
}
upgrade.prTitle = `${semanticPrefix}: ${upgrade.prTitle.toLowerCase()}`;
}
+ // Compile again to allow for nested handlebars templates
+ upgrade.prTitle = handlebars.compile(upgrade.prTitle)(upgrade);
logger.debug(`${upgrade.branchName}, ${upgrade.prTitle}`);
config.upgrades.push(upgrade);
}
|
fix: prTitle compilation with nested templates
Closes #<I>
|
renovatebot_renovate
|
train
|
c37c7ae101264c2d486b776988cac39bba16603d
|
diff --git a/codemods/transform-typography.js b/codemods/transform-typography.js
index <HASH>..<HASH> 100644
--- a/codemods/transform-typography.js
+++ b/codemods/transform-typography.js
@@ -4,25 +4,25 @@ const mappings = {
MainTitle: {
componentName: 'Typography',
props: {
- variant: 'h1'
+ variant: 'h3'
}
},
Title: {
componentName: 'Typography',
props: {
- variant: 'h2'
+ variant: 'h4'
}
},
SubTitle: {
componentName: 'Typography',
props: {
- variant: 'h3'
+ variant: 'h5'
}
},
Bold: {
componentName: 'Typography',
props: {
- variant: 'h4'
+ variant: 'h6'
}
},
Caption: {
diff --git a/react/MuiCozyTheme/theme.js b/react/MuiCozyTheme/theme.js
index <HASH>..<HASH> 100644
--- a/react/MuiCozyTheme/theme.js
+++ b/react/MuiCozyTheme/theme.js
@@ -24,26 +24,33 @@ export const normalTheme = createMuiTheme({
useNextVariants: true,
fontFamily: getCssVariableValue('primaryFont') || 'Lato',
h1: {
- fontSize: 40,
+ fontSize: 48,
fontWeight: 'bold',
- lineHeight: 1.313
+ lineHeight: 1.087,
+ letterSpacing: -0.8
},
h2: {
- fontSize: 24,
+ fontSize: 32,
fontWeight: 'bold',
- lineHeight: 1.313
+ lineHeight: 1.313,
+ letterSpacing: -0.4
},
h3: {
- fontSize: 20,
+ fontSize: 24,
fontWeight: 'bold',
- lineHeight: 1.313
+ lineHeight: 1.167
},
h4: {
+ fontSize: 20,
+ fontWeight: 'bold',
+ lineHeight: 1.167
+ },
+ h5: {
fontSize: 18,
fontWeight: 'bold',
lineHeight: 1.313
},
- h5: {
+ h6: {
fontSize: 16,
fontWeight: 'bold',
lineHeight: 1.313
diff --git a/react/Typography/Readme.md b/react/Typography/Readme.md
index <HASH>..<HASH> 100644
--- a/react/Typography/Readme.md
+++ b/react/Typography/Readme.md
@@ -56,19 +56,19 @@ const tdStyle = { borderRight: '1px solid gray'};
<tbody>
<tr style={trStyle}>
<td style={tdStyle}><MainTitle>MainTitle</MainTitle></td>
- <td><Typography variant='h2'>is replaced by <Typography variant="h2" ></Typography></td>
+ <td><Typography variant='h3'>is replaced by <Typography variant="h3" ></Typography></td>
</tr>
<tr style={trStyle}>
<td style={tdStyle}><Title>Title</Title></td>
- <td><Typography variant='h3'>is replaced by <Typography variant="h3" ></Typography></td>
+ <td><Typography variant='h4'>is replaced by <Typography variant="h4" ></Typography></td>
</tr>
<tr style={trStyle}>
<td style={tdStyle}><SubTitle>SubTitle</SubTitle></td>
- <td><Typography variant='h4'>is replaced by <Typography variant="h4" ></Typography></td>
+ <td><Typography variant='h5'>is replaced by <Typography variant="h5" ></Typography></td>
</tr>
<tr style={trStyle}>
<td style={tdStyle}><Bold>Bold</Bold></td>
- <td><Typography variant='h5'>is replaced by <Typography variant="h5" ></Typography></td>
+ <td><Typography variant='h6'>is replaced by <Typography variant="h6" ></Typography></td>
</tr>
<tr style={trStyle}>
<td style={tdStyle}><Caption>Caption</Caption></td>
|
feat: Increase scale of Typography components
This lets us be close to the material UI type scale. Bigger
fonts like h1/h2 are not used in apps but can be used on
websites
|
cozy_cozy-ui
|
train
|
4e5f14a962c2c370b648c66e0546ac985abe6e83
|
diff --git a/app/models/renalware/patient.rb b/app/models/renalware/patient.rb
index <HASH>..<HASH> 100644
--- a/app/models/renalware/patient.rb
+++ b/app/models/renalware/patient.rb
@@ -94,6 +94,8 @@ module Renalware
scope :dead, -> { where.not(died_on: nil) }
+ delegate :patient_at?, to: :hospital_identifiers
+
def self.policy_class
BasePolicy
end
@@ -144,6 +146,7 @@ module Renalware
private
+ # Before saving, convert all the local patient ids to upper case
# TODO: Use a constant for the max number of local patient ids
def upcase_local_patient_ids
self.local_patient_id = local_patient_id.upcase if local_patient_id.present?
diff --git a/app/models/renalware/patients/patient_hospital_identifiers.rb b/app/models/renalware/patients/patient_hospital_identifiers.rb
index <HASH>..<HASH> 100644
--- a/app/models/renalware/patients/patient_hospital_identifiers.rb
+++ b/app/models/renalware/patients/patient_hospital_identifiers.rb
@@ -49,6 +49,14 @@ module Renalware
all.map{ |name, hosp_no| "#{name}: #{hosp_no}" }.join(" ")
end
+ # Returns true if the patient has a hospital number at the requested hospital.
+ # Example usage
+ # PatientHospitalIdentifiers.new(patient).patient_at?(:KCH) # => true
+ def patient_at?(hospital_code)
+ return false if hospital_code.blank?
+ all.key?(hospital_code.to_sym.upcase)
+ end
+
private
def identifier_map
diff --git a/spec/models/renalware/patients/patient_hospital_identifiers_spec.rb b/spec/models/renalware/patients/patient_hospital_identifiers_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/renalware/patients/patient_hospital_identifiers_spec.rb
+++ b/spec/models/renalware/patients/patient_hospital_identifiers_spec.rb
@@ -6,6 +6,7 @@ module Renalware::Patients
# their 'display names' for use e.g. in the patient banner
def configure_patient_hospital_identifiers
Renalware.configure do |config|
+ # Note mixing up the order here is intentional
config.patient_hospital_identifiers = {
KCH: :local_patient_id,
HOSP2: :local_patient_id_4,
@@ -97,5 +98,37 @@ module Renalware::Patients
end
end
end
+
+ describe ".patient_at?" do
+ subject(:identifiers) { described_class.new(patient).patient_at?(hospital_code) }
+
+ context "when the patient has a local_patient_id for the requested hospital" do
+ let(:hospital_code) { "KCH" }
+ let(:patient) { build_stubbed(:patient, local_patient_id: "111") }
+
+ it { is_expected.to be_truthy }
+ end
+
+ context "when the patient does not have local_patient_id for the requested hospital" do
+ let(:hospital_code) { "KCH" }
+ let(:patient) { build_stubbed(:patient, local_patient_id: "") }
+
+ it { is_expected.to be_falsey }
+ end
+
+ context "when the hospital code is not configured" do
+ let(:patient) { build_stubbed(:patient, local_patient_id: "111") }
+ let(:hospital_code) { "XXX" }
+
+ it { is_expected.to be_falsey }
+ end
+
+ context "when the hospital code is blank" do
+ let(:patient) { build_stubbed(:patient) }
+ let(:hospital_code) { "" }
+
+ it { is_expected.to be_falsey }
+ end
+ end
end
end
diff --git a/spec/models/renalware/patients/patient_spec.rb b/spec/models/renalware/patients/patient_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/renalware/patients/patient_spec.rb
+++ b/spec/models/renalware/patients/patient_spec.rb
@@ -25,6 +25,8 @@ module Renalware
it { is_expected.to have_many(:alerts) }
it { is_expected.to belong_to(:country_of_birth) }
+ it { is_expected.to respond_to(:patient_at?) }
+
describe "diabetic? delegates to document.diabetes.diagnosis" do
context "when the patient is diabetic" do
before { allow(patient.document.diabetes).to receive(:diagnosis).and_return(true) }
|
Add .patient_at? helper to Patient
Example usage
Required for EPR reporting
|
airslie_renalware-core
|
train
|
e7080554de59c2392da7962877784a42a80a3ed3
|
diff --git a/blockstack_search/search/substring_search.py b/blockstack_search/search/substring_search.py
index <HASH>..<HASH> 100755
--- a/blockstack_search/search/substring_search.py
+++ b/blockstack_search/search/substring_search.py
@@ -235,19 +235,21 @@ def fetch_profiles(search_results,search_type="name"):
for search_result in search_results:
if search_type == 'name':
- result = search_profiles.find_one({"name":search_result})
+ response = search_profiles.find({"name":search_result})
elif search_type == 'twitter':
- result = search_profiles.find_one({"twitter_handle":search_result})
+ response = search_profiles.find({"twitter_handle":search_result})
- try:
- del result['name']
- del result['twitter_handle']
- del result['_id']
- except:
- pass
+ for result in response:
+
+ try:
+ del result['name']
+ del result['twitter_handle']
+ del result['_id']
+ except:
+ pass
- results.append(result)
+ results.append(result)
return results
|
turned dedup off for twitter search results
|
blockstack_blockstack-core
|
train
|
bb6f3ebd3111fb40ce678ad95fd940b580c97b77
|
diff --git a/_pytest/mark.py b/_pytest/mark.py
index <HASH>..<HASH> 100644
--- a/_pytest/mark.py
+++ b/_pytest/mark.py
@@ -7,8 +7,8 @@ def pytest_namespace():
def pytest_addoption(parser):
group = parser.getgroup("general")
group._addoption('-k',
- action="store", dest="keyword", default='', metavar="KEYWORDEXPR",
- help="only run tests which match the given expression. "
+ action="store", dest="keyword", default='', metavar="EXPRESSION",
+ help="only run tests which match the given substring expression. "
"An expression is a python evaluatable expression "
"where all names are substring-matched against test names "
"and keywords. Example: -k 'test_method or test_other' "
diff --git a/testing/test_nose.py b/testing/test_nose.py
index <HASH>..<HASH> 100644
--- a/testing/test_nose.py
+++ b/testing/test_nose.py
@@ -304,8 +304,9 @@ def test_apiwrapper_problem_issue260(testdir):
result = testdir.runpytest()
result.stdout.fnmatch_lines("*1 passed*")
+@pytest.mark.skipif("sys.version_info < (2,6)")
def test_setup_teardown_linking_issue265(testdir):
- # we accidnetially didnt integrate nose setupstate with normal setupstate
+ # we accidentally didnt integrate nose setupstate with normal setupstate
# this test ensures that won't happen again
testdir.makepyfile('''
import pytest
@@ -314,7 +315,8 @@ def test_setup_teardown_linking_issue265(testdir):
def test_nothing(self):
"""Tests the API of the implementation (for generic and specialized)."""
- @pytest.mark.skipif("True", reason="Skip tests to check if teardown is skipped as well.")
+ @pytest.mark.skipif("True", reason=
+ "Skip tests to check if teardown is skipped as well.")
class TestSkipTeardown(TestGeneric):
def setup(self):
|
slightly improve -k help string
cosmetic change to test_nose.py
|
pytest-dev_pytest
|
train
|
a5b7bb5d8290a299d182678da993452b0d727abd
|
diff --git a/lib/qless/qless-core b/lib/qless/qless-core
index <HASH>..<HASH> 160000
--- a/lib/qless/qless-core
+++ b/lib/qless/qless-core
@@ -1 +1 @@
-Subproject commit 776304913acdd6194c2b981d8d6094befdaa896f
+Subproject commit 1bb407137c102ce947681ad233ab910287018eef
diff --git a/lib/qless/server.rb b/lib/qless/server.rb
index <HASH>..<HASH> 100755
--- a/lib/qless/server.rb
+++ b/lib/qless/server.rb
@@ -161,6 +161,10 @@ module Qless
}
end
+ get '/failed.json' do
+ json(Server.client.jobs.failed)
+ end
+
get '/failed/?' do
# qless-core doesn't provide functionality this way, so we'll
# do it ourselves. I'm not sure if this is how the core library
diff --git a/spec/integration/server_spec.rb b/spec/integration/server_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/integration/server_spec.rb
+++ b/spec/integration/server_spec.rb
@@ -684,5 +684,17 @@ module Qless
get '/queues/testing.json'
JSON.parse(last_response.body).should eq(response)
end
+
+ it 'can access the JSON endpoint for failures' do
+ get '/failed.json'
+ JSON.parse(last_response.body).should eq({})
+
+ # Now, put a job in, pop it and fail it, make sure we see
+ jid = q.put(Qless::Job, {})
+ job = q.pop
+ job.fail('foo', 'bar')
+ get '/failed.json'
+ JSON.parse(last_response.body).should eq({'foo' => 1})
+ end
end
end
\ No newline at end of file
|
JSON endpoint for failed jobs.
|
seomoz_qless
|
train
|
c14f9a0b06ed21ff0bc11dd86b81a4a425924526
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,5 +4,5 @@
*.pyc
*.eggs
__pycache__
-
+.cache
*.swp
diff --git a/conformity/fields/basic.py b/conformity/fields/basic.py
index <HASH>..<HASH> 100644
--- a/conformity/fields/basic.py
+++ b/conformity/fields/basic.py
@@ -26,29 +26,43 @@ class Base(object):
raise NotImplementedError("You must override introspect() in a subclass")
-@attr.s
class Constant(Base):
"""
- Value that must match exactly.
+ Value that must match exactly. You can pass a series of options
+ and any will be accepted.
"""
- value = attr.ib()
- description = attr.ib(default=None)
+ def __init__(self, *args, **kwargs):
+ self.values = set(args)
+ if not self.values:
+ raise TypeError("You must provide at least one constant value")
+ self.description = kwargs.get("description", None)
+ # Check they didn't pass any other kwargs
+ if list(kwargs.keys()) not in ([], ["description"]):
+ raise TypeError("Invalid keyword arguments for Constant: %s" % kwargs.keys())
def errors(self, value):
"""
Returns a list of errors with the value. An empty/None return means
that it's valid.
"""
- if value != self.value:
- return [
- Error("Value is not %r" % self.value),
- ]
+ if value not in self.values:
+ if len(self.values) == 1:
+ return [
+ Error("Value is not %r" % (list(self.values)[0], )),
+ ]
+ else:
+ return [
+ Error("Value is not one of: %s" % (
+ ", ".join(sorted(repr(v) for v in self.values))
+ )),
+ ]
+ return []
def introspect(self):
result = {
"type": "constant",
- "value": self.value,
+ "values": list(self.values),
}
if self.description is not None:
result["description"] = self.description
diff --git a/conformity/tests/test_fields.py b/conformity/tests/test_fields.py
index <HASH>..<HASH> 100644
--- a/conformity/tests/test_fields.py
+++ b/conformity/tests/test_fields.py
@@ -257,7 +257,7 @@ class FieldTests(unittest.TestCase):
"contents": [
{"type": "integer", "gt": 0},
{"type": "unicode"},
- {"type": "constant", "value": "I love tuples"},
+ {"type": "constant", "values": ["I love tuples"]},
]
}
)
@@ -335,3 +335,21 @@ class FieldTests(unittest.TestCase):
schema.errors(-3.14159),
[Error("Invalid decimal value (not unicode string)")],
)
+
+ def test_multi_constant(self):
+ """
+ Tests constants with multiple options
+ """
+ schema = Constant(42, 36, 81, 9231)
+ self.assertEqual(
+ schema.errors(9231),
+ [],
+ )
+ self.assertEqual(
+ schema.errors(81),
+ [],
+ )
+ self.assertEqual(
+ schema.errors(360000),
+ [Error("Value is not one of: 36, 42, 81, 9231")],
+ )
diff --git a/conformity/tests/test_fields_meta.py b/conformity/tests/test_fields_meta.py
index <HASH>..<HASH> 100644
--- a/conformity/tests/test_fields_meta.py
+++ b/conformity/tests/test_fields_meta.py
@@ -126,7 +126,7 @@ class MetaFieldTests(unittest.TestCase):
"account": {"type": "unicode"},
"payment_type": {
"type": "constant",
- "value": "bankacc",
+ "values": ["bankacc"],
},
"routing": {
"type": "unicode",
@@ -146,7 +146,7 @@ class MetaFieldTests(unittest.TestCase):
"number": {"type": "unicode"},
"payment_type": {
"type": "constant",
- "value": "card",
+ "values": ["card"],
},
},
"optional_keys": [],
|
Allowed Constant to take multiple options for a more concise Any+Const (#<I>)
Since a lot of Any use was with constants, and the error messages were
long and a bit confusing, this gives the Constant field the ability to
have a set of options natively as multiple positional arguments to the
constructor. It's backwards compatible with the old calling style and
error messages, though the introspection format has changed.
|
eventbrite_conformity
|
train
|
a8d414c7ef4c669256d34d0208e0e46fef3c9a88
|
diff --git a/client/image_build.go b/client/image_build.go
index <HASH>..<HASH> 100644
--- a/client/image_build.go
+++ b/client/image_build.go
@@ -8,7 +8,6 @@ import (
"net/url"
"regexp"
"strconv"
- "strings"
"golang.org/x/net/context"
@@ -118,18 +117,3 @@ func getDockerOS(serverHeader string) string {
}
return osType
}
-
-// convertKVStringsToMap converts ["key=value"] to {"key":"value"}
-func convertKVStringsToMap(values []string) map[string]string {
- result := make(map[string]string, len(values))
- for _, value := range values {
- kv := strings.SplitN(value, "=", 2)
- if len(kv) == 1 {
- result[kv[0]] = ""
- } else {
- result[kv[0]] = kv[1]
- }
- }
-
- return result
-}
|
Remove some dead code.
convertKVStringsToMap is not use anywhere :)
|
docker_engine-api
|
train
|
580e8217dfd7ac9b827d6945e942acce6e1502ca
|
diff --git a/src/plaster/loaders.py b/src/plaster/loaders.py
index <HASH>..<HASH> 100644
--- a/src/plaster/loaders.py
+++ b/src/plaster/loaders.py
@@ -113,39 +113,38 @@ def find_loaders(scheme=None, protocol=None):
objects.
"""
- matched_loaders = []
- entry_points = None
+ matched_entry_points = []
if protocol is None:
group = 'plaster.loader_factory'
else:
group = 'plaster.loader_factory.' + protocol
- parts = scheme.rsplit('+', 1)
- if len(parts) == 2:
- try:
- distro = pkg_resources.get_distribution(parts[1])
- except pkg_resources.DistributionNotFound:
- pass
- else:
- scheme = parts[0]
- entry_points = distro.get_entry_map(group).values()
-
- # match the scheme case-insensitive
if scheme is not None:
scheme = scheme.lower()
- # only search entry points
- if entry_points is None:
- entry_points = pkg_resources.iter_entry_points(group)
-
- for loader in entry_points:
- if scheme is None or scheme == loader.name.lower():
- matched_loaders.append(loader)
+ parts = scheme.rsplit('+', 1)
+ if len(parts) == 2:
+ try:
+ distro = pkg_resources.get_distribution(parts[1])
+ except pkg_resources.DistributionNotFound:
+ pass
+ else:
+ scheme = parts[0]
+ for ep in distro.get_entry_map(group).values():
+ if scheme == ep.name.lower():
+ matched_entry_points.append(ep)
+
+ # only search entry points for all packages if the scheme is not pointing
+ # at an installed distribution that contains a matching entry point
+ if not matched_entry_points:
+ for ep in pkg_resources.iter_entry_points(group):
+ if scheme is None or scheme == ep.name.lower():
+ matched_entry_points.append(ep)
return [
EntryPointLoaderInfo(ep, protocol=protocol)
- for ep in matched_loaders
+ for ep in matched_entry_points
]
|
only match the distribution's entry points if a scheme resolves to a distribution
|
Pylons_plaster
|
train
|
ac256f38555a1045f5ea071920e5cebef059ae1e
|
diff --git a/zipline/sources/requests_csv.py b/zipline/sources/requests_csv.py
index <HASH>..<HASH> 100644
--- a/zipline/sources/requests_csv.py
+++ b/zipline/sources/requests_csv.py
@@ -230,7 +230,7 @@ class PandasCSV(with_metaclass(ABCMeta, object)):
parsed = pd.to_datetime(
date_str_series.values,
format=format_str,
- coerce=True,
+ errors='coerce',
).tz_localize(tz_str).tz_convert('UTC')
if data_frequency == 'daily':
|
MAINT: Use errors='coerce'.
coerce=True is deprecated.
|
quantopian_zipline
|
train
|
ede940183e2672d1046bf0eeef450a5decd36f98
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -4,6 +4,7 @@ var command = require('commander'),
stalerepos = require('./lib/stalerepos'),
notifiers = {
email: require('./lib/notifiers/email'),
+ github: require('./lib/notifiers/github')
},
notify = require('./lib/notify');
@@ -14,8 +15,9 @@ process.title = 'drillsergeant';
command
.version(pkg.version)
.option('-r, --repo [user/repository]', 'Define the [comma delimited] repositories to check PRs.')
- .option('-e, --email [email@address]', 'Set the [comma delimited] email address(es) to be notified.')
+ .option('-e, --email [email@address]', 'Set the [comma delimited] email address(es) to be notified.', null)
.option('-f, --replyto [Notifier Title <email@address>]', 'Set the reply to email address.', 'Drill Sergeant Notifier <no-reply@drillsergeant>')
+ .option('-l, --label', 'Should drill sergeant label the PR as stale?', false)
.option('-s, --staletime [number of hours]', 'Set the PR stale threshold. (default: 24)', 24)
.parse(process.argv);
@@ -29,8 +31,8 @@ if (!command.repo) {
process.exit(1);
}
-if (!command.email) {
- console.error('Email argument must be provided.');
+if (!command.email && !command.label) {
+ console.error('Email or label argument must be provided.');
process.exit(1);
}
@@ -48,5 +50,9 @@ stalerepos.retrieve(repos, ghClient, command.staletime, function(results) {
if (command.email) {
notifier.add(new notifiers.email(command.email, command.replyto));
}
+ if (command.label) {
+ notifier.add(new notifiers.github(ghClient));
+ }
+
notifier.notifyAll(results);
});
|
Added option for github label notifier.
Email is now optional if the label option is specified.
|
zumba_drill-sergeant
|
train
|
0338b1e36070d07e85a96c45673117fc3632b1a7
|
diff --git a/eZ/Publish/Core/IO/TolerantIOService.php b/eZ/Publish/Core/IO/TolerantIOService.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/IO/TolerantIOService.php
+++ b/eZ/Publish/Core/IO/TolerantIOService.php
@@ -83,7 +83,10 @@ class TolerantIOService extends IOService
} catch (BinaryFileNotFoundException $e) {
$this->logMissingFile($binaryFileId);
- return $this->createMissingBinaryFile($binaryFileId);
+ return new MissingBinaryFile([
+ 'id' => $binaryFileId,
+ 'uri' => $this->binarydataHandler->getUri($this->getPrefixedUri($binaryFileId)),
+ ]);
}
if (!isset($spiBinaryFile->uri)) {
@@ -108,23 +111,11 @@ class TolerantIOService extends IOService
} catch (BinaryFileNotFoundException $e) {
$this->logMissingFile($binaryFileUri);
- return $this->createMissingBinaryFile($binaryFileId);
- }
- }
-
- /**
- * @param $binaryFileId
- *
- * @return \eZ\Publish\Core\IO\Values\MissingBinaryFile
- */
- private function createMissingBinaryFile($binaryFileId)
- {
- return new MissingBinaryFile(
- array(
+ return new MissingBinaryFile([
'id' => $binaryFileId,
'uri' => $this->binarydataHandler->getUri($this->getPrefixedUri($binaryFileId)),
- )
- );
+ ]);
+ }
}
private function logMissingFile($id)
|
Removed private method TolerantIOService::createMissingBinaryFile() as unecessary.
(cherry picked from commit <I>c<I>e<I>f<I>acf<I>de<I>dda<I>d)
|
ezsystems_ezpublish-kernel
|
train
|
c5ce69466d7381536f87a11946028b1be5390e7f
|
diff --git a/plugin/init_npm.js b/plugin/init_npm.js
index <HASH>..<HASH> 100644
--- a/plugin/init_npm.js
+++ b/plugin/init_npm.js
@@ -29,12 +29,6 @@ if(canProceed() && !fs.existsSync(npmContainerDir)) {
// add new container as a package
echo.sync("\nnpm-container", ">>", ".meteor/packages");
-
- console.log();
- console.log("-> npm support has been initialized.");
- console.log("-> please start your app again.");
- console.log();
- process.exit(0);
}
// check whether is this `meteor test-packages` or not
|
Removed process.exit call
There's no need for the build process to stop after making the npm-container
directory. Meteor will automatically restart the build when it detects the
addition to .meteor/packages. I've tested that the declared npm modules in
package.json are brought in when running `meteor` in development and `meteor
build` for production
|
meteorhacks_npm
|
train
|
f407a4bcbce0ce35fab56199073e4c8b10698170
|
diff --git a/test/util.py b/test/util.py
index <HASH>..<HASH> 100644
--- a/test/util.py
+++ b/test/util.py
@@ -6,7 +6,7 @@ from ykman.cli.__main__ import cli
def ykman_cli(*argv, **kwargs):
runner = CliRunner()
- result = runner.invoke(cli, list(argv), **kwargs, obj={})
+ result = runner.invoke(cli, list(argv), obj={}, **kwargs)
if result.exit_code != 0:
click.echo(result.output)
traceback.print_tb(result.exc_info[2])
|
Try to fix python 2
|
Yubico_yubikey-manager
|
train
|
b75e87712e33fed397f6e7265066ead79a4862bc
|
diff --git a/yandextank/plugins/Bfg/reader.py b/yandextank/plugins/Bfg/reader.py
index <HASH>..<HASH> 100644
--- a/yandextank/plugins/Bfg/reader.py
+++ b/yandextank/plugins/Bfg/reader.py
@@ -1,5 +1,6 @@
import pandas as pd
import time
+import itertools as itt
def records_to_df(records):
@@ -11,6 +12,8 @@ def records_to_df(records):
records.set_index(['receive_sec'], inplace=True)
return records
+def _expand_steps(steps):
+ return list(itt.chain(*([rps] * duration for rps, duration in steps)))
class BfgReader(object):
def __init__(self, results):
@@ -40,7 +43,7 @@ class BfgStatsReader(object):
def __init__(self, instance_counter, steps):
self.closed = False
self.last_ts = 0
- self.steps = steps
+ self.steps = _expand_steps(steps)
self.instance_counter = instance_counter
self.start_time = int(time.time())
@@ -51,7 +54,7 @@ class BfgStatsReader(object):
offset = cur_ts - self.start_time
reqps = 0
if offset >= 0 and offset < len(self.steps):
- reqps = self.steps[offset][0]
+ reqps = self.steps[offset]
yield [{'ts': cur_ts,
'metrics': {'instances': self.instance_counter.get(),
'reqps': reqps}}]
|
fix load scheme in bfg
|
yandex_yandex-tank
|
train
|
d9b2c6d1cb1033973094d8798d27750304b8c559
|
diff --git a/test/e2e/helpers/database-init.js b/test/e2e/helpers/database-init.js
index <HASH>..<HASH> 100644
--- a/test/e2e/helpers/database-init.js
+++ b/test/e2e/helpers/database-init.js
@@ -7,9 +7,14 @@ const { createDb } = require('../../../lib/db/db-pool');
const dbState = require('./database.json');
+// require('db-migrate-shared').log.silence(false);
+
// because of migrator bug
delete process.env.DATABASE_URL;
+// because of db-migrate bug (https://github.com/Unleash/unleash/issues/171)
+process.setMaxListeners(0);
+
async function resetDatabase(stores) {
return Promise.all([
stores.db('strategies').del(),
@@ -59,7 +64,6 @@ module.exports = async function init(databaseSchema = 'test', getLogger) {
await db.raw(`CREATE SCHEMA IF NOT EXISTS ${options.databaseSchema}`);
await migrator(options);
- await db.destroy();
const stores = await createStores(options, eventBus);
await resetDatabase(stores);
await setupDatabase(stores);
|
chore: do not destroy db on startup
|
Unleash_unleash
|
train
|
0e98e6d259ba20690219c199d35fe0d4b6ea90f1
|
diff --git a/SALib/analyze/sobol.py b/SALib/analyze/sobol.py
index <HASH>..<HASH> 100644
--- a/SALib/analyze/sobol.py
+++ b/SALib/analyze/sobol.py
@@ -65,7 +65,7 @@ def analyze(problem, Y, calc_second_order=True, num_resamples=100,
"""
# determining if groups are defined and adjusting the number
# of rows in the cross-sampled matrix accordingly
- if problem['groups'] == None:
+ if not problem.get('groups'):
D = problem['num_vars']
else:
D = len(problem['groups'][1])
@@ -119,7 +119,6 @@ def analyze(problem, Y, calc_second_order=True, num_resamples=100,
if print_to_console:
print_indices(S, problem, calc_second_order)
-
return S
@@ -204,7 +203,7 @@ def create_task_list(D, calc_second_order, n_processors):
tasks_second_order = [[d, j, k] for j in range(D) for k in
range(j + 1, D) for d in ('S2', 'S2_conf')]
- if n_processors == None:
+ if n_processors is None:
n_processors = min(cpu_count(), len(tasks_first_order) + len(tasks_second_order))
if not calc_second_order:
@@ -236,7 +235,7 @@ def Si_list_to_dict(S_list, D, calc_second_order):
def print_indices(S, problem, calc_second_order):
# Output to console
- if problem['groups'] == None:
+ if not problem.get('groups'):
D = problem['num_vars']
print('Parameter S1 S1_conf ST ST_conf')
|
Replaced '== None' conditions
Replaced conditions that were ‘== None’ to be ‘no problem.get()’.
|
SALib_SALib
|
train
|
22a5c4673e3a1687655fce9eb95eca396508c5ef
|
diff --git a/src/main/java/rx/Statement.java b/src/main/java/rx/Statement.java
index <HASH>..<HASH> 100644
--- a/src/main/java/rx/Statement.java
+++ b/src/main/java/rx/Statement.java
@@ -17,8 +17,8 @@ package rx;
import java.util.Map;
+import rx.functions.Func0;
import rx.operators.OperationConditionals;
-import rx.util.functions.Func0;
/**
* Imperative statements expressed as Observable operators.
diff --git a/src/main/java/rx/operators/OperationConditionals.java b/src/main/java/rx/operators/OperationConditionals.java
index <HASH>..<HASH> 100644
--- a/src/main/java/rx/operators/OperationConditionals.java
+++ b/src/main/java/rx/operators/OperationConditionals.java
@@ -21,9 +21,9 @@ import rx.Observable;
import rx.Observable.OnSubscribeFunc;
import rx.Observer;
import rx.Subscription;
+import rx.functions.Func0;
import rx.subscriptions.MultipleAssignmentSubscription;
import rx.subscriptions.Subscriptions;
-import rx.util.functions.Func0;
/**
* Implementation of conditional-based operations such as Case, If, DoWhile and While.
diff --git a/src/test/java/rx/operators/OperationConditionalsTest.java b/src/test/java/rx/operators/OperationConditionalsTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/rx/operators/OperationConditionalsTest.java
+++ b/src/test/java/rx/operators/OperationConditionalsTest.java
@@ -33,10 +33,10 @@ import rx.Observable;
import rx.Observer;
import rx.Statement;
import rx.Subscription;
+import rx.functions.Func0;
import rx.observers.TestObserver;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
-import rx.util.functions.Func0;
public class OperationConditionalsTest {
@Mock
|
Move rx.util.functions to rx.functions
Eliminate dumping ground of rx.util
|
ReactiveX_RxJavaComputationExpressions
|
train
|
f5d64d408e2380e9351b41e5e331bf1ba6cb0416
|
diff --git a/src/voku/helper/HtmlMin.php b/src/voku/helper/HtmlMin.php
index <HASH>..<HASH> 100644
--- a/src/voku/helper/HtmlMin.php
+++ b/src/voku/helper/HtmlMin.php
@@ -1071,12 +1071,6 @@ class HtmlMin implements HtmlMinInterface
return '';
}
- // init
- static $CACHE_SELF_CLOSING_TAGS = null;
- if ($CACHE_SELF_CLOSING_TAGS === null) {
- $CACHE_SELF_CLOSING_TAGS = \implode('|', self::$selfClosingTags);
- }
-
// reset
$this->protectedChildNodes = [];
@@ -1100,7 +1094,7 @@ class HtmlMin implements HtmlMinInterface
$html = (string) \preg_replace_callback(
'#<([^/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(/?)>#u',
static function ($matches) {
- return '<' . $matches[1] . \preg_replace('#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#su', ' $1$2', $matches[2]) . $matches[3] . '>';
+ return '<' . $matches[1] . \preg_replace('#([^\s=]+)(=([\'"]?)(.*?)\3)?(\s+|$)#su', ' $1$2', $matches[2]) . $matches[3] . '>';
},
$html
);
@@ -1164,6 +1158,8 @@ class HtmlMin implements HtmlMinInterface
$replacement[] = '<' . $selfClosingTag . '>';
$replace[] = '<' . $selfClosingTag . ' />';
$replacement[] = '<' . $selfClosingTag . '>';
+ $replace[] = '></' . $selfClosingTag . '>';
+ $replacement[] = '>';
}
$html = \str_replace(
$replace,
@@ -1171,8 +1167,6 @@ class HtmlMin implements HtmlMinInterface
$html
);
- $html = (string) \preg_replace('#<\b(' . $CACHE_SELF_CLOSING_TAGS . ')([^>]*+)><\/\b\1>#', '<\\1\\2>', $html);
-
// ------------------------------------
// check if compression worked
// ------------------------------------
@@ -1213,10 +1207,12 @@ class HtmlMin implements HtmlMinInterface
*/
private function isConditionalComment($comment): bool
{
+ /** @noinspection RegExpRedundantEscape */
if (\preg_match('/^\[if [^\]]+\]/', $comment)) {
return true;
}
+ /** @noinspection RegExpRedundantEscape */
if (\preg_match('/\[endif\]$/', $comment)) {
return true;
}
diff --git a/tests/HtmlMinTest.php b/tests/HtmlMinTest.php
index <HASH>..<HASH> 100644
--- a/tests/HtmlMinTest.php
+++ b/tests/HtmlMinTest.php
@@ -1148,4 +1148,24 @@ HTML;
static::assertSame($expectedHtml, $actual);
}
+
+ public function testSelfClosingInput()
+ {
+ $html = '
+ <div class="form-group col-xl-10">
+ <label for="chars">Zeichen</label>
+ <div class="input-group">
+ <input type="text" id="chars" class="form-control" value="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789![]{}()%&*$#^<>~@|" aria-describedby="chars-refresh-icon">
+ <div class="input-group-append cursor-pointer" id="chars-refresh">
+ <div class="input-group-text" id="chars-refresh-icon"><i class="fas fa-undo fa-fw"></i></div>
+ </div>
+ </div>
+ </div>
+ ';
+
+ $expected = '<div class="col-xl-10 form-group"><label for=chars>Zeichen</label> <div class=input-group><input aria-describedby=chars-refresh-icon class=form-control id=chars type=text value="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789![]{}()%&*$#^<>~@|"> <div class="cursor-pointer input-group-append" id=chars-refresh><div class=input-group-text id=chars-refresh-icon><i class="fa-fw fa-undo fas"></i></div> </div></div></div>';
+
+ $htmlMin = new HtmlMin();
+ static::assertSame($expected, $htmlMin->minify($html));
+ }
}
|
[+]: fix regex for self-closing tags
-> fixed via removing the regex ;)
|
voku_HtmlMin
|
train
|
f8e564469f0cc215ab3ab4a57ae0d3a29dee777a
|
diff --git a/s3-extensions/src/main/java/io/druid/storage/s3/S3Utils.java b/s3-extensions/src/main/java/io/druid/storage/s3/S3Utils.java
index <HASH>..<HASH> 100644
--- a/s3-extensions/src/main/java/io/druid/storage/s3/S3Utils.java
+++ b/s3-extensions/src/main/java/io/druid/storage/s3/S3Utils.java
@@ -58,7 +58,7 @@ public class S3Utils
public static <T> T retryS3Operation(Callable<T> f) throws IOException, S3ServiceException, InterruptedException
{
int nTry = 0;
- final int maxTries = 3;
+ final int maxTries = 10;
while (true) {
try {
nTry++;
@@ -89,13 +89,10 @@ public class S3Utils
private static void awaitNextRetry(Exception e, int nTry) throws InterruptedException
{
final long baseSleepMillis = 1000;
- final double fuzziness = 0.2;
- final long sleepMillis = Math.max(
- baseSleepMillis,
- (long) (baseSleepMillis * Math.pow(2, nTry) *
- (1 + new Random().nextGaussian() * fuzziness))
- );
- log.info(e, "S3 fail on try %d, retrying in %,dms.", nTry, sleepMillis);
+ final long maxSleepMillis = 60000;
+ final double fuzzyMultiplier = Math.min(Math.max(1 + 0.2 * new Random().nextGaussian(), 0), 2);
+ final long sleepMillis = (long) (Math.min(maxSleepMillis, baseSleepMillis * Math.pow(2, nTry)) * fuzzyMultiplier);
+ System.out.println(String.format("S3 fail on try %d, retrying in %,dms.", nTry, sleepMillis));
Thread.sleep(sleepMillis);
}
|
S3Utils: More aggressive retries, S3 can be pretty unreliable sometimes
|
apache_incubator-druid
|
train
|
acf684dcab29c3481be4485a572396f49b1da30c
|
diff --git a/isvcs/isvc.go b/isvcs/isvc.go
index <HASH>..<HASH> 100644
--- a/isvcs/isvc.go
+++ b/isvcs/isvc.go
@@ -37,7 +37,7 @@ const (
IMAGE_REPO = "zenoss/serviced-isvcs"
IMAGE_TAG = "v71"
ZK_IMAGE_REPO = "zenoss/isvcs-zookeeper"
- ZK_IMAGE_TAG = "v15"
+ ZK_IMAGE_TAG = "v16"
OTSDB_BT_REPO = "zenoss/isvcs-metrics-bigtable"
OTSDB_BT_TAG = "v1"
API_KEY_PROXY_REPO = "gcr.io/zing-registry-188222/api-key-proxy"
|
CC-<I>: Zookeeper uses Log4j 1.x
|
control-center_serviced
|
train
|
f27b503db6663cdf38684c568ed236f779fe102b
|
diff --git a/packages/site/pages/components/tab.js b/packages/site/pages/components/tab.js
index <HASH>..<HASH> 100644
--- a/packages/site/pages/components/tab.js
+++ b/packages/site/pages/components/tab.js
@@ -14,12 +14,11 @@ import {
PropTypes,
SectionHeading,
withServerProps
-} from '../../src/ui'
+} from '../../src/ui/index.js'
class InAppExample extends React.Component {
constructor(props) {
super(props)
-
this.state = { activeIndex: 2 }
this.menus = [1, 2, 3, 4, 5].map(i => ({
id: `example${i}`,
@@ -28,22 +27,14 @@ class InAppExample extends React.Component {
}))
this.handleTabClick = this.handleTabClick.bind(this)
}
-
handleTabClick(i) {
this.setState({ activeIndex: i })
}
-
render() {
return (
<div>
- <SectionHeading>In-app example</SectionHeading>
- <P>
- The Tab component provides the look and feel and accessibility
- standards for the UI. You control the hiding and showing of content or
- other interaction specific to your application.
- </P>
- <Theme>
- <div className="app">
+ <div className="app">
+ <Theme>
<Tab.List>
{this.menus.map((menu, i) => (
<Tab.ListItem
@@ -63,8 +54,51 @@ class InAppExample extends React.Component {
</Tab.Panel>
) : null
)}
- </div>
- </Theme>
+ </Theme>
+ </div>
+ <Code
+ lang="javascript"
+ collapsible
+ >{`class InAppExample extends React.Component {
+ constructor(props) {
+ super(props)
+ this.state = { activeIndex: 2 }
+ this.menus = [1, 2, 3, 4, 5].map(i => ({
+ id: 'example' + i,
+ label: 'Menu ' + i,
+ content: 'Menu stuff ' + i
+ }))
+ this.handleTabClick = this.handleTabClick.bind(this)
+ }
+ handleTabClick(i) {
+ this.setState({ activeIndex: i })
+ }
+ render() {
+ return (
+ <div>
+ <Tab.List>
+ {this.menus.map((menu, i) => (
+ <Tab.ListItem
+ id={menu.id}
+ key={menu.id}
+ onClick={this.handleTabClick}
+ {...(i === this.state.activeIndex ? { active: true } : null)}
+ >
+ {menu.label}
+ </Tab.ListItem>
+ ))}
+ </Tab.List>
+ {this.menus.map((menu, i) =>
+ i === this.state.activeIndex ? (
+ <Tab.Panel labelledBy={menu.id} key={menu.id}>
+ <div className="content">{menu.content}</div>
+ </Tab.Panel>
+ ) : null
+ )}
+ </div>
+ )
+ }
+}`}</Code>
<style jsx>{`
.app {
background: ${core.colors.gray06};
@@ -137,6 +171,14 @@ export default withServerProps(_ => (
}}
/>
+ <SectionHeading>In-app example</SectionHeading>
+ <P>
+ The Tab component provides the look and feel and accessibility standards
+ for the UI. You control the hiding and showing of content or other
+ interaction specific to your application.
+ </P>
+ <InAppExample />
+
<SectionHeading>Tab List</SectionHeading>
<P>
Tabs are a navigational element used to show and pivot between related
@@ -179,8 +221,6 @@ export default withServerProps(_ => (
`
]}
/>
-
- <InAppExample />
</Content>
</Chrome>
))
|
feat(site): show code for tab in-app example
|
pluralsight_design-system
|
train
|
2fa0a279c93e09b8ede7b5385f3d81f6a38056be
|
diff --git a/java-trace/google-cloud-trace/pom.xml b/java-trace/google-cloud-trace/pom.xml
index <HASH>..<HASH> 100644
--- a/java-trace/google-cloud-trace/pom.xml
+++ b/java-trace/google-cloud-trace/pom.xml
@@ -32,7 +32,7 @@
<dependency>
<groupId>com.google.api.grpc</groupId>
<artifactId>grpc-google-cloud-trace-v1</artifactId>
- <version>0.1.7</version>
+ <version>0.1.8</version>
<exclusions>
<exclusion>
<groupId>io.grpc</groupId>
diff --git a/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.java b/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.java
index <HASH>..<HASH> 100644
--- a/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.java
+++ b/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.java
@@ -15,9 +15,9 @@
*/
package com.google.cloud.trace.spi.v1;
-import com.google.api.gax.core.ApiFunction;
-import com.google.api.gax.core.ApiFuture;
-import com.google.api.gax.core.ApiFutures;
+import com.google.api.core.ApiFunction;
+import com.google.api.core.ApiFuture;
+import com.google.api.core.ApiFutures;
import com.google.api.gax.grpc.AbstractFixedSizeCollection;
import com.google.api.gax.grpc.AbstractPage;
import com.google.api.gax.grpc.AbstractPagedListResponse;
diff --git a/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java b/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
index <HASH>..<HASH> 100644
--- a/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
+++ b/java-trace/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
@@ -17,7 +17,7 @@ package com.google.cloud.trace.spi.v1;
import static com.google.cloud.trace.spi.v1.PagedResponseWrappers.ListTracesPagedResponse;
-import com.google.api.gax.core.ApiFuture;
+import com.google.api.core.ApiFuture;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.PropertiesProvider;
import com.google.api.gax.core.RetrySettings;
|
Changes required for updated api-common (#<I>)
|
googleapis_google-cloud-java
|
train
|
b922e992d52ac4ec772b6bf1e4a8050e76d3391f
|
diff --git a/splinter/driver/webdriver/__init__.py b/splinter/driver/webdriver/__init__.py
index <HASH>..<HASH> 100644
--- a/splinter/driver/webdriver/__init__.py
+++ b/splinter/driver/webdriver/__init__.py
@@ -443,6 +443,9 @@ class AlertElement(object):
def accept(self):
self._alert.accept()
+ def dismiss(self):
+ self._alert.dismiss()
+
def fill_with(self, text):
self._alert.send_keys(text)
diff --git a/tests/base.py b/tests/base.py
index <HASH>..<HASH> 100644
--- a/tests/base.py
+++ b/tests/base.py
@@ -112,6 +112,7 @@ class WebDriverTests(BaseBrowserTests, IFrameElementsTest, ElementDoestNotExistT
alert = self.browser.get_alert()
self.assertEquals('This is an alert example.', alert.text)
alert.accept()
+
def test_access_prompts_and_be_able_to_fill_then(self):
self.browser.visit(EXAMPLE_APP + 'alert')
@@ -126,6 +127,27 @@ class WebDriverTests(BaseBrowserTests, IFrameElementsTest, ElementDoestNotExistT
self.assertEquals('Splinter', response.text)
response.accept()
+ def test_access_confirm_and_accept_and_dismiss_them(self):
+ self.browser.visit(EXAMPLE_APP + 'alert')
+
+ self.browser.find_by_tag('h3').first.click()
+ alert = self.browser.get_alert()
+
+ self.assertEquals('Should I continue?', alert.text)
+ alert.accept()
+ alert = self.browser.get_alert()
+ self.assertEquals('You say I should', alert.text)
+ alert.accept()
+
+ self.browser.find_by_tag('h3').first.click()
+ alert = self.browser.get_alert()
+ self.assertEquals('Should I continue?', alert.text)
+ alert.dismiss()
+ alert = self.browser.get_alert()
+ self.assertEquals('You say I should not', alert.text)
+ alert.accept()
+
+
def test_access_alerts_using_with(self):
"should access alerts using 'with' statement"
self.browser.visit(EXAMPLE_APP + 'alert')
diff --git a/tests/fake_webapp.py b/tests/fake_webapp.py
index <HASH>..<HASH> 100644
--- a/tests/fake_webapp.py
+++ b/tests/fake_webapp.py
@@ -145,12 +145,21 @@ EXAMPLE_ALERT_HTML = """\
$('.alerta').click(function() { alert('This is an alert example.'); });
$('.pergunta').click(function() { nome = prompt('What is your name?'); alert(nome); });
+
+ $('.confirmacao').click(function() {
+ answer = confirm('Should I continue?');
+ if (answer)
+ alert("You say I should");
+ else
+ alert("You say I should not");
+ });
})
</script>
</head>
<body>
<h1 class="alerta">Alert Example Title</h1>
<h2 class="pergunta">Prompt Example Subtitle</h2>
+ <h3 class="confirmacao">Confirm Example Subtitle</h3>
</body>
</html>
"""
|
Now browser.get_alert() has a dismiss() method as well
|
cobrateam_splinter
|
train
|
cd91b72d4d2615e89abce496a955b1da23bcf584
|
diff --git a/elifetools/parseJATS.py b/elifetools/parseJATS.py
index <HASH>..<HASH> 100644
--- a/elifetools/parseJATS.py
+++ b/elifetools/parseJATS.py
@@ -633,17 +633,7 @@ def graphics(soup):
copy_attribute(details, 'asset', graphic_item, 'p_parent_asset')
copy_attribute(details, 'sibling_ordinal', graphic_item, 'p_parent_sibling_ordinal')
copy_attribute(details, 'component_doi', graphic_item, 'p_parent_component_doi')
-
- p_p_parent_tag = first_parent(p_parent_tag, nodenames)
- if p_p_parent_tag:
- acting_p_p_parent_tag = component_acting_parent_tag(p_p_parent_tag, p_parent_tag)
- if acting_p_p_parent_tag:
- details = tag_details(acting_p_p_parent_tag, nodenames)
- copy_attribute(details, 'type', graphic_item, 'p_p_parent_type')
- copy_attribute(details, 'ordinal', graphic_item, 'p_p_parent_ordinal')
- copy_attribute(details, 'sibling_ordinal', graphic_item, 'p_p_parent_sibling_ordinal')
- copy_attribute(details, 'component_doi', graphic_item, 'p_p_parent_component_doi')
-
+
# Increment the position
graphic_item['position'] = position
# Ordinal should be the same as position in this case but set it anyway
|
Remove graphic p_p_parent, which does not exist yet and is extremely unlikely.
|
elifesciences_elife-tools
|
train
|
1ffa6beb3b2780bfa44812e9895eecc8c75e5984
|
diff --git a/lib/tty/cursor.rb b/lib/tty/cursor.rb
index <HASH>..<HASH> 100644
--- a/lib/tty/cursor.rb
+++ b/lib/tty/cursor.rb
@@ -118,7 +118,7 @@ module TTY
# @api public
def prev_line
- ECMA_CSI + 'F'
+ ECMA_CSI + 'A' + ECMA_CSI + '1G'
end
# Clear current line
diff --git a/spec/unit/cursor_spec.rb b/spec/unit/cursor_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/cursor_spec.rb
+++ b/spec/unit/cursor_spec.rb
@@ -64,7 +64,7 @@ RSpec.describe TTY::Cursor do
end
it "moves cursor to previous line" do
- expect(cursor.prev_line).to eq("\e[F")
+ expect(cursor.prev_line).to eq("\e[A\e[1G")
end
it "hides cursor for the duration of block call" do
|
Use more pessimistic escape sequence for Cursor.prev_line.
The previous sequence was not understood by some popular
terminal emulators (e.g. iTerm2 on OSX). This alternative
should work everywhere.
|
piotrmurach_tty-cursor
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.