hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
7e577405d2ed88defc95d45ad49c7fa353d9ea1f | diff --git a/pathvalidate/_file.py b/pathvalidate/_file.py
index <HASH>..<HASH> 100644
--- a/pathvalidate/_file.py
+++ b/pathvalidate/_file.py
@@ -25,6 +25,16 @@ from .error import (
_DEFAULT_MAX_FILENAME_LEN = 255
+class PlatformName(object):
+ """
+ Normalized platform names
+ """
+
+ LINUX = "linux"
+ WINDOWS = "windows"
+ MACOS = "macos"
+
+
class FileSanitizer(NameSanitizer):
_INVALID_PATH_CHARS = "".join(unprintable_ascii_char_list)
_INVALID_FILENAME_CHARS = _INVALID_PATH_CHARS + "/"
@@ -46,19 +56,35 @@ class FileSanitizer(NameSanitizer):
self._max_len = max_len
- if platform_name is None:
- platform_name = platform.system()
-
- self.__platform_name = platform_name.lower()
+ self.__platform_name = self.__normalize_platform(platform_name)
def _is_linux(self):
- return self.platform_name in ["linux"]
+ return self.platform_name == PlatformName.LINUX
def _is_windows(self):
- return self.platform_name in ["windows", "win"]
+ return self.platform_name == PlatformName.WINDOWS
def _is_macos(self):
- return self.platform_name in ["mac", "macos", "darwin"]
+ return self.platform_name == PlatformName.MACOS
+
+ @staticmethod
+ def __normalize_platform(name):
+ if name:
+ name = name.lower()
+
+ if name == "auto" or name is None:
+ name = platform.system().lower()
+
+ if name in ["linux"]:
+ return PlatformName.LINUX
+
+ if name in ["windows", "win"]:
+ return PlatformName.WINDOWS
+
+ if name in ["mac", "macos", "darwin"]:
+ return PlatformName.MACOS
+
+ raise ValueError()
class FileNameSanitizer(FileSanitizer): | Add platform name normalization at initialization | thombashi_pathvalidate | train |
fb1b4ab1e368ba06710bed5b5cf271ff3375f861 | diff --git a/src/Model/Invoice/Item.php b/src/Model/Invoice/Item.php
index <HASH>..<HASH> 100644
--- a/src/Model/Invoice/Item.php
+++ b/src/Model/Invoice/Item.php
@@ -19,6 +19,7 @@ class Item extends Base
{
/**
* The Currency service
+ *
* @var \Nails\Currency\Service\Currency
*/
protected $oCurrency;
@@ -44,21 +45,27 @@ class Item extends Base
$this->table = NAILS_DB_PREFIX . 'invoice_invoice_item';
$this->defaultSortColumn = 'order';
$this->oCurrency = Factory::service('Currency', 'nails/module-currency');
- $this->addExpandableField([
- 'trigger' => 'tax',
- 'type' => self::EXPANDABLE_TYPE_SINGLE,
- 'property' => 'tax',
- 'model' => 'Tax',
- 'provider' => 'nails/module-invoice',
- 'id_column' => 'tax_id',
- 'auto_expand' => true,
- ]);
+ $this
+ ->addExpandableField([
+ 'trigger' => 'invoice',
+ 'model' => 'Invoice',
+ 'provider' => 'nails/module-invoice',
+ 'id_column' => 'invoice_id',
+ ])
+ ->addExpandableField([
+ 'trigger' => 'tax',
+ 'model' => 'Tax',
+ 'provider' => 'nails/module-invoice',
+ 'id_column' => 'tax_id',
+ 'auto_expand' => true,
+ ]);
}
// --------------------------------------------------------------------------
/**
* Returns the item quantity units with human friendly names
+ *
* @return array
*/
public function getUnits()
@@ -79,7 +86,7 @@ class Item extends Base
/**
* Retrieve items which relate to a particular set of invoice IDs
*
- * @param array $aInvoiceIds The invoice IDs
+ * @param array $aInvoiceIds The invoice IDs
*
* @return array
*/
@@ -100,11 +107,11 @@ class Item extends Base
* The getAll() method iterates over each returned item with this method so as to
* correctly format the output. Use this to cast integers and booleans and/or organise data into objects.
*
- * @param object $oObj A reference to the object being formatted.
- * @param array $aData The same data array which is passed to getCountCommon, for reference if needed
- * @param array $aIntegers Fields which should be cast as integers if numerical and not null
- * @param array $aBools Fields which should be cast as booleans if not null
- * @param array $aFloats Fields which should be cast as floats if not null
+ * @param object $oObj A reference to the object being formatted.
+ * @param array $aData The same data array which is passed to getCountCommon, for reference if needed
+ * @param array $aIntegers Fields which should be cast as integers if numerical and not null
+ * @param array $aBools Fields which should be cast as booleans if not null
+ * @param array $aFloats Fields which should be cast as floats if not null
*
* @return void
*/ | Added expandable field for item -> invoice | nails_module-invoice | train |
5513893df6bbd3eb06470c29e2120971202baa50 | diff --git a/src/AsyncCreatable.js b/src/AsyncCreatable.js
index <HASH>..<HASH> 100644
--- a/src/AsyncCreatable.js
+++ b/src/AsyncCreatable.js
@@ -13,6 +13,10 @@ function reduce(obj, props = {}){
const AsyncCreatable = React.createClass({
displayName: 'AsyncCreatableSelect',
+ focus () {
+ this.select.focus();
+ },
+
render () {
return (
<Select.Async {...this.props}>
@@ -26,6 +30,7 @@ const AsyncCreatable = React.createClass({
return asyncProps.onInputChange(input);
}}
ref={(ref) => {
+ this.select = ref;
creatableProps.ref(ref);
asyncProps.ref(ref);
}}
diff --git a/test/AsyncCreatable-test.js b/test/AsyncCreatable-test.js
index <HASH>..<HASH> 100644
--- a/test/AsyncCreatable-test.js
+++ b/test/AsyncCreatable-test.js
@@ -59,4 +59,17 @@ describe('AsyncCreatable', () => {
class: ['foo']
});
});
+
+ describe('.focus()', () => {
+ beforeEach(() => {
+ createControl({});
+ TestUtils.Simulate.blur(filterInputNode);
+ });
+
+ it('focuses the search input', () => {
+ expect(filterInputNode, 'not to equal', document.activeElement);
+ creatableInstance.focus();
+ expect(filterInputNode, 'to equal', document.activeElement);
+ });
+ });
}); | Added .focus() to AsyncCreatable | HubSpot_react-select-plus | train |
a5f1b7494b53c17ec1237a08ddae7e7170875de0 | diff --git a/cmd/rqlited/main.go b/cmd/rqlited/main.go
index <HASH>..<HASH> 100644
--- a/cmd/rqlited/main.go
+++ b/cmd/rqlited/main.go
@@ -267,17 +267,17 @@ func startHTTPService(cfg *Config, str *store.Store, cltr *cluster.Client, credS
// startNodeMux starts the TCP mux on the given listener, which should be already
// bound to the relevant interface.
func startNodeMux(cfg *Config, ln net.Listener) (*tcp.Mux, error) {
- var adv net.Addr
var err error
+ adv := tcp.NameAddress{
+ Address: cfg.RaftAdv,
+ }
var mux *tcp.Mux
if cfg.NodeEncrypt {
log.Printf("enabling node-to-node encryption with cert: %s, key: %s", cfg.NodeX509Cert, cfg.NodeX509Key)
mux, err = tcp.NewTLSMux(ln, adv, cfg.NodeX509Cert, cfg.NodeX509Key, cfg.NodeX509CACert)
} else {
- mux, err = tcp.NewMux(ln, tcp.NameAddress{
- Address: cfg.RaftAdv,
- })
+ mux, err = tcp.NewMux(ln, adv)
}
if err != nil {
return nil, fmt.Errorf("failed to create node-to-node mux: %s", err.Error()) | Node TLS mux needs to use advertised Raft address | rqlite_rqlite | train |
fdd89b919c3ac717763785d5b1989d99e68809b3 | diff --git a/src/Silex/Provider/SecurityServiceProvider.php b/src/Silex/Provider/SecurityServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Silex/Provider/SecurityServiceProvider.php
+++ b/src/Silex/Provider/SecurityServiceProvider.php
@@ -137,12 +137,13 @@ class SecurityServiceProvider implements ServiceProviderInterface
$app['security.authentication_listener.'.$name.'.'.$type] = $app['security.authentication_listener.'.$type.'._proto']($name, $options);
}
- if (!isset($app['security.authentication_provider.'.$name])) {
- $app['security.authentication_provider.'.$name] = $app['security.authentication_provider.'.('anonymous' == $name ? 'anonymous' : 'dao').'._proto']($name);
+ $provider = 'anonymous' === $type ? 'anonymous' : 'dao';
+ if (!isset($app['security.authentication_provider.'.$name.'.'.$provider])) {
+ $app['security.authentication_provider.'.$name.'.'.$provider] = $app['security.authentication_provider.'.$provider.'._proto']($name);
}
return array(
- 'security.authentication_provider.'.$name,
+ 'security.authentication_provider.'.$name.'.'.$provider,
'security.authentication_listener.'.$name.'.'.$type,
$entryPoint ? 'security.entry_point.'.$name.'.'.$entryPoint : null,
$type | [Security] Create a distinct service for each authentication provider
When using multiple both | silexphp_Silex | train |
57bae808ba4d8ffa94bf1b6c88403c9e9197a4b5 | diff --git a/addon/properties/relations/belongs-to.js b/addon/properties/relations/belongs-to.js
index <HASH>..<HASH> 100644
--- a/addon/properties/relations/belongs-to.js
+++ b/addon/properties/relations/belongs-to.js
@@ -32,8 +32,7 @@ export default class BelongsToRelation extends Relation {
}, true);
}
- inverseDeleted(internal) {
- console.log(this.internal.docId, internal.docId, 'deleted');
+ inverseDeleted() {
this.withPropertyChange(changed => {
this.setValue(null, changed);
});
@@ -81,13 +80,9 @@ export default class BelongsToRelation extends Relation {
}
internalModelDidChange(internal, props) {
- if(internal === this.internal) {
- // TODO: observe self, notify inverse
- } else {
- assert(`internalModelDidChange internal must be this.value`, internal === this.value);
- if(internalModelDidChangeIsDeleted(internal, props)) {
- this.onValueDeleted();
- }
+ assert(`internalModelDidChange internal must be this.value`, internal === this.value);
+ if(internalModelDidChangeIsDeleted(internal, props)) {
+ this.onValueDeleted();
}
}
diff --git a/addon/properties/relations/has-many.js b/addon/properties/relations/has-many.js
index <HASH>..<HASH> 100644
--- a/addon/properties/relations/has-many.js
+++ b/addon/properties/relations/has-many.js
@@ -49,6 +49,11 @@ class ArrayWrapper {
export default class HasManyRelation extends Relation {
+ constructor(relationship, internal) {
+ super(...arguments);
+ internal.addObserver(this);
+ }
+
dirty() {
let internal = this.internal;
let relationship = this.relationship;
@@ -123,7 +128,7 @@ export default class HasManyRelation extends Relation {
setValue(value /*, changed*/) {
let next = Ember.A(value).map(model => getInternalModel(model));
if(next.length > 0) {
- this.isReplacingContent = true;
+ this.ignoreValueChanges = true;
let curr = this.getContent();
@@ -140,7 +145,7 @@ export default class HasManyRelation extends Relation {
this.didAddInternalModel(internal);
});
- this.isReplacingContent = false;
+ this.ignoreValueChanges = false;
// TODO: not sure about `changed` apart from dirty()
// changed();
@@ -149,7 +154,7 @@ export default class HasManyRelation extends Relation {
}
valueWillChange(proxy, removing) {
- if(this.isReplacingContent) {
+ if(this.ignoreValueChanges) {
return;
}
this.isValueChanging = true;
@@ -160,7 +165,7 @@ export default class HasManyRelation extends Relation {
}
valueDidChange(proxy, removeCount, adding) {
- if(this.isReplacingContent) {
+ if(this.ignoreValueChanges) {
return;
}
adding.forEach(model => {
@@ -172,10 +177,9 @@ export default class HasManyRelation extends Relation {
}
onContentInternalModelDeleted(internal) {
- this.isReplacingContent = true;
- // TODO: possibly don't touch wrapped content
+ this.ignoreValueChanges = true;
this.getWrappedContent().removeObject(internal);
- this.isReplacingContent = false;
+ this.ignoreValueChanges = false;
}
onInternalModelDeleted(internal) {
diff --git a/addon/properties/relations/relation.js b/addon/properties/relations/relation.js
index <HASH>..<HASH> 100644
--- a/addon/properties/relations/relation.js
+++ b/addon/properties/relations/relation.js
@@ -7,7 +7,6 @@ export default class Relation {
this.relationship = relationship;
this.internal = internal;
this.value = null;
- internal.addObserver(this);
}
get relationshipModelClass() { | observe this.internal in hasMany only
--HG--
branch : feature/has-many-persisted | ampatspell_ember-cli-sofa | train |
b65af57a425be7d151b8e0fdc8c7cacc1fa97258 | diff --git a/src/main/java/org/jamesframework/ext/analysis/JsonConverter.java b/src/main/java/org/jamesframework/ext/analysis/JsonConverter.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jamesframework/ext/analysis/JsonConverter.java
+++ b/src/main/java/org/jamesframework/ext/analysis/JsonConverter.java
@@ -17,6 +17,7 @@
package org.jamesframework.ext.analysis;
import mjson.Json;
+import org.jamesframework.core.subset.SubsetSolution;
/**
* A JSON converter is a functional interface defining a single method to convert objects
@@ -30,6 +31,11 @@ import mjson.Json;
*/
@FunctionalInterface
public interface JsonConverter<T> {
+
+ /**
+ * Predefined converter for subset solutions that creates a JSON array containing the selected IDs.
+ */
+ public static final JsonConverter<SubsetSolution> SUBSET_SOLUTION = sol -> Json.array(sol.getSelectedIDs().toArray());
/**
* Convert an object to a JSON representation.
diff --git a/src/test/java/org/jamesframework/ext/analysis/AnalysisResultsTest.java b/src/test/java/org/jamesframework/ext/analysis/AnalysisResultsTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/jamesframework/ext/analysis/AnalysisResultsTest.java
+++ b/src/test/java/org/jamesframework/ext/analysis/AnalysisResultsTest.java
@@ -18,7 +18,6 @@ package org.jamesframework.ext.analysis;
import java.nio.file.Files;
import java.nio.file.Paths;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
@@ -559,7 +558,7 @@ public class AnalysisResultsTest {
// write to JSON file (including solutions)
String filePath = folder.newFile().getPath();
- results.writeJSON(filePath, sol -> Json.array(sol.getSelectedIDs().toArray()));
+ results.writeJSON(filePath, JsonConverter.SUBSET_SOLUTION);
// read file
List<String> lines = Files.readAllLines(Paths.get(filePath)); | provided predefined JSON converter for subset solutions | hdbeukel_james-extensions | train |
07e876592b3fc2993bec85248ce868c784c42284 | diff --git a/rafthttp/sender.go b/rafthttp/sender.go
index <HASH>..<HASH> 100644
--- a/rafthttp/sender.go
+++ b/rafthttp/sender.go
@@ -153,7 +153,8 @@ func (s *sender) Send(m raftpb.Message) error {
case s.q <- data:
return nil
default:
- log.Printf("sender: reach the maximal serving to %s", s.u)
+ log.Printf("sender: dropping %s because maximal number %d of sender buffer entries to %s has been reached",
+ m.Type, senderBufSize, s.u)
return fmt.Errorf("reach maximal serving")
}
} | rafthttp: log the type of message that is dropped when sending | etcd-io_etcd | train |
b44ce11d1b8b7011c1019dbede6b91905f92e27b | diff --git a/web/web.go b/web/web.go
index <HASH>..<HASH> 100644
--- a/web/web.go
+++ b/web/web.go
@@ -666,7 +666,7 @@ func tmplFuncs(consolesPath string, opts *Options) template_text.FuncMap {
return time.Since(t) / time.Millisecond * time.Millisecond
},
"consolesPath": func() string { return consolesPath },
- "pathPrefix": func() string {
+ "pathPrefix": func() string {
if opts.RoutePrefix == "/" {
return ""
} else {
diff --git a/web/web_test.go b/web/web_test.go
index <HASH>..<HASH> 100644
--- a/web/web_test.go
+++ b/web/web_test.go
@@ -274,6 +274,41 @@ func TestRoutePrefix(t *testing.T) {
testutil.Equals(t, http.StatusOK, resp.StatusCode)
}
+func TestPathPrefix(t *testing.T) {
+
+ tests := []struct {
+ routePrefix string
+ pathPrefix string
+ }{
+ {
+ routePrefix: "/",
+ // If we have pathPrefix as "/", URL in UI gets "//"" as prefix,
+ // hence doesn't remain relative path anymore.
+ pathPrefix: "",
+ },
+ {
+ routePrefix: "/prometheus",
+ pathPrefix: "/prometheus",
+ },
+ {
+ routePrefix: "/p1/p2/p3/p4",
+ pathPrefix: "/p1/p2/p3/p4",
+ },
+ }
+
+ for _, test := range tests {
+ opts := &Options{
+ RoutePrefix: test.routePrefix,
+ }
+
+ pathPrefix := tmplFuncs("", opts)["pathPrefix"].(func() string)
+ pp := pathPrefix()
+
+ testutil.Equals(t, test.pathPrefix, pp)
+ }
+
+}
+
func TestDebugHandler(t *testing.T) {
for _, tc := range []struct {
prefix, url string | Added test to check pathPrefix | prometheus_prometheus | train |
04c687bc6d068c2fa0a4a7516996fd6cf36f0b77 | diff --git a/lib/fork.js b/lib/fork.js
index <HASH>..<HASH> 100644
--- a/lib/fork.js
+++ b/lib/fork.js
@@ -32,7 +32,7 @@ module.exports = function (args) {
ps.on('error', reject);
ps.on('exit', function (code) {
- if (code > 0) {
+ if (code > 0 && code !== 143) {
reject();
} else {
resolve(testResults); | Check for SIGTERM exit code | andywer_ava-ts | train |
64239321b9db84c4f3c0674bf8caff3c77f0b614 | diff --git a/lib/plugins/tag/code.js b/lib/plugins/tag/code.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/tag/code.js
+++ b/lib/plugins/tag/code.js
@@ -11,23 +11,31 @@ var rCaptionUrl = /(\S[\S\s]*)\s+(https?:\/\/)(\S+)/i;
var rCaption = /(\S[\S\s]*)/;
var rLang = /\s*lang:(\w+)/i;
var rLineNumber = /\s*line_number:(\w+)/i;
+var rHighlight = /\s*highlight:(\w+)/i;
/**
* Code block tag
*
* Syntax:
- * {% codeblock [title] [lang:language] [url] [link text] [line_number:(true|false)] %}
+ * {% codeblock [title] [lang:language] [url] [link text] [line_number:(true|false)] [highlight:(true|false)] %}
* code snippet
* {% endcodeblock %}
*/
module.exports = function(ctx) {
-
return function codeTag(args, content) {
var arg = args.join(' ');
var config = ctx.config.highlight || {};
+ var enable = config.enable;
+
+ if (rHighlight.test(arg)) {
+ arg = arg.replace(rHighlight, function() {
+ enable = arguments[1] === 'true';
+ return '';
+ });
+ }
- if (!config.enable) {
+ if (!enable) {
return '<pre><code>' + content + '</code></pre>';
} | might as well add a configuration option to enable/disable highlight all together. | hexojs_hexo | train |
621bc96e8a2bf2327c209bf0e2933a30f6c8d98d | diff --git a/uncompyle6/parsers/reducecheck/ifstmts_jump.py b/uncompyle6/parsers/reducecheck/ifstmts_jump.py
index <HASH>..<HASH> 100644
--- a/uncompyle6/parsers/reducecheck/ifstmts_jump.py
+++ b/uncompyle6/parsers/reducecheck/ifstmts_jump.py
@@ -9,12 +9,6 @@ def ifstmts_jump(self, lhs, n, rule, ast, tokens, first, last):
return False
come_froms = ast[-1]
- # Make sure all of the "come froms" offset at the
- # end of the "if" come from somewhere inside the "if".
- # Since the come_froms are ordered so that lowest
- # offset COME_FROM is last, it is sufficient to test
- # just the last one.
-
# This is complicated, but note that the JUMP_IF instruction comes immediately
# *before* _ifstmts_jump so that's what we have to test
# the COME_FROM against. This can be complicated by intervening
@@ -28,31 +22,30 @@ def ifstmts_jump(self, lhs, n, rule, ast, tokens, first, last):
"COME_FROM",
):
pop_jump_index -= 1
- come_froms = ast[-1]
# FIXME: something is fishy when and EXTENDED ARG is needed before the
# pop_jump_index instruction to get the argment. In this case, the
# _ifsmtst_jump can jump to a spot beyond the come_froms.
# That is going on in the non-EXTENDED_ARG case is that the POP_JUMP_IF
# jumps to a JUMP_(FORWARD) which is changed into an EXTENDED_ARG POP_JUMP_IF
- # to the jumped forwareded address
+ # to the jumped forwarded address
if tokens[pop_jump_index].attr > 256:
return False
+ pop_jump_offset = tokens[pop_jump_index].off2int(prefer_last=False)
if isinstance(come_froms, Token):
if (
- tokens[pop_jump_index].attr < tokens[pop_jump_index].offset
- and ast[0] != "pass"
+ tokens[pop_jump_index].attr < pop_jump_offset and ast[0] != "pass"
):
# This is a jump backwards to a loop. All bets are off here when there the
# unless statement is "pass" which has no instructions associated with it.
return False
return (
come_froms.attr is not None
- and tokens[pop_jump_index].offset > come_froms.attr
+ and pop_jump_offset > come_froms.attr
)
elif len(come_froms) == 0:
return False
else:
- return tokens[pop_jump_index].offset > come_froms[-1].attr
+ return pop_jump_offset > come_froms[-1].attr | Ensure offset is an int in offset test | rocky_python-uncompyle6 | train |
879ee8362d8667d02b96053f7a98ca243dd23556 | diff --git a/src/Enums/ApiDocFormatTypes.php b/src/Enums/ApiDocFormatTypes.php
index <HASH>..<HASH> 100644
--- a/src/Enums/ApiDocFormatTypes.php
+++ b/src/Enums/ApiDocFormatTypes.php
@@ -1,7 +1,7 @@
<?php
namespace DreamFactory\Core\ApiDoc\Enums;
-use DreamFactory\Library\Utility\Enums\FactoryEnum;
+use DreamFactory\Core\Enums\FactoryEnum;
use DreamFactory\Core\Exceptions\NotImplementedException;
/**
diff --git a/src/Services/Swagger.php b/src/Services/Swagger.php
index <HASH>..<HASH> 100644
--- a/src/Services/Swagger.php
+++ b/src/Services/Swagger.php
@@ -9,7 +9,6 @@ use DreamFactory\Core\Models\Service;
use DreamFactory\Core\Services\BaseRestService;
use DreamFactory\Core\Utility\ResourcesWrapper;
use DreamFactory\Core\Utility\Session;
-use DreamFactory\Library\Utility\Inflector;
use Config;
use Log;
@@ -226,7 +225,7 @@ HTML;
public static function getApiDocInfo($service)
{
$name = strtolower($service->name);
- $capitalized = Inflector::camelize($service->name);
+ $capitalized = camelize($service->name);
return [
'paths' => [
diff --git a/tests/SystemServiceTest.php b/tests/SystemServiceTest.php
index <HASH>..<HASH> 100644
--- a/tests/SystemServiceTest.php
+++ b/tests/SystemServiceTest.php
@@ -1,6 +1,6 @@
<?php
-use DreamFactory\Library\Utility\Enums\Verbs;
+use DreamFactory\Core\Enums\Verbs;
use DreamFactory\Core\Enums\ApiOptions;
use Illuminate\Support\Arr; | cleanup - removal of php-utils dependency | dreamfactorysoftware_df-apidoc | train |
83ea35635c208d15af3b67f005881725bdf94373 | diff --git a/lib/graphql/static_validation/rules/fragments_are_used.rb b/lib/graphql/static_validation/rules/fragments_are_used.rb
index <HASH>..<HASH> 100644
--- a/lib/graphql/static_validation/rules/fragments_are_used.rb
+++ b/lib/graphql/static_validation/rules/fragments_are_used.rb
@@ -12,7 +12,7 @@ module GraphQL
end
dependency_map.unused_dependencies.each do |fragment|
- if !fragment.name.nil?
+ if fragment && !fragment.name.nil?
add_error("Fragment #{fragment.name} was defined, but not used", fragment.node, path: fragment.path)
end
end | handle invalid fragment types in fragments are used validator | rmosolgo_graphql-ruby | train |
5907c3836e9abb00a2215794bbee9ffa5ddd8937 | diff --git a/test_jujupy.py b/test_jujupy.py
index <HASH>..<HASH> 100644
--- a/test_jujupy.py
+++ b/test_jujupy.py
@@ -418,19 +418,23 @@ class TestEnvironment(TestCase):
'Timed out waiting for agents to start in local'):
env.wait_for_started()
+ @staticmethod
+ def make_status_yaml(key, machine_value, unit_value):
+ return dedent("""\
+ machines:
+ "0":
+ {0}: {1}
+ services:
+ jenkins:
+ units:
+ jenkins/0:
+ {0}: {2}
+ """.format(key, machine_value, unit_value))
+
def test_wait_for_version(self):
def output_iterator():
yield
- yield dedent("""\
- machines:
- "0":
- agent-version: 1.17.2
- services:
- jenkins:
- units:
- jenkins/0:
- agent-version: 1.17.2
- """)
+ yield self.make_status_yaml('agent-version', '1.17.2', '1.17.2')
JujuClientDevelFake.set_output(output_iterator())
env = Environment('local', JujuClientDevelFake(None, None))
env.wait_for_version('1.17.2') | Added a helper to make status yaml. | juju_juju | train |
e2004c2dcb152bd92f723dd259b5364c13c084f3 | diff --git a/extensions/tags/migrations/2018_06_27_085300_change_tags_add_foreign_keys.php b/extensions/tags/migrations/2018_06_27_085300_change_tags_add_foreign_keys.php
index <HASH>..<HASH> 100644
--- a/extensions/tags/migrations/2018_06_27_085300_change_tags_add_foreign_keys.php
+++ b/extensions/tags/migrations/2018_06_27_085300_change_tags_add_foreign_keys.php
@@ -42,7 +42,9 @@ return [
'down' => function (Builder $schema) {
$schema->table('tags', function (Blueprint $table) use ($schema) {
- $table->dropForeign(['parent_id', 'last_posted_discussion_id', 'last_posted_user_id']);
+ $table->dropForeign(['parent_id']);
+ $table->dropForeign(['last_posted_discussion_id']);
+ $table->dropForeign(['last_posted_user_id']);
Migration::fixIndexNames($schema, $table);
});
diff --git a/extensions/tags/migrations/2018_06_27_100200_change_tag_user_add_foreign_keys.php b/extensions/tags/migrations/2018_06_27_100200_change_tag_user_add_foreign_keys.php
index <HASH>..<HASH> 100644
--- a/extensions/tags/migrations/2018_06_27_100200_change_tag_user_add_foreign_keys.php
+++ b/extensions/tags/migrations/2018_06_27_100200_change_tag_user_add_foreign_keys.php
@@ -37,7 +37,8 @@ return [
'down' => function (Builder $schema) {
$schema->table('tag_user', function (Blueprint $table) use ($schema) {
- $table->dropForeign(['tag_id', 'user_id']);
+ $table->dropForeign(['tag_id']);
+ $table->dropForeign(['user_id']);
Migration::fixIndexNames($schema, $table);
});
diff --git a/extensions/tags/migrations/2018_06_27_103100_add_discussion_tag_foreign_keys.php b/extensions/tags/migrations/2018_06_27_103100_add_discussion_tag_foreign_keys.php
index <HASH>..<HASH> 100644
--- a/extensions/tags/migrations/2018_06_27_103100_add_discussion_tag_foreign_keys.php
+++ b/extensions/tags/migrations/2018_06_27_103100_add_discussion_tag_foreign_keys.php
@@ -37,7 +37,8 @@ return [
'down' => function (Builder $schema) {
$schema->table('discussion_tag', function (Blueprint $table) use ($schema) {
- $table->dropForeign(['discussion_id', 'tag_id']);
+ $table->dropForeign(['discussion_id']);
+ $table->dropForeign(['tag_id']);
Migration::fixIndexNames($schema, $table);
}); | Migrations: Fix dropping foreign keys
Passing an array to dropForeign does not mean dropping multiple indices,
but rather dropping a key on multiple tables.
Passing a string means that this string will be interpreted as index
name, not as name of the indexed column. Passing an array with one
string is therefore correct, in order to benefit from automatic index
name generation. | flarum_core | train |
9cff5f74d384dd209a1fbfe4e4c64be976cc2c47 | diff --git a/server.go b/server.go
index <HASH>..<HASH> 100644
--- a/server.go
+++ b/server.go
@@ -16,6 +16,7 @@
package lunarc
import (
+ "errors"
"fmt"
"log"
"net"
@@ -39,9 +40,10 @@ type Server interface {
//WebServer is a Server with a specialize Context.
type WebServer struct {
Context MongoContext
+ Error chan error
+ Done chan bool
server http.Server
quit chan bool
- err chan error
interrupt chan os.Signal
}
@@ -52,18 +54,18 @@ func NewWebServer(filename string, environment string) (server *WebServer, err e
cnf, err = configUtil.Construct(filename, environment)
context := MongoContext{cnf, nil}
- server = &WebServer{Context: context, server: http.Server{Handler: http.NewServeMux()}, quit: make(chan bool), err: make(chan error, 1)}
+ server = &WebServer{Context: context, Done: make(chan bool, 1), Error: make(chan error, 1), server: http.Server{Handler: http.NewServeMux()}, quit: make(chan bool)}
return
}
//Start the server.
func (ws *WebServer) Start() (err error) {
- log.Println("Lunarc is starting...")
+ log.Printf("Lunarc is starting on port :%d", ws.Context.Cnf.Server.Port)
go func() {
l, err := net.Listen("tcp", fmt.Sprintf(":%d", ws.Context.Cnf.Server.Port))
if err != nil {
log.Printf("Error: %v", err)
- ws.err <- err
+ ws.Error <- err
return
}
go ws.handleInterrupt(l)
@@ -71,20 +73,14 @@ func (ws *WebServer) Start() (err error) {
if err != nil {
log.Printf("Error: %v", err)
ws.interrupt <- syscall.SIGINT
- ws.err <- err
+ ws.Error <- err
return
}
}()
- for {
- select {
- case <-ws.quit:
- ws.interrupt <- syscall.SIGINT
- return
- default:
- //continue
- }
- }
+ <-ws.quit
+ ws.interrupt <- syscall.SIGINT
+ return
}
func (ws *WebServer) handleInterrupt(listener net.Listener) {
@@ -104,8 +100,10 @@ func (ws *WebServer) Stop() {
ws.quit <- true
<-ws.quit
log.Println("Lunarc stopped.")
+ ws.Done <- true
} else {
log.Println("Lunarc is not running")
+ ws.Error <- errors.New("Lunarc is not running")
}
}
diff --git a/server_test.go b/server_test.go
index <HASH>..<HASH> 100644
--- a/server_test.go
+++ b/server_test.go
@@ -49,7 +49,8 @@ func TestStart(t *testing.T) {
t.Fatalf("Unexpected error: %v", err)
}
- server.Stop()
+ go server.Stop()
+ <-server.Done
}
func TestStartWithError(t *testing.T) {
@@ -61,7 +62,7 @@ func TestStartWithError(t *testing.T) {
go server.Start()
- err = <-server.err
+ err = <-server.Error
if err == nil {
t.Fatalf("Expected error: listen tcp :8888: bind: address already in use")
@@ -82,9 +83,8 @@ func TestStopNormal(t *testing.T) {
t.Fatalf("Unexpected error: %v", err)
}
- server.Stop()
-
- time.Sleep(time.Second * 3)
+ go server.Stop()
+ <-server.Done
resp, err := http.Get("http://localhost:8888/")
if err == nil {
@@ -98,5 +98,15 @@ func TestStopUnstarted(t *testing.T) {
t.Fatalf("Non expected error: %v", err)
}
- server.Stop()
+ go server.Stop()
+
+ select {
+ case <-server.Done:
+ t.Fatalf("Non expected behavior")
+ case err := <-server.Error:
+ if err == nil {
+ t.Fatalf("Non expected error")
+ }
+ return
+ }
} | err becomes Error. Add Done to warn done state | DamienFontaine_lunarc | train |
5597c649991ba47ff0858f32f4cd944286534dd3 | diff --git a/lib/marklogic.js b/lib/marklogic.js
index <HASH>..<HASH> 100644
--- a/lib/marklogic.js
+++ b/lib/marklogic.js
@@ -718,7 +718,12 @@ MarkLogicClient.prototype.createProxy = function createProxy(serviceDeclaration)
function initClient(client, inputParams) {
var connectionParams = {};
+ var isSSL = (inputParams.ssl == null) ? false : inputParams.ssl;
var keys = ['host', 'port', 'database', 'user', 'password', 'authType', 'token'];
+ if(isSSL) {
+ keys.push('ca', 'cert', 'ciphers', 'clientCertEngine', 'crl', 'dhparam', 'ecdhCurve', 'honorCipherOrder', 'key', 'passphrase',
+ 'pfx', 'rejectUnauthorized', 'secureOptions', 'secureProtocol', 'servername', 'sessionIdContext', 'highWaterMark');
+ }
for (var i=0; i < keys.length; i++) {
var key = keys[i];
var value = inputParams[key];
@@ -765,9 +770,6 @@ function initClient(client, inputParams) {
connectionParams.user+':'+connectionParams.password;
}
- var isSSL = (inputParams.ssl == null) ?
- false : inputParams.ssl;
-
var noAgent = (inputParams.agent == null);
var agentOptions = noAgent ? {
keepAlive: true
@@ -776,9 +778,8 @@ function initClient(client, inputParams) {
client.request = https.request;
if (noAgent) {
mlutil.copyProperties(inputParams, agentOptions, [
- 'ca', 'cert', 'ciphers', 'keepAliveMsecs', 'key', 'maxSockets',
- 'maxFreeSockets', 'passphrase', 'pfx', 'rejectUnauthorized',
- 'secureProtocol', 'timeout'
+ 'keepAliveMsecs', 'maxSockets', 'maxTotalSockets',
+ 'maxFreeSockets', 'timeout', 'scheduling'
]);
connectionParams.agent = new https.Agent(agentOptions);
} else {
@@ -788,7 +789,9 @@ function initClient(client, inputParams) {
client.request = http.request;
if (noAgent) {
mlutil.copyProperties(inputParams, agentOptions, [
- 'keepAliveMsecs', 'maxSockets', 'maxFreeSockets', 'timeout'
+ 'ca', 'cert', 'ciphers', 'keepAliveMsecs', 'key', 'maxSockets',
+ 'maxFreeSockets', 'passphrase', 'pfx', 'rejectUnauthorized',
+ 'secureProtocol', 'timeout', 'maxCachedSessions'
]);
connectionParams.agent = new http.Agent(agentOptions);
} else { | #<I> - rejectUnauthorized option ignored in webpacked typescript (impacts mlxprs extension in latest VSCode on Mac) | marklogic_node-client-api | train |
ee3bfcefcea21c9061513b1d1726c70ab8a505af | diff --git a/src/Comparator/Variance/TypeIsContravariant.php b/src/Comparator/Variance/TypeIsContravariant.php
index <HASH>..<HASH> 100644
--- a/src/Comparator/Variance/TypeIsContravariant.php
+++ b/src/Comparator/Variance/TypeIsContravariant.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Roave\ApiCompare\Comparator\Variance;
+use Roave\BetterReflection\Reflection\ReflectionClass;
use Roave\BetterReflection\Reflection\ReflectionType;
use Roave\BetterReflection\Reflector\ClassReflector;
use function in_array;
@@ -61,7 +62,9 @@ final class TypeIsContravariant
return false;
}
+ /** @var ReflectionClass $typeReflectionClass */
$typeReflectionClass = $reflector->reflect($typeAsString);
+ /** @var ReflectionClass $comparedTypeReflectionClass */
$comparedTypeReflectionClass = $reflector->reflect($comparedTypeAsString);
if ($comparedTypeReflectionClass->isInterface()) {
diff --git a/src/Comparator/Variance/TypeIsCovariant.php b/src/Comparator/Variance/TypeIsCovariant.php
index <HASH>..<HASH> 100644
--- a/src/Comparator/Variance/TypeIsCovariant.php
+++ b/src/Comparator/Variance/TypeIsCovariant.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Roave\ApiCompare\Comparator\Variance;
+use Roave\BetterReflection\Reflection\ReflectionClass;
use Roave\BetterReflection\Reflection\ReflectionType;
use Roave\BetterReflection\Reflector\ClassReflector;
use function strtolower;
@@ -73,7 +74,9 @@ final class TypeIsCovariant
return false;
}
+ /** @var ReflectionClass $typeReflectionClass */
$typeReflectionClass = $reflector->reflect($typeAsString);
+ /** @var ReflectionClass $comparedTypeReflectionClass */
$comparedTypeReflectionClass = $reflector->reflect($comparedTypeAsString);
if ($typeReflectionClass->isInterface()) { | Adding IDE hints for the reflection issues around the `Reflector` interface in `BetterReflection` | Roave_BackwardCompatibilityCheck | train |
58db5c63f077c8c736f61a4a1fbeaed271942844 | diff --git a/src/integration/server_test.go b/src/integration/server_test.go
index <HASH>..<HASH> 100644
--- a/src/integration/server_test.go
+++ b/src/integration/server_test.go
@@ -1153,6 +1153,7 @@ func (self *ServerSuite) TestContinuousQueryWithMixedGroupByOperations(c *C) {
time.Sleep(time.Second)
self.serverProcesses[0].QueryAsRoot("test_cq", "select mean(reqtime), url from cqtest group by time(10s), url into cqtest.10s", false, c)
+ defer self.serverProcesses[0].QueryAsRoot("test_cq", "drop continuous query 1;", false, c)
collection := self.serverProcesses[0].QueryAsRoot("test_cq", "select * from cqtest.10s", false, c)
series := collection.GetSeries("cqtest.10s", c) | Make sure we drop the continuous query at the end of the test. | influxdata_influxdb | train |
16b3474c1fcbe55b263f4e701f38e7f4463698bd | diff --git a/djangoautoconf/auto_conf_utils.py b/djangoautoconf/auto_conf_utils.py
index <HASH>..<HASH> 100644
--- a/djangoautoconf/auto_conf_utils.py
+++ b/djangoautoconf/auto_conf_utils.py
@@ -66,6 +66,25 @@ def get_module_path(mod):
return os.path.dirname(mod.__file__)
+def get_source_filename(compiled_name):
+ return compiled_name.replace("pyc", "py")
+
+
+def get_module_file_path(mod):
+ return get_source_filename(mod.__file__)
+
+
+def get_module_filename(mod):
+ return get_source_filename(os.path.basename(mod.__file__))
+
+
+def get_module_include_files_config(mod, prefix=None):
+ if prefix is None:
+ return get_module_file_path(mod), get_module_filename(mod)
+ else:
+ return get_module_file_path(mod), os.path.join(prefix, get_module_filename(mod))
+
+
def enum_folders(parent_folder):
logging.debug("Listing folder: "+parent_folder)
for folder in os.listdir(parent_folder):
diff --git a/djangoautoconf/django_autoconf.py b/djangoautoconf/django_autoconf.py
index <HASH>..<HASH> 100644
--- a/djangoautoconf/django_autoconf.py
+++ b/djangoautoconf/django_autoconf.py
@@ -96,8 +96,8 @@ class DjangoAutoConf(DjangoSettingManager):
dump_attrs(self.setting_storage.get_settings())
@staticmethod
- def set_settings_env():
- executable_folder = get_executable_folder()
+ def set_settings_env(executable_folder=None):
+ executable_folder = executable_folder or get_executable_folder()
# print "!!!!!!!!!!!!!! executable:", executable_folder
if os.path.exists(os.path.join(executable_folder, "local/total_settings.py")):
print "Using total settings" | Added executable_folder for set_settings_env. | weijia_djangoautoconf | train |
66b7769cebfbe1a40811addbe881f502464321e4 | diff --git a/lib/jsi.rb b/lib/jsi.rb
index <HASH>..<HASH> 100644
--- a/lib/jsi.rb
+++ b/lib/jsi.rb
@@ -23,8 +23,6 @@ module JSI
autoload :Arraylike, 'jsi/typelike_modules'
autoload :Schema, 'jsi/schema'
autoload :Base, 'jsi/base'
- autoload :BaseArray, 'jsi/base'
- autoload :BaseHash, 'jsi/base'
autoload :Metaschema, 'jsi/metaschema'
autoload :MetaschemaNode, 'jsi/metaschema_node'
autoload :SchemaClasses, 'jsi/schema_classes'
diff --git a/lib/jsi/base.rb b/lib/jsi/base.rb
index <HASH>..<HASH> 100644
--- a/lib/jsi/base.rb
+++ b/lib/jsi/base.rb
@@ -131,9 +131,9 @@ module JSI
end
if self.jsi_instance.respond_to?(:to_hash)
- extend BaseHash
+ extend PathedHashNode
elsif self.jsi_instance.respond_to?(:to_ary)
- extend BaseArray
+ extend PathedArrayNode
end
if self.schema.describes_schema?
extend JSI::Schema
@@ -157,7 +157,7 @@ module JSI
alias_method :jsi_instance, :node_content
alias_method :instance, :node_content
- # each is overridden by BaseHash or BaseArray when appropriate. the base
+ # each is overridden by PathedHashNode or PathedArrayNode when appropriate. the base
# #each is not actually implemented, along with all the methods of Enumerable.
def each
raise NoMethodError, "Enumerable methods and #each not implemented for instance that is not like a hash or array: #{jsi_instance.pretty_inspect.chomp}"
@@ -397,14 +397,4 @@ module JSI
JSI.class_for_schema(schema)
end
end
-
- # module extending a {JSI::Base} object when its instance is Hash-like (responds to #to_hash)
- module BaseHash
- include PathedHashNode
- end
-
- # module extending a {JSI::Base} object when its instance is Array-like (responds to #to_ary)
- module BaseArray
- include PathedArrayNode
- end
end
diff --git a/lib/jsi/schema_classes.rb b/lib/jsi/schema_classes.rb
index <HASH>..<HASH> 100644
--- a/lib/jsi/schema_classes.rb
+++ b/lib/jsi/schema_classes.rb
@@ -61,7 +61,7 @@ module JSI
extend SchemaModule
- include JSI::SchemaClasses.accessor_module_for_schema(schema, conflicting_modules: [JSI::Base, JSI::BaseArray, JSI::BaseHash])
+ include JSI::SchemaClasses.accessor_module_for_schema(schema, conflicting_modules: [JSI::Base, JSI::PathedArrayNode, JSI::PathedHashNode])
@possibly_schema_node = schema
extend(SchemaModulePossibly)
diff --git a/test/base_array_test.rb b/test/base_array_test.rb
index <HASH>..<HASH> 100644
--- a/test/base_array_test.rb
+++ b/test/base_array_test.rb
@@ -12,7 +12,7 @@ base = {
NamedArrayInstance = JSI.class_for_schema(base)
NamedIdArrayInstance = JSI.class_for_schema({'$id' => 'https://schemas.jsi.unth.net/test/base/named_array_schema'}.merge(base))
-describe JSI::BaseArray do
+describe 'JSI::Base array' do
let(:instance) { ['foo', {'lamp' => [3]}, ['q', 'r'], {'four' => 4}] }
let(:schema_content) do
{
diff --git a/test/base_hash_test.rb b/test/base_hash_test.rb
index <HASH>..<HASH> 100644
--- a/test/base_hash_test.rb
+++ b/test/base_hash_test.rb
@@ -11,7 +11,7 @@ base = {
NamedHashInstance = JSI.class_for_schema(base)
NamedIdHashInstance = JSI.class_for_schema({'$id' => 'https://schemas.jsi.unth.net/test/base/named_hash_schema'}.merge(base))
-describe JSI::BaseHash do
+describe 'JSI::Base hash' do
let(:instance) { {'foo' => {'x' => 'y'}, 'bar' => [9], 'baz' => [true]} }
let(:schema_content) do
{
diff --git a/test/base_test.rb b/test/base_test.rb
index <HASH>..<HASH> 100644
--- a/test/base_test.rb
+++ b/test/base_test.rb
@@ -389,7 +389,7 @@ describe JSI::Base do
'inspect' => {}, # Base
'pretty_inspect' => {}, # Kernel
'as_json' => {}, # Base::OverrideFromExtensions, extended on initialization
- 'each' => {}, # BaseHash / BaseArray
+ 'each' => {}, # PathedHashNode / PathedArrayNode
'instance_exec' => {}, # BasicObject
'jsi_instance' => {}, # Base
'schema' => {}, # module_for_schema singleton definition | rm JSI::BaseHash and BaseArray; all their functionality now lives in PathedHashNode and PathedArrayNode | notEthan_jsi | train |
a0c4c5cb7846140eba5f1a732701955c8c44a0e8 | diff --git a/test/service_latency_test.go b/test/service_latency_test.go
index <HASH>..<HASH> 100644
--- a/test/service_latency_test.go
+++ b/test/service_latency_test.go
@@ -1303,6 +1303,72 @@ func TestServiceAndStreamStackOverflow(t *testing.T) {
})
}
+func TestServiceCycle(t *testing.T) {
+ t.Skip("Remove the skip to run this test and shows the issue")
+
+ conf := createConfFile(t, []byte(`
+ accounts {
+ A {
+ users = [ { user: "a", pass: "a" } ]
+ exports [
+ { service: help }
+ ]
+ imports [
+ { service { subject: help, account: B } }
+ ]
+ }
+ B {
+ users = [ { user: "b", pass: "b" } ]
+ exports [
+ { service: help }
+ ]
+ imports [
+ { service { subject: help, account: A } }
+ ]
+ }
+ }
+ `))
+ defer os.Remove(conf)
+
+ srv, opts := RunServerWithConfig(conf)
+ defer srv.Shutdown()
+
+ // Responder (just request sub)
+ nc, err := nats.Connect(fmt.Sprintf("nats://a:a@%s:%d", opts.Host, opts.Port))
+ if err != nil {
+ t.Fatalf("Error on connect: %v", err)
+ }
+ defer nc.Close()
+
+ cb := func(m *nats.Msg) {
+ m.Respond(nil)
+ }
+ sub, _ := nc.Subscribe("help", cb)
+ nc.Flush()
+
+ // Requestor
+ nc2, err := nats.Connect(fmt.Sprintf("nats://b:b@%s:%d", opts.Host, opts.Port))
+ if err != nil {
+ t.Fatalf("Error on connect: %v", err)
+ }
+ defer nc2.Close()
+
+ // Send a single request.
+ if _, err := nc2.Request("help", []byte("hi"), time.Second); err != nil {
+ t.Fatal("Did not get the reply")
+ }
+
+ // Make sure works for queue subscribers as well.
+ sub.Unsubscribe()
+ sub, _ = nc.QueueSubscribe("help", "prod", cb)
+ nc.Flush()
+
+ // Send a single request.
+ if _, err := nc2.Request("help", []byte("hi"), time.Second); err != nil {
+ t.Fatal("Did not get the reply")
+ }
+}
+
// Check we get the proper detailed information for the requestor when allowed.
func TestServiceLatencyRequestorSharesDetailedInfo(t *testing.T) {
sc := createSuperCluster(t, 3, 3) | Add test with service import cycle
Not sure if this should be detected as misconfiguration or if
code need to be fixed to work properly. | nats-io_gnatsd | train |
3d3da496293ec05d076a413cb7a38905cfa9544f | diff --git a/spec/acceptance/em_http_request/em_http_request_spec.rb b/spec/acceptance/em_http_request/em_http_request_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/acceptance/em_http_request/em_http_request_spec.rb
+++ b/spec/acceptance/em_http_request/em_http_request_spec.rb
@@ -199,6 +199,11 @@ unless RUBY_PLATFORM =~ /java/
http_request(:post, "http://www.example.com", :body => {:a => "1", :b => "2"}).body.should == "ok"
end
+ it "should work when a file is passed as body" do
+ stub_request(:post, "www.example.com").with(:body => File.read(__FILE__)).to_return(:body => "ok")
+ http_request(:post, "http://www.example.com", :file => __FILE__).body.should == "ok"
+ end
+
it "should work with UTF-8 strings" do
body = "Привет, Мир!"
stub_request(:post, "www.example.com").to_return(:body => body)
diff --git a/spec/acceptance/em_http_request/em_http_request_spec_helper.rb b/spec/acceptance/em_http_request/em_http_request_spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/acceptance/em_http_request/em_http_request_spec_helper.rb
+++ b/spec/acceptance/em_http_request/em_http_request_spec_helper.rb
@@ -17,6 +17,7 @@ module EMHttpRequestSpecHelper
http = request.send(method, {
:timeout => 30,
:body => options[:body],
+ :file => options[:file],
:query => options[:query],
:head => head.merge('authorization' => [uri.user, uri.password])
}, &block) | add a test case for passing :file for em-http-request. | bblimke_webmock | train |
dd3662079f8b163469be248488cab53e242ae8ab | diff --git a/lib/plugins/aws/deploy/lib/checkForChanges.js b/lib/plugins/aws/deploy/lib/checkForChanges.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/aws/deploy/lib/checkForChanges.js
+++ b/lib/plugins/aws/deploy/lib/checkForChanges.js
@@ -101,8 +101,8 @@ module.exports = {
return crypto.createHash('sha256').update(zipFile).digest('base64');
});
- zipFileHashes.push(localCfHash);
const localHashes = zipFileHashes;
+ localHashes.push(localCfHash);
if (_.isEqual(remoteHashes.sort(), localHashes.sort())) {
this.serverless.service.provider.shouldNotDeploy = true; | Update variable usage to ensure better readability | serverless_serverless | train |
46c64394e489b253df7d8c91b2ab6748aad15aab | diff --git a/chance.js b/chance.js
index <HASH>..<HASH> 100644
--- a/chance.js
+++ b/chance.js
@@ -1326,23 +1326,30 @@
};
Chance.prototype.states = function (options) {
- options = initOptions(options, { us_states_and_dc: true });
+ options = initOptions(options, { country: 'us', us_states_and_dc: true } );
- var states,
- us_states_and_dc = this.get("us_states_and_dc"),
- territories = this.get("territories"),
- armed_forces = this.get("armed_forces");
+ var states;
- states = [];
+ switch (options.country.toLowerCase()) {
+ case 'us':
+ var us_states_and_dc = this.get("us_states_and_dc"),
+ territories = this.get("territories"),
+ armed_forces = this.get("armed_forces");
- if (options.us_states_and_dc) {
- states = states.concat(us_states_and_dc);
- }
- if (options.territories) {
- states = states.concat(territories);
- }
- if (options.armed_forces) {
- states = states.concat(armed_forces);
+ states = [];
+
+ if (options.us_states_and_dc) {
+ states = states.concat(us_states_and_dc);
+ }
+ if (options.territories) {
+ states = states.concat(territories);
+ }
+ if (options.armed_forces) {
+ states = states.concat(armed_forces);
+ }
+ break;
+ case 'it':
+ states = this.get("country_regions")[options.country.toLowerCase()];
}
return states;
@@ -2362,6 +2369,31 @@
{name: 'Armed Forces the Americas', abbreviation: 'AA'}
],
+ country_regions: {
+ it: [
+ { name: "Valle d'Aosta", abbreviation: "VDA" },
+ { name: "Piemonte", abbreviation: "PIE" },
+ { name: "Lombardia", abbreviation: "LOM" },
+ { name: "Veneto", abbreviation: "VEN" },
+ { name: "Trentino Alto Adige", abbreviation: "TAA" },
+ { name: "Friuli Venezia Giulia", abbreviation: "FVG" },
+ { name: "Liguria", abbreviation: "LIG" },
+ { name: "Emilia Romagna", abbreviation: "EMR" },
+ { name: "Toscana", abbreviation: "TOS" },
+ { name: "Umbria", abbreviation: "UMB" },
+ { name: "Marche", abbreviation: "MAR" },
+ { name: "Abruzzo", abbreviation: "ABR" },
+ { name: "Lazio", abbreviation: "LAZ" },
+ { name: "Campania", abbreviation: "CAM" },
+ { name: "Puglia", abbreviation: "PUG" },
+ { name: "Basilicata", abbreviation: "BAS" },
+ { name: "Molise", abbreviation: "MOL" },
+ { name: "Calabria", abbreviation: "CAL" },
+ { name: "Sicilia", abbreviation: "SIC" },
+ { name: "Sardegna", abbreviation: "SAR" }
+ ]
+ },
+
street_suffixes: [
{name: 'Avenue', abbreviation: 'Ave'},
{name: 'Boulevard', abbreviation: 'Blvd'}, | support internationalisation on chance.state(s)
Fully backward compatible
Since U.S. territories were semantically partitioned, a new object has been created
(country_regions) following the same structure as other country based data
(each country has a property that contains an array of data)
Source for data: ISTAT (public government body for statistical analysis) | chancejs_chancejs | train |
a1c968d9ff56e26ca18191845e6e7cb5fef0edeb | diff --git a/example_site/example/admin.py b/example_site/example/admin.py
index <HASH>..<HASH> 100644
--- a/example_site/example/admin.py
+++ b/example_site/example/admin.py
@@ -1,10 +1,11 @@
from django.contrib import admin
-from address.forms import AddressField, AddressWidget
+from address.models import AddressField
+from address.forms import AddressWidget
from .models import Example
class ExampleAdmin(admin.ModelAdmin):
formfield_overrides = {
- AddressField: {'widget': AddressWidget}
+ AddressField: {'widget': AddressWidget(attrs={'style': 'width: 300px;'})}
}
admin.site.register(Example, ExampleAdmin) | Adding an example test for modifying admin widgets. | furious-luke_django-address | train |
0aa8266a786d631c00224954e8be3d7b2cd26661 | diff --git a/modules/admin/ngrest/Config.php b/modules/admin/ngrest/Config.php
index <HASH>..<HASH> 100644
--- a/modules/admin/ngrest/Config.php
+++ b/modules/admin/ngrest/Config.php
@@ -55,6 +55,11 @@ class Config implements \admin\ngrest\base\ConfigInterface
return array_key_exists($pointer, $this->config);
}
+ public function isDeletable()
+ {
+ return ($this->getKey('delete') === true) ? true : false;
+ }
+
public function __get($key)
{
// @TODO see if pointer exists in $this->$pointersMap
diff --git a/modules/admin/ngrest/base/ConfigInterface.php b/modules/admin/ngrest/base/ConfigInterface.php
index <HASH>..<HASH> 100644
--- a/modules/admin/ngrest/base/ConfigInterface.php
+++ b/modules/admin/ngrest/base/ConfigInterface.php
@@ -17,4 +17,6 @@ interface ConfigInterface
public function getNgRestConfigHash();
public function onFinish();
+
+ public function isDeletable();
} | added isDeletable() #<I> | luyadev_luya | train |
55b1e6bc1a40b78555e5141965cf3586ec471dd9 | diff --git a/http/eventsource.go b/http/eventsource.go
index <HASH>..<HASH> 100644
--- a/http/eventsource.go
+++ b/http/eventsource.go
@@ -23,8 +23,8 @@ type eventSource struct {
staled chan *consumer
add chan *consumer
close chan bool
- idleTimeout int
- retry int
+ idleTimeout time.Duration
+ retry time.Duration
timeout time.Duration
closeOnTimeout bool
@@ -34,7 +34,7 @@ type eventSource struct {
type Settings struct {
// Sets the delay between a connection loss and the client attempting to
// reconnect. This is given in milliseconds. The default is 3 seconds.
- Retry int
+ Retry time.Duration
// SetTimeout sets the write timeout for individual messages. The
// default is 2 seconds.
@@ -53,7 +53,7 @@ type Settings struct {
// Sets the timeout for an idle connection. This is given in minutes. The
// default is 30 minutes.
- IdleTimeout int
+ IdleTimeout time.Duration
}
func DefaultSettings() *Settings { | change idle timeout and retry to time.Duration type | antage_eventsource | train |
7f64f6dfc7891bd7fcc06222e400cd28bcb9cfa5 | diff --git a/pypsa/plot.py b/pypsa/plot.py
index <HASH>..<HASH> 100644
--- a/pypsa/plot.py
+++ b/pypsa/plot.py
@@ -166,7 +166,7 @@ def plot(n, margin=None, ax=None, geomap=True, projection=None,
transform = draw_map_cartopy(n, x, y, ax, geomap, color_geomap)
x, y, z = ax.projection.transform_points(transform, x.values, y.values).T
x, y = pd.Series(x, n.buses.index), pd.Series(y, n.buses.index)
- if boundaries:
+ if boundaries is not None:
ax.set_extent(boundaries, crs=transform)
elif ax is None:
ax = plt.gca()
@@ -216,7 +216,7 @@ def plot(n, margin=None, ax=None, geomap=True, projection=None,
360*start, 360*(start+ratio),
facecolor=bus_colors[i], alpha=bus_alpha))
start += ratio
- bus_collection = PatchCollection(patches, match_original=True)
+ bus_collection = PatchCollection(patches, match_original=True, zorder=5)
ax.add_collection(bus_collection)
else:
c = pd.Series(bus_colors, index=n.buses.index) | plot: fix zorder of wedges, fix boundaries to be an array | PyPSA_PyPSA | train |
0d6dd8339e02ae6fd3f4b3ac8281a0179d417c6d | diff --git a/CHANGES.rst b/CHANGES.rst
index <HASH>..<HASH> 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,6 +1,12 @@
Changelog for nextversion
=========================
+0.2.8 (unreleased)
+------------------
+
+- Outputs log when executing commands
+
+
0.2.7 (2014-01-09)
------------------
diff --git a/relshell/base_shelloperator.py b/relshell/base_shelloperator.py
index <HASH>..<HASH> 100644
--- a/relshell/base_shelloperator.py
+++ b/relshell/base_shelloperator.py
@@ -66,6 +66,7 @@ class BaseShellOperator(object):
env = env,
bufsize = 1 if non_blocking_stdout else 0,
)
+ BaseShellOperator._logger.info('[Command execution] $ %s' % (batcmd.sh_cmd))
except OSError as e:
raise OSError('Following command fails - %s:%s$ %s' % (e, os.linesep, batcmd.sh_cmd))
diff --git a/relshell/logger.py b/relshell/logger.py
index <HASH>..<HASH> 100644
--- a/relshell/logger.py
+++ b/relshell/logger.py
@@ -21,6 +21,7 @@ class Logger(object):
Do not use this function. Use `instance()`.
"""
self._logger = logging.getLogger('relshell_logger')
+ self._logger.setLevel(logging.INFO)
handler = RainbowLoggingHandler(sys.stderr)
self._logger.addHandler(handler)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -9,7 +9,7 @@ setup(
long_description = open('README.rst').read(),
url = 'https://github.com/laysakura/relshell',
license = 'LICENSE.txt',
- version = '0.2.7',
+ version = '0.2.8',
author = 'Sho Nakatani',
author_email = '[email protected]',
test_suite = 'nose.collector', | Outputs log when executing commands | laysakura_relshell | train |
f3456c10143f2054c878de7c7d7418e040e733f6 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -136,7 +136,8 @@ if 'py2exe' in sys.argv:
# additional modules used by snmpsimd but not seen by py2exe
for m in ('dbm', 'gdbm', 'dbhash', 'dumbdb',
- 'shelve', 'random', 'math'):
+ 'shelve', 'random', 'math', 'bisect',
+ 'sqlite3', 'subprocess'):
try:
__import__(m)
except ImportError: | some more Python modules not seen by py2exe registered | etingof_snmpsim | train |
9bcb7aa6c16dd2e7c919fff71644c6fa0024a8d9 | diff --git a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java
index <HASH>..<HASH> 100644
--- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java
+++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java
@@ -1091,6 +1091,7 @@ public class JShellTool implements MessageHandler {
}
if (path.isEmpty()) {
StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false)
+ .filter(root -> Files.exists(root))
.filter(root -> accept.test(root) && root.toString().startsWith(prefix))
.map(root -> new ArgSuggestion(root.toString()))
.forEach(result::add);
diff --git a/test/jdk/jshell/CommandCompletionTest.java b/test/jdk/jshell/CommandCompletionTest.java
index <HASH>..<HASH> 100644
--- a/test/jdk/jshell/CommandCompletionTest.java
+++ b/test/jdk/jshell/CommandCompletionTest.java
@@ -46,6 +46,7 @@ import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
import org.testng.annotations.Test;
@@ -144,7 +145,7 @@ public class CommandCompletionTest extends ReplToolTesting {
Compiler compiler = new Compiler();
assertCompletion("/o|", false, "/open ");
List<String> p1 = listFiles(Paths.get(""));
- FileSystems.getDefault().getRootDirectories().forEach(s -> p1.add(s.toString()));
+ getRootDirectories().forEach(s -> p1.add(s.toString()));
Collections.sort(p1);
assertCompletion("/open |", false, p1.toArray(new String[p1.size()]));
Path classDir = compiler.getClassDir();
@@ -157,7 +158,7 @@ public class CommandCompletionTest extends ReplToolTesting {
assertCompletion("/s|", false, "/save ", "/set ");
List<String> p1 = listFiles(Paths.get(""));
Collections.addAll(p1, "-all ", "-history ", "-start ");
- FileSystems.getDefault().getRootDirectories().forEach(s -> p1.add(s.toString()));
+ getRootDirectories().forEach(s -> p1.add(s.toString()));
Collections.sort(p1);
assertCompletion("/save |", false, p1.toArray(new String[p1.size()]));
Path classDir = compiler.getClassDir();
@@ -198,7 +199,7 @@ public class CommandCompletionTest extends ReplToolTesting {
public void testSet() throws IOException {
List<String> p1 = listFiles(Paths.get(""));
- FileSystems.getDefault().getRootDirectories().forEach(s -> p1.add(s.toString()));
+ getRootDirectories().forEach(s -> p1.add(s.toString()));
Collections.sort(p1);
String[] modes = {"concise ", "normal ", "silent ", "verbose "};
@@ -267,4 +268,13 @@ public class CommandCompletionTest extends ReplToolTesting {
(Files.isDirectory(file) ||
file.getFileName().toString().endsWith(".jar") ||
file.getFileName().toString().endsWith(".zip"));
+
+ private static Iterable<? extends Path> getRootDirectories() {
+ return StreamSupport.stream(FileSystems.getDefault()
+ .getRootDirectories()
+ .spliterator(),
+ false)
+ .filter(p -> Files.exists(p))
+ .collect(Collectors.toList());
+ }
} | <I>: langtools\test\jdk\jshell\CommandCompletionTest.java fails on some windows
Summary: Ignoring non-existent default FileSystem roots.
Reviewed-by: rfield | google_error-prone-javac | train |
642999ed7aede2daab388d00d510f05efad8bfbb | diff --git a/rapidoid-utils/src/main/java/org/rapidoid/util/Metadata.java b/rapidoid-utils/src/main/java/org/rapidoid/util/Metadata.java
index <HASH>..<HASH> 100644
--- a/rapidoid-utils/src/main/java/org/rapidoid/util/Metadata.java
+++ b/rapidoid-utils/src/main/java/org/rapidoid/util/Metadata.java
@@ -57,4 +57,8 @@ public class Metadata {
return (T) fieldAnnotations(clazz, fieldName).get(annotationClass);
}
+ public static boolean isAnnotated(Class<?> target, Class<?> annotation) {
+ return classAnnotations(target).containsKey(annotation);
+ }
+
} | Added metadata util for convenient checking if a class is annotated. | rapidoid_rapidoid | train |
fa87a4b74bc5bbd17b73e6a20709d1398d33d6ab | diff --git a/lib/multiarray.rb b/lib/multiarray.rb
index <HASH>..<HASH> 100644
--- a/lib/multiarray.rb
+++ b/lib/multiarray.rb
@@ -2,6 +2,34 @@ require 'malloc'
require 'multiarray/storage'
require 'multiarray/list'
require 'multiarray/memory'
+require 'multiarray/scalar_operation'
require 'multiarray/type'
require 'multiarray/descriptortype'
require 'multiarray/int'
+
+class Proc
+
+ unless method_defined? :bind
+ def bind( object )
+ block, time = self, Time.now
+ ( class << object; self end ).class_eval do
+ method_name = "__bind_#{time.to_i}_#{time.usec}"
+ define_method method_name, &block
+ method = instance_method method_name
+ remove_method method_name
+ method
+ end.bind object
+ end
+ end
+
+end
+
+class Object
+
+ unless method_defined? :instance_exec
+ def instance_exec( *arguments, &block )
+ block.bind( self )[ *arguments ]
+ end
+ end
+
+end
diff --git a/lib/multiarray/type.rb b/lib/multiarray/type.rb
index <HASH>..<HASH> 100644
--- a/lib/multiarray/type.rb
+++ b/lib/multiarray/type.rb
@@ -46,4 +46,6 @@ module MultiArray
end
+ Type.class_eval { include ScalarOperation }
+
end
diff --git a/test/ts_int.rb b/test/ts_int.rb
index <HASH>..<HASH> 100644
--- a/test/ts_int.rb
+++ b/test/ts_int.rb
@@ -69,4 +69,11 @@ class TC_Int < Test::Unit::TestCase
end
end
+ def test_op
+ @@types.each do |t|
+ i = t.new 1
+ assert_equal 3, i.op( 2 ) { |x| set get + x }.get
+ end
+ end
+
end | Add test for scalar operation | wedesoft_multiarray | train |
e69b6214699b7d778143b90dc32bb0dabc0f012b | diff --git a/jaxrs/src/main/java/org/killbill/billing/jaxrs/json/OverdueConditionJson.java b/jaxrs/src/main/java/org/killbill/billing/jaxrs/json/OverdueConditionJson.java
index <HASH>..<HASH> 100644
--- a/jaxrs/src/main/java/org/killbill/billing/jaxrs/json/OverdueConditionJson.java
+++ b/jaxrs/src/main/java/org/killbill/billing/jaxrs/json/OverdueConditionJson.java
@@ -58,7 +58,7 @@ public class OverdueConditionJson {
public OverdueConditionJson(final OverdueCondition overdueCondition) {
this.timeSinceEarliestUnpaidInvoiceEqualsOrExceeds = overdueCondition.getTimeSinceEarliestUnpaidInvoiceEqualsOrExceeds() == null ?
- new DurationJson(null, 0) :
+ null :
new DurationJson(overdueCondition.getTimeSinceEarliestUnpaidInvoiceEqualsOrExceeds());
this.controlTagInclusion = overdueCondition.getInclusionControlTagType();
this.controlTagExclusion = overdueCondition.getExclusionControlTagType(); | set timeSinceEarliestUnpaidInvoice.... null instead of set to default value | killbill_killbill | train |
b20bcc285ef29a1d9ea2f77bb0097f8cd922246a | diff --git a/asammdf/gui/widgets/tree.py b/asammdf/gui/widgets/tree.py
index <HASH>..<HASH> 100644
--- a/asammdf/gui/widgets/tree.py
+++ b/asammdf/gui/widgets/tree.py
@@ -40,49 +40,66 @@ class TreeWidget(QtWidgets.QTreeWidget):
def mouseMoveEvent(self, e):
- selected_items = self.selectedItems()
-
- mimeData = QtCore.QMimeData()
-
- data = []
-
- for item in selected_items:
-
+ def get_data(item):
+ data = set()
count = item.childCount()
if count:
for i in range(count):
child = item.child(i)
- name = child.name.encode("utf-8")
- entry = child.entry
-
- data.append(
- pack(
- f"<36s3q{len(name)}s",
- str(child.mdf_uuid).encode("ascii"),
- entry[0],
- entry[1],
- len(name),
- name,
- )
- )
+ if child.childCount():
+ data = data | get_data(child)
+ else:
+
+ name = child.name.encode("utf-8")
+ entry = child.entry
+ if entry[1] != 0xFFFFFFFFFFFFFFFF:
+ data.add(
+ (
+ str(child.mdf_uuid).encode("ascii"),
+ name,
+ entry[0],
+ entry[1],
+ len(name),
+ )
+ )
else:
-
name = item.name.encode("utf-8")
entry = item.entry
if entry[1] != 0xFFFFFFFFFFFFFFFF:
- data.append(
- pack(
- f"<36s3q{len(name)}s",
+ data.add(
+ (
str(item.mdf_uuid).encode("ascii"),
+ name,
entry[0],
entry[1],
len(name),
- name,
)
)
+ return data
+
+ selected_items = self.selectedItems()
+
+ mimeData = QtCore.QMimeData()
+
+ data = set()
+ for item in selected_items:
+ data = data | get_data(item)
+
+ data = [
+ pack(
+ f"<36s3q{name_length}s",
+ uuid,
+ group_index,
+ channel_index,
+ name_length,
+ name,
+ )
+ for uuid, name, group_index, channel_index, name_length in sorted(data)
+ ]
+
mimeData.setData(
"application/octet-stream-asammdf", QtCore.QByteArray(b"".join(data))
)
diff --git a/asammdf/version.py b/asammdf/version.py
index <HASH>..<HASH> 100644
--- a/asammdf/version.py
+++ b/asammdf/version.py
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
""" asammdf version module """
-__version__ = "5.20.6.dev-4"
+__version__ = "5.20.6.dev-5" | fix drag and drop selection from channels tree | danielhrisca_asammdf | train |
c27776425c007d2c216899caaacda8d527f798ef | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -159,31 +159,40 @@ $app->add(new Tuupola\Middleware\HttpBasicAuthentication([
## Security
-Browsers send passwords over the wire basically as cleartext. You should always use HTTPS. If the middleware detects insecure usage over HTTP it will throw `RuntimeException`. This rule is relaxed for localhost. To allow insecure usage you must enable it manually by setting `secure` to `false`.
+Basic authentication transmits credentials in clear text. For this reason HTTPS should always be used together with basic authentication. If the middleware detects insecure usage over HTTP it will throw a `RuntimeException` with the following message: `Insecure use of middleware over HTTP denied by configuration`.
+By default, localhost is allowed to use HTTP. The security behavior of `HttpBasicAuthentication` can also be configured to allow:
+
+- [a whitelist of domains to connect insecurely](#security-whitelist)
+- [forwarding of an HTTPS connection to HTTP](#security-forwarding)
+- [all traffic](#security-disabling)
+
+### <a name="security-whitelist"></a>How to configure a whitelist:
+You can list hosts to allow access insecurely. For example, to allow HTTP traffic from your development host `dev.example.com`, add the hostname to the `relaxed` config key:
``` php
$app = new Slim\App;
$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
"path" => "/admin",
- "secure" => false,
+ "secure" => true,
+ "relaxed" => ["localhost", "dev.example.com"],
"users" => [
"root" => "t00r",
"somebody" => "passw0rd"
]
]));
```
+### <a name="security-forwarding"></a> Allow HTTPS termination and forwarding
+If public traffic terminates SSL on a load balancer or proxy and forwards to the application host insecurely, `HttpBasicAuthentication` can inspect request headers to ensure that the original client request was initiated securely. To enable, add the string `headers` to the `relaxed` config key:
-Alternatively you can list your development host to have relaxed security.
-
-``` php
+```php
$app = new Slim\App;
$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
"path" => "/admin",
"secure" => true,
- "relaxed" => ["localhost", "dev.example.com"],
+ "relaxed" => ["localhost", "headers"],
"users" => [
"root" => "t00r",
"somebody" => "passw0rd"
@@ -191,6 +200,21 @@ $app->add(new Tuupola\Middleware\HttpBasicAuthentication([
]));
```
+### <a name="security-disabling"></a>
+To allow insecure usage by any host, you must enable it manually by setting `secure` to `false`:
+
+``` php
+$app = new Slim\App;
+
+$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
+ "path" => "/admin",
+ "secure" => false,
+ "users" => [
+ "root" => "t00r",
+ "somebody" => "passw0rd"
+ ]
+]));
+```
## Custom authentication methods
Sometimes passing users in an array is not enough. To authenticate against custom datasource you can pass a callable as `authenticator` parameter. This can be either a class which implements AuthenticatorInterface or anonymous function. Callable receives an array containing `user` and `password` as argument. In both cases authenticator must return either `true` or `false`.
diff --git a/src/HttpBasicAuthentication.php b/src/HttpBasicAuthentication.php
index <HASH>..<HASH> 100644
--- a/src/HttpBasicAuthentication.php
+++ b/src/HttpBasicAuthentication.php
@@ -99,7 +99,19 @@ final class HttpBasicAuthentication implements MiddlewareInterface
/* HTTP allowed only if secure is false or server is in relaxed array. */
if ("https" !== $scheme && true === $this->options["secure"]) {
- if (!in_array($host, $this->options["relaxed"])) {
+ $allowedHost = in_array($host, $this->options["relaxed"]);
+
+ /* if 'headers' is in the 'relaxed' key, then we check for forwarding */
+ $allowedForward = false;
+ if (in_array("headers", $this->options["relaxed"])) {
+ if ($request->getHeaderLine("X-Forwarded-Proto") === "https"
+ && $request->getHeaderLine('X-Forwarded-Port') === "443"
+ ) {
+ $allowedForward = true;
+ }
+ }
+
+ if (!($allowedHost || $allowedForward)) {
$message = sprintf(
"Insecure use of middleware over %s denied by configuration.",
strtoupper($scheme)
diff --git a/tests/BasicAuthenticationTest.php b/tests/BasicAuthenticationTest.php
index <HASH>..<HASH> 100644
--- a/tests/BasicAuthenticationTest.php
+++ b/tests/BasicAuthenticationTest.php
@@ -547,6 +547,35 @@ class HttpBasicAuthenticationTest extends TestCase
$this->assertEquals(401, $response->getStatusCode());
}
+ public function testShouldRelaxForwardedViaSetting()
+ {
+ $request = (new ServerRequestFactory)
+ ->createServerRequest("GET", "http://example.com/api")
+ ->withHeader("X-Forwarded-Proto", "https")
+ ->withHeader("X-Forwarded-Port", "443");
+
+ $response = (new ResponseFactory)->createResponse();
+
+ $auth = new HttpBasicAuthentication([
+ "secure" => true,
+ "relaxed" => ["localhost", "headers"],
+ "path" => "/api",
+ "users" => [
+ "root" => "t00r",
+ "user" => "passw0rd"
+ ]
+ ]);
+
+ $next = function (ServerRequestInterface $request, ResponseInterface $response) {
+ $response->getBody()->write("Success");
+ return $response;
+ };
+
+ $response = $auth($request, $response, $next);
+
+ $this->assertEquals(401, $response->getStatusCode());
+ }
+
public function testShouldBeImmutable()
{
$auth = new HttpBasicAuthentication([ | Allow 'headers' as a key in 'relaxed' config key to allow https forwarding (#<I>)
* Add a test that fails because it doesn't allow forwarded https
requests even when configured to allow.
* Make the test pass by implementing the logic.
* Document the option to relax security to allow for forwarded https
* Take a crack at a fresh re-write of the security section of README | tuupola_slim-basic-auth | train |
13a7a04706337300f9da7cf7e5e62453c9f1f334 | diff --git a/lib/seahorse/client/request.rb b/lib/seahorse/client/request.rb
index <HASH>..<HASH> 100644
--- a/lib/seahorse/client/request.rb
+++ b/lib/seahorse/client/request.rb
@@ -23,6 +23,7 @@ module Seahorse
def initialize(operation_name, params = {})
@operation_name = operation_name
@params = params
+ @listeners = {}
end
# @return [String]
@@ -37,9 +38,27 @@ module Seahorse
# @return [Response]
def send
resp = Response.new
+ emit(:validate)
+ emit(:build)
+ emit(:sign)
+ emit(:send)
+ emit(:parse)
+ emit(:success)
+ emit(:complete)
resp
end
+ # @param [Symbol,String] event_name
+ def on(event_name, &block)
+ @listeners[event_name] = block
+ end
+
+ private
+
+ def emit event_name
+ @listeners[event_name].call if @listeners[event_name]
+ end
+
end
end
end
diff --git a/test/seahorse/client/request_test.rb b/test/seahorse/client/request_test.rb
index <HASH>..<HASH> 100644
--- a/test/seahorse/client/request_test.rb
+++ b/test/seahorse/client/request_test.rb
@@ -18,7 +18,7 @@ module Seahorse
describe Request do
def request params = {}
- @req = Request.new('operation_name', params)
+ @req ||= Request.new('operation_name', params)
end
describe '#operation_name' do
@@ -67,9 +67,13 @@ module Seahorse
describe 'lifecycle' do
+ # standard lifecycle events emitted for a successful request
+ def events
+ [:validate, :build, :sign, :send, :parse, :success, :complete]
+ end
+
it 'emits a sequence of standard events as a result of #send' do
emitted = []
- events = [:validate, :build, :sign, :send, :parse, :success, :complete]
events.each do |event_name|
request.on(event_name) { |*args| emitted << event_name }
end | Calling Request#send now emits a fixed list of events. | aws_aws-sdk-ruby | train |
405c0fae36a56a61c93218ab40ceb4b632553c84 | diff --git a/packages/lib/PubSub.js b/packages/lib/PubSub.js
index <HASH>..<HASH> 100644
--- a/packages/lib/PubSub.js
+++ b/packages/lib/PubSub.js
@@ -13,16 +13,18 @@
* Calling the super constructor is not required for descendants of
* lib.PubSub.
*/
+
var ctx = jsio.__env.global,
SLICE = Array.prototype.slice;
-exports = Class(function() {
- this.init = function() {}
+exports = Class(function () {
+
+ this.init = function () {};
- this.publish = function(signal) {
- if(this._subscribers) {
+ this.publish = function (signal) {
+ if (this._subscribers) {
var args = SLICE.call(arguments, 1);
- if(this._subscribers.__any) {
+ if (this._subscribers.__any) {
var anyArgs = [signal].concat(args),
subs = this._subscribers.__any.slice(0);
for(var i = 0, sub; sub = subs[i]; ++i) {
@@ -30,17 +32,19 @@ exports = Class(function() {
}
}
- if(!this._subscribers[signal]) { return this; }
+ if (!this._subscribers[signal]) {
+ return this;
+ }
var subs = this._subscribers[signal].slice(0);
- for(var i = 0, sub; sub = subs[i]; ++i) {
+ for (var i = 0, sub; sub = subs[i]; ++i) {
sub.apply(ctx, args);
}
}
return this;
- }
+ };
- this.subscribe = function(signal, ctx, method) {
+ this.subscribe = function (signal, ctx, method) {
var cb;
if (arguments.length == 2) {
cb = ctx;
@@ -53,11 +57,11 @@ exports = Class(function() {
var s = this._subscribers || (this._subscribers = {});
(s[signal] || (s[signal] = [])).push(cb);
return this;
- }
+ };
- this.subscribeOnce = function(signal, ctx, method) {
+ this.subscribeOnce = function (signal, ctx, method) {
var args = arguments,
- cb = bind(this, function() {
+ cb = bind(this, function () {
this.unsubscribe(signal, cb);
if (args.length == 2) {
ctx.apply(GLOBAL, arguments);
@@ -67,17 +71,21 @@ exports = Class(function() {
}
});
- if ( args.length === 3 ) {
+ if (args.length === 3) {
cb._ctx = ctx;
cb._method = method;
}
return this.subscribe(signal, cb);
- }
+ };
- // if no method is specified, all subscriptions with a callback context of ctx will be removed
- this.unsubscribe = function(signal, ctx, method) {
- if (!this._subscribers || !this._subscribers[signal]) { return this; }
+ // If no method is specified, all subscriptions with a callback context
+ // of ctx will be removed.
+
+ this.unsubscribe = function (signal, ctx, method) {
+ if (!this._subscribers || !this._subscribers[signal]) {
+ return this;
+ }
var subs = this._subscribers[signal];
for (var i = 0, c; c = subs[i]; ++i) {
if (c == ctx || c._ctx == ctx && (!method || c._method == method)) {
@@ -85,13 +93,60 @@ exports = Class(function() {
}
}
return this;
+ };
+
+ /**
+ * EventEmitter-style API
+ * http://nodejs.org/api/events.html
+ */
+
+ this.listeners = function (type) {
+ this._subscribers = (this._subscribers ? this._subscribers : {});
+ return (this.hasOwnProperty.call(this._subscribers, type))
+ ? this._subscribers[type]
+ : (this._subscribers[type] = []);
+ }
+ };
+
+ this.addListener = this.on = function (type, f) {
+ if (this.listeners(type).length + 1 > this._maxListeners && this._maxListeners !== 0) {
+ if (typeof console !== "undefined") {
+ console.warn("Possible EventEmitter memory leak detected. " + this._subscribers[type].length + " listeners added. Use emitter.setMaxListeners() to increase limit.");
+ }
+ }
+ this.emit("newListener", type, f);
+ return this.subscribe(type, this, f);
+ };
+
+ this.once = function (type, f) {
+ return this.subscribeOnce(type, this, f);
+ };
+
+ this.removeListener = function (type, f) {
+ this.unsubscribe(type, this, f);
+ return this;
+ };
+
+ this.removeAllListeners = function (type) {
+ if (this._subscribers) {
+ for (var k in this._subscribers) {
+ if (type == null || type == k) {
+ delete this._subscribers[k];
+ }
+ }
+ }
+ return this;
+ };
+
+ this.emit = function (type) {
+ this.publish.apply(this, arguments);
+ return this.listeners(type).length > 0;
}
-
- // alternate common convention for events (used in Node, jQuery, Backbone, etc.)
- this.emit = this.publish;
- this.on = this.subscribe;
- this.off = this.unsubscribe;
- this.once = this.subscribeOnce;
-
+
+ this._maxListeners = 10;
+
+ this.setMaxListeners = function (_maxListeners) {
+ this._maxListeners = _maxListeners;
+ };
}); | Normalize API with Node's | gameclosure_js.io | train |
8e9331770b7a4905efffa6e4317d6e236fb0b541 | diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -55,6 +55,6 @@
"flow-bin": "0.100.0",
"mocha": "6.1.4",
"nyc": "14.1.1",
- "prettier": "1.17.1"
+ "prettier": "1.18.0"
}
}
diff --git a/src/execution/execute.js b/src/execution/execute.js
index <HASH>..<HASH> 100644
--- a/src/execution/execute.js
+++ b/src/execution/execute.js
@@ -855,9 +855,7 @@ function completeValue(
);
if (completed === null) {
throw new Error(
- `Cannot return null for non-nullable field ${info.parentType.name}.${
- info.fieldName
- }.`,
+ `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`,
);
}
return completed;
@@ -934,9 +932,7 @@ function completeListValue(
): PromiseOrValue<$ReadOnlyArray<mixed>> {
invariant(
isCollection(result),
- `Expected Iterable, but did not find one for field ${
- info.parentType.name
- }.${info.fieldName}.`,
+ `Expected Iterable, but did not find one for field ${info.parentType.name}.${info.fieldName}.`,
);
// This is specified as a simple map, however we're optimizing the path
diff --git a/src/jsutils/instanceOf.js b/src/jsutils/instanceOf.js
index <HASH>..<HASH> 100644
--- a/src/jsutils/instanceOf.js
+++ b/src/jsutils/instanceOf.js
@@ -18,7 +18,7 @@ declare function instanceOf(
// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
// See: https://webpack.js.org/guides/production/
-export default (process.env.NODE_ENV === 'production'
+export default process.env.NODE_ENV === 'production'
? // eslint-disable-next-line no-shadow
function instanceOf(value: mixed, constructor: mixed) {
return value instanceof constructor;
@@ -49,4 +49,4 @@ spurious results.`,
}
}
return false;
- });
+ };
diff --git a/src/utilities/findBreakingChanges.js b/src/utilities/findBreakingChanges.js
index <HASH>..<HASH> 100644
--- a/src/utilities/findBreakingChanges.js
+++ b/src/utilities/findBreakingChanges.js
@@ -269,9 +269,7 @@ function findUnionTypeChanges(
for (const newPossibleType of possibleTypesDiff.added) {
schemaChanges.push({
type: DangerousChangeType.TYPE_ADDED_TO_UNION,
- description: `${newPossibleType.name} was added to union type ${
- oldType.name
- }.`,
+ description: `${newPossibleType.name} was added to union type ${oldType.name}.`,
});
}
@@ -304,9 +302,7 @@ function findEnumTypeChanges(
for (const oldValue of valuesDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,
- description: `${oldValue.name} was removed from enum type ${
- oldType.name
- }.`,
+ description: `${oldValue.name} was removed from enum type ${oldType.name}.`,
});
}
@@ -389,9 +385,7 @@ function findArgChanges(
for (const oldArg of argsDiff.removed) {
schemaChanges.push({
type: BreakingChangeType.ARG_REMOVED,
- description: `${oldType.name}.${oldField.name} arg ${
- oldArg.name
- } was removed.`,
+ description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`,
});
}
diff --git a/yarn.lock b/yarn.lock
index <HASH>..<HASH> 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2141,10 +2141,10 @@ prettier-linter-helpers@^1.0.0:
dependencies:
fast-diff "^1.1.2"
[email protected]:
- version "1.17.1"
- resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.17.1.tgz#ed64b4e93e370cb8a25b9ef7fef3e4fd1c0995db"
- integrity sha512-TzGRNvuUSmPgwivDqkZ9tM/qTGW9hqDKWOE9YHiyQdixlKbv7kvEqsmDPrcHJTKwthU774TQwZXVtaQ/mMsvjg==
[email protected]:
+ version "1.18.0"
+ resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.18.0.tgz#d1701ca9b2941864b52f3262b35946d2c9cd88f0"
+ integrity sha512-YsdAD29M0+WY2xXZk3i0PA16olY9qZss+AuODxglXcJ+2ZBwFv+6k5tE8GS8/HKAthaajlS/WqhdgcjumOrPlg==
private@^0.1.6:
version "0.1.8" | Update prettier to <I> (#<I>) | graphql_graphql-js | train |
6e945ba5da1e8874029b1560a97c69596638bed0 | diff --git a/spec/ebay_trading/fetch_token_spec.rb b/spec/ebay_trading/fetch_token_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/ebay_trading/fetch_token_spec.rb
+++ b/spec/ebay_trading/fetch_token_spec.rb
@@ -44,9 +44,20 @@ describe FetchToken do
if interactive
puts 'Launching system browser...'
- puts "You now have #{login_delay} seconds to MANUALLY log in and grant application access"
+ puts "You now have #{login_delay} seconds to MANUALLY log in and click 'I agree' to grant application access..."
+ puts
+ puts session_id.sign_in_url
+ puts
+
+ case RUBY_PLATFORM
+ when /linux|arch|sunos|solaris/i
+ system('xdg-open', session_id.sign_in_url)
+ when /darwin/i
+ system('open', session_id.sign_in_url)
+ when /mswin|cygwin|mingw|windows/i
+ system("start #{session_id.sign_in_url}")
+ end
- system('open', session_id.sign_in_url)
sleep(login_delay)
token = FetchToken.new(session_id) | Launch OS specific system browser in fetch_token_spec. | altabyte_ebay_trader | train |
ccc86648c7ee7361ff8442088951e06ddfc0fe54 | diff --git a/lib/odba.rb b/lib/odba.rb
index <HASH>..<HASH> 100644
--- a/lib/odba.rb
+++ b/lib/odba.rb
@@ -11,5 +11,5 @@ require 'odba/index'
require 'odba/odba'
class Odba
- VERSION = '1.0.0'
+ VERSION = '1.0.1'
end | Updated gem Version to <I> | zdavatz_odba | train |
ed7f40e63588eaa7c3e80703aa1d73da1a8476e0 | diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java b/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java
index <HASH>..<HASH> 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java
@@ -172,12 +172,12 @@ public final class ObservableCallAdapterFactory implements CallAdapter.Factory {
return Observable.create(new CallOnSubscribe<>(call)) //
.map(new Func1<Response<T>, Result<T>>() {
@Override public Result<T> call(Response<T> response) {
- return Result.fromResponse(response);
+ return Result.response(response);
}
})
.onErrorReturn(new Func1<Throwable, Result<T>>() {
@Override public Result<T> call(Throwable throwable) {
- return Result.fromError(throwable);
+ return Result.error(throwable);
}
});
}
diff --git a/retrofit-adapters/rxjava/src/main/java/retrofit/Result.java b/retrofit-adapters/rxjava/src/main/java/retrofit/Result.java
index <HASH>..<HASH> 100644
--- a/retrofit-adapters/rxjava/src/main/java/retrofit/Result.java
+++ b/retrofit-adapters/rxjava/src/main/java/retrofit/Result.java
@@ -21,11 +21,11 @@ import static retrofit.Utils.checkNotNull;
/** The result of executing an HTTP request. */
public final class Result<T> {
- static <T> Result<T> fromError(Throwable error) {
+ public static <T> Result<T> error(Throwable error) {
return new Result<>(null, checkNotNull(error, "error == null"));
}
- static <T> Result<T> fromResponse(Response<T> response) {
+ public static <T> Result<T> response(Response<T> response) {
return new Result<>(checkNotNull(response, "response == null"), null);
}
diff --git a/retrofit-adapters/rxjava/src/test/java/retrofit/ResultTest.java b/retrofit-adapters/rxjava/src/test/java/retrofit/ResultTest.java
index <HASH>..<HASH> 100644
--- a/retrofit-adapters/rxjava/src/test/java/retrofit/ResultTest.java
+++ b/retrofit-adapters/rxjava/src/test/java/retrofit/ResultTest.java
@@ -24,7 +24,7 @@ import static org.junit.Assert.fail;
public final class ResultTest {
@Test public void response() {
Response<String> response = Response.success("Hi");
- Result<String> result = Result.fromResponse(response);
+ Result<String> result = Result.response(response);
assertThat(result.isError()).isFalse();
assertThat(result.error()).isNull();
assertThat(result.response()).isSameAs(response);
@@ -32,7 +32,7 @@ public final class ResultTest {
@Test public void nullResponseThrows() {
try {
- Result.fromResponse(null);
+ Result.response(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("response == null");
@@ -41,7 +41,7 @@ public final class ResultTest {
@Test public void error() {
Throwable error = new IOException();
- Result<Object> result = Result.fromError(error);
+ Result<Object> result = Result.error(error);
assertThat(result.isError()).isTrue();
assertThat(result.error()).isSameAs(error);
assertThat(result.response()).isNull();
@@ -49,7 +49,7 @@ public final class ResultTest {
@Test public void nullErrorThrows() {
try {
- Result.fromError(null);
+ Result.error(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("error == null"); | Make Result's factory methods public. | square_retrofit | train |
a053863fe08bea32941c472bc007a9a428266647 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -11,6 +11,14 @@ function Pager (pageSize, opts) {
}
Pager.prototype.updated = function (page) {
+ while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) {
+ page.deduplicate++
+ if (page.deduplicate === this.deduplicate.length) {
+ page.deduplicate = 0
+ if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate
+ break
+ }
+ }
if (page.updated || !this.updates) return
page.updated = true
this.updates.push(page)
@@ -38,6 +46,7 @@ Pager.prototype.get = function (i, noAllocate) {
if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) {
page.buffer = copy(page.buffer)
+ page.deduplicate = 0
}
return page
@@ -109,4 +118,5 @@ function Page (i, buf) {
this.offset = i * buf.length
this.buffer = buf
this.updated = false
+ this.deduplicate = 0
} | dedup when updated is run as well | mafintosh_memory-pager | train |
4d26d3470dcf835f45ddbb91ee03e18972a3a7fd | diff --git a/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java b/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java
+++ b/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java
@@ -450,10 +450,6 @@ public class SeleniumServer {
postResultsHandler.addListener(listener);
}
- public String doCommand(String cmd, Vector values, String sessionId) {
- return driver.doCommand(cmd, values, sessionId, null);
- }
-
/** Starts the Jetty server */
public void start() throws Exception {
server.start(); | cruft removal
r<I> | SeleniumHQ_selenium | train |
89b78178f9409c5dcae741ef7935984bebf6604e | diff --git a/lib/cnapi.js b/lib/cnapi.js
index <HASH>..<HASH> 100644
--- a/lib/cnapi.js
+++ b/lib/cnapi.js
@@ -240,4 +240,29 @@ CNAPI.prototype.deleteVm = function (server, uuid, callback) {
+/**
+ * Runs a command on the specified server. The optional 'params' argument can
+ * contain two fields:
+ *
+ * @param {Array} args Array containing arguments to be passed in to command
+ * @param {Object} env Object containing environment variables to be passed in
+ */
+function commandExecute(server, script, params, callback) {
+ if (!server)
+ throw new TypeError('Server UUID is required');
+ if (!script)
+ throw new TypeError('Script is required');
+
+ if (arguments.length === 3) {
+ callback = params;
+ params = {};
+ }
+
+ params.script = script;
+
+ return this.post('/servers/' + server + '/execute', params, callback);
+}
+
+CNAPI.prototype.commandExecute = commandExecute;
+
module.exports = CNAPI;
diff --git a/test/cnapi.test.js b/test/cnapi.test.js
index <HASH>..<HASH> 100644
--- a/test/cnapi.test.js
+++ b/test/cnapi.test.js
@@ -206,3 +206,22 @@ exports.test_wait_for_deleted = function (test) {
test.done();
});
};
+
+exports.test_command_execute = function (test) {
+ var script = '#!/usr/bin/bash\n\necho Hello\n';
+
+ cnapi.commandExecute(SERVER, script, function (err) {
+ test.ifError(err);
+ test.done();
+ });
+};
+
+exports.test_command_execute_with_env = function (test) {
+ var script = '#!/usr/bin/bash\n\necho Hello\n';
+ var env = { FOO: 'bar' };
+
+ cnapi.commandExecute(SERVER, script, { env: env }, function (err) {
+ test.ifError(err);
+ test.done();
+ });
+}; | CNAPI-<I> CommandExecute method needed in CNAPI client | joyent_node-sdc-clients | train |
4bf3749a54311cc1a7ac460d7009e3dd8f0eebd5 | diff --git a/text-serializer-legacy/src/main/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerImpl.java b/text-serializer-legacy/src/main/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerImpl.java
index <HASH>..<HASH> 100644
--- a/text-serializer-legacy/src/main/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerImpl.java
+++ b/text-serializer-legacy/src/main/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerImpl.java
@@ -190,7 +190,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
current = TextComponent.builder();
}
- reset |= applyFormat(current, decoded.format);
+ if(!reset) {
+ reset = applyFormat(current, decoded.format);
+ }
if(decoded.encodedFormat == FormatCodeType.BUNGEECORD_UNUSUAL_HEX) {
// BungeeCord hex characters are a repeating set of characters, all of which are also valid
// legacy Mojang chat colors. Subtract the number of characters in the format, and only then
@@ -231,11 +233,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
builder.decoration((TextDecoration) format, TextDecoration.State.TRUE);
return false;
} else if(format instanceof Reset) {
- builder.colorIfAbsent(null);
- for(int i = 0, length = DECORATIONS.length; i < length; i++) {
- final TextDecoration decoration = DECORATIONS[i];
- builder.decoration(decoration, TextDecoration.State.NOT_SET);
- }
return true;
}
throw new IllegalArgumentException(String.format("unknown format '%s'", format.getClass()));
diff --git a/text-serializer-legacy/src/test/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerTest.java b/text-serializer-legacy/src/test/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerTest.java
index <HASH>..<HASH> 100644
--- a/text-serializer-legacy/src/test/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerTest.java
+++ b/text-serializer-legacy/src/test/java/net/kyori/adventure/text/serializer/legacy/LegacyComponentSerializerTest.java
@@ -208,9 +208,9 @@ class LegacyComponentSerializerTest {
assertEquals(expected, LegacyComponentSerializer.builder().hexColors().build().deserialize("§x§eKittens!"));
}
+ // https://github.com/KyoriPowered/adventure/issues/108
@Test
void testFromLegacyWithNewline() {
- // https://github.com/KyoriPowered/adventure/issues/108
final TextComponent comp = TextComponent.builder("One: Test ")
.append(TextComponent.of("String\nTwo: ", NamedTextColor.GREEN))
.append(TextComponent.of("Test ", NamedTextColor.AQUA))
@@ -220,9 +220,9 @@ class LegacyComponentSerializerTest {
assertEquals(comp, LegacyComponentSerializer.legacy('&').deserialize(in));
}
+ // https://github.com/KyoriPowered/adventure/issues/108
@Test
void testBeginningTextUnformatted() {
- // https://github.com/KyoriPowered/adventure/issues/108
final String input = "Test &cString";
final TextComponent expected = TextComponent.builder("Test ")
.append(TextComponent.of("String", NamedTextColor.RED))
@@ -230,4 +230,23 @@ class LegacyComponentSerializerTest {
assertEquals(expected, LegacyComponentSerializer.legacy(LegacyComponentSerializer.AMPERSAND_CHAR).deserialize(input));
}
+
+ // https://github.com/KyoriPowered/adventure/issues/92
+ @Test
+ void testStackedFormattingFlags() {
+ final String input = "§r§r§c§k||§e§lProfile§c§k||";
+ final TextComponent output = TextComponent.builder().append(
+ TextComponent.of("||", Style.of(NamedTextColor.RED, TextDecoration.OBFUSCATED)),
+ TextComponent.of("Profile", Style.of(NamedTextColor.YELLOW, TextDecoration.BOLD)),
+ TextComponent.of("||", Style.of(NamedTextColor.RED, TextDecoration.OBFUSCATED))
+ ).build();
+ assertEquals(output, LegacyComponentSerializer.legacy().deserialize(input));
+ }
+
+ @Test
+ void testResetClearsColorInSameBlock() {
+ final String input = "§c§rCleared";
+ final TextComponent output = TextComponent.of("Cleared");
+ assertEquals(output, LegacyComponentSerializer.legacy().deserialize(input));
+ }
} | Correctly handle resets followed by more styling
Fixes #<I> | KyoriPowered_text | train |
3b403fda1480fef93db3fbc8a8bc3dce8f2d3ad7 | diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/GroupingOperationRewriter.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/GroupingOperationRewriter.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/planner/GroupingOperationRewriter.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/GroupingOperationRewriter.java
@@ -13,7 +13,6 @@
*/
package com.facebook.presto.sql.planner;
-import com.facebook.presto.sql.analyzer.Analysis;
import com.facebook.presto.sql.analyzer.FieldId;
import com.facebook.presto.sql.analyzer.RelationId;
import com.facebook.presto.sql.tree.ArithmeticBinaryExpression;
@@ -23,7 +22,6 @@ import com.facebook.presto.sql.tree.GenericLiteral;
import com.facebook.presto.sql.tree.GroupingOperation;
import com.facebook.presto.sql.tree.LongLiteral;
import com.facebook.presto.sql.tree.NodeRef;
-import com.facebook.presto.sql.tree.QuerySpecification;
import com.facebook.presto.sql.tree.SubscriptExpression;
import java.util.List;
@@ -40,26 +38,21 @@ public final class GroupingOperationRewriter
{
private GroupingOperationRewriter() {}
- public static Expression rewriteGroupingOperation(GroupingOperation expression, QuerySpecification queryNode, Analysis analysis, Optional<Symbol> groupIdSymbol)
+ public static Expression rewriteGroupingOperation(GroupingOperation expression, List<List<Expression>> groupingSets, Map<NodeRef<Expression>, FieldId> columnReferenceFields, Optional<Symbol> groupIdSymbol)
{
- requireNonNull(queryNode, "node is null");
- requireNonNull(analysis, "analysis is null");
requireNonNull(groupIdSymbol, "groupIdSymbol is null");
- checkState(queryNode.getGroupBy().isPresent(), "GroupBy node must be present");
-
// No GroupIdNode and a GROUPING() operation imply a single grouping, which
// means that any columns specified as arguments to GROUPING() will be included
// in the group and none of them will be aggregated over. Hence, re-write the
// GroupingOperation to a constant literal of 0.
// See SQL:2011:4.16.2 and SQL:2011:6.9.10.
- if (analysis.getGroupingSets(queryNode).size() == 1) {
+ if (groupingSets.size() == 1) {
return new LongLiteral("0");
}
else {
checkState(groupIdSymbol.isPresent(), "groupId symbol is missing");
- Map<NodeRef<Expression>, FieldId> columnReferenceFields = analysis.getColumnReferenceFields();
RelationId relationId = columnReferenceFields.get(NodeRef.of(expression.getGroupingColumns().get(0))).getRelationId();
List<Integer> columns = expression.getGroupingColumns().stream()
@@ -69,7 +62,7 @@ public final class GroupingOperationRewriter
.map(fieldId -> translateFieldToInteger(fieldId, relationId))
.collect(toImmutableList());
- List<List<Integer>> groupingSetDescriptors = analysis.getGroupingSets(queryNode).stream()
+ List<List<Integer>> groupingSetDescriptors = groupingSets.stream()
.map(groupingSet -> groupingSet.stream()
.map(NodeRef::of)
.filter(columnReferenceFields::containsKey)
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java
@@ -571,7 +571,7 @@ class QueryPlanner
projections.putIdentities(subPlan.getRoot().getOutputSymbols());
for (GroupingOperation groupingOperation : analysis.getGroupingOperations(node)) {
- Expression rewritten = GroupingOperationRewriter.rewriteGroupingOperation(groupingOperation, node, analysis, groupIdSymbol);
+ Expression rewritten = GroupingOperationRewriter.rewriteGroupingOperation(groupingOperation, analysis.getGroupingSets(node), analysis.getColumnReferenceFields(), groupIdSymbol);
Type coercion = analysis.getCoercion(groupingOperation);
Symbol symbol = symbolAllocator.newSymbol(rewritten, analysis.getTypeWithCoercions(groupingOperation));
if (coercion != null) { | Generalize grouping set rewriter
Break its dependency on Analysis and QuerySpecification node by passing
the required data directly. This is to prepare for the split between AST -> IR,
which requires getting rid of expression rewriters (AST -> AST) during planning
and replace them with AST -> IR translations. | prestodb_presto | train |
ffd883bb133438aaa10bfd11b75303a76cc238c4 | diff --git a/lib/reda/importers/eit_version_2013.py b/lib/reda/importers/eit_version_2013.py
index <HASH>..<HASH> 100644
--- a/lib/reda/importers/eit_version_2013.py
+++ b/lib/reda/importers/eit_version_2013.py
@@ -6,6 +6,7 @@ from reda.importers.eit_version_2010 import _average_swapped_current_injections
def _extract_md(mat, **kwargs):
+ return
md = mat['MD'].squeeze()
# Labview epoch
epoch = datetime.datetime(1904, 1, 1) | [eit fzj <I>] don't try to import md data for now | geophysics-ubonn_reda | train |
0c0c7b5f64b468d2c96fc04b0c160a22a2775961 | diff --git a/channel.go b/channel.go
index <HASH>..<HASH> 100644
--- a/channel.go
+++ b/channel.go
@@ -204,6 +204,12 @@ func (ch *Channel) ListenAndServe(hostPort string) error {
return ch.Serve(l)
}
+// Registrar is the base interface for registering handlers on either the base
+// Channel or the SubChannel
+type Registrar interface {
+ Register(h Handler, operationName string)
+}
+
// Register registers a handler for a service+operation pair
func (ch *Channel) Register(h Handler, operationName string) {
ch.handlers.register(h, ch.PeerInfo().ServiceName, operationName)
@@ -234,16 +240,7 @@ func (ch *Channel) createCommonStats() {
// GetSubChannel returns a SubChannel for the given service name. If the subchannel does not
// exist, it is created.
func (ch *Channel) GetSubChannel(serviceName string) *SubChannel {
- subChMap := ch.subChannels
- subChMap.mut.RLock()
-
- if sc, ok := subChMap.subchannels[serviceName]; ok {
- subChMap.mut.RUnlock()
- return sc
- }
-
- subChMap.mut.RUnlock()
- return subChMap.registerNewSubChannel(serviceName, ch)
+ return ch.subChannels.getOrAdd(serviceName, ch)
}
// Peers returns the PeerList for the channel.
diff --git a/examples/ping/main.go b/examples/ping/main.go
index <HASH>..<HASH> 100644
--- a/examples/ping/main.go
+++ b/examples/ping/main.go
@@ -103,7 +103,7 @@ func main() {
subCh := ch.GetSubChannel("PingServiceOther")
// Register a handler on the subchannel
- json.RegisterSub(subCh, json.Handlers{
+ json.Register(subCh, json.Handlers{
"pingOther": pingOtherHandler,
}, onError)
diff --git a/json/handler.go b/json/handler.go
index <HASH>..<HASH> 100644
--- a/json/handler.go
+++ b/json/handler.go
@@ -90,7 +90,7 @@ func toHandler(f interface{}) (*handler, error) {
// Register registers the specified methods specified as a map from method name to the
// JSON handler function. The handler functions should have the following signature:
// func(context.Context, *ArgType)(*ResType, error)
-func Register(ch *tchannel.Channel, funcs Handlers, onError func(context.Context, error)) error {
+func Register(registrar tchannel.Registrar, funcs Handlers, onError func(context.Context, error)) error {
handlers := make(map[string]*handler)
handler := tchannel.HandlerFunc(func(ctx context.Context, call *tchannel.InboundCall) {
@@ -111,34 +111,7 @@ func Register(ch *tchannel.Channel, funcs Handlers, onError func(context.Context
return fmt.Errorf("%v cannot be used as a handler: %v", m, err)
}
handlers[m] = h
- ch.Register(handler, m)
- }
-
- return nil
-}
-
-func RegisterSub(ch *tchannel.SubChannel, funcs Handlers, onError func(context.Context, error)) error {
- handlers := make(map[string]*handler)
-
- handler := tchannel.HandlerFunc(func(ctx context.Context, call *tchannel.InboundCall) {
- h, ok := handlers[string(call.Operation())]
- if !ok {
- onError(ctx, fmt.Errorf("call for unregistered method: %s", call.Operation()))
- return
- }
-
- if err := h.Handle(ctx, call); err != nil {
- onError(ctx, err)
- }
- })
-
- for m, f := range funcs {
- h, err := toHandler(f)
- if err != nil {
- return fmt.Errorf("%v cannot be used as a handler: %v", m, err)
- }
- handlers[m] = h
- ch.Register(handler, m)
+ registrar.Register(handler, m)
}
return nil
diff --git a/subchannel.go b/subchannel.go
index <HASH>..<HASH> 100644
--- a/subchannel.go
+++ b/subchannel.go
@@ -59,14 +59,10 @@ func (c *SubChannel) Register(h Handler, operationName string) {
// Find if a handler for the given service+operation pair exists
func (subChMap *subChannelMap) find(serviceName string, operation []byte) Handler {
- subChMap.mut.RLock()
-
- if sc, ok := subChMap.subchannels[serviceName]; ok {
- subChMap.mut.RUnlock()
+ if sc, ok := subChMap.get(serviceName); ok {
return sc.handlers.find(serviceName, operation)
}
- subChMap.mut.RUnlock()
return nil
}
@@ -87,3 +83,20 @@ func (subChMap *subChannelMap) registerNewSubChannel(serviceName string, ch *Cha
subChMap.subchannels[serviceName] = sc
return sc
}
+
+// Get subchannel if, we have one
+func (subChMap *subChannelMap) get(serviceName string) (*SubChannel, bool) {
+ subChMap.mut.RLock()
+ sc, ok := subChMap.subchannels[serviceName]
+ subChMap.mut.RUnlock()
+ return sc, ok
+}
+
+// GetOrAdd a subchannel for the given serviceName on the map
+func (subChMap *subChannelMap) getOrAdd(serviceName string, ch *Channel) *SubChannel {
+ if sc, ok := subChMap.get(serviceName); ok {
+ return sc
+ }
+
+ return subChMap.registerNewSubChannel(serviceName, ch)
+} | Address PR feedback
* Move the logic of GetSubChannel() inside subChannelMap
* Utilize getSubchannel() finding handler within subchannel
* Remove code duplication by using a Registrar interface | uber_tchannel-go | train |
e9af9bb095008c09140c3178cb5df46db2acefd0 | diff --git a/Socks/Server.php b/Socks/Server.php
index <HASH>..<HASH> 100644
--- a/Socks/Server.php
+++ b/Socks/Server.php
@@ -73,6 +73,8 @@ class Server extends SocketServer
return $reader->readByte()->then(function ($version) use ($stream, $that){
if ($version === 0x04) {
return $that->handleSocks4($stream);
+ } else if ($version === 0x05) {
+ return $that->handleSocks5($stream);
}
throw new UnexpectedValueException('Unexpected version number');
});
@@ -126,15 +128,91 @@ class Server extends SocketServer
});
}
+ public function handleSocks5(Stream $stream)
+ {
+ $reader = new StreamReader($stream);
+ $that = $this;
+ return $reader->readByte()->then(function ($num) use ($reader) {
+ // $num different authentication mechanisms offered
+ return $reader->readLength($num);
+ })->then(function ($methods) use ($reader, $stream) {
+ if (strpos($methods,"\x00") !== false) {
+ // accept "no authentication"
+ $stream->write(pack('C2', 0x05, 0x00));
+ return 0x00;
+ } else if (false) {
+ // TODO: support username/password authentication (0x01)
+ } else {
+ // reject all offered authentication methods
+ $stream->end(pack('C2', 0x05, 0xFF));
+ throw new UnexpectedValueException('No acceptable authentication mechanism found');
+ }
+ })->then(function ($method) use ($reader, $stream) {
+ $stream->emit('authenticate',array($method));
+ return $reader->readBinary(array(
+ 'version' => 'C',
+ 'command' => 'C',
+ 'null' => 'C',
+ 'type' => 'C'
+ ));
+ })->then(function ($data) use ($reader) {
+ if ($data['version'] !== 0x05) {
+ throw new UnexpectedValueException('Invalid SOCKS version');
+ }
+ if ($data['command'] !== 0x01) {
+ throw new UnexpectedValueException('Only CONNECT requests supported');
+ }
+// if ($data['null'] !== 0x00) {
+// throw new UnexpectedValueException('Reserved byte has to be NULL');
+// }
+ if ($data['type'] === 0x03) {
+ // target hostname string
+ return $reader->readByte()->then(function ($len) use ($reader) {
+ return $reader->readLength($len);
+ });
+ } else if ($data['type'] === 0x01) {
+ // target IPv4
+ return $reader->readLength(4)->then(function ($addr) {
+ return inet_ntop($addr);
+ });
+ } else if ($data['type'] === 0x04) {
+ // target IPv6
+ return $reader->readLength(16)->then(function ($addr) {
+ return inet_ntop($addr);
+ });
+ } else {
+ throw new UnexpectedValueException('Invalid target type');
+ }
+ })->then(function ($host) use ($reader) {
+ return $reader->readBinary(array('port'=>'n'))->then(function ($data) use ($host) {
+ return array($host, $data['port']);
+ });
+ })->then(function ($target) use ($that, $stream) {
+ return $that->connectTarget($stream, $target);
+ }, function($error) use ($stream) {
+ throw new UnexpectedValueException('SOCKS5 protocol error',0,$error);
+ })->then(function ($remote) use ($stream) {
+ $stream->write(pack('C4Nn', 0x05, 0x00, 0x00, 0x01, 0, 0));
+
+ $stream->pipe($remote);
+ $remote->pipe($stream);
+ }, function($error) use ($stream){
+ $code = 0x01;
+ $stream->write(pack('C4Nn', 0x05, $code, 0x00, 0x01, 0, 0));
+ $stream->end();
+ throw new UnexpectedValueException('Unable to connect to remote target', 0, $error);
+ });
+ }
+
public function connectTarget(Stream $stream, $target)
{
- $stream->emit('target',$target);
- return $this->connectionManager->getConnection($target[0], $target[1])->then(function ($remote) use ($stream) {
- if (!$stream->isWritable()) {
- $remote->close();
- throw new UnexpectedValueException('Remote connection successfully established after client connection closed');
- }
- return $remote;
- });
+ $stream->emit('target',$target);
+ return $this->connectionManager->getConnection($target[0], $target[1])->then(function ($remote) use ($stream) {
+ if (!$stream->isWritable()) {
+ $remote->close();
+ throw new UnexpectedValueException('Remote connection successfully established after client connection closed');
+ }
+ return $remote;
+ });
}
} | Add support for SOCKS5 protocol | clue_php-socks | train |
8e0f7484c37c5d1a02ab0e1b33f8505f93312a74 | diff --git a/storage/storage_transport.go b/storage/storage_transport.go
index <HASH>..<HASH> 100644
--- a/storage/storage_transport.go
+++ b/storage/storage_transport.go
@@ -73,11 +73,11 @@ func (s storageTransport) ParseStoreReference(store storage.Store, ref string) (
}
if ref[0] == '[' {
// Ignore the store specifier.
- close := strings.IndexRune(ref, ']')
- if close < 1 {
+ closeIndex := strings.IndexRune(ref, ']')
+ if closeIndex < 1 {
return nil, ErrInvalidReference
}
- ref = ref[close+1:]
+ ref = ref[closeIndex+1:]
}
refInfo := strings.SplitN(ref, "@", 2)
if len(refInfo) == 1 {
@@ -152,12 +152,12 @@ func (s *storageTransport) ParseReference(reference string) (types.ImageReferenc
// storage.GetStore(), or be enough to let the storage library fill out
// the rest using knowledge that it has from elsewhere.
if reference[0] == '[' {
- close := strings.IndexRune(reference, ']')
- if close < 1 {
+ closeIndex := strings.IndexRune(reference, ']')
+ if closeIndex < 1 {
return nil, ErrInvalidReference
}
- storeSpec := reference[1:close]
- reference = reference[close+1:]
+ storeSpec := reference[1:closeIndex]
+ reference = reference[closeIndex+1:]
storeInfo := strings.SplitN(storeSpec, "@", 2)
if len(storeInfo) == 1 && storeInfo[0] != "" {
// One component: the graph root.
@@ -225,12 +225,12 @@ func (s storageTransport) ValidatePolicyConfigurationScope(scope string) error {
return ErrInvalidReference
}
// Parse the store location prefix.
- close := strings.IndexRune(scope, ']')
- if close < 1 {
+ closeIndex := strings.IndexRune(scope, ']')
+ if closeIndex < 1 {
return ErrInvalidReference
}
- storeSpec := scope[1:close]
- scope = scope[close+1:]
+ storeSpec := scope[1:closeIndex]
+ scope = scope[closeIndex+1:]
storeInfo := strings.SplitN(storeSpec, "@", 2)
if len(storeInfo) == 1 && storeInfo[0] != "" {
// One component: the graph root. | Avoid using builtin "close" as a variable name
Don't use the name of a builtin ("close") as a variable name. | containers_image | train |
3eee3bf881e174187edb3d675e31adc3b4a702e8 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,7 @@
# ActFramework Change Log
**1.8.8**
+* @On(async = true) not work #611
* Issue with global URL context setting #614
* Date format not applied when returned type is `DateTime[]` #610
* DateTime return result not formatted as configured #604
diff --git a/src/main/java/act/event/EventBus.java b/src/main/java/act/event/EventBus.java
index <HASH>..<HASH> 100644
--- a/src/main/java/act/event/EventBus.java
+++ b/src/main/java/act/event/EventBus.java
@@ -36,8 +36,6 @@ import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.S;
-import javax.enterprise.context.ApplicationScoped;
-import javax.inject.Inject;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Modifier;
@@ -45,6 +43,8 @@ import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
/**
* The event bus manages event binding and distribution.
@@ -54,7 +54,6 @@ public class EventBus extends AppServiceBase<EventBus> {
// The key to index adhoc event listeners
private static class Key {
- private static Logger logger = LogManager.get(EventBus.class);
private enum IdType {
STRING, ENUM, CLASS
}
diff --git a/src/main/java/act/event/bytecode/ReflectedSimpleEventListener.java b/src/main/java/act/event/bytecode/ReflectedSimpleEventListener.java
index <HASH>..<HASH> 100644
--- a/src/main/java/act/event/bytecode/ReflectedSimpleEventListener.java
+++ b/src/main/java/act/event/bytecode/ReflectedSimpleEventListener.java
@@ -47,7 +47,7 @@ public class ReflectedSimpleEventListener implements SimpleEventListener {
private final boolean isStatic;
private final boolean isAsync;
- ReflectedSimpleEventListener(String className, String methodName, List<BeanSpec> paramTypes, boolean isStatic) {
+ ReflectedSimpleEventListener(String className, String methodName, List<BeanSpec> paramTypes, boolean isStatic, boolean isAsync) {
this.isStatic = isStatic;
this.paramTypes = C.newList();
this.providedParamTypes = C.newList();
@@ -77,7 +77,7 @@ public class ReflectedSimpleEventListener implements SimpleEventListener {
}
this.hostClass = Act.app().classForName(className);
this.method = $.getMethod(hostClass, methodName, argList);
- this.isAsync = EventBus.isAsync(hostClass) || EventBus.isAsync(method);
+ this.isAsync = isAsync || EventBus.isAsync(hostClass) || EventBus.isAsync(method);
}
@Override
diff --git a/src/main/java/act/event/bytecode/SimpleEventListenerByteCodeScanner.java b/src/main/java/act/event/bytecode/SimpleEventListenerByteCodeScanner.java
index <HASH>..<HASH> 100644
--- a/src/main/java/act/event/bytecode/SimpleEventListenerByteCodeScanner.java
+++ b/src/main/java/act/event/bytecode/SimpleEventListenerByteCodeScanner.java
@@ -71,7 +71,7 @@ public class SimpleEventListenerByteCodeScanner extends AppByteCodeScannerBase {
public void run() {
for (final Object event : metaInfo.events()) {
final boolean isStatic = metaInfo.isStatic();
- eventBus.bind(event, new ReflectedSimpleEventListener(metaInfo.className(), metaInfo.methodName(), metaInfo.paramTypes(), isStatic));
+ eventBus.bind(event, new ReflectedSimpleEventListener(metaInfo.className(), metaInfo.methodName(), metaInfo.paramTypes(), isStatic, metaInfo.isAsync()));
}
}
}); | fix @On(async = true) not work #<I> | actframework_actframework | train |
7648bcd88966a3fd48dab8b0a43ad1b6dde7a331 | diff --git a/lib/rufus/sc/jobs.rb b/lib/rufus/sc/jobs.rb
index <HASH>..<HASH> 100644
--- a/lib/rufus/sc/jobs.rb
+++ b/lib/rufus/sc/jobs.rb
@@ -370,6 +370,7 @@ module Scheduler
else
Rufus.parse_duration_string(@t)
end
+ raise ArgumentError.new("cannot initialize an EveryJob with a 0.0 frequency") if @frequency == 0.0
end
def determine_at | Raise ArgumentError when creating an EveryJob with <I> frequency. | jmettraux_rufus-scheduler | train |
54be23aeb72bac1bc6de9cd0ca85814463b944c9 | diff --git a/lave.js b/lave.js
index <HASH>..<HASH> 100644
--- a/lave.js
+++ b/lave.js
@@ -47,6 +47,13 @@ function isNativeFunction(fn) {
return length === source.length
}
+function Identifiers() { this.id = 0 }
+Identifiers.prototype.next = function() {
+ var id = (this.id++).toString(36)
+ try { Function(`var ${id}`); return id }
+ catch (e) { return this.next() }
+}
+
export default function(value, options) {
if (!options) options = {}
@@ -119,9 +126,10 @@ export default function(value, options) {
return {type: 'VariableDeclarator', id, init: entry[0]}
})
+ let ids = new Identifiers
declarations
.sort((a, b) => has(a.init, b.id) - has(b.init, a.id))
- .forEach((declaration, i) => declaration.id.name = '$' + i)
+ .forEach(declaration => declaration.id.name = ids.next())
return declarations
}
diff --git a/test.js b/test.js
index <HASH>..<HASH> 100755
--- a/test.js
+++ b/test.js
@@ -4,7 +4,7 @@
const equal = require('assert').equal
const generate = require('escodegen').generate
-const lave = require('..')
+const lave = require('.')
const format = {compact: true, semicolons: false}
const options = {generate: ast => generate(ast, {format})}
@@ -30,8 +30,8 @@ const tests = {
sparse: [ Array(10) , `${g}.Array(10)` ],
global: [ (0,eval)('this') , g ],
slice: [ [].slice , `${g}.Array.prototype.slice` ],
- cycle: [ (o=>o[0]=o)([]) , `const $0=[null];$0[0]=$0;$0` ],
- dipole: [ (o=>[o,o])({}) , 'const $0={};[$0,$0]' ]
+ cycle: [ (o=>o[0]=o)([]) , `const a=[null];a[0]=a;a` ],
+ dipole: [ (o=>[o,o])({}) , `const a={};[a,a]` ]
}
for (let i in tests) equal(s(tests[i][0]), tests[i][1], ` | find shortest <I>-radix ids | jed_lave | train |
add60c3e54f569299bd09ae1f532b468a1297338 | diff --git a/src/PHPMailer.php b/src/PHPMailer.php
index <HASH>..<HASH> 100644
--- a/src/PHPMailer.php
+++ b/src/PHPMailer.php
@@ -2372,16 +2372,18 @@ class PHPMailer
*/
protected function generateId()
{
- $len = 23;
+ $len = 32; //32 bytes = 256 bits
if (function_exists('random_bytes')) {
$bytes = random_bytes($len);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($len);
} else {
- $bytes = uniqid((string) mt_rand(), true);
+ //Use a hash to force the length to the same as the other methods
+ $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
}
- return hash('sha256', $bytes);
+ //We don't care about messing up base64 format here, just want a random string
+ return str_replace(['=','+','/'], '', base64_encode(hash('sha256', $bytes, true)));
}
/** | Generate shorter IDs (with more entropy) to work around iCloud RFC non-compliance, fixes #<I> | PHPMailer_PHPMailer | train |
2c9b54823c06da9901883ed950409af6336d2d74 | diff --git a/client/cmd/cas/lib/download.go b/client/cmd/cas/lib/download.go
index <HASH>..<HASH> 100644
--- a/client/cmd/cas/lib/download.go
+++ b/client/cmd/cas/lib/download.go
@@ -87,6 +87,28 @@ func (r *downloadRun) parse(a subcommands.Application, args []string) error {
return nil
}
+func createDirectories(outputs map[string]*client.TreeOutput) error {
+ dirs := make([]string, 0, len(outputs))
+ for path, output := range outputs {
+ if output.IsEmptyDirectory {
+ dirs = append(dirs, path)
+ } else {
+ dirs = append(dirs, filepath.Dir(path))
+ }
+ }
+ sort.Strings(dirs)
+
+ for i, dir := range dirs {
+ if i > 0 && dirs[i-1] == dir {
+ continue
+ }
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return errors.Annotate(err, "failed to create directory").Err()
+ }
+ }
+ return nil
+}
+
// doDownload downloads directory tree from the CAS server.
func (r *downloadRun) doDownload(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
@@ -137,32 +159,14 @@ func (r *downloadRun) doDownload(ctx context.Context) error {
defer diskcache.Close()
}
+ if err := createDirectories(outputs); err != nil {
+ return err
+ }
+
// Files have the same digest are downloaded only once, so we need to
// copy duplicates files later.
var dups []*client.TreeOutput
- {
- // Create directories in this scope.
- dirs := make([]string, 0, len(outputs))
- for path, output := range outputs {
- if output.IsEmptyDirectory {
- dirs = append(dirs, path)
- } else {
- dirs = append(dirs, filepath.Dir(path))
- }
- }
- sort.Strings(dirs)
-
- for i, dir := range dirs {
- if i > 0 && dirs[i-1] == dir {
- continue
- }
- if err := os.MkdirAll(dir, 0o700); err != nil {
- return errors.Annotate(err, "failed to create directory").Err()
- }
- }
- }
-
for path, output := range outputs {
if output.IsEmptyDirectory {
continue | [cas] extract directory creation to separated function
This is for
<URL> | luci_luci-go | train |
985a8f832f19d598afcfb9e4d87b8d54767c4965 | diff --git a/raiden/tests/smart_contracts/test_decoder_netting_channel.py b/raiden/tests/smart_contracts/test_decoder_netting_channel.py
index <HASH>..<HASH> 100644
--- a/raiden/tests/smart_contracts/test_decoder_netting_channel.py
+++ b/raiden/tests/smart_contracts/test_decoder_netting_channel.py
@@ -4,13 +4,10 @@ import os
from secp256k1 import PrivateKey
from ethereum import tester
from raiden.utils import sha3, privatekey_to_address
-from raiden.messages import DirectTransfer, MediatedTransfer, Lock
+from raiden.messages import DirectTransfer, Lock, MediatedTransfer, RefundTransfer
from raiden.encoding.signing import GLOBAL_CTX
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-PRIVKEY = 'x' * 32
-ADDRESS = privatekey_to_address(PRIVKEY)
-HASH = sha3(PRIVKEY)
def deploy_decoder_tester(asset_address, address1, address2, settle_timeout):
@@ -61,7 +58,7 @@ def test_decode_direct_transfer(
dtester = deploy_decoder_tester(tester_token.address, address0, address1, settle_timeout)
- locksroot = HASH
+ locksroot = sha3("Waldemarstr")
message = DirectTransfer(
identifier=1,
@@ -119,8 +116,49 @@ def test_decode_mediated_transfer(
assert dtester.testDecodeTransfer(message.encode()) is True
assert dtester.decodedNonce() == 88924902
- assert dtester.decodedExpiration() == 5
+ assert dtester.decodedExpiration() == expiration
assert dtester.decodedAsset() == tester_token.address.encode('hex')
assert dtester.decodedRecipient() == address1.encode('hex')
- assert dtester.decodedAmount() == 1337
+ assert dtester.decodedAmount() == amount
+ assert dtester.decodedLocksroot() == locksroot
+
+
+def test_decode_refund_transfer(
+ private_keys,
+ settle_timeout,
+ tester_state,
+ tester_token,
+ tester_events,
+ tester_registry):
+
+ privatekey0 = tester.DEFAULT_KEY
+ privatekey1 = private_keys[1]
+ address0 = privatekey_to_address(privatekey0)
+ address1 = privatekey_to_address(privatekey1)
+
+ dtester = deploy_decoder_tester(tester_token.address, address0, address1, settle_timeout)
+
+ locksroot = sha3("Mainz")
+ amount = 1337
+ expiration = 19
+ lock = Lock(amount, expiration, locksroot)
+
+ message = RefundTransfer(
+ identifier=321313,
+ nonce=4242452,
+ asset=tester_token.address,
+ transferred_amount=amount,
+ recipient=address1,
+ locksroot=locksroot,
+ lock=lock
+ )
+
+ message.sign(PrivateKey(privatekey0, ctx=GLOBAL_CTX, raw=True), address0)
+
+ assert dtester.testDecodeTransfer(message.encode()) is True
+ assert dtester.decodedNonce() == 4242452
+ assert dtester.decodedExpiration() == expiration
+ assert dtester.decodedAsset() == tester_token.address.encode('hex')
+ assert dtester.decodedRecipient() == address1.encode('hex')
+ assert dtester.decodedAmount() == amount
assert dtester.decodedLocksroot() == locksroot | Test for decoding of a RefundTransfer | raiden-network_raiden | train |
f1df5f74699a152d8dc2cac8e4dcf80a1523ca99 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,8 +1,8 @@
from distutils.core import setup
setup(name='dshelpers',
version='1.3.0',
- description="Provides some helper functions used by the ScraperWiki Data Services team.",
- long_description="Provides some helper functions used by the ScraperWiki Data Services team.",
+ description="Provides some helper functions used by The Sensible Code Company's Data Services team.",
+ long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.",
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
@@ -10,8 +10,8 @@ setup(name='dshelpers',
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
],
- author="ScraperWiki Limited",
- author_email='[email protected]',
+ author="The Sensible Code Company Limited",
+ author_email='[email protected]',
url='https://github.com/scraperwiki/data-services-helpers',
license='BSD', | Rename ScraperWiki to Sensible Code in README | scraperwiki_data-services-helpers | train |
ef3379a4800a47da4d5bcd5d68e637a47bc531a1 | diff --git a/lib/utils.js b/lib/utils.js
index <HASH>..<HASH> 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -151,7 +151,7 @@ module.exports = {
// by accident, eg: from calling values.map(utils.prepareValue)
return prepareValue(value)
},
- normalizeQueryConfig: normalizeQueryConfig,
- postgresMd5PasswordHash: postgresMd5PasswordHash,
- md5: md5
+ normalizeQueryConfig,
+ postgresMd5PasswordHash,
+ md5
} | Normalize export in utils to use short form | brianc_node-postgres | train |
f969fde27adb6a941085b655262010924110a90e | diff --git a/acceptancetests/assess_recovery.py b/acceptancetests/assess_recovery.py
index <HASH>..<HASH> 100755
--- a/acceptancetests/assess_recovery.py
+++ b/acceptancetests/assess_recovery.py
@@ -32,16 +32,6 @@ from utility import (
until_timeout,
)
-#
-# The following acceptance test has been modifed to remove the HA testing
-# strategy from the test. The CLI no longer supports the following:
-# - constraints when restoring a backup file
-# - HA backup and restore
-#
-# Once HA backup and restore are reinstanted in Juju, we should restore the
-# the HA nature of this acceptance test.
-#
-
__metaclass__ = type
running_instance_pattern = re.compile('\["([^"]+)"\]')
@@ -64,6 +54,15 @@ def deploy_stack(client, charm_series):
check_token(client, 'One')
log.info("%s is ready to testing", client.env.environment)
+def enable_ha(bs_manager, controller_client):
+ """Enable HA and wait for the controllers to be ready."""
+ log.info("Enabling HA.")
+ controller_client.enable_ha()
+ controller_client.wait_for_ha()
+ show_controller(controller_client)
+ remote_machines = get_remote_machines(
+ controller_client, bs_manager.known_hosts)
+ bs_manager.known_hosts = remote_machines
def show_controller(client):
controller_info = client.show_controller(format='yaml')
@@ -105,6 +104,9 @@ def parse_args(argv=None):
strategy.add_argument(
'--backup', action='store_const', dest='strategy', const='backup',
help="Test backup/restore.")
+ strategy.add_argument(
+ '--ha-backup', action='store_const', dest='strategy',
+ const='ha-backup', help="Test backup of HA.")
return parser.parse_args(argv)
@contextmanager
@@ -126,10 +128,19 @@ def assess_recovery(bs_manager, strategy, charm_series):
log.info("Test started.")
controller_client = client.get_controller_client()
- backup_file = controller_client.backup()
- create_tmp_model(client)
- restore_backup(bs_manager, controller_client, backup_file)
-
+ # ha-backup allows us to still backup in HA mode, so allow us to still
+ # create a cluster of controllers.
+ if strategy in ('ha-backup'):
+ enable_ha(bs_manager, controller_client)
+ backup_file = controller_client.backup()
+ # at the moment we can't currently restore a backup in HA without
+ # removing the controllers and replica set. This test will need to
+ # be fix to accommodate this setup.
+ else:
+ backup_file = controller_client.backup()
+ create_tmp_model(client)
+ restore_backup(bs_manager, controller_client, backup_file)
+
log.info("Test complete.")
def main(argv):
diff --git a/acceptancetests/jujupy/client.py b/acceptancetests/jujupy/client.py
index <HASH>..<HASH> 100644
--- a/acceptancetests/jujupy/client.py
+++ b/acceptancetests/jujupy/client.py
@@ -1603,11 +1603,6 @@ class ModelClient:
reporter = GroupReporter(sys.stdout, desired_state)
self._wait_for_status(reporter, status_to_ha, VotingNotEnabled,
timeout=timeout, start=start)
- # XXX sinzui 2014-12-04: bug 1399277 happens because
- # juju claims HA is ready when the monogo replica sets
- # are not. Juju is not fully usable. The replica set
- # lag might be 5 minutes.
- self._backend.pause(300)
def wait_for_deploy_started(self, service_count=1, timeout=1200):
"""Wait until service_count services are 'started'. | Enable HA backup
The following code allows HA backup, so that we can test that we
can still backup in HA mode. Currently you can't restore in HA
mode without first pulling machines out of the replicaset and
then allowing restoring.
The commit tests pulling out of HA mode so that we have a tar file
backup to do so. | juju_juju | train |
13316f6263acfa01073b418f8fc00eb06f9efce3 | diff --git a/src/frontend/org/voltdb/export/ExportDataSource.java b/src/frontend/org/voltdb/export/ExportDataSource.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/export/ExportDataSource.java
+++ b/src/frontend/org/voltdb/export/ExportDataSource.java
@@ -439,15 +439,16 @@ public class ExportDataSource implements Comparable<ExportDataSource> {
//There will be 8 bytes of no data that we can ignore, it is header space for storing
//the USO in stream block
if (buffer.capacity() > 8) {
+ final BBContainer cont = DBBPool.wrapBB(buffer);
if (m_lastReleaseOffset > 0 && m_lastReleaseOffset >= (uso + (buffer.capacity() - 8))) {
//What ack from future is known?
if (exportLog.isDebugEnabled()) {
exportLog.debug("Dropping already acked USO: " + m_lastReleaseOffset
+ " Buffer info: " + uso + " Size: " + buffer.capacity());
}
+ cont.discard();
return;
}
- final BBContainer cont = DBBPool.wrapBB(buffer);
try {
m_committedBuffers.offer(new StreamBlock(
new BBContainer(buffer) { | ENG-<I>: Fix off-heap memory for acks. | VoltDB_voltdb | train |
a98a206dd2e5c99d63896d505b8c6af4fc18350d | diff --git a/cmd/shell_test.go b/cmd/shell_test.go
index <HASH>..<HASH> 100644
--- a/cmd/shell_test.go
+++ b/cmd/shell_test.go
@@ -145,7 +145,7 @@ func TestLoadCert(t *testing.T) {
"open ../does/not/exist: no such file or directory",
},
{
- "../test/test-ca.key",
+ "./testdata/key.pem",
"Invalid certificate value returned",
},
}
@@ -156,8 +156,8 @@ func TestLoadCert(t *testing.T) {
test.AssertEquals(t, err.Error(), tc.expectedErr)
}
- bytes, err := LoadCert("../test/test-ca.pem")
- test.AssertNotError(t, err, "LoadCert(../test/test-ca.pem) errored")
+ bytes, err := LoadCert("./testdata/cert.pem")
+ test.AssertNotError(t, err, "LoadCert(\"./testdata/cert.pem\") errored")
test.AssertNotEquals(t, len(bytes), 0)
}
diff --git a/publisher/publisher_test.go b/publisher/publisher_test.go
index <HASH>..<HASH> 100644
--- a/publisher/publisher_test.go
+++ b/publisher/publisher_test.go
@@ -115,8 +115,6 @@ CspkK71IGqM9UwwMtCZBp0fK/Xv9o1d85paXcJ/aH8zg6EK4UkuXDFnLsg1LrIru
OY8B7wwvZTLzU6WWs781TJXx2CE04PneeeArLpVLkiGIWjk=
-----END CERTIFICATE-----`
-const issuerPath = "../test/test-ca.pem"
-
var log = blog.UseMock()
var ctx = context.Background() | Remove references to test-ca.pem. (#<I>)
shell_test.go and publisher_test.go had unnecessary references to
../test/test-ca.pem. This change makes them a little more self-contained.
Note: ca/ca_test.go still depends on test-ca.pem, but removing the dependency
turns out to be a little more complicated due to hardcoded expectations in some
of the test cases. | letsencrypt_boulder | train |
b7d25056a7e32c2f4a17603a38e55658ceef0078 | diff --git a/core/src/main/java/cucumber/runtime/model/CucumberScenarioOutline.java b/core/src/main/java/cucumber/runtime/model/CucumberScenarioOutline.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/cucumber/runtime/model/CucumberScenarioOutline.java
+++ b/core/src/main/java/cucumber/runtime/model/CucumberScenarioOutline.java
@@ -67,6 +67,9 @@ public class CucumberScenarioOutline extends CucumberTagStatement {
// Create a step with replaced tokens
String name = replaceTokens(matchedColumns, headerCells, exampleCells, step.getName());
+ if (name.isEmpty()) {
+ throw new CucumberException("Step generated from scenario outline '" + step.getName() + "' is empty");
+ }
return new ExampleStep(
step.getComments(),
@@ -111,9 +114,6 @@ public class CucumberScenarioOutline extends CucumberTagStatement {
if (text.contains(token)) {
text = text.replace(token, value);
- if (text.isEmpty()) {
- throw new CucumberException("Step generated from scenario outline '" + token + "' is empty");
- }
matchedColumns.add(col);
}
}
diff --git a/core/src/test/java/cucumber/runtime/model/CucumberScenarioOutlineTest.java b/core/src/test/java/cucumber/runtime/model/CucumberScenarioOutlineTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/cucumber/runtime/model/CucumberScenarioOutlineTest.java
+++ b/core/src/test/java/cucumber/runtime/model/CucumberScenarioOutlineTest.java
@@ -1,5 +1,6 @@
package cucumber.runtime.model;
+import cucumber.runtime.CucumberException;
import gherkin.formatter.model.Comment;
import gherkin.formatter.model.DataTableRow;
import gherkin.formatter.model.DocString;
@@ -44,6 +45,32 @@ public class CucumberScenarioOutlineTest {
assertEquals(asList("I", "have 10 cukes"), exampleStep.getRows().get(0).getCells());
}
+ @Test(expected=CucumberException.class)
+ public void does_not_allow_the_step_to_be_empty_after_replacement() {
+ Step outlineStep = new Step(C, null, "<step>", 0, null, null);
+
+ CucumberScenarioOutline.createExampleStep(outlineStep, new ExamplesTableRow(C, asList("step"), 1, ""), new ExamplesTableRow(C, asList(""), 1, ""));
+ }
+
+ @Test
+ public void allows_doc_strings_to_be_empty_after_replacement() {
+ Step outlineStep = new Step(C, null, "Some step", 0, null, new DocString(null, "<doc string>", 1));
+
+ Step exampleStep = CucumberScenarioOutline.createExampleStep(outlineStep, new ExamplesTableRow(C, asList("doc string"), 1, ""), new ExamplesTableRow(C, asList(""), 1, ""));
+
+ assertEquals("", exampleStep.getDocString().getValue());
+ }
+
+ @Test
+ public void allows_data_table_entries_to_be_empty_after_replacement() {
+ List<DataTableRow> rows = asList(new DataTableRow(C, asList("<entry>"), 1));
+ Step outlineStep = new Step(C, null, "Some step", 0, rows, null);
+
+ Step exampleStep = CucumberScenarioOutline.createExampleStep(outlineStep, new ExamplesTableRow(C, asList("entry"), 1, ""), new ExamplesTableRow(C, asList(""), 1, ""));
+
+ assertEquals(asList(""), exampleStep.getRows().get(0).getCells());
+ }
+
/***
* From a scenario outline, we create one or more "Example Scenario"s. This is composed
* of each step from the outline, with the tokens replaced with the pertient values | Allow emtpy doc string and data table entries from outlines
After token replacement for instantiated scenarios from scenario
outlines, the doc string and data table entries are allowed to be
emtpy. The step itself on the other hand, must be non-empty. | cucumber_cucumber-jvm | train |
3a5b2bf2fef882e0ae812f6c7ff508d95456e31f | diff --git a/internal/service/dynamodb/table_test.go b/internal/service/dynamodb/table_test.go
index <HASH>..<HASH> 100644
--- a/internal/service/dynamodb/table_test.go
+++ b/internal/service/dynamodb/table_test.go
@@ -332,7 +332,7 @@ func TestAccDynamoDBTable_basic(t *testing.T) {
"type": "S",
}),
resource.TestCheckResourceAttr(resourceName, "tags.%", "0"),
- resource.TestCheckResourceAttr(resourceName, "table_class", "STANDARD"),
+ resource.TestCheckResourceAttr(resourceName, "table_class", ""),
),
},
{ | If never specified, table_class is empty. | terraform-providers_terraform-provider-aws | train |
a7e08e2a3266efa9c82eb859e7141c798fcf07ae | diff --git a/src/client/index.js b/src/client/index.js
index <HASH>..<HASH> 100644
--- a/src/client/index.js
+++ b/src/client/index.js
@@ -71,7 +71,12 @@ const SessionContext = createContext()
*/
export function useSession (session) {
const context = useContext(SessionContext)
- const [data, setData] = useState(context?.[0] ?? session)
+ if (context) return context
+ return _useSessionHook(session)
+}
+
+function _useSessionHook (session) {
+ const [data, setData] = useState(session)
const [loading, setLoading] = useState(!data)
useEffect(() => { | fix: make sure useSession populates session correctly (#<I>) | iaincollins_next-auth | train |
c8df3440135e66ebccd2acd0806751fc55746528 | diff --git a/extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServer.java b/extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServer.java
index <HASH>..<HASH> 100644
--- a/extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServer.java
+++ b/extension-impl/remoting-bolt/src/main/java/com/alipay/sofa/rpc/server/bolt/BoltServer.java
@@ -24,6 +24,7 @@ import com.alipay.sofa.rpc.config.ConfigUniqueNameGenerator;
import com.alipay.sofa.rpc.config.ProviderConfig;
import com.alipay.sofa.rpc.config.ServerConfig;
import com.alipay.sofa.rpc.context.RpcRuntimeContext;
+import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException;
import com.alipay.sofa.rpc.ext.Extension;
import com.alipay.sofa.rpc.invoke.Invoker;
import com.alipay.sofa.rpc.log.Logger;
@@ -105,8 +106,16 @@ public class BoltServer implements Server {
}
// 生成Server对象
remotingServer = initRemotingServer();
- remotingServer.start(serverConfig.getBoundHost());
- started = true;
+ try {
+ if (!remotingServer.start(serverConfig.getBoundHost())) {
+ throw new SofaRpcRuntimeException("Failed to start bolt server, see more detail from bolt log.");
+ }
+ started = true;
+ } catch (SofaRpcRuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new SofaRpcRuntimeException("Failed to start bolt server!", e);
+ }
}
}
diff --git a/extension-impl/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/BoltServerTest.java b/extension-impl/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/BoltServerTest.java
index <HASH>..<HASH> 100644
--- a/extension-impl/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/BoltServerTest.java
+++ b/extension-impl/remoting-bolt/src/test/java/com/alipay/sofa/rpc/server/bolt/BoltServerTest.java
@@ -16,12 +16,11 @@
*/
package com.alipay.sofa.rpc.server.bolt;
-import org.junit.Assert;
-import org.junit.Test;
-
import com.alipay.sofa.rpc.common.RpcConstants;
import com.alipay.sofa.rpc.common.utils.NetUtils;
import com.alipay.sofa.rpc.config.ServerConfig;
+import org.junit.Assert;
+import org.junit.Test;
/**
*
@@ -44,6 +43,21 @@ public class BoltServerTest {
Assert.assertTrue(server.started);
Assert.assertTrue(NetUtils.canTelnet(host, port, 1000));
+ // start use bound port will throw exception
+ ServerConfig serverConfig2 = new ServerConfig();
+ serverConfig2.setBoundHost(host);
+ serverConfig2.setPort(port);
+ serverConfig2.setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
+ BoltServer server2 = new BoltServer();
+ server2.init(serverConfig2);
+ boolean error = false;
+ try {
+ server2.start();
+ } catch (Exception e) {
+ error = true;
+ }
+ Assert.assertTrue(error);
+
server.stop();
Assert.assertFalse(server.started);
Thread.sleep(1000); // 升级bolt后删除此行 | Fix bolt server started failed but not throw exception. (#<I>) | alipay_sofa-rpc | train |
41b2d37c47df85b75c179b8be3d9700c42df54fa | diff --git a/scapy/config.py b/scapy/config.py
index <HASH>..<HASH> 100644
--- a/scapy/config.py
+++ b/scapy/config.py
@@ -315,6 +315,7 @@ extensions_paths: path or list of paths where extensions are to be looked for
promisc = 1
sniff_promisc = 1
raw_layer = None
+ raw_summary = False
default_l2 = None
l2types = Num2Layer()
l3types = Num2Layer()
diff --git a/scapy/packet.py b/scapy/packet.py
index <HASH>..<HASH> 100644
--- a/scapy/packet.py
+++ b/scapy/packet.py
@@ -1067,6 +1067,14 @@ class Raw(Packet):
# t = self.load
# l = min(len(s), len(t))
# return s[:l] == t[:l]
+ def mysummary(self):
+ cs = conf.raw_summary
+ if cs:
+ if callable(cs):
+ return "Raw %s" % cs(self.load)
+ else:
+ return "Raw %r" % self.load
+ return Packet.mysummary(self)
class Padding(Raw):
name = "Padding" | Added Raw.mysummary() that can be configured with conf.raw_summary
Either False, or True or a function to be applied to Raw.load | secdev_scapy | train |
b9f9e46f2fc6fa57addd19a5ce0ed65547c9b6c1 | diff --git a/comments-bundle/contao/dca/tl_comments.php b/comments-bundle/contao/dca/tl_comments.php
index <HASH>..<HASH> 100644
--- a/comments-bundle/contao/dca/tl_comments.php
+++ b/comments-bundle/contao/dca/tl_comments.php
@@ -578,7 +578,7 @@ class tl_comments extends Backend
{
if (strlen(Input::get('tid')))
{
- $this->toggleVisibility(Input::get('tid'), (Input::get('state') == 1));
+ $this->toggleVisibility(Input::get('tid'), (Input::get('state') == 1), (@func_get_arg(12) ?: null));
$this->redirect($this->getReferer());
}
@@ -608,8 +608,9 @@ class tl_comments extends Backend
* Disable/enable a user group
* @param integer
* @param boolean
+ * @param \DataContainer
*/
- public function toggleVisibility($intId, $blnVisible)
+ public function toggleVisibility($intId, $blnVisible, DataContainer $dc=null)
{
// Check permissions to edit
Input::setGet('id', $intId);
@@ -634,11 +635,11 @@ class tl_comments extends Backend
if (is_array($callback))
{
$this->import($callback[0]);
- $blnVisible = $this->$callback[0]->$callback[1]($blnVisible, $this);
+ $blnVisible = $this->$callback[0]->$callback[1]($blnVisible, ($dc ?: $this));
}
elseif (is_callable($callback))
{
- $blnVisible = $callback($blnVisible, $this);
+ $blnVisible = $callback($blnVisible, ($dc ?: $this));
}
}
} | [Comments] Always pass a DC object in the `toggleVisibility` callback (see #<I>) | contao_contao | train |
a0bc41f9fa2e60f5c879d9f5fd2c18be6a0cd4a1 | diff --git a/tempora/tests/test_schedule.py b/tempora/tests/test_schedule.py
index <HASH>..<HASH> 100644
--- a/tempora/tests/test_schedule.py
+++ b/tempora/tests/test_schedule.py
@@ -131,7 +131,7 @@ class TestScheduler:
def test_periodic_command(self):
sched = schedule.InvokeScheduler()
target = mock.MagicMock()
- cmd = schedule.PeriodicCommand.at_time(time.time() + 0.1, target)
+ cmd = schedule.PeriodicCommand.after(0.1, target)
sched.add(cmd)
sched.run_pending()
target.assert_not_called() | Use 'after' to construct PeriodicCommand with a more predictable delay. | jaraco_tempora | train |
daf52bf91997ca7aaf51b40da0d6ea439e0cb895 | diff --git a/modules/wyc/src/wyc/io/NewWhileyFileParser.java b/modules/wyc/src/wyc/io/NewWhileyFileParser.java
index <HASH>..<HASH> 100644
--- a/modules/wyc/src/wyc/io/NewWhileyFileParser.java
+++ b/modules/wyc/src/wyc/io/NewWhileyFileParser.java
@@ -841,13 +841,13 @@ public class NewWhileyFileParser {
return new Expr.Constant(wyil.lang.Constant.V_CHAR(c), sourceAttr(
start, index - 1));
}
- case IntValue: {
- BigInteger val = parseInteger(token.text);
+ case IntValue: {
+ BigInteger val = new BigInteger(token.text);
return new Expr.Constant(wyil.lang.Constant.V_INTEGER(val), sourceAttr(
start, index - 1));
}
case RealValue: {
- BigDecimal val = parseDecimal(token.text);
+ BigDecimal val = new BigDecimal(token.text);
return new Expr.Constant(wyil.lang.Constant.V_DECIMAL(val), sourceAttr(
start, index - 1));
}
@@ -1398,4 +1398,3 @@ public class NewWhileyFileParser {
*/
private static final Indent ROOT_INDENT = new Indent("", 0);
}
-} | WyC: a few more little tweaks. | Whiley_WhileyCompiler | train |
1d85d0cc0ef117e5df34b34079941ebd2ad9c8e9 | diff --git a/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/avro/AvroUtils.java b/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/avro/AvroUtils.java
index <HASH>..<HASH> 100644
--- a/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/avro/AvroUtils.java
+++ b/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/avro/AvroUtils.java
@@ -304,6 +304,9 @@ public class AvroUtils {
} else if (schema1.getType() == Schema.Type.RECORD) {
// Compare record fields that match in name by comparing their schemas
// recursively calling this method.
+ if (schema1.getFields().size() != schema2.getFields().size()) {
+ return false;
+ }
for (Field field1 : schema1.getFields()) {
Field field2 = schema2.getField(field1.name());
if (field2 == null) { | CDK-<I>: Fix avro schema comparison bug.
This adds a check that the number of sub-fields in a record matches.
Otherwise, when fields are added at the end of the record, equals may
return incorrectly depending on which schema is the left operand. | kite-sdk_kite | train |
5991a5f9629c4a58061d21ecd9a1b89009141264 | diff --git a/ViewRenderer.php b/ViewRenderer.php
index <HASH>..<HASH> 100644
--- a/ViewRenderer.php
+++ b/ViewRenderer.php
@@ -111,11 +111,6 @@ class ViewRenderer extends BaseViewRenderer
$this->addExtensions($this->extensions);
}
- // Change lexer syntax
- if (!empty($this->lexerOptions)) {
- $this->setLexerOptions($this->lexerOptions);
- }
-
// Adding global 'void' function (usage: {{void(App.clientScript.registerScriptFile(...))}})
$this->twig->addFunction('void', new \Twig_Function_Function(function ($argument) {
}));
@@ -137,6 +132,11 @@ class ViewRenderer extends BaseViewRenderer
}));
$this->twig->addGlobal('app', \Yii::$app);
+
+ // Change lexer syntax (must be set after other settings)
+ if (!empty($this->lexerOptions)) {
+ $this->setLexerOptions($this->lexerOptions);
+ }
}
/** | Fixes Twig lexerOptions throwing exception (#<I>) and adds test for lexerOptions | yiisoft_yii2-twig | train |
ccff0e6ea5cfd9cd9b18e42ea0008f10d2e83c08 | diff --git a/go/cmd/vtctld/vtctld.go b/go/cmd/vtctld/vtctld.go
index <HASH>..<HASH> 100644
--- a/go/cmd/vtctld/vtctld.go
+++ b/go/cmd/vtctld/vtctld.go
@@ -302,21 +302,19 @@ func main() {
})
// Serve the static files for the vtctld web app.
- if *webDir != "" {
- http.HandleFunc("/app/", func(w http.ResponseWriter, r *http.Request) {
- // Strip the prefix.
- parts := strings.SplitN(r.URL.Path, "/", 3)
- if len(parts) != 3 {
- http.NotFound(w, r)
- return
- }
- rest := parts[2]
- if rest == "" {
- rest = "index.html"
- }
- http.ServeFile(w, r, path.Join(*webDir, rest))
- })
- }
+ http.HandleFunc("/app/", func(w http.ResponseWriter, r *http.Request) {
+ // Strip the prefix.
+ parts := strings.SplitN(r.URL.Path, "/", 3)
+ if len(parts) != 3 {
+ http.NotFound(w, r)
+ return
+ }
+ rest := parts[2]
+ if rest == "" {
+ rest = "index.html"
+ }
+ http.ServeFile(w, r, path.Join(*webDir, rest))
+ })
// Serve the REST API for the vtctld web app.
initAPI(context.Background(), ts, actionRepo) | vtctld: Always handle /app/ path.
Now that we redirect / to /app/, we need to always handle /app/.
Otherwise, it leads to a redirect loop when /app/ is not handled,
such as if -web_dir is not specified. | vitessio_vitess | train |
ed74f1b0aef33904dcb1644035f50377e334c74d | diff --git a/galpy/potential_src/interpRZPotential.py b/galpy/potential_src/interpRZPotential.py
index <HASH>..<HASH> 100644
--- a/galpy/potential_src/interpRZPotential.py
+++ b/galpy/potential_src/interpRZPotential.py
@@ -194,10 +194,16 @@ class interpRZPotential(Potential):
else:
self._epifreqGrid= numpy.array([epifreq(self._origPot,r) for r in self._rgrid])
indx= True-numpy.isnan(self._epifreqGrid)
- if self._logR:
- self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid[indx],self._epifreqGrid[indx],k=3)
+ if numpy.sum(indx) < 4:
+ if self._logR:
+ self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid[indx],self._epifreqGrid[indx],k=1)
+ else:
+ self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid[indx],self._epifreqGrid[indx],k=1)
else:
- self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid[indx],self._epifreqGrid[indx],k=3)
+ if self._logR:
+ self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._logrgrid[indx],self._epifreqGrid[indx],k=3)
+ else:
+ self._epifreqInterp= interpolate.InterpolatedUnivariateSpline(self._rgrid[indx],self._epifreqGrid[indx],k=3)
if interpverticalfreq:
from galpy.potential import verticalfreq
if not numcores is None: | try to fix epifreq for extreme dblexps | jobovy_galpy | train |
7dd95f5bbf25efd2710146b696ce4b80e3c8072e | diff --git a/quickbooks/client.py b/quickbooks/client.py
index <HASH>..<HASH> 100644
--- a/quickbooks/client.py
+++ b/quickbooks/client.py
@@ -262,7 +262,7 @@ class QuickBooks(object):
'Connection': 'close'
})
- binary_data = str(base64.b64encode(attachment.read()))
+ binary_data = str(base64.b64encode(attachment.read()).decode('ascii'))
content_type = json.loads(request_body)['ContentType'] | Update client.py uploads to be Python3 compatible
Updates the attachment encoding to be Python-version agnostic | sidecars_python-quickbooks | train |
e9d541841d081f5a428568ed46e054a12fafcb64 | diff --git a/application/delete_machines.py b/application/delete_machines.py
index <HASH>..<HASH> 100755
--- a/application/delete_machines.py
+++ b/application/delete_machines.py
@@ -47,7 +47,8 @@ def destroyNodes(aFilter):
try:
machine.destroy()
machines.append(machine)
- except MachineException:
+ except MachineException as exc:
+ print("Unable to delete: " + str(item.name) + " because exception: " + str(exc))
continue
#join
diff --git a/dynamic_machine/machine.py b/dynamic_machine/machine.py
index <HASH>..<HASH> 100644
--- a/dynamic_machine/machine.py
+++ b/dynamic_machine/machine.py
@@ -111,8 +111,8 @@ class Machine(object):
try:
if not self.__onProvider.destroy_node(nodeToDestroy):
raise MachineException("Unable to destroy node "+self.__hostname+" please manually destroy or try again later.")
- except:
- raise MachineException("Unable to destroy node " + self.__hostname + " please manually destroy or try again later.")
+ except Exception as exc:
+ raise MachineException("Unable to destroy node " + self.__hostname + " please manually destroy or try again later. \n(" + str(exc) + ")" )
def __returnNodeIfExists(self, hostname):
nodeOfInterest = None | debug around unable to delete machines. | lwoydziak_dynamic_machine | train |
cbdc5340a71bee1f4a5731cabd03c9aab6fa242b | diff --git a/chess/xboard.py b/chess/xboard.py
index <HASH>..<HASH> 100644
--- a/chess/xboard.py
+++ b/chess/xboard.py
@@ -243,7 +243,7 @@ class FeatureMap(object):
"debug": 0,
"memory": 0,
"smp": 0,
- "egt": 0,
+ "egt": None,
"option": OptionMap(),
"done": None
}
@@ -865,6 +865,62 @@ class Engine(object):
command = self.command("random")
return self._queue_command(command, async_callback)
+ def name(self, name_str, async_callback=None):
+ """
+ Informs the engine of its opponent's name.
+ The engine may choose to play differently based on this parameter.
+
+ :param name_str: The name of the opponent.
+
+ :return: Nothing.
+ """
+ command = self.command("name " + str(name_str))
+ return self._queue_command(command, async_callback)
+
+ def rating(self, engine_rating, opponent_rating, async_callback=None):
+ """
+ Informs the engine of its own rating followed by the opponent's.
+ The engine may choose to play differently based on these parameters.
+
+ :param engine_rating: The rating of this engine.
+ :param opponent_rating: The rating of the opponent.
+
+ :return: Nothing
+ """
+ builder = ["rating", str(engine_rating), str(opponent_rating)]
+ command = self.command(" ".join(builder))
+ return self._queue_command(command, async_callback)
+
+ def computer(self, async_callback=None):
+ """
+ Informs the engine that the opponent is a computer as well.
+ The engine may choose to play differently upon receiving this command.
+
+ :return: Nothing.
+ """
+ command = self.command("computer")
+ return self._queue_command(command, async_callback)
+
+ def egtpath(self, egt_type, egt_path, async_callback=None):
+ """
+ Tells the engine to use the *egt_type* endgame tablebases at *egt_path*.
+
+ The engine must have this type specified in the feature egt. For example,
+ the engine may have *feature egt=syzygy*. Then it is legal to call
+ *egtpath("syzygy", "<path-to-syzygy>)*.
+
+ :param egt_type: The type of EGT pointed to(syzygy, gaviota, etc...).
+ :param egt_path: The path to the desired EGT.
+
+ :return: Nothing.
+ """
+ if not (egt_type in self.features.get("egt")):
+ raise EngineStateException("engine does not support the '{}' egt", egt_type)
+
+ builder = ["egtpath", egt_type, egt_path]
+ command = self.command(" ".join(builder))
+ return self._queue_command(command, async_callback)
+
def nps(self, target_nps, async_callback=None):
"""
Tells the engine to limit its speed of search in terms of | Added name, rating, computer and egtpath functions | niklasf_python-chess | train |
108f0cab822308747c57fc14d6315009f443f701 | diff --git a/alpaca_trade_api/__init__.py b/alpaca_trade_api/__init__.py
index <HASH>..<HASH> 100644
--- a/alpaca_trade_api/__init__.py
+++ b/alpaca_trade_api/__init__.py
@@ -1,4 +1,4 @@
from .rest import REST # noqa
from .stream2 import StreamConn # noqa
-__version__ = '0.16'
+__version__ = '0.17' | Bumpt to <I> | alpacahq_alpaca-trade-api-python | train |
d39c3be779a42a628e0f6f7442fad83af38efb11 | diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/HttpFoundation/Response.php
+++ b/src/Symfony/Component/HttpFoundation/Response.php
@@ -101,16 +101,16 @@ class Response
$this->fixContentType();
// status
- $content .= sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\n";
+ $content .= sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n";
// headers
foreach ($this->headers->all() as $name => $values) {
foreach ($values as $value) {
- $content .= "$name: $value\n";
+ $content .= "$name: $value\r\n";
}
}
- $content .= "\n".$this->getContent();
+ $content .= "\r\n".$this->getContent();
return $content;
} | [HttpFoundation] replaced LF by CRLF as per the spec | symfony_symfony | train |
ec4a85cc89fb47762690fad69d694ef93dac5cc5 | diff --git a/src/2D.js b/src/2D.js
index <HASH>..<HASH> 100644
--- a/src/2D.js
+++ b/src/2D.js
@@ -492,14 +492,25 @@ Crafty.c("gravity", {
this._gy = 0; //reset change in y
}
- var obj, hit = false,
- q = Crafty.map.search(this.pos()),
- i = 0, l = q.length;
-
+ var obj, hit = false, pos = this.pos(),
+ q, i = 0, l;
+
+ //Increase by 1 to make sure map.search() finds the floor
+ pos._y++;
+
+ //map.search wants _x and intersect wants x...
+ pos.x = pos._x;
+ pos.y = pos._y;
+ pos.w = pos._w;
+ pos.h = pos._h;
+
+ q = Crafty.map.search(pos);
+ l = q.length;
+
for(;i<l;++i) {
obj = q[i];
//check for an intersection directly below the player
- if(obj !== this && obj.has(this._anti) && obj.intersect(this)) {
+ if(obj !== this && obj.has(this._anti) && obj.intersect(pos)) {
hit = obj;
break;
} | Fix gravity properly this time.
(Adding 1 to the y value, to please map.search()) | craftyjs_Crafty | train |
990df4ed5bce46cf7205f8bdcf3cb7b9a8b9e565 | diff --git a/packages/table/src/table-column.js b/packages/table/src/table-column.js
index <HASH>..<HASH> 100644
--- a/packages/table/src/table-column.js
+++ b/packages/table/src/table-column.js
@@ -290,7 +290,7 @@ export default {
}
return _self.showOverflowTooltip || _self.showTooltipWhenOverflow
- ? <div class="cell el-tooltip" style={{width: (data.column.realWidth || data.column.width) + 'px'}}>{ renderCell(h, data) }</div>
+ ? <div class="cell el-tooltip" style={ {width: (data.column.realWidth || data.column.width) - 1 + 'px'} }>{ renderCell(h, data) }</div>
: <div class="cell">{ renderCell(h, data) }</div>;
};
},
diff --git a/packages/table/src/table-header.js b/packages/table/src/table-header.js
index <HASH>..<HASH> 100644
--- a/packages/table/src/table-header.js
+++ b/packages/table/src/table-header.js
@@ -137,7 +137,10 @@ export default {
}
{
this.hasGutter
- ? <th class="gutter" style={{ width: this.layout.scrollY ? this.layout.gutterWidth + 'px' : '0' }}></th>
+ ? <th class="gutter" style={{
+ width: this.layout.scrollY ? this.layout.gutterWidth + 'px' : '0',
+ display: this.layout.scrollY ? '' : 'none'
+ }}></th>
: ''
}
</tr>
diff --git a/packages/table/src/table.vue b/packages/table/src/table.vue
index <HASH>..<HASH> 100644
--- a/packages/table/src/table.vue
+++ b/packages/table/src/table.vue
@@ -25,7 +25,7 @@
<div
class="el-table__body-wrapper"
ref="bodyWrapper"
- :class="[`is-scroll-${scrollPosition}`]"
+ :class="[layout.scrollX ? `is-scroll-${scrollPosition}` : 'is-scroll-none']"
:style="[bodyHeight]">
<table-body
:context="context" | Table: fix table column width bug in safari & hide shadow of fixed when scrollX is false (#<I>) | ElemeFE_element | train |
0005ad3711597c8aa371a38413150ad223ea1671 | diff --git a/lib/sugarcrm/session.rb b/lib/sugarcrm/session.rb
index <HASH>..<HASH> 100644
--- a/lib/sugarcrm/session.rb
+++ b/lib/sugarcrm/session.rb
@@ -102,10 +102,11 @@ module SugarCRM; class Session
end
# load credentials from file, and (re)connect to SugarCRM
- def load_config(path)
+ def load_config(path, opts = {})
+ opts.reverse_merge! :reconnect => true
new_config = self.class.parse_config_file(path)
- @config[:config] = new_config[:config] if new_config
- reconnect(@config[:base_url], @config[:username], @config[:password]) if connection_info_loaded?
+ update_config(new_config[:config]) if new_config and new_config[:config]
+ reconnect(@config[:base_url], @config[:username], @config[:password]) if opts[:reconnect] and connection_info_loaded?
@config
end
@@ -207,4 +208,4 @@ module SugarCRM; class Session
result[:wait_timeout] = wait_timeout if wait_timeout
result
end
-end; end
\ No newline at end of file
+end; end
diff --git a/test/connection/test_get_entry_list.rb b/test/connection/test_get_entry_list.rb
index <HASH>..<HASH> 100644
--- a/test/connection/test_get_entry_list.rb
+++ b/test/connection/test_get_entry_list.rb
@@ -2,12 +2,13 @@ require 'helper'
class TestGetEntryList < ActiveSupport::TestCase
context "A SugarCRM.connection" do
- should "return a list of entries when sent #get_entry_list and no fields." do
+ should "return a list of entries when sent #get_entry_list" do
users = SugarCRM.connection.get_entry_list(
"Users",
"users.deleted = 0"
)
- assert_equal "admin", users.first.user_name
+ assert_kind_of Array, users
+ assert_equal SugarCRM.config[:username], users.first.user_name
end
should "return an object when #get_entry_list" do
@response = SugarCRM.connection.get_entry_list(
@@ -19,4 +20,4 @@ class TestGetEntryList < ActiveSupport::TestCase
assert_instance_of SugarCRM::User, @response[0]
end
end
-end
\ No newline at end of file
+end
diff --git a/test/helper.rb b/test/helper.rb
index <HASH>..<HASH> 100644
--- a/test/helper.rb
+++ b/test/helper.rb
@@ -1,6 +1,7 @@
require 'rubygems'
require 'test/unit'
require 'shoulda'
+require 'active_support/test_case'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
diff --git a/test/test_finders.rb b/test/test_finders.rb
index <HASH>..<HASH> 100644
--- a/test/test_finders.rb
+++ b/test/test_finders.rb
@@ -5,9 +5,9 @@ class TestFinders < ActiveSupport::TestCase
should "always return an Array when :all" do
users = SugarCRM::User.all(:limit => 10)
assert_instance_of Array, users
- users = SugarCRM::User.find(:all, :conditions => {:user_name => '= admin'})
+ users = SugarCRM::User.find(:all, :conditions => {:user_name => "= #{users.first.user_name}"})
assert_instance_of Array, users
- assert users.length == 1
+ assert_equal 1, users.length
users = SugarCRM::User.find(:all, :conditions => {:user_name => '= invalid_user_123'})
assert_instance_of Array, users
assert users.length == 0
@@ -101,12 +101,12 @@ class TestFinders < ActiveSupport::TestCase
should "receive a response containing all fields when sent #get_entry" do
u = SugarCRM::User.find(1)
- assert_equal u.user_name, "admin"
+ assert_not_nil u.user_name
end
should "return an array of records when sent #find([id1, id2, id3])" do
users = SugarCRM::User.find(["seed_sarah_id", 1])
- assert_equal "admin", users.last.user_name
+ assert_not_nil users.last.user_name
end
# test Base#find_by_sql edge case
@@ -198,4 +198,4 @@ class TestFinders < ActiveSupport::TestCase
assert a.delete
end
end
-end
\ No newline at end of file
+end
diff --git a/test/test_session.rb b/test/test_session.rb
index <HASH>..<HASH> 100644
--- a/test/test_session.rb
+++ b/test/test_session.rb
@@ -15,6 +15,7 @@ CONFIG_CONTENTS.freeze
class TestSession < ActiveSupport::TestCase
context "The SugarCRM::Session class" do
should "raise SugarCRM::MissingCredentials if at least one of url/username/password is missing" do
+
assert_raise(SugarCRM::MissingCredentials){ SugarCRM.connect('http://127.0.0.1/sugarcrm', nil, nil) }
end
@@ -33,7 +34,7 @@ class TestSession < ActiveSupport::TestCase
end
should "parse config parameters from a file" do
- assert_equal CONFIG_CONTENTS, SugarCRM::Session.parse_config_file(CONFIG_PATH)
+ assert_equal CONFIG_CONTENTS, SugarCRM::Session.parse_config_file(CONFIG_TEST_PATH)
end
should "create a session from a config file" do
@@ -59,8 +60,9 @@ class TestSession < ActiveSupport::TestCase
end
should "load config file" do
- SugarCRM.load_config CONFIG_TEST_PATH
+ SugarCRM.load_config CONFIG_TEST_PATH, :reconnect => false
CONFIG_CONTENTS[:config].each{|k,v| assert_equal v, SugarCRM.config[k]}
+ SugarCRM.load_config CONFIG_PATH
end
should "be able to disconnect, and log in to Sugar automatically if credentials are present in config file" do | makes the tests more independent from the sugarCRM
now the tests work with SugarCRM servers other than <I> and
accepts admin users with other usernames than admin | chicks_sugarcrm | train |
4b540287e246a8635f84eb69dd8ea8dae0115357 | diff --git a/mechanicalsoup/browser.py b/mechanicalsoup/browser.py
index <HASH>..<HASH> 100644
--- a/mechanicalsoup/browser.py
+++ b/mechanicalsoup/browser.py
@@ -77,6 +77,10 @@ class Browser(object):
"""Straightforward wrapper around `requests.Session.request
<http://docs.python-requests.org/en/master/api/#requests.Session.request>`__.
+ :return: `requests.Response
+ <http://docs.python-requests.org/en/master/api/#requests.Response>`__
+ object with a *soup*-attribute added by :func:`add_soup`.
+
This is a low-level function that should not be called for
basic usage (use :func:`get` or :func:`post` instead). Use it if you
need an HTTP verb that MechanicalSoup doesn't manage (e.g. MKCOL) for
@@ -89,6 +93,10 @@ class Browser(object):
def get(self, *args, **kwargs):
"""Straightforward wrapper around `requests.Session.get
<http://docs.python-requests.org/en/master/api/#requests.Session.get>`__.
+
+ :return: `requests.Response
+ <http://docs.python-requests.org/en/master/api/#requests.Response>`__
+ object with a *soup*-attribute added by :func:`add_soup`.
"""
response = self.session.get(*args, **kwargs)
if self.__raise_on_404 and response.status_code == 404:
@@ -99,6 +107,10 @@ class Browser(object):
def post(self, *args, **kwargs):
"""Straightforward wrapper around `requests.Session.post
<http://docs.python-requests.org/en/master/api/#requests.Session.post>`__.
+
+ :return: `requests.Response
+ <http://docs.python-requests.org/en/master/api/#requests.Response>`__
+ object with a *soup*-attribute added by :func:`add_soup`.
"""
response = self.session.post(*args, **kwargs)
Browser.add_soup(response, self.soup_config)
@@ -182,6 +194,10 @@ class Browser(object):
relative path, then this must be specified.
:param \*\*kwargs: Arguments forwarded to `requests.Request
<http://docs.python-requests.org/en/master/api/#requests.Request>`__.
+
+ :return: `requests.Response
+ <http://docs.python-requests.org/en/master/api/#requests.Response>`__
+ object with a *soup*-attribute added by :func:`add_soup`.
"""
if isinstance(form, Form):
form = form.form | browser.py: add some method return types
Document all the return types for methods that return a
requests.Response with a soup-attribute attached to it. | MechanicalSoup_MechanicalSoup | train |
68e9ecaa07e5922610996931d31075ebbcc707ba | diff --git a/twarc/client.py b/twarc/client.py
index <HASH>..<HASH> 100644
--- a/twarc/client.py
+++ b/twarc/client.py
@@ -836,7 +836,9 @@ class Twarc(object):
else:
raise e
else:
- raise RuntimeError('Incomplete credentials provided.')
+ print('Incomplete credentials provided.')
+ print('Please run the command "twarc configure" to get started.')
+ sys.exit()
def load_config(self):
path = self.config | Provide getting started message to client on first run.
Provide message to client on getting started when credentials
have not yet been supplied. Previously, a stack trace was shown
attributing the exception/error that was invoked. This fix
makes the output when getting started more user friendly and
gives the user an action to perform to progress their usage of
the tool.
Closes #<I> | DocNow_twarc | train |
dde3d644a2ef5b32fd1d0cfadabc05c6828d76b6 | diff --git a/src/cli/commands/program.js b/src/cli/commands/program.js
index <HASH>..<HASH> 100644
--- a/src/cli/commands/program.js
+++ b/src/cli/commands/program.js
@@ -25,7 +25,9 @@ function lookupFirmwareBundleForHardwareVersion(hardwareVersion) {
let bundle = []
for (let filename of fs.readdirSync(bundleDir).sort())
- bundle.push(path.join(bundleDir, filename))
+ // Sometimes there are hidden files we don't want to include (.DS_Store)
+ if (!filename.startsWith('.'))
+ bundle.push(path.join(bundleDir, filename))
return bundle
} | cli: make sure firmware bundle doesn't include dotfiles | PunchThrough_bean-sdk-node | train |
4dba9ac12fe022d5a123ece5b7c7e4239a916b12 | diff --git a/tests/test_vts.py b/tests/test_vts.py
index <HASH>..<HASH> 100644
--- a/tests/test_vts.py
+++ b/tests/test_vts.py
@@ -20,6 +20,7 @@ import logging
from unittest import TestCase
from unittest.mock import Mock
+from collections import OrderedDict
from ospd.errors import OspdError
from ospd.vts import Vts
from hashlib import sha256
@@ -140,7 +141,7 @@ class VtsTestCase(TestCase):
self.assertIsNot(vta, vtb)
def test_calculate_vts_collection_hash(self):
- vts = Vts()
+ vts = Vts(storage=OrderedDict())
vts.add(
'id_1',
@@ -164,7 +165,7 @@ class VtsTestCase(TestCase):
self.assertEqual(hash_test, vts.sha256_hash)
def test_calculate_vts_collection_hash_no_params(self):
- vts = Vts()
+ vts = Vts(storage=OrderedDict())
vts.add(
'id_1', | Use an OrderedDict in test to ensure the order of the vts for the hash calculation | greenbone_ospd | train |
6890d73a4aa18bb803a357002f92f26e9193a7a2 | diff --git a/lib/motion/RMXEventManager.rb b/lib/motion/RMXEventManager.rb
index <HASH>..<HASH> 100644
--- a/lib/motion/RMXEventManager.rb
+++ b/lib/motion/RMXEventManager.rb
@@ -20,7 +20,7 @@
# `eventsSignal` is a rac property observer on `events`
#
# `enableRefresh` will start listening and buffering the following events 0.5s:
-# instantly when called, app launch, returning from background, event store changes
+# app launch, returning from background, event store changes
#
# `disableRefresh` will stop listening for events that would trigger a refresh
#
@@ -45,7 +45,24 @@
#
class RMXEventManager
- attr_accessor :accessible, :events, :sources, :selectedCalendars, :calendar, :store
+ # for logging status changes
+ STATUSES = {
+ EKAuthorizationStatusNotDetermined => "EKAuthorizationStatusNotDetermined",
+ EKAuthorizationStatusRestricted => "EKAuthorizationStatusRestricted",
+ EKAuthorizationStatusDenied => "EKAuthorizationStatusDenied",
+ EKAuthorizationStatusAuthorized => "EKAuthorizationStatusAuthorized",
+ nil => "Not Set"
+ }
+
+ # the current EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent)
+ attr_accessor :status
+
+ # a bool based on `status`, true if EKAuthorizationStatusAuthorized, otherwise false
+ attr_accessor :granted
+
+ attr_accessor :events
+
+ attr_accessor :sources, :selectedCalendars, :calendar, :store
attr_reader :refreshSignal, :eventsSignal, :storeChangedSignal
@@ -68,14 +85,16 @@ class RMXEventManager
@calendar = NSCalendar.autoupdatingCurrentCalendar
@store = EKEventStore.new
@events = []
- @accessible = EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent) == EKAuthorizationStatusAuthorized
+
+ @status = _status
+ @granted = _authorized?
+
@sources = []
@selectedCalendars = NSMutableSet.new
@storeChangedSignal = NSNotificationCenter.defaultCenter.rac_addObserverForName(EKEventStoreChangedNotification, object:@store).takeUntil(rac_willDeallocSignal)
@refreshSignal = RACSignal.merge([
- RACSignal.return(true),
RMX.rac_appDidFinishLaunchingNotification,
RMX.rac_appDidBecomeActiveFromBackground,
@storeChangedSignal
@@ -83,6 +102,14 @@ class RMXEventManager
.bufferWithTime(0.5, onScheduler:RACScheduler.mainThreadScheduler)
@eventsSignal = RMX(self).racObserve("events")
+
+ # log status changes
+ RMX(self).racObserve("status")
+ .distinctUntilChanged
+ .subscribeNext(->(s) {
+ NSLog("[#{className}] status=#{STATUSES[s]}")
+ }.rmx_weak!)
+
end
def self.shared
@@ -111,16 +138,15 @@ class RMXEventManager
def accessSignal
RACSignal.createSignal(->(subscriber) {
- if EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent) == EKAuthorizationStatusAuthorized
+ if _authorized?
subscriber.sendNext(true)
subscriber.sendCompleted
else
- @store.requestAccessToEntityType(EKEntityTypeEvent, completion:->(granted, error) {
+ @store.requestAccessToEntityType(EKEntityTypeEvent, completion:->(_granted, _error) {
RACScheduler.mainThreadScheduler.schedule(-> {
- self.accessible = granted
resetStoredSelectedCalendars
refresh
- subscriber.sendNext(granted)
+ subscriber.sendNext(_authorized?)
subscriber.sendCompleted
})
})
@@ -131,8 +157,10 @@ class RMXEventManager
def refresh
RMX.assert_main_thread!
- NSLog("[#{className}] refresh")
- if accessible
+ self.status = _status
+ self.granted = _authorized?
+ if granted
+ NSLog("[#{className}] refresh")
resetSources
loadEvents
else
@@ -143,7 +171,7 @@ class RMXEventManager
def selectedCalendarObjects
RMX.assert_main_thread!
set = NSMutableSet.new
- if accessible
+ if granted
calendars = @store.calendarsForEntityType(EKEntityTypeEvent).select do |calendarObject|
@selectedCalendars.containsObject(calendarObject.calendarIdentifier)
end
@@ -198,6 +226,14 @@ class RMXEventManager
private
+ def _authorized?
+ _status == EKAuthorizationStatusAuthorized
+ end
+
+ def _status
+ EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent)
+ end
+
def resetSources
RMX.assert_main_thread!
new_sources = []
@@ -229,6 +265,7 @@ class RMXEventManager
def resetStoredSelectedCalendars
RMX.assert_main_thread!
+ NSLog("[#{className}] resetStoredSelectedCalendars")
NSUserDefaults.standardUserDefaults.removeObjectForKey(selectedCalendarsKey)
NSUserDefaults.standardUserDefaults.synchronize
end | rework RMXEventManager, now maintains status and granted accessors | joenoon_rmx | train |
a62e190a2237ea3cdad2cfbbaf20082de3d6c4c4 | diff --git a/module/Image/public/scripts/zork/paragraph/dashboard/image.js b/module/Image/public/scripts/zork/paragraph/dashboard/image.js
index <HASH>..<HASH> 100644
--- a/module/Image/public/scripts/zork/paragraph/dashboard/image.js
+++ b/module/Image/public/scripts/zork/paragraph/dashboard/image.js
@@ -39,12 +39,13 @@
"lightBox" : form.find( ":input[name='paragraph-image[lightBox]']:not([type='hidden'])" )
},
before = {
- "url" : img.attr( "src" ),
- "caption" : element.find( "figcaption" ).html(),
- "alternate" : img.attr( "alt" ),
- "linkTo" : elements.linkTo.val(),
- "linkTarget": elements.linkTarget.val(),
- "lightBox" : elements.lightBox.attr( "checked" )
+ "url" : img.attr( "src" ),
+ "caption" : caption.html(),
+ "captionEmpty" : caption.hasClass( "empty" ),
+ "alternate" : img.attr( "alt" ),
+ "linkTo" : elements.linkTo.val(),
+ "linkTarget" : elements.linkTarget.val(),
+ "lightBox" : elements.lightBox.attr( "checked" )
},
changeTtl = 2000,
changeTimeout = null,
@@ -116,7 +117,7 @@
var val = $( this ).val();
caption.html( val )
- .toggleClass( "empty", !! val );
+ .toggleClass( "empty", ! val );
} );
elements.alternate.on( "keyup change", function () {
@@ -150,13 +151,16 @@
return {
"update": function () {
+ var captionVal = elements.caption.val();
+
before = {
- "url" : img.attr( "src" ),
- "caption" : elements.caption.val(),
- "alternate" : elements.alternate.val(),
- "linkTo" : elements.linkTo.val(),
- "linkTarget": elements.linkTarget.val(),
- "lightBox" : elements.lightBox.prop( "checked" )
+ "url" : img.attr( "src" ),
+ "caption" : captionVal,
+ "captionEmpty" : ! captionVal,
+ "alternate" : elements.alternate.val(),
+ "linkTo" : elements.linkTo.val(),
+ "linkTarget" : elements.linkTarget.val(),
+ "lightBox" : elements.lightBox.prop( "checked" )
};
link.attr( {
@@ -165,7 +169,8 @@
} );
},
"restore": function () {
- caption.html( before.caption );
+ caption.html( before.caption )
+ .toggleClass( "empty", before.captionEmpty );
link.attr( {
"href": before.linkTo ? before.linkTo : null, | image paragraph: fix caption edit on-the-fly | webriq_core | train |
6290e9b343f6a0410da195d93b3ad5908426dcd6 | diff --git a/Readme.md b/Readme.md
index <HASH>..<HASH> 100644
--- a/Readme.md
+++ b/Readme.md
@@ -48,7 +48,7 @@ See [the documentation](http://rubydoc.info/gems/foursquare2/frames) for a list
#### Search tips from a user (optionally filter a user's tips based on some term)
- client.user_tips_by_text(:user_id => "123456", :query => 'coffee')
+ client.user_tips_by_text("123456", :query => 'coffee')
#### Search venues by tip
diff --git a/lib/foursquare2/tips.rb b/lib/foursquare2/tips.rb
index <HASH>..<HASH> 100644
--- a/lib/foursquare2/tips.rb
+++ b/lib/foursquare2/tips.rb
@@ -29,14 +29,14 @@ module Foursquare2
# Search for tips from a venue.
#
# @param [Hash] options
- # @option options String :venue_id The ID of the venue
+ # @option options String :venueId The ID of the venue
# @option options String :sort [recent] One of recent or popular.
# @option options Integer :limit [100] Number of results to return, up to 500.
# @option options Integer :offset [100] Used to page through results
# @option options String :query - Only find tips matching this term.
def venue_tips(options={})
- response = connection.get("venues/#{options[:venue_id]}/tips")
+ response = connection.get("venues/#{options[:venueId]}/tips")
tips = return_error_or_body(response, response.body.response.tips)
tips = Foursquare2.filter(tips, options[:query]) if options.has_key? :query
tips
diff --git a/lib/foursquare2/venues.rb b/lib/foursquare2/venues.rb
index <HASH>..<HASH> 100644
--- a/lib/foursquare2/venues.rb
+++ b/lib/foursquare2/venues.rb
@@ -44,7 +44,7 @@ module Foursquare2
venues << tip['venue']
end
venues
- end
+ end
# Retrieve information about all venue categories.
diff --git a/test/test_venues.rb b/test/test_venues.rb
index <HASH>..<HASH> 100644
--- a/test/test_venues.rb
+++ b/test/test_venues.rb
@@ -34,14 +34,14 @@ class TestVenues < Test::Unit::TestCase
should "get tips from a venue" do
stub_get("https://api.foursquare.com/v2/venues/4b8c3d87f964a520f7c532e3/tips?oauth_token=#{@client.oauth_token}", "venue_tips.json")
- tips = @client.venue_tips(:venue_id => '4b8c3d87f964a520f7c532e3')
+ tips = @client.venue_tips(:venueId => '4b8c3d87f964a520f7c532e3')
tips.items.first.id.should == "4c94a45c82b56dcb47cad0aa"
tips.items.size.should == 4
end
should "get tips from a venue only with some term" do
stub_get("https://api.foursquare.com/v2/venues/4c94a45c82b56dcb47cad0aa/tips?oauth_token=#{@client.oauth_token}", "venue_tips.json")
- tips = @client.venue_tips({:venue_id => '4c94a45c82b56dcb47cad0aa', :query => "legal"})
+ tips = @client.venue_tips({:venueId => '4c94a45c82b56dcb47cad0aa', :query => "legal"})
tips.items.count.should == 1
tips.items.first.id.should == "4c94a45c82b56dcb47cad0aa"
@@ -49,7 +49,7 @@ class TestVenues < Test::Unit::TestCase
should "no tips from a venue with term lorem" do
stub_get("https://api.foursquare.com/v2/venues/4c94a45c82b56dcb47cad0aa/tips?oauth_token=#{@client.oauth_token}", "venue_tips.json")
- tips = @client.venue_tips({:venue_id => '4c94a45c82b56dcb47cad0aa', :query => "lorem"})
+ tips = @client.venue_tips({:venueId => '4c94a45c82b56dcb47cad0aa', :query => "lorem"})
tips.items.count.should == 0
end | Making tests pass and moving to valid API calls. | mattmueller_foursquare2 | train |
d9162a8dec31c63f03c0cea1985aca6a8ba7a942 | diff --git a/src/NukaCode/Menu/Menu.php b/src/NukaCode/Menu/Menu.php
index <HASH>..<HASH> 100644
--- a/src/NukaCode/Menu/Menu.php
+++ b/src/NukaCode/Menu/Menu.php
@@ -41,7 +41,7 @@ class Menu {
$dropDown = new MenuDropDown($this);
$dropDown->setName($name);
- $this->dropDowns->add($dropDown);
+ $this->dropDowns[] = $dropDown;
return $dropDown;
}
diff --git a/src/NukaCode/Menu/MenuDropDown.php b/src/NukaCode/Menu/MenuDropDown.php
index <HASH>..<HASH> 100644
--- a/src/NukaCode/Menu/MenuDropDown.php
+++ b/src/NukaCode/Menu/MenuDropDown.php
@@ -9,6 +9,17 @@
namespace NukaCode\Menu;
-class MenuDropDown {
+class MenuDropDown extends MenuLink{
+ public $dropDownOptions = [];
+
+ public function addLink($name)
+ {
+ $link = new MenuLink($this);
+ $link->setName($name);
+
+ $this->dropDownOptions[] = $link;
+
+ return $link;
+ }
}
\ No newline at end of file
diff --git a/src/NukaCode/Menu/MenuLink.php b/src/NukaCode/Menu/MenuLink.php
index <HASH>..<HASH> 100644
--- a/src/NukaCode/Menu/MenuLink.php
+++ b/src/NukaCode/Menu/MenuLink.php
@@ -16,11 +16,13 @@ class MenuLink {
public $icon;
+ public $restricted = false;
+
public $options = [];
public $active = false;
- function __construct(Menu $menu)
+ function __construct($menu)
{
$this->menu = $menu;
}
@@ -67,6 +69,15 @@ class MenuLink {
return $this;
}
+ public function setFilter(\Closure $filter)
+ {
+ if ($filter() == false) {
+ $this->restricted = true;
+ }
+
+ return $this;
+ }
+
public function setActive()
{
$this->active = true; | Added drop down menus and filtering callback to menu link | JumpGateio_Menu | train |
0abcbc382efb86541b9ddcf33bf4ea4f25f8f69c | diff --git a/.eslintrc b/.eslintrc
index <HASH>..<HASH> 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -5,8 +5,5 @@
"quotes": [2, "single"],
"consistent-return": 0,
"no-console": 0
- },
- "globals": {
- "console": true
}
}
diff --git a/src/components/index.js b/src/components/index.js
index <HASH>..<HASH> 100644
--- a/src/components/index.js
+++ b/src/components/index.js
@@ -1,4 +1,4 @@
-/* global document */
+/* global document console */
console.log('main.js');
let text = 'ES2015';
diff --git a/src/server/index.js b/src/server/index.js
index <HASH>..<HASH> 100644
--- a/src/server/index.js
+++ b/src/server/index.js
@@ -1,4 +1,4 @@
-/* global __dirname */
+/* global __dirname console */
import _ from 'lodash';
import chalk from 'chalk'; | Remove global 'console' ignore from lint rules. | philcockfield_ui-harness | train |
22763cc7e338989700708e808fb6fbe012bccec9 | diff --git a/lib/flickr/object/attribute_locations/photo.rb b/lib/flickr/object/attribute_locations/photo.rb
index <HASH>..<HASH> 100644
--- a/lib/flickr/object/attribute_locations/photo.rb
+++ b/lib/flickr/object/attribute_locations/photo.rb
@@ -129,7 +129,7 @@ module Flickr
@attributes["sizes"] && @attributes["sizes"]["size"].find { |h| h["label"] == size.label }
end
- sizes.map(&:name)
+ SIZES.first(9) | sizes.map(&:name) | ["Original"]
},
],
largest_size: [
@@ -140,15 +140,29 @@ module Flickr
],
source_url: [
-> { @attributes["url_#{@size.abbreviation}"] },
- -> { @attributes["sizes"]["size"].find { |hash| hash["label"] == @size.label }["source"] }
+ -> { @attributes["sizes"]["size"].find { |hash| hash["label"] == @size.label }["source"] },
+ -> {
+ if @size.between?(Size.new("Square 75"), Size.new("Large 1024"))
+ url = "https://farm#{farm}.staticflickr.com/#{server}/#{id}_#{secret}"
+ url << "_#{@size.other_abbreviation}" if @size.other_abbreviation =~ /\w/
+ url << ".jpg"
+ url
+ elsif @size == Size.new("Original")
+ url = "https://farm#{farm}.staticflickr.com/#{server}/#{id}"
+ url << "_#{@attributes.fetch("originalsecret")}"
+ url << "_o"
+ url << ".#{@attributes.fetch("originalformat")}"
+ url
+ end
+ },
],
height: [
-> { @attributes["height_#{@size.abbreviation}"] },
- -> { @attributes["sizes"]["size"].find { |hash| hash["label"] == @size.label }["height"] }
+ -> { @attributes["sizes"]["size"].find { |hash| hash["label"] == @size.label }["height"] },
],
width: [
-> { @attributes["width_#{@size.abbreviation}"] },
- -> { @attributes["sizes"]["size"].find { |hash| hash["label"] == @size.label }["width"] }
+ -> { @attributes["sizes"]["size"].find { |hash| hash["label"] == @size.label }["width"] },
],
url: [
-> { "http://www.flickr.com/photos/#{owner.id}/#{id}" if owner.id && id },
diff --git a/lib/flickr/object/photo.rb b/lib/flickr/object/photo.rb
index <HASH>..<HASH> 100644
--- a/lib/flickr/object/photo.rb
+++ b/lib/flickr/object/photo.rb
@@ -332,11 +332,7 @@ module Flickr
raise ArgumentError, "\"#{name}\" isn't a valid photo size"
end
- if available_sizes.include? name
- @size = Size.new(name)
- else
- @size = nil
- end
+ @size = Size.new(name)
self
end
diff --git a/lib/flickr/object/photo/size.rb b/lib/flickr/object/photo/size.rb
index <HASH>..<HASH> 100644
--- a/lib/flickr/object/photo/size.rb
+++ b/lib/flickr/object/photo/size.rb
@@ -19,6 +19,10 @@ module Flickr
# Used by Flickr for hash key names.
#
ABBREVIATIONS = %w[sq t q s n m z c l h k o]
+ ##
+ # Used by Flickr for generating source URLs.
+ #
+ OTHER_ABBREVIATIONS = %w[s t q m n - z c b]
##
# Used by Flickr in response from "flickr.photos.getSizes".
@@ -43,13 +47,30 @@ module Flickr
all.include? new(name)
end
- attr_reader :name, :type, :number, :abbreviation, :label
+ attr_reader :name
def initialize(name)
- @name = name
- @type, @number = name.split
- @abbreviation = ABBREVIATIONS[NAMES.index(name)]
- @label = LABELS[NAMES.index(name)]
+ @name = name
+ end
+
+ def type
+ name.split[0]
+ end
+
+ def number
+ name.split[1]
+ end
+
+ def abbreviation
+ ABBREVIATIONS[NAMES.index(name)]
+ end
+
+ def other_abbreviation
+ OTHER_ABBREVIATIONS[NAMES.index(name)]
+ end
+
+ def label
+ LABELS[NAMES.index(name)]
end
##
diff --git a/spec/lib/flickr/object/photo_spec.rb b/spec/lib/flickr/object/photo_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/flickr/object/photo_spec.rb
+++ b/spec/lib/flickr/object/photo_spec.rb
@@ -11,17 +11,25 @@ describe Flickr::Object::Photo do
end
end
+ describe "#source_url" do
+ let(:it) { Flickr.photos.get_info("8130464513") }
+
+ it "is generated from photo's info" do
+ expect(it.medium500.source_url).to be_a_nonempty(String)
+ end
+
+ it "generates original image URLs" do
+ described_class.any_instance.unstub(:available_sizes)
+ expect(it.original.source_url).to be_a_nonempty(String)
+ end
+ end
+
describe "#size!" do
it "changes the size" do
it.send(:size!, "Square 75")
expect(it.size).to eq "Square 75"
end
- it "only changes the size if available" do
- it.send(:size!, "Small 240")
- expect(it.size).to eq nil
- end
-
it "raises an error if size doesn't exist" do
expect { it.send(:size!, "Foobar") }.to raise_error
end | Generate photos' source URLs from info
Fixes #5 | janko_flickr-objects | train |
c0e92660b5d7ea0d272d0e715502f86fd20d1689 | diff --git a/lib/codemirror.js b/lib/codemirror.js
index <HASH>..<HASH> 100644
--- a/lib/codemirror.js
+++ b/lib/codemirror.js
@@ -494,6 +494,7 @@ window.CodeMirror = (function() {
else intactLines += range.to - range.from;
}
if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
+ updateHeightsInViewport(cm);
updateViewOffset(cm);
return;
}
@@ -518,6 +519,14 @@ window.CodeMirror = (function() {
}
display.showingFrom = from; display.showingTo = to;
+ updateHeightsInViewport(cm);
+ updateViewOffset(cm);
+
+ return true;
+ }
+
+ function updateHeightsInViewport(cm) {
+ var display = cm.display;
var prevBottom = display.lineDiv.offsetTop;
for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
if (ie_lt8) {
@@ -537,9 +546,6 @@ window.CodeMirror = (function() {
widgets[i].height = widgets[i].node.offsetHeight;
}
}
- updateViewOffset(cm);
-
- return true;
}
function updateViewOffset(cm) {
@@ -1304,6 +1310,7 @@ window.CodeMirror = (function() {
// An array of ranges of lines that have to be updated. See
// updateDisplay.
changes: [],
+ forceUpdate: false,
updateInput: null,
userSelChange: null,
textChanged: null,
@@ -1336,7 +1343,7 @@ window.CodeMirror = (function() {
var coords = cursorCoords(cm, doc.sel.head);
newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
}
- if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) {
+ if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) {
updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
}
@@ -3123,7 +3130,7 @@ window.CodeMirror = (function() {
if (height != null) this.display.wrapper.style.height = interpret(height);
if (this.options.lineWrapping)
cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
- regChange(this);
+ this.curOp.forceUpdate = true;
}),
operation: function(f){return runInOp(this, f);}, | Add a cleaner way to force a display update without changed lines
Issue #<I> | codemirror_CodeMirror | train |
741480d6ef2c2a3f9b73d871302f8b41ba608998 | diff --git a/sagui.config.js b/sagui.config.js
index <HASH>..<HASH> 100644
--- a/sagui.config.js
+++ b/sagui.config.js
@@ -3,5 +3,13 @@
* see: http://sagui.js.org/
*/
module.exports = {
- libraries: ['index', 'deprecated', 'namespacedDisplayName', 'overridable', 'themeable', 'uncontrolled']
+ libraries: [
+ 'index',
+ 'deprecated',
+ 'namespacedDisplayName',
+ 'notifyOnLowFPS',
+ 'overridable',
+ 'themeable',
+ 'uncontrolled'
+ ]
} | Add notifyOnLowFPS to 🐒 config | klarna_higher-order-components | train |
4850ab65c433a53cffaf97f0e7066c69c6bf2e7a | diff --git a/devrant.go b/devrant.go
index <HASH>..<HASH> 100644
--- a/devrant.go
+++ b/devrant.go
@@ -40,6 +40,9 @@ func (c *Client) Rants(sort string, limit int, skip int) ([]RantModel, error) {
}
var data RantsResponse
json.NewDecoder(res.Body).Decode(&data)
+ if !data.Success && data.Error != "" {
+ return nil, errors.New(data.Error)
+ }
return data.Rants, nil
}
@@ -52,6 +55,9 @@ func (c *Client) Rant(rantId int) (RantModel, []CommentModel, error) {
}
var data RantResponse
json.NewDecoder(res.Body).Decode(&data)
+ if !data.Success && data.Error != "" {
+ return RantModel{}, nil, errors.New(data.Error)
+ }
return data.Rant, data.Comments, nil
}
@@ -68,6 +74,9 @@ func (c *Client) Profile(username string) (UserModel, ContentModel, error) {
}
var data UserResponse
json.NewDecoder(res.Body).Decode(&data)
+ if !data.Success && data.Error != "" {
+ return UserModel{}, ContentModel{}, errors.New(data.Error)
+ }
return data.Profile, data.Profile.Content.Content, nil
}
@@ -80,6 +89,9 @@ func (c *Client) Search(term string) ([]RantModel, error) {
}
var data SearchResponse
json.NewDecoder(res.Body).Decode(&data)
+ if !data.Success && data.Error != "" {
+ return nil, errors.New(data.Error)
+ }
return data.Rants, nil
}
@@ -92,6 +104,9 @@ func (c *Client) Surprise() (RantModel, error) {
}
var data RantResponse
json.NewDecoder(res.Body).Decode(&data)
+ if !data.Success && data.Error != "" {
+ return RantModel{}, errors.New(data.Error)
+ }
return data.Rant, nil
}
@@ -104,6 +119,9 @@ func (c *Client) WeeklyRants() ([]RantModel, error) {
}
var data RantsResponse
json.NewDecoder(res.Body).Decode(&data)
+ if !data.Success && data.Error != "" {
+ return nil, errors.New(data.Error)
+ }
return data.Rants, nil
}
@@ -116,6 +134,9 @@ func getUserId(username string) (int, error) {
}
var data GetUserIdResponse
json.NewDecoder(res.Body).Decode(&data)
+ if !data.Success && data.Error != "" {
+ return 0, errors.New(data.Error)
+ }
return data.UserId, nil
}
diff --git a/models.go b/models.go
index <HASH>..<HASH> 100644
--- a/models.go
+++ b/models.go
@@ -66,6 +66,7 @@ type NewsModel struct {
type RantsResponse struct {
Success bool `json:"success"`
+ Error string `json:"error"`
Rants []RantModel `json:"rants"`
Settings string `json:"settings"`
Set string `json:"set"`
@@ -75,21 +76,25 @@ type RantsResponse struct {
type RantResponse struct {
Success bool `json:"success"`
+ Error string `json:"error"`
Rant RantModel `json:"rant"`
Comments []CommentModel `json:"comments"`
}
type UserResponse struct {
Success bool `json:"success"`
+ Error string `json:"error"`
Profile UserModel `json:"profile"`
}
type SearchResponse struct {
Success bool `json:"success"`
+ Error string `json:"error"`
Rants []RantModel `json:"results"`
}
type GetUserIdResponse struct {
- Success bool `json:"success"`
- UserId int `json:"user_id"`
+ Success bool `json:"success"`
+ Error string `json:"error"`
+ UserId int `json:"user_id"`
} | Handle 'success' param of the api | jayeshsolanki93_devgorant | train |
644d932fb4daf84bec949b66e9210e9ac795faa1 | diff --git a/waliki/attachments/views.py b/waliki/attachments/views.py
index <HASH>..<HASH> 100644
--- a/waliki/attachments/views.py
+++ b/waliki/attachments/views.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import json
import imghdr
+import posixpath
from django.shortcuts import render, get_object_or_404
from django.contrib import messages
from django.utils.six import text_type
@@ -27,7 +28,7 @@ def delete_attachment(request, slug, attachment_id_or_filename):
if attachment_id_or_filename.isnumeric():
attachment = get_object_or_404(Attachment, id=attachment_id_or_filename, page__slug=slug)
else:
- attachment = get_object_or_404(Attachment, file__endswith=attachment_id_or_filename, page__slug=slug)
+ attachment = get_object_or_404(Attachment, file__endswith='%s%s' % (posixpath.sep, attachment_id_or_filename), page__slug=slug)
name = text_type(attachment)
if request.is_ajax() and request.method in ('POST', 'DELETE'):
attachment.delete()
@@ -37,7 +38,7 @@ def delete_attachment(request, slug, attachment_id_or_filename):
@permission_required('view_page', raise_exception=True)
def get_file(request, slug, attachment_id=None, filename=None):
- attachment = get_object_or_404(Attachment, file__endswith=filename, page__slug=slug)
+ attachment = get_object_or_404(Attachment, file__endswith='%s%s' % (posixpath.sep, filename), page__slug=slug)
as_attachment = ((not imghdr.what(attachment.file.path) and 'embed' not in request.GET)
or 'as_attachment' in request.GET)
# ref https://github.com/johnsensible/django-sendfile | Make attachments work even if their filenames overlap at the end. | mgaitan_waliki | train |
9f507feccddeeabfbf307d20ecf4585269bc3cea | diff --git a/tests/Http/Middleware/RateLimitTest.php b/tests/Http/Middleware/RateLimitTest.php
index <HASH>..<HASH> 100644
--- a/tests/Http/Middleware/RateLimitTest.php
+++ b/tests/Http/Middleware/RateLimitTest.php
@@ -162,8 +162,8 @@ class RateLimitTest extends TestCase
$this->assertArrayHasKey('x-ratelimit-limit', $response->headers->all());
$this->assertArrayHasKey('x-ratelimit-remaining', $response->headers->all());
$this->assertArrayHasKey('x-ratelimit-reset', $response->headers->all());
- $this->assertSame(4, $response->headers->get('x-ratelimit-remaining'));
- $this->assertSame(5, $response->headers->get('x-ratelimit-limit'));
+ $this->assertSame(4, (int) $response->headers->get('x-ratelimit-remaining'));
+ $this->assertSame(5, (int) $response->headers->get('x-ratelimit-limit'));
}
public function testRateLimitingWithRouteThrottle()
@@ -185,7 +185,7 @@ class RateLimitTest extends TestCase
$this->assertArrayHasKey('x-ratelimit-limit', $response->headers->all());
$this->assertArrayHasKey('x-ratelimit-remaining', $response->headers->all());
$this->assertArrayHasKey('x-ratelimit-reset', $response->headers->all());
- $this->assertSame(9, $response->headers->get('x-ratelimit-remaining'));
- $this->assertSame(10, $response->headers->get('x-ratelimit-limit'));
+ $this->assertSame(9, (int) $response->headers->get('x-ratelimit-remaining'));
+ $this->assertSame(10, (int) $response->headers->get('x-ratelimit-limit'));
}
} | fix: cast to int for correct assertSame result | dingo_api | train |
edcfaf8220a39804e5556d3ba48ed900f47c7b77 | diff --git a/bika/lims/browser/js/ar_add.js b/bika/lims/browser/js/ar_add.js
index <HASH>..<HASH> 100644
--- a/bika/lims/browser/js/ar_add.js
+++ b/bika/lims/browser/js/ar_add.js
@@ -1343,6 +1343,10 @@ function fill_column(data) {
}
}
+function expand_default_categories() {
+ $("th.prefill").click();
+}
+
$(document).ready(function() {
// Only if the view is the Analysis Request Add View
@@ -1361,6 +1365,7 @@ $(document).ready(function() {
// dateFormat = 'yy-mm-dd';
// }
+
ar_rename_elements();
ar_referencewidget_lookups();
ar_set_tabindexes();
@@ -1370,6 +1375,7 @@ $(document).ready(function() {
$(".copyButton").live("click", copyButton );
$("th[class^='analysiscategory']").click(clickAnalysisCategory);
+ expand_default_categories();
$("input[name^='Price']").live("change", recalc_prices ); | reapply e4f<I>de (LIMS-<I>) | senaite_senaite.core | train |
Subsets and Splits