hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
a5dcf2fff8444e751e8fc3119bfc3e86a5b9f77a
diff --git a/lib/netsuite/records/deposit_payment_list.rb b/lib/netsuite/records/deposit_payment_list.rb index <HASH>..<HASH> 100644 --- a/lib/netsuite/records/deposit_payment_list.rb +++ b/lib/netsuite/records/deposit_payment_list.rb @@ -1,35 +1,15 @@ module NetSuite module Records - class DepositPaymentList - include Support::Fields + class DepositPaymentList < Support::Sublist include Namespaces::TranBank - attr_accessor :replace_all - - fields :deposit_payment - - def initialize(attributes = {}) - initialize_from_attributes_hash(attributes) - end - - def payment=(payments) - case payments - when Hash - self.payments << DepositPayment.new(payments) - when Array - payments.each { |p| self.payments << DepositPayment.new(p) } - end - end + sublist :deposit_payment, DepositPayment + # legacy support def payments - @payments ||= [] + self.deposit_payment end - def to_record - rec = { "#{record_namespace}:depositPayment" => payments.map(&:to_record) } - rec[:@replaceAll] = @replace_all unless @replace_all.nil? - rec - end end end end
Use sublist on deposit payment sublist This may be a breaking change for some people!
NetSweet_netsuite
train
1709ec7898c87e4369f5324302f274f254857dc3
diff --git a/sdk/core/azure-mgmt-core/azure/mgmt/core/policies/_base_async.py b/sdk/core/azure-mgmt-core/azure/mgmt/core/policies/_base_async.py index <HASH>..<HASH> 100644 --- a/sdk/core/azure-mgmt-core/azure/mgmt/core/policies/_base_async.py +++ b/sdk/core/azure-mgmt-core/azure/mgmt/core/policies/_base_async.py @@ -83,7 +83,7 @@ class AsyncARMAutoResourceProviderRegistrationPolicy( return False while True: - asyncio.sleep(10) + await asyncio.sleep(10) get_response = await self.next.send( self._build_next_request(initial_request, "GET", get_url) )
Adding a missing await in _async_register_rp (#<I>)
Azure_azure-sdk-for-python
train
85d962dbd1fc78ea933ed0a0fe57e776ee753795
diff --git a/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/DefaultMappingTransformer.java b/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/DefaultMappingTransformer.java index <HASH>..<HASH> 100644 --- a/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/DefaultMappingTransformer.java +++ b/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/DefaultMappingTransformer.java @@ -62,17 +62,16 @@ public class DefaultMappingTransformer implements MappingTransformer { @Override public OBDASpecification transform(ImmutableList<MappingAssertion> mapping, DBParameters dbParameters, Optional<Ontology> ontology, ImmutableSet<RDFFact> facts) { - if (ontology.isPresent()) { - ImmutableList<MappingAssertion> factsAsMapping = factConverter.convert(facts); - - ImmutableList<MappingAssertion> mappingWithFacts = - Stream.concat(mapping.stream(), factsAsMapping.stream()).collect(ImmutableCollectors.toList()); + ImmutableList<MappingAssertion> factsAsMapping = factConverter.convert(facts); + ImmutableList<MappingAssertion> mappingWithFacts = + Stream.concat(mapping.stream(), factsAsMapping.stream()).collect(ImmutableCollectors.toList()); + if (ontology.isPresent()) { return createSpecification(mappingWithFacts, dbParameters, ontology.get().tbox()); } else { ClassifiedTBox emptyTBox = OntologyBuilderImpl.builder(rdfFactory, termFactory).build().tbox(); - return createSpecification(mapping, dbParameters, emptyTBox); + return createSpecification(mappingWithFacts, dbParameters, emptyTBox); } }
Disconnect facts from ontology pres. in DefaultMappingTransformer.
ontop_ontop
train
edaed3597c9dc02ec81e8e3d33b4772c6f831188
diff --git a/py/testdir_multi_jvm/test_KMeans_covtype20x.py b/py/testdir_multi_jvm/test_KMeans_covtype20x.py index <HASH>..<HASH> 100644 --- a/py/testdir_multi_jvm/test_KMeans_covtype20x.py +++ b/py/testdir_multi_jvm/test_KMeans_covtype20x.py @@ -42,7 +42,7 @@ class Basic(unittest.TestCase): # creates csvFilename.hex from file in importFolder dir start = time.time() parseKey = h2i.parseImportFolderFile(None, csvFilename, importFolderPath, - timeoutSecs=2000, key2=key2, noise=('JStack', None)) + timeoutSecs=2000, key2=key2) # noise=('JStack', None) print "parse end on ", csvPathname, 'took', time.time() - start, 'seconds' h2o.check_sandbox_for_errors() diff --git a/py/testdir_multi_jvm/test_KMeans_winesPCA.py b/py/testdir_multi_jvm/test_KMeans_winesPCA.py index <HASH>..<HASH> 100644 --- a/py/testdir_multi_jvm/test_KMeans_winesPCA.py +++ b/py/testdir_multi_jvm/test_KMeans_winesPCA.py @@ -46,7 +46,7 @@ class Basic(unittest.TestCase): # creates csvFilename.hex from file in importFolder dir start = time.time() parseKey = h2i.parseImportFolderFile(None, 'winesPCA.csv', importFolderPath, - timeoutSecs=2000, key2=key2, noise=('JStack', None)) + timeoutSecs=2000, key2=key2) # noise=('JStack', None) print "parse end on ", csvPathname, 'took', time.time() - start, 'seconds' h2o.check_sandbox_for_errors() diff --git a/py/testdir_multi_jvm/test_parse_1k_files.py b/py/testdir_multi_jvm/test_parse_1k_files.py index <HASH>..<HASH> 100644 --- a/py/testdir_multi_jvm/test_parse_1k_files.py +++ b/py/testdir_multi_jvm/test_parse_1k_files.py @@ -69,7 +69,7 @@ class Basic(unittest.TestCase): tryHeap = 4 DO_GLM = True noPoll = False - benchmarkLogging = ['cpu','disk', 'iostats', 'jstack'] + benchmarkLogging = ['cpu','disk', 'iostats'] # , 'jstack' benchmarkLogging = ['cpu','disk'] pollTimeoutSecs = 120 retryDelaySecs = 10 @@ -82,12 +82,21 @@ class Basic(unittest.TestCase): else: h2o_hosts.build_cloud_with_hosts(1, java_heap_GB=tryHeap, base_port=base_port, enable_benchmark_log=True) - h2b.browseTheCloud() + ### h2b.browseTheCloud() + + # don't let the config json redirect import folder to s3 or s3n, because + # we're writing to the syn_datasets locally. (just have to worry about node 0's copy of this state) + print "This test creates files in syn_datasets for import folder\n" + \ + "so h2o and python need to be same machine" + h2o.nodes[0].redirect_import_folder_to_s3_path = False + h2o.nodes[0].redirect_import_folder_to_s3n_path = False for trial in range(trialMax): importFolderResult = h2i.setupImportFolder(None, importFolderPath) importFullList = importFolderResult['succeeded'] + print "importFullList:", importFullList importFailList = importFolderResult['failed'] + print "importFailList:", importFailList print "\n Problem if this is not empty: importFailList:", h2o.dump_json(importFailList) h2o.cloudPerfH2O.change_logfile(csvFilename)
don't do Jstack polling..has a problem. test_parse_1k_files: don't redirect to s3. creates local files
h2oai_h2o-2
train
cee331a3b3ed500e2f3311c2c4f84cb5933f87aa
diff --git a/fsnotify_bsd.go b/fsnotify_bsd.go index <HASH>..<HASH> 100644 --- a/fsnotify_bsd.go +++ b/fsnotify_bsd.go @@ -50,7 +50,9 @@ func (e *FileEvent) IsCreate() bool { return e.create } func (e *FileEvent) IsDelete() bool { return (e.mask & NOTE_DELETE) == NOTE_DELETE } // IsModify reports whether the FileEvent was triggerd by a file modification -func (e *FileEvent) IsModify() bool { return ((e.mask & NOTE_WRITE) == NOTE_WRITE || (e.mask & NOTE_ATTRIB) == NOTE_ATTRIB) } +func (e *FileEvent) IsModify() bool { + return ((e.mask&NOTE_WRITE) == NOTE_WRITE || (e.mask&NOTE_ATTRIB) == NOTE_ATTRIB) +} // IsRename reports whether the FileEvent was triggerd by a change name func (e *FileEvent) IsRename() bool { return (e.mask & NOTE_RENAME) == NOTE_RENAME } @@ -183,10 +185,6 @@ func (w *Watcher) readEvents() { *twait = syscall.NsecToTimespec(keventWaitTime) for { - if len(events) == 0 { - n, errno = syscall.Kevent(w.kq, nil, eventbuf[:], twait) - events = eventbuf[0:n] - } // See if there is a message on the "done" channel var done bool select { @@ -204,9 +202,19 @@ func (w *Watcher) readEvents() { close(w.Error) return } - if n < 0 { - w.Error <- os.NewSyscallError("kevent", errno) - continue + + // Get new events + if len(events) == 0 { + n, errno = syscall.Kevent(w.kq, nil, eventbuf[:], twait) + + // EINTR is okay, basically the syscall was interrupted before + // timeout expired. + if errno != nil && errno != syscall.EINTR { + w.Error <- os.NewSyscallError("kevent", errno) + continue + } else { + events = eventbuf[0:n] + } } // Timeout, no big deal
BSD - Fix issue reported by robfig EINTR can be returned by kevent in two cases: 1) fork() while parent/child is calling kevent() will result in the process calling kevent() to get EINTR while other process is registering the same kqueue at the kernel level. 2) A file event occurs before timeout expires, but is not yet on the queue to be returned by kevent(). In either case, we can ignore the error and continue as if timeout expired without any events.
howeyc_fsnotify
train
c26d1e89d31987251b034d97b977ee9eedd0a534
diff --git a/domainutil/util.go b/domainutil/util.go index <HASH>..<HASH> 100644 --- a/domainutil/util.go +++ b/domainutil/util.go @@ -23,6 +23,16 @@ func Subdomain(url string) string { return "" } +// DomainPrefix returns second-level domain from provided url. +// If no SLD is found in provided url, this function returns empty string. +func DomainPrefix(url string) string { + domain := Domain(url) + if len(domain) != 0 { + return domain[:strings.Index(domain, ".")] + } + return "" +} + // DomainSuffix returns domain suffix from provided url. // If no TLD is found in provided url, this function returns empty string. func DomainSuffix(url string) string { diff --git a/domainutil/util_test.go b/domainutil/util_test.go index <HASH>..<HASH> 100644 --- a/domainutil/util_test.go +++ b/domainutil/util_test.go @@ -89,6 +89,35 @@ func ExampleDomainSuffix() { // com } +// TestDomainPrefix tests DomainPrefix function +func TestDomainPrefix(t *testing.T) { + //Test cases + cases := map[string]string{ + "http://google.com": "google", + "http://google.com/ding?true": "google", + "google.com/?ding=false": "google", + "google.com?ding=false": "google", + "google.com": "google", + "google.co.uk": "google", + "gama.google.com": "google", + "gama.google.co.uk": "google", + "beta.gama.google.co.uk": "google", + } + + for url, expectedPrefix := range cases { + domainPrefix := DomainPrefix(url) + if domainPrefix != expectedPrefix { + t.Errorf("Url (%q) returned %q for DomainPrefix(), but %q was expected", url, domainPrefix, expectedPrefix) + } + } +} + +func BenchmarkDomainPrefix(b *testing.B) { + for i := 0; i < b.N; i++ { + DomainPrefix("https://beta.gama.google.co.uk?test=true") + } +} + // TestDomainSuffix tests DomainSuffix() function func TestDomainSuffix(t *testing.T) { //Test cases
Add DomainPrefix function, returns second-level domain from provided url
bobesa_go-domain-util
train
6df1105de37e55810dc4c8f64218e992d67927c9
diff --git a/lib/guideline/checkers/abc_complexity_checker.rb b/lib/guideline/checkers/abc_complexity_checker.rb index <HASH>..<HASH> 100644 --- a/lib/guideline/checkers/abc_complexity_checker.rb +++ b/lib/guideline/checkers/abc_complexity_checker.rb @@ -1,4 +1,4 @@ -require "ripper" +require "code_analyzer" module Guideline class AbcComplexityChecker < Checker
Require code analyzer in AbcComplexityChecker forgot by mistake
r7kamura_guideline
train
983c0868e7155d8983cd9073f68f1f2fc28e03c0
diff --git a/src/parse-mockdb.js b/src/parse-mockdb.js index <HASH>..<HASH> 100644 --- a/src/parse-mockdb.js +++ b/src/parse-mockdb.js @@ -684,7 +684,7 @@ function runHook(className, hookType, data) { // TODO Stub out Parse.Cloud.useMasterKey() so that we can report the correct 'master' // value here. - return hook(makeRequestObject(model, false)).done((beforeSaveOverrideValue) => { + return hook(makeRequestObject(model, false)).then((beforeSaveOverrideValue) => { debugPrint('HOOK', { beforeSaveOverrideValue }); // Unlike BeforeDeleteResponse, BeforeSaveResponse might specify diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -164,14 +164,25 @@ function behavesLikeParseObjectOnBeforeDelete(typeName, ParseObjectOrUserSubclas }); } -function behavesLikeParseObjectOnAfterSave(typeName, ParseObjectOrUserSubclass) { +/** + * @param promiseType 'ES' for Promise, or 'Parse' for Parse.Promise + */ +function behavesLikeParseObjectOnAfterSaveForPromiseType( + typeName, ParseObjectOrUserSubclass, promiseType) { context('when object has afterSave hook registered', () => { let didAfterSave; let objectInAfterSave; function afterSavePromise(request) { didAfterSave = true; objectInAfterSave = request.object; - return Parse.Promise.as(); + switch (promiseType) { + case 'Parse': + return Parse.Promise.as(); + case 'ES': + return Promise.resolve(); + default: + throw Error(`Invalid Promise type: ${promiseType}`); + } } beforeEach(() => { @@ -289,6 +300,16 @@ function behavesLikeParseObjectOnAfterSave(typeName, ParseObjectOrUserSubclass) }); } +function behavesLikeParseObjectOnAfterSave(typeName, ParseObjectOrUserSubclass) { + context('using Parse.Promise', () => { + behavesLikeParseObjectOnAfterSaveForPromiseType(typeName, ParseObjectOrUserSubclass, 'Parse'); + }); + + context('using standard JS Promise', () => { + behavesLikeParseObjectOnAfterSaveForPromiseType(typeName, ParseObjectOrUserSubclass, 'ES'); + }); +} + function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
Use .then instead of .done to get a promise result. (#<I>) Use .then instead of .done This makes it so that hooks returning Promises instead of Parse.Promises will work correctly.
Hustle_parse-mockdb
train
566fbdd777a9333e07ccf468e1eec5603dd2630f
diff --git a/salt/netapi/rest_cherrypy/app.py b/salt/netapi/rest_cherrypy/app.py index <HASH>..<HASH> 100644 --- a/salt/netapi/rest_cherrypy/app.py +++ b/salt/netapi/rest_cherrypy/app.py @@ -814,6 +814,7 @@ def urlencoded_processor(entity): body_bytes.seek(0) # Patch fp entity.fp = body_bytes + del contents # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) @@ -836,6 +837,7 @@ def json_processor(entity): body = entity.fp.read(fp_out=contents) contents.seek(0) body = contents.read() + del contents try: cherrypy.serving.request.unserialized_data = json.loads(body) except ValueError:
Tell python we're done with `contents`
saltstack_salt
train
876a6ed7571ee455e0339c14adc54cbf3488daa9
diff --git a/cmd/deployment_cmd.go b/cmd/deployment_cmd.go index <HASH>..<HASH> 100644 --- a/cmd/deployment_cmd.go +++ b/cmd/deployment_cmd.go @@ -2,6 +2,15 @@ package cmd import ( "errors" + "fmt" + "io/ioutil" + "os" + "os/user" + "path" +) + +const ( + BOSH_MICRO_FILENAME = ".bosh_micro" ) type deploymentCmd struct { @@ -15,5 +24,29 @@ func NewDeploymentCmd() *deploymentCmd { func (f *deploymentCmd) Run(args []string) error { f.args = args - return errors.New("Implement me!") + if f.args == nil { + return errors.New("Deployment command argument cannot be nil") + } + + if len(f.args) < 1 { + return errors.New("Deployment command arguments must have at least one arg") + } + + manifestFilePath := f.args[0] + if _, err := os.Stat(manifestFilePath); os.IsNotExist(err) { + return errors.New(fmt.Sprintf("Deployment command manifest path %s does not exist", manifestFilePath)) + } + + usr, err := user.Current() + if err != nil { + return errors.New("Could not access current user") + } + + boshMicroPath := path.Join(usr.HomeDir, BOSH_MICRO_FILENAME) + err = ioutil.WriteFile(boshMicroPath, []byte(manifestFilePath), os.ModePerm) + if err != nil { + return errors.New(fmt.Sprintf("Could not write to file %s", boshMicroPath)) + } + + return nil } diff --git a/cmd/deployment_cmd_test.go b/cmd/deployment_cmd_test.go index <HASH>..<HASH> 100644 --- a/cmd/deployment_cmd_test.go +++ b/cmd/deployment_cmd_test.go @@ -1,5 +1,73 @@ package cmd_test -// Create new DeploymentCmd -// verify validate args (valid and invalid) -// store manifestPath to a file (.bosh-micro-cli) +import ( + "io/ioutil" + "os" + "os/user" + "path" + + cmd "github.com/cloudfoundry/bosh-micro-cli/cmd" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe("DeploymentCmd", func() { + var command cmd.Cmd + var manifestPath string + var args []string + + BeforeEach(func() { + command = cmd.NewDeploymentCmd() + Expect(command).ToNot(BeNil()) + }) + + Context("#Run", func() { + Context("ran with valid args", func() { + BeforeEach(func() { + file, err := ioutil.TempFile("", "bosh-micro-cli-manifest") + Expect(err).ToNot(HaveOccurred()) + + manifestPath = file.Name() + args = []string{manifestPath} + }) + + AfterEach(func() { + err := os.RemoveAll(manifestPath) + Expect(err).NotTo(HaveOccurred()) + }) + + It("stores the manifest file path to a hidden file at the home dir", func() { + err := command.Run(args) + Expect(err).ToNot(HaveOccurred()) + usr, err := user.Current() + Expect(err).ToNot(HaveOccurred()) + + expectedFilePath := path.Join(usr.HomeDir, ".bosh_micro") + expectedFileContent, err := ioutil.ReadFile(expectedFilePath) + Expect(err).NotTo(HaveOccurred()) + Expect(string(expectedFileContent)).To(ContainSubstring(manifestPath)) + }) + }) + + Context("ran with invalid args", func() { + It("fails when manifest file path is nil", func() { + err := command.Run(nil) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("Deployment command argument cannot be nil")) + }) + + It("fails when manifest file path is empty", func() { + err := command.Run([]string{}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("Deployment command arguments must have at least one arg")) + }) + + It("fails when manifest file path does not exist", func() { + err := command.Run([]string{"fake/manifest/path"}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("Deployment command manifest path fake/manifest/path does not exist")) + }) + }) + }) +})
Completed DeploymentCmd implementation [#<I>]
cloudfoundry_bosh-init
train
547406b85521653486ca07b54c6eee2791229598
diff --git a/src/Wt2Html/TT/Sanitizer.php b/src/Wt2Html/TT/Sanitizer.php index <HASH>..<HASH> 100644 --- a/src/Wt2Html/TT/Sanitizer.php +++ b/src/Wt2Html/TT/Sanitizer.php @@ -397,8 +397,9 @@ class Sanitizer extends TokenHandler { */ public static function attributeWhitelist( string $element ): array { // PORT-FIXME: this method is private in core, but used by Gallery - $list = self::setupAttributeWhitelist(); - return $list[$element] ?? []; + $lists = self::setupAttributeWhitelist(); + $list = $lists[$element] ?? []; + return array_flip( $list ); } /** @@ -1054,7 +1055,7 @@ class Sanitizer extends TokenHandler { ): array { $tag = $tagName ?: $token->getName(); - $wlist = array_flip( self::attributeWhitelist( $tag ) ); + $wlist = self::attributeWhitelist( $tag ); $newAttrs = []; $n = count( $attrs ); for ( $i = 0; $i < $n; $i++ ) {
Move flipping array into Sanitizer::attributeWhitelist Fixes the usage in the gallery extension and more tests pass. Change-Id: I0a8a<I>de2d<I>fe<I>f<I>b8f5e<I>da0ab
wikimedia_parsoid
train
dd4db347f34c6f114b9b8db74b2706cb7f8f73fa
diff --git a/python-package/xgboost/callback.py b/python-package/xgboost/callback.py index <HASH>..<HASH> 100644 --- a/python-package/xgboost/callback.py +++ b/python-package/xgboost/callback.py @@ -549,7 +549,7 @@ class EarlyStopping(TrainingCallback): # user to decide. maximize_metrics = ('auc', 'aucpr', 'map', 'ndcg', 'auc@', 'aucpr@', 'map@', 'ndcg@') - if any(metric.startswith(x) for x in maximize_metrics): + if metric != 'mape' and any(metric.startswith(x) for x in maximize_metrics): self.maximize = True else: self.maximize = False
Fix early stopping behavior with MAPE metric (#<I>)
dmlc_xgboost
train
99365cb8693f10829aebb5d329595eaa4503e926
diff --git a/resource.go b/resource.go index <HASH>..<HASH> 100644 --- a/resource.go +++ b/resource.go @@ -203,7 +203,13 @@ func resolveIDs(draft *Draft, base string, v interface{}, ids map[string]map[str return resolveIDs(draft, base, v, ids) } - schemaKeys := []string{"not", "additionalProperties"} + schemaKeys := []string{"not", "additionalProperties", "items", "additionalItems"} + if draft.version >= 6 { + schemaKeys = append(schemaKeys, "propertyNames", "contains") + } + if draft.version >= 7 { + schemaKeys = append(schemaKeys, "if", "then", "else") + } if draft.version >= 2019 { schemaKeys = append(schemaKeys, "unevaluatedProperties", "unevaluatedItems") } @@ -215,15 +221,17 @@ func resolveIDs(draft *Draft, base string, v interface{}, ids map[string]map[str } } - schemasKeys := []string{"allOf", "anyOf", "oneOf"} + schemasKeys := []string{"items", "allOf", "anyOf", "oneOf"} if draft.version >= 2020 { schemasKeys = append(schemasKeys, "prefixItems") } for _, pname := range schemasKeys { - if arr, ok := m[pname]; ok { - for _, m := range arr.([]interface{}) { - if err := resolveIDs(m); err != nil { - return err + if pvalue, ok := m[pname]; ok { + if arr, ok := pvalue.([]interface{}); ok { + for _, m := range arr { + if err := resolveIDs(m); err != nil { + return err + } } } } @@ -243,52 +251,5 @@ func resolveIDs(draft *Draft, base string, v interface{}, ids map[string]map[str } } - if items, ok := m["items"]; ok { - switch items := items.(type) { - case map[string]interface{}: - if err := resolveIDs(items); err != nil { - return err - } - case []interface{}: - for _, item := range items { - if err := resolveIDs(item); err != nil { - return err - } - } - } - if additionalItems, ok := m["additionalItems"]; ok { - if additionalItems, ok := additionalItems.(map[string]interface{}); ok { - if err := resolveIDs(additionalItems); err != nil { - return err - } - } - } - } - - if draft.version >= 6 { - for _, pname := range []string{"propertyNames", "contains"} { - if m, ok := m[pname]; ok { - if err := resolveIDs(m); err != nil { - return err - } - } - } - } - - if draft.version >= 7 { - if iff, ok := m["if"]; ok { - if err := resolveIDs(iff); err != nil { - return err - } - for _, pname := range []string{"then", "else"} { - if m, ok := m[pname]; ok { - if err := resolveIDs(m); err != nil { - return err - } - } - } - } - } - return nil }
cleanup: simlify resolveIDs impl
santhosh-tekuri_jsonschema
train
383c7e5c8f125f43218ba92c954619f8d75beb54
diff --git a/web/app/ner/ner.js b/web/app/ner/ner.js index <HASH>..<HASH> 100644 --- a/web/app/ner/ner.js +++ b/web/app/ner/ner.js @@ -300,6 +300,14 @@ function processFile(filename, id) { }; } +function generate_id(filename){ + // TODO(choudhury): technically, this can lead to identical ids (e.g., + // "letter_1.txt" and "letter 1.txt" will both wind up with + // "letter_1-txt" as their id string). + return filename.replace(/\./g, "-") + .replace(/ /g, "_"); +} + function handleFileSelect(evt) { "use strict"; @@ -346,12 +354,9 @@ function handleFileSelect(evt) { // Create globally usable names to use to refer to the current file. filename = escape(f.name); - // TODO(choudhury): technically, this can lead to identical ids (e.g., - // "letter_1.txt" and "letter 1.txt" will both wind up with - // "letter_1-txt" as their id string). - id = f.name - .replace(/\./g, "-") - .replace(/ /g, "_"); + // Get a unique id by which to refer to the this file in the html + // document. + id = generate_id(f.name); // Decide whether to process a selected file or not - accept everything // with a mime-type of text/*, as well as those with unspecified type
Abstracted out notion of making a unique idea per file into own function.
Kitware_tangelo
train
59d19be599b639936a8b05b3d972e502dacc28b8
diff --git a/src/com/google/javascript/jscomp/CheckJSDoc.java b/src/com/google/javascript/jscomp/CheckJSDoc.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/CheckJSDoc.java +++ b/src/com/google/javascript/jscomp/CheckJSDoc.java @@ -45,6 +45,10 @@ final class CheckJSDoc extends AbstractPostOrderCallback implements CompilerPass DiagnosticType.warning("JSC_DISALLOWED_MEMBER_JSDOC", "Class level JSDocs (@interface, @extends, etc.) are not allowed on class members"); + static final DiagnosticType ARROW_FUNCTION_AS_CONSTRUCTOR = DiagnosticType.error( + "JSC_ARROW_FUNCTION_AS_CONSTRUCTOR", + "Arrow functions cannot be used as constructors"); + private final AbstractCompiler compiler; CheckJSDoc(AbstractCompiler compiler) { @@ -66,6 +70,7 @@ final class CheckJSDoc extends AbstractPostOrderCallback implements CompilerPass validateDeprecatedJsDoc(t, n, info); validateNoCollapse(t, n, info); validateClassLevelJsDoc(t, n, info); + validateArrowFunction(n); } @@ -266,4 +271,16 @@ final class CheckJSDoc extends AbstractPostOrderCallback implements CompilerPass } } } + + /** + * Check that an arrow function is not annotated with {@constructor}. + */ + private void validateArrowFunction(Node n) { + if (n.isArrowFunction()) { + JSDocInfo info = NodeUtil.getBestJSDocInfo(n); + if (info != null && info.isConstructorOrInterface()) { + compiler.report(JSError.make(n, ARROW_FUNCTION_AS_CONSTRUCTOR)); + } + } + } } diff --git a/test/com/google/javascript/jscomp/CheckJsDocTest.java b/test/com/google/javascript/jscomp/CheckJsDocTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/CheckJsDocTest.java +++ b/test/com/google/javascript/jscomp/CheckJsDocTest.java @@ -17,19 +17,18 @@ package com.google.javascript.jscomp; import static com.google.javascript.jscomp.CheckJSDoc.ANNOTATION_DEPRECATED; +import static com.google.javascript.jscomp.CheckJSDoc.ARROW_FUNCTION_AS_CONSTRUCTOR; import static com.google.javascript.jscomp.CheckJSDoc.DISALLOWED_MEMBER_JSDOC; import static com.google.javascript.jscomp.CheckJSDoc.MISPLACED_ANNOTATION; import static com.google.javascript.jscomp.CheckJSDoc.MISPLACED_MSG_ANNOTATION; -import com.google.javascript.jscomp.CompilerOptions.LanguageMode; - /** * Tests for {@link CheckJSDoc}. * * @author chadkillingsworth@gmail.com (Chad Killingsworth) */ -public final class CheckJsDocTest extends CompilerTestCase { +public final class CheckJsDocTest extends Es6CompilerTestCase { @Override protected CompilerPass getProcessor(final Compiler compiler) { @@ -45,23 +44,21 @@ public final class CheckJsDocTest extends CompilerTestCase { } public void testInvalidClassJsdoc() { - this.setAcceptedLanguage(LanguageMode.ECMASCRIPT6_STRICT); - - testSame("class Foo { /** @param {number} x */ constructor(x) {}}"); + testSameEs6("class Foo { /** @param {number} x */ constructor(x) {}}"); - testWarning( + testWarningEs6( "class Foo { /** @constructor */ constructor() {}}", DISALLOWED_MEMBER_JSDOC); - testWarning( + testWarningEs6( "class Foo { /** @interface */ constructor() {}}", DISALLOWED_MEMBER_JSDOC); - testWarning( + testWarningEs6( "class Foo { /** @extends {Foo} */ constructor() {}}", DISALLOWED_MEMBER_JSDOC); - testWarning( + testWarningEs6( "class Foo { /** @implements {Foo} */ constructor() {}}", DISALLOWED_MEMBER_JSDOC); } @@ -158,8 +155,20 @@ public final class CheckJsDocTest extends CompilerTestCase { } public void testNocollapseInExterns() { - test("var foo = {}; /** @nocollapse */ foo.bar = true;", - "foo.bar;", "foo.bar;", null, - MISPLACED_ANNOTATION); + testSame("var foo = {}; /** @nocollapse */ foo.bar = true;", + "foo.bar;", MISPLACED_ANNOTATION); + } + + public void testArrowFuncAsConstructor() { + testErrorEs6("/** @constructor */ var a = ()=>{}; var b = a();", + ARROW_FUNCTION_AS_CONSTRUCTOR); + testErrorEs6("var a = /** @constructor */ ()=>{}; var b = a();", + ARROW_FUNCTION_AS_CONSTRUCTOR); + testErrorEs6("/** @constructor */ let a = ()=>{}; var b = a();", + ARROW_FUNCTION_AS_CONSTRUCTOR); + testErrorEs6("/** @constructor */ const a = ()=>{}; var b = a();", + ARROW_FUNCTION_AS_CONSTRUCTOR); + testErrorEs6("var a; /** @constructor */ a = ()=>{}; var b = a();", + ARROW_FUNCTION_AS_CONSTRUCTOR); } }
Added an error for using arrow function as constructor. The addition is to catch the following case /** @constructor */ var a = ()=>{}; ------------- Created by MOE: <URL>
google_closure-compiler
train
ade5aa4c5a5bc9e4a40292bb6592f6a74000955e
diff --git a/benchmark/benchmark.rb b/benchmark/benchmark.rb index <HASH>..<HASH> 100644 --- a/benchmark/benchmark.rb +++ b/benchmark/benchmark.rb @@ -11,7 +11,7 @@ require "representative/xml" @books = [ OpenStruct.new( - :title => "Sailing for old dogs", + :title => "Sailing for old dogs", :authors => ["Jim Watson"], :published => OpenStruct.new( :by => "Credulous Print", @@ -19,7 +19,7 @@ require "representative/xml" ) ), OpenStruct.new( - :title => "On the horizon", + :title => "On the horizon", :authors => ["Zoe Primpton", "Stan Ford"], :published => OpenStruct.new( :by => "McGraw-Hill", @@ -69,7 +69,6 @@ end def nokogiri iterations.times do - xml = Builder::XmlMarkup.new(:indent => 2) r = Representative::Nokogiri.new represent_books_using(r) r.to_xml
Delete a redundant line of code.
mdub_representative
train
039b3ba4bc3fc4422cbce846548dc51ba85505b3
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -594,7 +594,7 @@ var CodeMirror = (function() { if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); if (window.opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if (((window.opera && !e.which) || khtml) && handleKeyBinding(e)) return; + if (((window.opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return; var ch = String.fromCharCode(charCode == null ? keyCode : charCode); if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) { if (mode.electricChars.indexOf(ch) > -1)
Fix repeating of backspace and tab keys in Opera Windows
codemirror_CodeMirror
train
5dd74572e73e4af1b18e8bc5a68f0d5a9c5c1f0e
diff --git a/prov-dot/src/main/java/org/openprovenance/prov/dot/ProvToDot.java b/prov-dot/src/main/java/org/openprovenance/prov/dot/ProvToDot.java index <HASH>..<HASH> 100644 --- a/prov-dot/src/main/java/org/openprovenance/prov/dot/ProvToDot.java +++ b/prov-dot/src/main/java/org/openprovenance/prov/dot/ProvToDot.java @@ -266,7 +266,7 @@ public class ProvToDot { System.out.println("Error: " + s_error); } proc.waitFor(); - System.err.println("exit value " + proc.exitValue()); + //System.err.println("exit value " + proc.exitValue()); } catch (InterruptedException e){}; } diff --git a/prov-interop/src/main/java/org/openprovenance/prov/interop/CommandLineArguments.java b/prov-interop/src/main/java/org/openprovenance/prov/interop/CommandLineArguments.java index <HASH>..<HASH> 100644 --- a/prov-interop/src/main/java/org/openprovenance/prov/interop/CommandLineArguments.java +++ b/prov-interop/src/main/java/org/openprovenance/prov/interop/CommandLineArguments.java @@ -188,7 +188,7 @@ public class CommandLineArguments implements ErrorCodes { } - static final String toolboxVersion = getPropertiesFromClasspath(fileName) + static public final String toolboxVersion = getPropertiesFromClasspath(fileName) .getProperty("toolbox.version");
removed exit message in prov-dot
lucmoreau_ProvToolbox
train
b04a8405745857c59c531364546abd19bd4ed626
diff --git a/lib/utils/config.js b/lib/utils/config.js index <HASH>..<HASH> 100644 --- a/lib/utils/config.js +++ b/lib/utils/config.js @@ -485,8 +485,8 @@ const initParams = (persistent, options) => { stdin: options.stdin != null, env: env ? env.split(',') : [], }; - if (options.production == null) { - process.env.NODE_ENV = 'development'; + if (options.production == null && process.env.NODE_ENV !== 'production') { + process.env.NODE_ENV = process.env.NODE_ENV || 'development'; } else { process.env.NODE_ENV = 'production'; params.isProduction = true;
Do not overwrite the NODE_ENV environment variable (#<I>)
brunch_brunch
train
3e8edc7341508e21f769b88651cfac3663f52d02
diff --git a/lib/core/plugin/fog_machine.rb b/lib/core/plugin/fog_machine.rb index <HASH>..<HASH> 100644 --- a/lib/core/plugin/fog_machine.rb +++ b/lib/core/plugin/fog_machine.rb @@ -49,9 +49,11 @@ class Fog < CORL.plugin_class(:machine) #--- def server=id + @server = nil + if id.is_a?(String) - @server = compute.servers.get(id) - else + @server = compute.servers.get(id) unless id.empty? + elsif ! id.nil? @server = id end @@ -140,8 +142,8 @@ class Fog < CORL.plugin_class(:machine) def load super do - myself.server = plugin_name if compute && ! plugin_name.empty? - ! plugin_name.empty? && @server.nil? ? false : true + myself.server = plugin_name if compute && plugin_name + ! plugin_name && @server.nil? ? false : true end end
Fixing load issue related to empty plugin_name in the base fog machine provider.
coralnexus_corl
train
0a4e226c8ffa016fede311955f23831f727740d3
diff --git a/src/components/com_application/application.php b/src/components/com_application/application.php index <HASH>..<HASH> 100644 --- a/src/components/com_application/application.php +++ b/src/components/com_application/application.php @@ -222,4 +222,4 @@ class ComApplication extends AnObject implements AnServiceInstantiatable return $name; } -} +} \ No newline at end of file diff --git a/src/components/com_people/helpers/person.php b/src/components/com_people/helpers/person.php index <HASH>..<HASH> 100644 --- a/src/components/com_people/helpers/person.php +++ b/src/components/com_people/helpers/person.php @@ -45,7 +45,7 @@ class ComPeopleHelperPerson extends AnObject } // create a remember cookie that contains the ecrypted username and password - if ($remember) { + if ($remember && false) { $key = get_hash('AN_LOGIN_REMEMBER', 'md5'); $crypt = $this->getService('anahita:encrypter', array('key' => $key, 'cipher' => 'AES-256-CBC')); $cookie = $crypt->encrypt(serialize(array( diff --git a/src/libraries/default/sessions/sessions.php b/src/libraries/default/sessions/sessions.php index <HASH>..<HASH> 100644 --- a/src/libraries/default/sessions/sessions.php +++ b/src/libraries/default/sessions/sessions.php @@ -343,13 +343,13 @@ class LibSessions extends AnObject implements AnServiceInstantiatable * @param string $namespace Namespace to use, default to 'default' * @return mixed Value of a variable */ - public function get($property = null, $default = null, $namespace = 'default') + public function get($property = null, $default = null, $namespace = '') { if($this->_state !== self::STATE_ACTIVE && $this->_state !== self::STATE_EXPIRED) { throw new LibSessionsException("Session does not exist!\n"); } - $namespace = $namespace === 'default' ? $this->_namespace : $namespace; + $namespace = empty($namespace) ? $this->_namespace : $namespace; if (isset($_SESSION[$namespace][$property])) { return $_SESSION[$namespace][$property]; @@ -366,13 +366,13 @@ class LibSessions extends AnObject implements AnServiceInstantiatable * @param mixed $value Value of a variable * @return mixed Old value of a variable */ - public function set($name, $value = null, $namespace = 'default') + public function set($name, $value = null, $namespace = '') { if ($this->_state !== self::STATE_ACTIVE) { throw new LibSessionsException("Session isn't active!\n"); } - $namespace = $namespace === 'default' ? $this->_namespace : $namespace; + $namespace = empty($namespace) ? $this->_namespace : $namespace; if (is_null($value)) { unset($_SESSION[$namespace][$name]); @@ -608,4 +608,4 @@ class LibSessions extends AnObject implements AnServiceInstantiatable return true; } -} +} \ No newline at end of file
reverting to <I> files
anahitasocial_anahita
train
34b53e70998ca80006c5b1732ea7865f67c9fc75
diff --git a/agent/consul/acl_test.go b/agent/consul/acl_test.go index <HASH>..<HASH> 100644 --- a/agent/consul/acl_test.go +++ b/agent/consul/acl_test.go @@ -214,7 +214,6 @@ func (d *ACLResolverTestDelegate) RPC(method string, args interface{}, reply int panic("Bad Test Implmentation: should provide a policyResolveFn to the ACLResolverTestDelegate") } panic("Bad Test Implementation: Was the ACLResolver updated to use new RPC methods") - return nil } func newTestACLResolver(t *testing.T, delegate ACLResolverDelegate, cb func(*ACLResolverConfig)) *ACLResolver { diff --git a/agent/consul/fsm/snapshot_oss.go b/agent/consul/fsm/snapshot_oss.go index <HASH>..<HASH> 100644 --- a/agent/consul/fsm/snapshot_oss.go +++ b/agent/consul/fsm/snapshot_oss.go @@ -446,7 +446,7 @@ func restoreACLBootstrap(header *snapshotHeader, restore *state.Restore, decoder // With V2 ACLs whether bootstrapping has been performed is stored in the index table like nomad // so this "restores" into that index table. - return restore.IndexRestore(&state.IndexEntry{"acl-token-bootstrap", req.ModifyIndex}) + return restore.IndexRestore(&state.IndexEntry{Key: "acl-token-bootstrap", Value: req.ModifyIndex}) } func restoreCoordinates(header *snapshotHeader, restore *state.Restore, decoder *codec.Decoder) error { diff --git a/agent/consul/state/acl.go b/agent/consul/state/acl.go index <HASH>..<HASH> 100644 --- a/agent/consul/state/acl.go +++ b/agent/consul/state/acl.go @@ -210,7 +210,7 @@ func (s *Store) ACLBootstrap(idx, resetIndex uint64, token *structs.ACLToken, le // We must have initialized before this will ever be possible. existing, err := tx.First("index", "id", "acl-token-bootstrap") if err != nil { - fmt.Errorf("bootstrap check failed: %v", err) + return fmt.Errorf("bootstrap check failed: %v", err) } if existing != nil { if resetIndex == 0 { diff --git a/testutil/server.go b/testutil/server.go index <HASH>..<HASH> 100644 --- a/testutil/server.go +++ b/testutil/server.go @@ -89,7 +89,7 @@ type TestServerConfig struct { PrimaryDatacenter string `json:"primary_datacenter,omitempty"` ACLDefaultPolicy string `json:"acl_default_policy,omitempty"` ACLEnforceVersion8 bool `json:"acl_enforce_version_8"` - ACL TestACLs `json:"acl",omitempty` + ACL TestACLs `json:"acl,omitempty"` Encrypt string `json:"encrypt,omitempty"` CAFile string `json:"ca_file,omitempty"` CertFile string `json:"cert_file,omitempty"`
A few misc fixes found by go vet
hashicorp_consul
train
45071db32ef4eeafc5d4e8026c818d0560338404
diff --git a/dbusmock/mockobject.py b/dbusmock/mockobject.py index <HASH>..<HASH> 100644 --- a/dbusmock/mockobject.py +++ b/dbusmock/mockobject.py @@ -84,6 +84,7 @@ class DBusMockObject(dbus.service.Object): self.path = path self.interface = interface self.is_object_manager = is_object_manager + self.object_manager = None self._template = None self._template_parameters = None @@ -115,6 +116,7 @@ class DBusMockObject(dbus.service.Object): 'GetManagedObjects', '', 'a{oa{sa{sv}}}', 'ret = {dbus.ObjectPath(k): objects[k].props ' + ' for k in objects.keys() if ' + cond + '}') + self.object_manager = self def _reset(self, props): # interface -> name -> value @@ -232,6 +234,7 @@ class DBusMockObject(dbus.service.Object): properties) # make sure created objects inherit the log file stream obj.logfile = self.logfile + obj.object_manager = self.object_manager obj.is_logfile_owner = False obj.AddMethods(interface, methods) @@ -531,6 +534,18 @@ class DBusMockObject(dbus.service.Object): ''' pass + def object_manager_emit_added(self, path): + if self.object_manager is not None: + self.object_manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', + 'oa{sa{sv}}', [dbus.ObjectPath(path), + objects[path].props]) + + def object_manager_emit_removed(self, path): + if self.object_manager is not None: + self.object_manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesRemoved', + 'oas', [dbus.ObjectPath(path), + objects[path].props]) + def mock_method(self, interface, dbus_method, in_signature, *args, **kwargs): '''Master mock method.
mockobject: Add convenience methods for emitting ObjectManager signals Constructing the property lists from the subclass that is creating the object is just too much hassle. Also, track the manager object, so that the methods can be invoked on any objects in the hierarchy.
martinpitt_python-dbusmock
train
247c7c974e7fb582c5dba6192066bfea4773e609
diff --git a/dwave/cloud/client.py b/dwave/cloud/client.py index <HASH>..<HASH> 100644 --- a/dwave/cloud/client.py +++ b/dwave/cloud/client.py @@ -1206,7 +1206,7 @@ class Client(object): if 'id' not in message: raise InvalidAPIResponseError("'id' missing in problem description response") - future.id = message['id'] + future.set_id(message['id']) future.remote_status = status = message['status'] # The future may not have the ID set yet
Use the new submission id setter from the client
dwavesystems_dwave-cloud-client
train
fc4aa7cc7944534e9dfd84ffca44583572d53119
diff --git a/monstro/urls/resolver.py b/monstro/urls/resolver.py index <HASH>..<HASH> 100644 --- a/monstro/urls/resolver.py +++ b/monstro/urls/resolver.py @@ -24,9 +24,10 @@ class Resolver(object): yield URLSpec(**pattern) elif isinstance(pattern, URLSpec): yield pattern + elif isinstance(pattern, Resolver): + yield from pattern.resolve() elif len(pattern) > 1 and isinstance(pattern[1], Resolver): - for pattern in self.include(*pattern): - yield pattern + yield from self.include(*pattern) else: yield URLSpec(*pattern) diff --git a/monstro/urls/tests/test_resolver.py b/monstro/urls/tests/test_resolver.py index <HASH>..<HASH> 100644 --- a/monstro/urls/tests/test_resolver.py +++ b/monstro/urls/tests/test_resolver.py @@ -55,6 +55,15 @@ class ResolverTest(unittest.TestCase): self.assertEqual(url.regex.pattern, r'^/home/login/$') self.assertEqual(url.name, 'home:login') + def test__with_resolver(self): + urls = Resolver(((r'^/login/$', object, {}, 'login'),)) + resolver = Resolver((urls,)) + url = list(resolver.resolve())[0] + + self.assertIsInstance(url, tornado.web.url) + self.assertEqual(url.regex.pattern, r'^/login/$') + self.assertEqual(url.name, 'login') + def test_iterable(self): pattern = tornado.web.url(r'^/login/$', object) resolver = Resolver((pattern,))
Added handling nested resolvers without inclusion.
bindlock_monstro
train
8158ebd43098c40832103894ec68bc0ff8b619b0
diff --git a/src/test/java/jp/co/future/uroborosql/context/SqlContextFactoryTest.java b/src/test/java/jp/co/future/uroborosql/context/SqlContextFactoryTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/jp/co/future/uroborosql/context/SqlContextFactoryTest.java +++ b/src/test/java/jp/co/future/uroborosql/context/SqlContextFactoryTest.java @@ -67,7 +67,8 @@ public class SqlContextFactoryTest { "CLS_STRING", "AAA", "CLS_INT", 1, "CLS_INNER_CLASS_ISTRING", TestConsts.InnerClass.ISTRING, - "CLS_OVERLAP_OVERLAP_VAL", "重複テスト2", + // コンパイラによりバイトコード差異で安定しないためテストしない + // "CLS_OVERLAP_OVERLAP_VAL", "重複テスト2", "CLS_BOOLEAN", TestConsts.BOOLEAN, "CLS_BYTE", TestConsts.BYTE, "CLS_SHORT", TestConsts.SHORT, diff --git a/src/test/java/jp/co/future/uroborosql/context/test/TestConsts.java b/src/test/java/jp/co/future/uroborosql/context/test/TestConsts.java index <HASH>..<HASH> 100644 --- a/src/test/java/jp/co/future/uroborosql/context/test/TestConsts.java +++ b/src/test/java/jp/co/future/uroborosql/context/test/TestConsts.java @@ -57,13 +57,14 @@ public class TestConsts { public static final String ISTRING = "BBB"; } - public final class Overlap { - public static final String OVERLAP_VAL = "重複テスト1"; - } - - public final class OverlapOverlap { - public static final String VAL = "重複テスト2"; - } + // コンパイラによりバイトコード差異で安定しないためテストしない + // public final class Overlap { + // public static final String OVERLAP_VAL = "重複テスト1"; + // } + // + // public final class OverlapOverlap { + // public static final String VAL = "重複テスト2"; + // } interface ProxyContainer { Object getOriginal();
[fix] failed jenkins test (#<I>) * [update] SqlContextFactoryImpl now accepts other types close #<I> SqlContextFactoryImpl now accepts types that can be mapped to JDBC * [fix] failed jenkins test
future-architect_uroborosql
train
0e246409e964a94680dd75a18d2cd4be287ff403
diff --git a/yellowbrick/classifier.py b/yellowbrick/classifier.py index <HASH>..<HASH> 100644 --- a/yellowbrick/classifier.py +++ b/yellowbrick/classifier.py @@ -522,3 +522,46 @@ class ClassBalance(ClassificationScoreVisualizer): # Compute the ceiling for the y limit cmax, cmin = max(self.support.values()), min(self.support.values()) self.ax.set_ylim(0, cmax + cmax* 0.1) + +def class_balance(model, X, y=None, ax=None, classes=None, **kwargs): + """Quick method: + + Displays the support for each class in the + fitted classification model displayed as a bar plot. + + This helper function is a quick wrapper to utilize the ClassBalance + ScoreVisualizer for one-off analysis. + + Parameters + ---------- + X : ndarray or DataFrame of shape n x m + A matrix of n instances with m features. + + y : ndarray or Series of length n + An array or series of target or class values. + + ax : matplotlib axes + The axes to plot the figure on. + + model : the Scikit-Learn estimator + + classes : list of strings + The names of the classes in the target + + Returns + ------- + ax : matplotlib axes + Returns the axes that the class balance plot was drawn on. + """ + # Instantiate the visualizer + visualizer = ClassBalance(model, ax, classes, **kwargs) + + # Create the train and test splits + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) + + # Fit and transform the visualizer (calls draw) + visualizer.fit(X_train, y_train, **kwargs) + visualizer.score(X_test, y_test) + + # Return the axes object on the visualizer + return visualizer.ax
added single call wrapper for ClassBalance for issue #<I>
DistrictDataLabs_yellowbrick
train
c1d3bbee9e3854686551bfc1ddcf9429964ba35c
diff --git a/examples/example_1_toy_function_locally/run_me.py b/examples/example_1_toy_function_locally/run_me.py index <HASH>..<HASH> 100644 --- a/examples/example_1_toy_function_locally/run_me.py +++ b/examples/example_1_toy_function_locally/run_me.py @@ -48,10 +48,10 @@ for i in range(num_workers): #Try BOHB here instead of Hyperband: #simply add -#from hpbandster.api.optimizers.bohb import BOHB +from hpbandster.api.optimizers.bohb import BOHB # and change Hyperband to BOHB below -HB = HyperBand( configspace = config_space, +HB = BOHB( configspace = config_space, run_id = run_id, eta=3,min_budget=27, max_budget=243, # HB parameters nameserver=ns_host, diff --git a/hpbandster/config_generators/bohb.py b/hpbandster/config_generators/bohb.py index <HASH>..<HASH> 100644 --- a/hpbandster/config_generators/bohb.py +++ b/hpbandster/config_generators/bohb.py @@ -267,6 +267,9 @@ class BOHB(base_config_generator): bad_kde = sm.nonparametric.KDEMultivariate(data=train_data_bad, var_type=self.kde_vartypes, bw=bw_estimation) good_kde = sm.nonparametric.KDEMultivariate(data=train_data_good, var_type=self.kde_vartypes, bw=bw_estimation) + bad_kde.bw = np.clip(bad_kde.bw, self.min_bandwidth,None) + good_kde.bw = np.clip(good_kde.bw, self.min_bandwidth,None) + self.kde_models[budget] = { 'good': good_kde, 'bad' : bad_kde
added min_bandwidth also to the kde
automl_HpBandSter
train
684628fd660db66a6236f8244e1627afed574208
diff --git a/lib/cucumber/formatter/ansicolor.rb b/lib/cucumber/formatter/ansicolor.rb index <HASH>..<HASH> 100644 --- a/lib/cucumber/formatter/ansicolor.rb +++ b/lib/cucumber/formatter/ansicolor.rb @@ -93,7 +93,7 @@ module Cucumber # def failed_param(string=nil, &proc) # red(bold(string, &proc)) + red # end - ALIASES.each_value do |method_name| + ALIASES.each_key do |method_name| unless method_name =~ /.*_param/ code = <<-EOF def #{method_name}(string=nil, &proc)
Fixed typo in PR #<I>. > we should use each_key not each_value in ansicolor
cucumber_cucumber-ruby
train
babbc3786c1e67c7e222bd0e341ea15633ba9d0d
diff --git a/app/models/manifestation.rb b/app/models/manifestation.rb index <HASH>..<HASH> 100644 --- a/app/models/manifestation.rb +++ b/app/models/manifestation.rb @@ -515,6 +515,7 @@ class Manifestation < ActiveRecord::Base manifestation_created_at manifestation_updated_at manifestation_identifier + access_address note ) identifiers = {} @@ -551,6 +552,7 @@ class Manifestation < ActiveRecord::Base item_lines << m.created_at item_lines << m.updated_at item_lines << m.manifestation_identifier + item_lines << access_address item_lines << note identifiers.each do |identifier_type| item_lines << m.identifier_contents(identifier_type.to_sym).first @@ -580,6 +582,7 @@ class Manifestation < ActiveRecord::Base line << m.created_at line << m.updated_at line << m.manifestation_identifier + line << access_address line << m.note identifiers.each do |identifier_type| line << m.identifier_contents(identifier_type.to_sym).first
export addess_address next-l/enju_leaf#<I>
next-l_enju_biblio
train
c46af91f3dee7e7334bb7f39e05a986e15919542
diff --git a/presto-orc/src/main/java/com/facebook/presto/orc/metadata/OrcMetadataReader.java b/presto-orc/src/main/java/com/facebook/presto/orc/metadata/OrcMetadataReader.java index <HASH>..<HASH> 100644 --- a/presto-orc/src/main/java/com/facebook/presto/orc/metadata/OrcMetadataReader.java +++ b/presto-orc/src/main/java/com/facebook/presto/orc/metadata/OrcMetadataReader.java @@ -74,7 +74,7 @@ public class OrcMetadataReader private static StripeStatistics toStripeStatistics(OrcProto.StripeStatistics stripeStatistics) { - return new StripeStatistics(toColumnStatistics(stripeStatistics.getColStatsList())); + return new StripeStatistics(toColumnStatistics(stripeStatistics.getColStatsList(), false)); } @Override @@ -88,7 +88,7 @@ public class OrcMetadataReader footer.getRowIndexStride(), toStripeInformation(footer.getStripesList()), toType(footer.getTypesList()), - toColumnStatistics(footer.getStatisticsList())); + toColumnStatistics(footer.getStatisticsList(), false)); } private static List<StripeInformation> toStripeInformation(List<OrcProto.StripeInformation> types) @@ -184,21 +184,21 @@ public class OrcMetadataReader positions.add(intPosition); } - return new RowGroupIndex(positions.build(), toColumnStatistics(rowIndexEntry.getStatistics())); + return new RowGroupIndex(positions.build(), toColumnStatistics(rowIndexEntry.getStatistics(), true)); } - private static ColumnStatistics toColumnStatistics(OrcProto.ColumnStatistics statistics) + private static ColumnStatistics toColumnStatistics(OrcProto.ColumnStatistics statistics, boolean isRowGroup) { return new ColumnStatistics( statistics.getNumberOfValues(), toBooleanStatistics(statistics.getBucketStatistics()), toIntegerStatistics(statistics.getIntStatistics()), toDoubleStatistics(statistics.getDoubleStatistics()), - toStringStatistics(statistics.getStringStatistics()), - toDateStatistics(statistics.getDateStatistics())); + toStringStatistics(statistics.getStringStatistics(), isRowGroup), + toDateStatistics(statistics.getDateStatistics(), isRowGroup)); } - private static List<ColumnStatistics> toColumnStatistics(List<OrcProto.ColumnStatistics> columnStatistics) + private static List<ColumnStatistics> toColumnStatistics(List<OrcProto.ColumnStatistics> columnStatistics, final boolean isRowGroup) { if (columnStatistics == null) { return ImmutableList.of(); @@ -208,7 +208,7 @@ public class OrcMetadataReader @Override public ColumnStatistics apply(OrcProto.ColumnStatistics columnStatistics) { - return toColumnStatistics(columnStatistics); + return toColumnStatistics(columnStatistics, isRowGroup); } })); } @@ -244,8 +244,13 @@ public class OrcMetadataReader doubleStatistics.hasMaximum() ? doubleStatistics.getMaximum() : null); } - private static StringStatistics toStringStatistics(OrcProto.StringStatistics stringStatistics) + private static StringStatistics toStringStatistics(OrcProto.StringStatistics stringStatistics, boolean isRowGroup) { + // TODO remove this when date statistics in ORC are fixed https://issues.apache.org/jira/browse/HIVE-8732 + if (!isRowGroup) { + return null; + } + if (!stringStatistics.hasMinimum() && !stringStatistics.hasMaximum()) { return null; } @@ -255,8 +260,13 @@ public class OrcMetadataReader stringStatistics.hasMaximum() ? stringStatistics.getMaximum() : null); } - private static DateStatistics toDateStatistics(OrcProto.DateStatistics dateStatistics) + private static DateStatistics toDateStatistics(OrcProto.DateStatistics dateStatistics, boolean isRowGroup) { + // TODO remove this when date statistics in ORC are fixed https://issues.apache.org/jira/browse/HIVE-8732 + if (!isRowGroup) { + return null; + } + if (!dateStatistics.hasMinimum() && !dateStatistics.hasMaximum()) { return null; }
Disable ORC String and Date statistics which are broken The merge logic ORC String and Date statistics are broken so the statistics for stripes and files in ORC can not be used for String and Date columns.
prestodb_presto
train
ed69d5ba4eb8d0afc497346c9a4a3b21499cd663
diff --git a/lxd/db/node.go b/lxd/db/node.go index <HASH>..<HASH> 100644 --- a/lxd/db/node.go +++ b/lxd/db/node.go @@ -391,8 +391,9 @@ func (c *ClusterTx) NodeOfflineThreshold() (time.Duration, error) { return threshold, nil } -// NodeWithLeastContainers returns the name of the non-offline node with -// with the least number of containers. +// NodeWithLeastContainers returns the name of the non-offline node with with +// the least number of containers (either already created or being created with +// an operation). func (c *ClusterTx) NodeWithLeastContainers() (string, error) { threshold, err := c.NodeOfflineThreshold() if err != nil { @@ -409,10 +410,21 @@ func (c *ClusterTx) NodeWithLeastContainers() (string, error) { if node.IsOffline(threshold) { continue } - count, err := query.Count(c.tx, "containers", "node_id=?", node.ID) + + // Fetch the number of containers already created on this node. + created, err := query.Count(c.tx, "containers", "node_id=?", node.ID) if err != nil { - return "", errors.Wrap(err, "failed to get containers count") + return "", errors.Wrap(err, "Failed to get containers count") } + + // Fetch the number of containers currently being created on this node. + pending, err := query.Count( + c.tx, "operations", "node_id=? AND type=?", node.ID, OperationContainerCreate) + if err != nil { + return "", errors.Wrap(err, "Failed to get pending containers count") + } + + count := created + pending if containers == -1 || count < containers { containers = count name = node.Name diff --git a/lxd/db/node_test.go b/lxd/db/node_test.go index <HASH>..<HASH> 100644 --- a/lxd/db/node_test.go +++ b/lxd/db/node_test.go @@ -260,3 +260,23 @@ INSERT INTO containers (id, node_id, name, architecture, type) VALUES (1, ?, 'fo require.NoError(t, err) assert.Equal(t, "buzz", name) } + +// If there are 2 online nodes, and a container is pending on one of them, +// return the address of the other one number of containers. +func TestNodeWithLeastContainers_Pending(t *testing.T) { + tx, cleanup := db.NewTestClusterTx(t) + defer cleanup() + + _, err := tx.NodeAdd("buzz", "1.2.3.4:666") + require.NoError(t, err) + + // Add a pending container to the default node (ID 1) + _, err = tx.Tx().Exec(` +INSERT INTO operations (id, uuid, node_id, type) VALUES (1, 'abc', 1, ?) +`, db.OperationContainerCreate) + require.NoError(t, err) + + name, err := tx.NodeWithLeastContainers() + require.NoError(t, err) + assert.Equal(t, "buzz", name) +}
Consider pending containers when placing a new container
lxc_lxd
train
192295041b8b94d7479d47fe8c11db076c53404a
diff --git a/libraries/common/constants/Device.js b/libraries/common/constants/Device.js index <HASH>..<HASH> 100644 --- a/libraries/common/constants/Device.js +++ b/libraries/common/constants/Device.js @@ -4,7 +4,14 @@ export const OS_IOS = 'ios'; export const TYPE_PHONE = 'phone'; -export const MODEL_NAMES_IPHONE_X = ['iPhone10,3', 'iPhone10,6']; +export const MODEL_NAMES_IPHONE_X = [ + 'iPhone10,3', + 'iPhone10,6', + 'iPhone11,2', + 'iPhone11,4', + 'iPhone11,6', + 'iPhone11,8', +]; /** * Page insets are device screen areas which can't be used to display content. Those come especially
PWA-<I> added support for iphoneXs, XsMax, XR
shopgate_pwa
train
2c1c8580db1facb1cf640d14dfd1063a79d20b2a
diff --git a/AntiSpoofHooks.php b/AntiSpoofHooks.php index <HASH>..<HASH> 100644 --- a/AntiSpoofHooks.php +++ b/AntiSpoofHooks.php @@ -52,7 +52,7 @@ class AntiSpoofHooks { } $name = $user->getName(); - $spoof = self::makeSpoofUser( $name ); + $spoof = static::makeSpoofUser( $name ); if ( $spoof->isLegal() ) { $normalized = $spoof->getNormalized(); $conflicts = $spoof->getConflicts(); @@ -108,7 +108,7 @@ class AntiSpoofHooks { * @return bool */ public static function asAddNewAccountHook( $user ) { - $spoof = self::makeSpoofUser( $user->getName() ); + $spoof = static::makeSpoofUser( $user->getName() ); $spoof->record(); return true; } @@ -123,7 +123,7 @@ class AntiSpoofHooks { * @return bool */ public static function asAddRenameUserHook( $uid, $oldName, $newName ) { - $spoof = self::makeSpoofUser( $newName ); + $spoof = static::makeSpoofUser( $newName ); $spoof->update( $oldName ); return true; }
Few more LSB for good measure
wikimedia_mediawiki-extensions-AntiSpoof
train
d26a177b678836b198b63330ae164972fcef6a67
diff --git a/ChangeLog b/ChangeLog index <HASH>..<HASH> 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,6 +3,7 @@ * Enhanced TabeleCell to return nil when there is no corresponding cell for a referenced column * Added css selector support for SelectList and Div * Added ability to pass clasname as string to visit_page, on_page, and if_page methods + * Added params class instance variable to hold hash values that can be used in the page === Version 0.7.4 / 2012-9-8 * Enhancements diff --git a/lib/page-object/accessors.rb b/lib/page-object/accessors.rb index <HASH>..<HASH> 100644 --- a/lib/page-object/accessors.rb +++ b/lib/page-object/accessors.rb @@ -10,6 +10,24 @@ module PageObject module Accessors # + # Set some values that can be used withing the class. This is + # typically used to provide values that help build dynamic urls in + # the page_url method + # + # @param [Hash] the value to set the params + # + def params=(the_params) + @params = the_params + end + + # + # Return the params that exist on this page class + # + def params + @params ||= {} + end + + # # Specify the url for the page. A call to this method will generate a # 'goto' method to take you to the page. # diff --git a/spec/page-object/page-object_spec.rb b/spec/page-object/page-object_spec.rb index <HASH>..<HASH> 100644 --- a/spec/page-object/page-object_spec.rb +++ b/spec/page-object/page-object_spec.rb @@ -13,7 +13,7 @@ describe PageObject do let(:watir_page_object) { PageObjectTestPageObject.new(watir_browser) } let(:selenium_page_object) { PageObjectTestPageObject.new(selenium_browser) } - context "setting values for the Javascript Framework" do + context "setting values on the PageObject module" do it "should set the javascript framework" do PageObject::JavascriptFrameworkFacade.should_receive(:framework=) PageObject.javascript_framework = :foo @@ -23,8 +23,58 @@ describe PageObject do PageObject::JavascriptFrameworkFacade.should_receive(:add_framework) PageObject.add_framework(:foo, :bar) end + + it "should set a default page wait value" do + PageObject.default_page_wait = 20 + wait = PageObject.instance_variable_get("@page_wait") + wait.should == 20 + end + + it "should provide the default page wait value" do + PageObject.instance_variable_set("@page_wait", 10) + PageObject.default_page_wait.should == 10 + end + + it "should default the page wait value to 30" do + PageObject.instance_variable_set("@page_wait", nil) + PageObject.default_page_wait.should == 30 + end + + it "should set the default element wait value" do + PageObject.default_element_wait = 20 + wait = PageObject.instance_variable_get("@element_wait") + wait.should == 20 + end + + it "should provide the default element wait value" do + PageObject.instance_variable_set("@element_wait", 10) + PageObject.default_element_wait.should == 10 + end + + it "should default the element wait to 5" do + PageObject.instance_variable_set("@element_wait", nil) + PageObject.default_element_wait.should == 5 + end end - + + context "setting values on the PageObject class instance" do + it "should set the params value" do + PageObjectTestPageObject.params = {:some => :value} + params = PageObjectTestPageObject.instance_variable_get("@params") + params[:some].should == :value + end + + it "should provide the params value" do + PageObjectTestPageObject.instance_variable_set("@params", {:value => :updated}) + PageObjectTestPageObject.params[:value].should == :updated + end + + it "should default the params to an empty hash" do + PageObjectTestPageObject.instance_variable_set("@params", nil) + PageObjectTestPageObject.params.should == {} + end + end + context "when created with a watir-webdriver browser" do it "should include the WatirPageObject module" do watir_page_object.platform.should be_kind_of PageObject::Platforms::WatirWebDriver::PageObject
added params hash as new page class variable
cheezy_page-object
train
959c1f8d11f4ee5a47f20e7f9d1e9e73caf342ab
diff --git a/O365/__init__.py b/O365/__init__.py index <HASH>..<HASH> 100644 --- a/O365/__init__.py +++ b/O365/__init__.py @@ -1,6 +1,8 @@ """ A simple python library to interact with Microsoft Graph and Office 365 API """ +import warnings + from .__version__ import __version__ from .account import Account from .address_book import AddressBook, Contact, RecipientType @@ -17,3 +19,7 @@ from .planner import Planner, Task from .utils import ImportanceLevel, Query, Recipient from .utils import OneDriveWellKnowFolderNames, OutlookWellKnowFolderNames from .utils import FileSystemTokenBackend, FirestoreBackend + + +# allow Deprecation warnings to appear +warnings.simplefilter('always', DeprecationWarning) diff --git a/O365/connection.py b/O365/connection.py index <HASH>..<HASH> 100644 --- a/O365/connection.py +++ b/O365/connection.py @@ -384,6 +384,13 @@ class Connection: :rtype: str """ + # TODO: remove this warning in future releases + if redirect_uri == OAUTH_REDIRECT_URL: + warnings.warn('The default redirect uri was changed in version 1.1.4. to' + ' "https://login.microsoftonline.com/common/oauth2/nativeclient".' + ' You may have to change the registered app "redirect uri" or pass here the old "redirect_uri"', + DeprecationWarning) + client_id, client_secret = self.auth if requested_scopes:
DeprecationWarnings should now be printed out
O365_python-o365
train
fdb7a073d62dde565db0083811e5ada3e4875660
diff --git a/library/src/main/java/de/mrapp/android/dialog/decorator/ListDialogDecorator.java b/library/src/main/java/de/mrapp/android/dialog/decorator/ListDialogDecorator.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/de/mrapp/android/dialog/decorator/ListDialogDecorator.java +++ b/library/src/main/java/de/mrapp/android/dialog/decorator/ListDialogDecorator.java @@ -305,7 +305,11 @@ public class ListDialogDecorator extends AbstractDialogDecorator<ButtonBarDialog this.multiChoiceListener = null; this.choiceMode = ListView.CHOICE_MODE_SINGLE; this.checkedItems = new boolean[items.length]; - this.checkedItems[checkedItem] = true; + + if (checkedItem >= 0) { + this.checkedItems[checkedItem] = true; + } + inflateListView(); } @@ -329,7 +333,11 @@ public class ListDialogDecorator extends AbstractDialogDecorator<ButtonBarDialog this.multiChoiceListener = null; this.choiceMode = ListView.CHOICE_MODE_SINGLE; this.checkedItems = new boolean[adapter.getCount()]; - this.checkedItems[checkedItem] = true; + + if (checkedItem >= 0) { + this.checkedItems[checkedItem] = true; + } + inflateListView(); }
Prevent IndexOutOfBoundsException in single choice list dialog, if selected item index is less than 0.
michael-rapp_AndroidMaterialDialog
train
567671a29f29818ff2fd5e1719db9bcbfe7709da
diff --git a/src/Flare/Traits/ModelAdmin/ModelQuerying.php b/src/Flare/Traits/ModelAdmin/ModelQuerying.php index <HASH>..<HASH> 100644 --- a/src/Flare/Traits/ModelAdmin/ModelQuerying.php +++ b/src/Flare/Traits/ModelAdmin/ModelQuerying.php @@ -88,7 +88,7 @@ trait ModelQuerying return $model->paginate($this->perPage); } - return $model->all(); + return $model->get(); } public function totals()
Fix Model Query Ordering when Pagination is off
laravelflare_flare
train
b0978fbcc7065181f83dcb4f0ebbd790d223912f
diff --git a/src/helpers/d3.dynamicBackground.js b/src/helpers/d3.dynamicBackground.js index <HASH>..<HASH> 100644 --- a/src/helpers/d3.dynamicBackground.js +++ b/src/helpers/d3.dynamicBackground.js @@ -22,6 +22,7 @@ export default Class.extend({ this.xAlign = "center"; this.yAlign = "center"; this.element = this.context.append("text").style("font-size", "20px"); + this.sample = this.context.append("text").style("font-size", "20px").style("opacity", 0); if (conditions) { this.setConditions(conditions); @@ -73,23 +74,23 @@ export default Class.extend({ setText(text, delay) { this._timeout && !delay && clearTimeout(this._timeout); this._timeout = setTimeout(() => { - this.element.text(text); + this.sample.text(text); this._resizeText(); + this.element.text(text); }, delay); return this; }, - _resizeText() { - - const bbox = this.element.node().getBBox(); + _resizeText() { + const bbox = this.sample.node().getBBox(); if (!bbox.width || !bbox.height || !this.width || !this.height) return this; // method from http://stackoverflow.com/a/22580176 const widthTransform = this.width * this.widthRatio / bbox.width; const heightTransform = this.height * this.heightRatio / bbox.height; - this.scalar = Math.round(Math.min(widthTransform, heightTransform)); + this.scalar = Math.min(widthTransform, heightTransform); this.element.attr("transform", "scale(" + this.scalar + ")"); this.textHeight = bbox.height * this.scalar;
Calculate text size on hidden sample (#<I>)
vizabi_vizabi
train
02b19f337f0a045fe3ba1c8b21e8ca016763c8b8
diff --git a/modules/ve2/dm/ve.dm.Document.js b/modules/ve2/dm/ve.dm.Document.js index <HASH>..<HASH> 100644 --- a/modules/ve2/dm/ve.dm.Document.js +++ b/modules/ve2/dm/ve.dm.Document.js @@ -119,6 +119,15 @@ ve.dm.Document = function( data, parentDocument ) { // This can only happen if we got unbalanced data throw 'Unbalanced input passed to document'; } + + if ( children.length === 0 && + ve.dm.nodeFactory.canNodeContainContent( + currentNode.getType() + ) + ) { + // Content nodes cannot be childless, add a zero-length text node + children.push( new ve.dm.TextNode( 0 ) ); + } // Attach the children to the node ve.batchSplice( currentNode, 0, 0, children ); } diff --git a/tests/ve2/dm/ve.dm.Document.test.js b/tests/ve2/dm/ve.dm.Document.test.js index <HASH>..<HASH> 100644 --- a/tests/ve2/dm/ve.dm.Document.test.js +++ b/tests/ve2/dm/ve.dm.Document.test.js @@ -2,7 +2,7 @@ module( 've.dm.Document' ); /* Tests */ -test( 'constructor', 3, function() { +test( 'constructor', 4, function() { var doc = new ve.dm.Document( ve.dm.example.data ); deepEqual( ve.example.getNodeTreeSummary( doc.getDocumentNode() ), @@ -27,6 +27,13 @@ test( 'constructor', 3, function() { ve.example.getNodeTreeSummary( new ve.dm.DocumentNode( [ new ve.dm.TextNode( 4 ) ] ) ), 'plain text input is handled correctly' ); + + doc = new ve.dm.Document( [ { 'type': 'paragraph' }, { 'type': '/paragraph' } ] ); + deepEqual( + ve.example.getNodeTreeSummary( doc.getDocumentNode() ), + ve.example.getNodeTreeSummary( new ve.dm.DocumentNode( [ new ve.dm.ParagraphNode( [ new ve.dm.TextNode( 0 ) ] ) ] ) ), + 'empty paragraph gets a zero-length text node' + ); } ); test( 'getData', 1, function() {
Add zero-length text nodes to empty content nodes This is needed to make the results of certain transactions' tree sync round-trip cleanly through the ve.dm.Document constructor Change-Id: I2ab<I>ec6bd7afba5b<I>c<I>f9fa2d<I>d
wikimedia_parsoid
train
4754e6c91aee2499ea11cd2af521432fa7db757d
diff --git a/payex/pxorder.py b/payex/pxorder.py index <HASH>..<HASH> 100644 --- a/payex/pxorder.py +++ b/payex/pxorder.py @@ -105,3 +105,23 @@ class PxOrderCapture4Handler(PxOrderHandler): self._endpoint = self._client.service.Capture4 return self._send_request() + +class PxOrderGetTransactionDetails2Handler(PxOrderHandler): + """ + Reference: + http://www.payexpim.com/technical-reference/pxorder/gettransactiondetails2/ + """ + + field_order = [ + 'accountNumber', + 'transactionNumber' + ] + + def __call__(self, *args, **kwargs): + + super(PxOrderGetTransactionDetails2Handler, self).__call__(*args, **kwargs) + + # Set endpoint and send request + self._endpoint = self._client.service.GetTransactionDetails2 + + return self._send_request() diff --git a/payex/service.py b/payex/service.py index <HASH>..<HASH> 100644 --- a/payex/service.py +++ b/payex/service.py @@ -1,5 +1,5 @@ from payex.pxagreement import PxCreateAgreement3Handler, PxAutoPay2Handler, PxDeleteAgreementHandler, PxAgreementCheckHandler -from payex.pxorder import PxOrderInitialize7Handler, PxOrderCompleteHandler, PxOrderCapture4Handler +from payex.pxorder import PxOrderInitialize7Handler, PxOrderCompleteHandler, PxOrderCapture4Handler, PxOrderGetTransactionDetails2Handler class Payex(object): @@ -24,6 +24,7 @@ class Payex(object): self.add_resource('initialize', PxOrderInitialize7Handler) self.add_resource('complete', PxOrderCompleteHandler) self.add_resource('capture', PxOrderCapture4Handler) + self.add_resource('get_transaction_details', PxOrderGetTransactionDetails2Handler) def add_resource(self, name, handler): """
Added GetTransactionDetails2 handler
PayEx_pypayex
train
3abffe16d46db5e79389a66f0ed723ad77ed3700
diff --git a/test/runtime/kafka.go b/test/runtime/kafka.go index <HASH>..<HASH> 100644 --- a/test/runtime/kafka.go +++ b/test/runtime/kafka.go @@ -129,6 +129,9 @@ var _ = Describe("RuntimeValidatedKafka", func() { }) It("Kafka Policy Ingress", func() { + // GH-3440 Re-enable when stable + return + _, err := vm.PolicyImportAndWait(vm.GetFullPath("Policies-kafka.json"), 300) Expect(err).Should(BeNil()) @@ -170,6 +173,9 @@ var _ = Describe("RuntimeValidatedKafka", func() { }) It("Kafka Policy Role Ingress", func() { + // GH-3440 Re-enable when stable + return + _, err := vm.PolicyImportAndWait(vm.GetFullPath("Policies-kafka-Role.json"), 300) Expect(err).Should(BeNil(), "Expected nil got %s while importing policy Policies-kafka-Role.json", err)
test: Disable unstable Kafka runtime test
cilium_cilium
train
79638b3185dbd638e72447e3dbd9f52464e93ec9
diff --git a/src/consumer/runner.js b/src/consumer/runner.js index <HASH>..<HASH> 100644 --- a/src/consumer/runner.js +++ b/src/consumer/runner.js @@ -132,6 +132,7 @@ module.exports = class Runner { this.consumerGroup.resolveOffset({ topic, partition, offset: message.offset }) await this.consumerGroup.heartbeat({ interval: this.heartbeatInterval }) + await this.consumerGroup.commitOffsetsIfNecessary() } }
Use conditional commit when running each message
tulios_kafkajs
train
0710050472babcbfe11ab9670b1060c23beb1b00
diff --git a/examples/change-query/webpack.config.js b/examples/change-query/webpack.config.js index <HASH>..<HASH> 100644 --- a/examples/change-query/webpack.config.js +++ b/examples/change-query/webpack.config.js @@ -21,9 +21,6 @@ module.exports = { }], }, resolve: { - alias: { - 'redux-filterlist': path.join(__dirname, '../../dist/redux-filterlist.js'), - }, modules: [ 'src', 'node_modules', diff --git a/examples/filters/webpack.config.js b/examples/filters/webpack.config.js index <HASH>..<HASH> 100644 --- a/examples/filters/webpack.config.js +++ b/examples/filters/webpack.config.js @@ -21,9 +21,6 @@ module.exports = { }], }, resolve: { - alias: { - 'redux-filterlist': path.join(__dirname, '../../dist/redux-filterlist.js'), - }, modules: [ 'src', 'node_modules', diff --git a/examples/loading-list/webpack.config.js b/examples/loading-list/webpack.config.js index <HASH>..<HASH> 100644 --- a/examples/loading-list/webpack.config.js +++ b/examples/loading-list/webpack.config.js @@ -21,9 +21,6 @@ module.exports = { }], }, resolve: { - alias: { - 'redux-filterlist': path.join(__dirname, '../../dist/redux-filterlist.js'), - }, modules: [ 'src', 'node_modules', diff --git a/examples/pagination/webpack.config.js b/examples/pagination/webpack.config.js index <HASH>..<HASH> 100644 --- a/examples/pagination/webpack.config.js +++ b/examples/pagination/webpack.config.js @@ -21,9 +21,6 @@ module.exports = { }], }, resolve: { - alias: { - 'redux-filterlist': path.join(__dirname, '../../dist/redux-filterlist.js'), - }, modules: [ 'src', 'node_modules', diff --git a/examples/plugin/webpack.config.js b/examples/plugin/webpack.config.js index <HASH>..<HASH> 100644 --- a/examples/plugin/webpack.config.js +++ b/examples/plugin/webpack.config.js @@ -21,9 +21,6 @@ module.exports = { }], }, resolve: { - alias: { - 'redux-filterlist': path.join(__dirname, '../../dist/redux-filterlist.js'), - }, modules: [ 'src', 'node_modules', diff --git a/examples/simple/webpack.config.js b/examples/simple/webpack.config.js index <HASH>..<HASH> 100644 --- a/examples/simple/webpack.config.js +++ b/examples/simple/webpack.config.js @@ -21,9 +21,6 @@ module.exports = { }], }, resolve: { - alias: { - 'redux-filterlist': path.join(__dirname, '../../dist/redux-filterlist.js'), - }, modules: [ 'src', 'node_modules', diff --git a/examples/sorting/webpack.config.js b/examples/sorting/webpack.config.js index <HASH>..<HASH> 100644 --- a/examples/sorting/webpack.config.js +++ b/examples/sorting/webpack.config.js @@ -21,9 +21,6 @@ module.exports = { }], }, resolve: { - alias: { - 'redux-filterlist': path.join(__dirname, '../../dist/redux-filterlist.js'), - }, modules: [ 'src', 'node_modules',
Removed excess webpack aliases from examples
vtaits_redux-filterlist
train
7fb6b54afa66a65a5025760118d803c764d03539
diff --git a/cumulusci/cli/cli.py b/cumulusci/cli/cli.py index <HASH>..<HASH> 100644 --- a/cumulusci/cli/cli.py +++ b/cumulusci/cli/cli.py @@ -19,6 +19,7 @@ from cumulusci.core.config import TaskConfig from cumulusci.core.config import YamlGlobalConfig from cumulusci.core.config import YamlProjectConfig from cumulusci.core.exceptions import ApexTestException +from cumulusci.core.exceptions import BrowserTestException from cumulusci.core.exceptions import ConfigError from cumulusci.core.exceptions import FlowNotFoundError from cumulusci.core.exceptions import KeychainConnectedAppNotFound @@ -741,6 +742,8 @@ def task_run(config, task_name, org, o, debug, debug_before, debug_after, no_pro exception = click.UsageError(e.message) except ApexTestException as e: exception = click.ClickException('Failed: ApexTestFailure') + except BrowserTestFailure as e: + exception = click.ClickException('Failed: BrowserTestFailure') except MetadataComponentFailure as e: exception = click.ClickException( 'Failed: MetadataComponentFailure') @@ -876,6 +879,8 @@ def flow_run(config, flow_name, org, delete_org, debug, o, skip, no_prompt): exception = click.UsageError(e.message) except ApexTestException as e: exception = click.ClickException('Failed: ApexTestException') + except BrowserTestFailure as e: + exception = click.ClickException('Failed: BrowserTestFailure') except MetadataComponentFailure as e: exception = click.ClickException( 'Failed: MetadataComponentFailure')
Issue #<I>, handle BrowserTestFailure in the CLI
SFDO-Tooling_CumulusCI
train
e3ddd0ffa9d934eb4f41c569e6999a8a02964b3e
diff --git a/lib/hawkejs.js b/lib/hawkejs.js index <HASH>..<HASH> 100644 --- a/lib/hawkejs.js +++ b/lib/hawkejs.js @@ -415,7 +415,7 @@ hawkejs._renderTemplates = function _renderTemplates (template, payload, $update * * @author Jelle De Loecker <jelle@kipdola.be> * @since 2013.01.22 - * @version 2013.01.22 + * @version 2013.02.04 * * @param {object} payload */ @@ -428,8 +428,8 @@ hawkejs._joinBlocksBuffer = function _joinBlocksBuffer (payload) { // Get the block var block = payload.request.blocks[i]; - // Join the html, using newline as a separator - var blockHtml = block.buf.join('\n'); + // Join the html, using EMPTYNESS as a separator + var blockHtml = block.buf.join(''); // Store the html back into the item payload.request.blocks[i] = {html: blockHtml, $: false, name: i,
Join blocks using no separator (in stead of a newline), this fixes newlines popping up for no reason, fixes #1
skerit_hawkejs
train
189c7ea54e18fa69f00928ab9d0dfb2483a77601
diff --git a/retry_hijackable_client_test.go b/retry_hijackable_client_test.go index <HASH>..<HASH> 100644 --- a/retry_hijackable_client_test.go +++ b/retry_hijackable_client_test.go @@ -44,14 +44,13 @@ var _ = Describe("RetryHijackableClient", func() { }) retryableErrors := []error{ - syscall.ECONNREFUSED, - syscall.ECONNRESET, - syscall.ETIMEDOUT, + syscall.ECONNREFUSED, // "connection refused" + syscall.ECONNRESET, // "connection reset by peer" + syscall.ETIMEDOUT, // "operation timed out" errors.New("i/o timeout"), errors.New("no such host"), errors.New("handshake failure"), errors.New("handshake timeout"), - errors.New("connection reset by peer"), errors.New("timeout awaiting response headers"), } diff --git a/retry_round_tripper_test.go b/retry_round_tripper_test.go index <HASH>..<HASH> 100644 --- a/retry_round_tripper_test.go +++ b/retry_round_tripper_test.go @@ -44,14 +44,13 @@ var _ = Describe("RetryRoundTripper", func() { }) retryableErrors := []error{ - syscall.ECONNREFUSED, - syscall.ECONNRESET, - syscall.ETIMEDOUT, + syscall.ECONNREFUSED, // "connection refused" + syscall.ECONNRESET, // "connection reset by peer" + syscall.ETIMEDOUT, // "operation timed out" errors.New("i/o timeout"), errors.New("no such host"), errors.New("handshake failure"), errors.New("handshake timeout"), - errors.New("connection reset by peer"), errors.New("timeout awaiting response headers"), } diff --git a/retryer.go b/retryer.go index <HASH>..<HASH> 100644 --- a/retryer.go +++ b/retryer.go @@ -33,13 +33,12 @@ func (r *DefaultRetryer) IsRetryable(err error) bool { } var defaultRetryableErrors = []error{ - syscall.ECONNREFUSED, - syscall.ECONNRESET, - syscall.ETIMEDOUT, + syscall.ECONNREFUSED, // "connection refused" + syscall.ECONNRESET, // "connection reset by peer" + syscall.ETIMEDOUT, // "operation timed out" errors.New("i/o timeout"), errors.New("no such host"), errors.New("handshake failure"), errors.New("handshake timeout"), - errors.New("connection reset by peer"), errors.New("timeout awaiting response headers"), }
added comments and removed redundant connection reset by peer" message
concourse_retryhttp
train
6a6665effe03bd15df3bd63ad2d512e7f84a1778
diff --git a/src/main/java/com/twilio/sdk/resource/instance/sip/CredentialListInstance.java b/src/main/java/com/twilio/sdk/resource/instance/sip/CredentialListInstance.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/twilio/sdk/resource/instance/sip/CredentialListInstance.java +++ b/src/main/java/com/twilio/sdk/resource/instance/sip/CredentialListInstance.java @@ -14,7 +14,13 @@ import com.twilio.sdk.resource.factory.sip.CredentialFactory; import com.twilio.sdk.resource.instance.sip.Credential; import com.twilio.sdk.resource.list.sip.CredentialList; - +/** + * This class is the instance resource corresponding to /CredentialLists/CLXXX. + * + * NOTE: The 'Instance' suffix in the name was added to avoid a name clash with the list resource + * that corresponds to /Credentials. This unfortunate quirk is caused by this library's convention of + * appending 'List' to instance resources to form their list counterpart. + */ public class CredentialListInstance extends InstanceResource { /** The Constant SID_PROPERTY. */ @@ -30,7 +36,7 @@ public class CredentialListInstance extends InstanceResource { } /** - * Instantiates a new CredentialList. + * Instantiates a new CredentialListInstance. * * @param client the client * @param sid the sid diff --git a/src/main/java/com/twilio/sdk/resource/list/sip/IpAccessControlListList.java b/src/main/java/com/twilio/sdk/resource/list/sip/IpAccessControlListList.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/twilio/sdk/resource/list/sip/IpAccessControlListList.java +++ b/src/main/java/com/twilio/sdk/resource/list/sip/IpAccessControlListList.java @@ -11,6 +11,11 @@ import com.twilio.sdk.resource.factory.sip.IpAccessControlListFactory; import com.twilio.sdk.resource.instance.sip.IpAccessControlList; import org.apache.http.NameValuePair; +/** + * This class is a list of IpAccessControlLists. + * While the name may seem odd at first, it actually is a list of lists, + * so the name is correct. + */ public class IpAccessControlListList extends ListResource<IpAccessControlList> implements IpAccessControlListFactory { /**
add comments explaining naming quirks for sip
twilio_twilio-java
train
02e7ad99cca2cf77a4b3678f402cfdc6259b4332
diff --git a/shadows/supportv4/src/main/java/org/robolectric/shadows/support/v4/SupportFragmentController.java b/shadows/supportv4/src/main/java/org/robolectric/shadows/support/v4/SupportFragmentController.java index <HASH>..<HASH> 100644 --- a/shadows/supportv4/src/main/java/org/robolectric/shadows/support/v4/SupportFragmentController.java +++ b/shadows/supportv4/src/main/java/org/robolectric/shadows/support/v4/SupportFragmentController.java @@ -203,6 +203,17 @@ public class SupportFragmentController<F extends Fragment> return this; } + public SupportFragmentController<F> saveInstanceState(final Bundle outState) { + shadowMainLooper.runPaused( + new Runnable() { + @Override + public void run() { + activityController.saveInstanceState(outState); + } + }); + return this; + } + private static class FragmentControllerActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { diff --git a/shadows/supportv4/src/test/java/org/robolectric/shadows/support/v4/SupportFragmentControllerTest.java b/shadows/supportv4/src/test/java/org/robolectric/shadows/support/v4/SupportFragmentControllerTest.java index <HASH>..<HASH> 100644 --- a/shadows/supportv4/src/test/java/org/robolectric/shadows/support/v4/SupportFragmentControllerTest.java +++ b/shadows/supportv4/src/test/java/org/robolectric/shadows/support/v4/SupportFragmentControllerTest.java @@ -151,6 +151,23 @@ public class SupportFragmentControllerTest { assertThat(fragment.isVisible()).isTrue(); } + @Test + public void savesInstanceState() { + final LoginFragment fragment = new LoginFragment(); + final SupportFragmentController<LoginFragment> controller = + SupportFragmentController.of(fragment, LoginActivity.class); + controller.create().start().resume().visible(); + LoginActivity activity = (LoginActivity) controller.get().getActivity(); + Bundle expectedState = new Bundle(); + expectedState.putBoolean("isRestored", true); + activity.setState(expectedState); + final Bundle savedInstanceState = new Bundle(); + + controller.saveInstanceState(savedInstanceState); + + assertThat(savedInstanceState.getBoolean("isRestored")).isTrue(); + } + public static class LoginFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -159,6 +176,8 @@ public class SupportFragmentControllerTest { } public static class LoginActivity extends FragmentActivity { + private Bundle state = new Bundle(); + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -167,6 +186,16 @@ public class SupportFragmentControllerTest { setContentView(view); } + + @Override + protected void onSaveInstanceState(Bundle savedInstanceState) { + super.onSaveInstanceState(savedInstanceState); + savedInstanceState.putAll(state); + } + + public void setState(Bundle state) { + this.state = state; + } } public static class CustomizedViewIdLoginActivity extends FragmentActivity {
Add saveInstanceState method to SupportFragmentController PiperOrigin-RevId: <I>
robolectric_robolectric
train
9701bacb2e577099adf436ed74fcb01e7e3d31fc
diff --git a/lib/Github/Api/Repo.php b/lib/Github/Api/Repo.php index <HASH>..<HASH> 100644 --- a/lib/Github/Api/Repo.php +++ b/lib/Github/Api/Repo.php @@ -33,6 +33,16 @@ class Repo extends Api } /** + * Get a list of the repositories that the authenticated user can push to + * + * @return array list of repositories + */ + public function getPushableRepos() + { + throw new \BadMethodCallException('Method cannot be implemented using new api version'); + } + + /** * Get the repositories of a user * http://develop.github.com/p/repo.html * diff --git a/test/Github/Tests/Api/RepoTest.php b/test/Github/Tests/Api/RepoTest.php index <HASH>..<HASH> 100644 --- a/test/Github/Tests/Api/RepoTest.php +++ b/test/Github/Tests/Api/RepoTest.php @@ -20,6 +20,16 @@ class RepoTest extends ApiTestCase $api->search('github api', 'fr', 3); } + /** + * @expectedException BadMethodCallException + */ + public function testThatPushableReposIsNotSupported() + { + $api = $this->getApiMock(); + + $api->getPushableRepos(); + } + protected function getApiClass() { return 'Github\Api\Repo';
Invert removal of method. Throw exception instead
KnpLabs_php-github-api
train
534989c8ea0beaad97d32fb57ae81d7006194421
diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java index <HASH>..<HASH> 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java @@ -123,12 +123,12 @@ public class JdbcTokenRepositoryImplTests { // SEC-1964 @Test public void retrievingTokenWithNoSeriesReturnsNull() { - when(logger.isInfoEnabled()).thenReturn(true); + when(logger.isDebugEnabled()).thenReturn(true); assertNull(repo.getTokenForSeries("missingSeries")); - verify(logger).isInfoEnabled(); - verify(logger).info(eq("Querying token for series 'missingSeries' returned no results."), + verify(logger).isDebugEnabled(); + verify(logger).debug(eq("Querying token for series 'missingSeries' returned no results."), any(EmptyResultDataAccessException.class)); verifyNoMoreInteractions(logger); }
SEC-<I>: Fix tests to verify debug logging instead of info
spring-projects_spring-security
train
e79d6984e190e18187b55f85df45d2b80b818adb
diff --git a/aws/resource_aws_instance.go b/aws/resource_aws_instance.go index <HASH>..<HASH> 100644 --- a/aws/resource_aws_instance.go +++ b/aws/resource_aws_instance.go @@ -116,6 +116,7 @@ func resourceAwsInstance() *schema.Resource { return "" } }, + ValidateFunc: validateInstanceUserDataSize, }, "user_data_base64": { diff --git a/aws/validators.go b/aws/validators.go index <HASH>..<HASH> 100644 --- a/aws/validators.go +++ b/aws/validators.go @@ -15,6 +15,15 @@ import ( "github.com/hashicorp/terraform/helper/schema" ) +func validateInstanceUserDataSize(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + if len(value) > 16384 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 16384 bytes", k)) + } + return +} + func validateRdsIdentifier(v interface{}, k string) (ws []string, errors []error) { value := v.(string) if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { diff --git a/aws/validators_test.go b/aws/validators_test.go index <HASH>..<HASH> 100644 --- a/aws/validators_test.go +++ b/aws/validators_test.go @@ -9,6 +9,30 @@ import ( "github.com/aws/aws-sdk-go/service/s3" ) +func TestValidateInstanceUserDataSize(t *testing.T) { + validValues := []string{ + "#!/bin/bash", + "#!/bin/bash\n" + strings.Repeat("#", 16372), // = 16384 + } + + for _, s := range validValues { + _, errors := validateInstanceUserDataSize(s, "user_data") + if len(errors) > 0 { + t.Fatalf("%q should be valid user data with limited size: %v", s, errors) + } + } + + invalidValues := []string{ + "#!/bin/bash\n" + strings.Repeat("#", 16373), // = 16385 + } + + for _, s := range invalidValues { + _, errors := validateInstanceUserDataSize(s, "user_data") + if len(errors) == 0 { + t.Fatalf("%q should not be valid user data with limited size: %v", s, errors) + } + } +} func TestValidateEcrRepositoryName(t *testing.T) { validNames := []string{ "nginx-web-app",
r/aws_instance: validate user data size during plan
terraform-providers_terraform-provider-aws
train
297487d6201308f83bb71704399c1d2f9e3561eb
diff --git a/lxd/db/instance_profiles.go b/lxd/db/instance_profiles.go index <HASH>..<HASH> 100644 --- a/lxd/db/instance_profiles.go +++ b/lxd/db/instance_profiles.go @@ -22,9 +22,9 @@ import "fmt" // InstanceProfile is an association table struct that associates Instances // to Profiles. type InstanceProfile struct { - InstanceID int `db:"primary=yes"` + InstanceID int `db:"primary=yes&order=yes"` ProfileID int - ApplyOrder int + ApplyOrder int `db:"order=yes"` } // InstanceProfileFilter specifies potential query parameter fields.
lxd/db/instance/profiles: Use 'order' tag to order queries by apply order
lxc_lxd
train
d7b8b716efdb7c3c7d6b1645563871a5f3389ee7
diff --git a/src/ReflectionEngine.php b/src/ReflectionEngine.php index <HASH>..<HASH> 100644 --- a/src/ReflectionEngine.php +++ b/src/ReflectionEngine.php @@ -53,18 +53,31 @@ class ReflectionEngine */ protected static $traverser = null; + /** + * @var null|Lexer + */ + protected static $lexer = null; + private function __construct() {} public static function init(LocatorInterface $locator) { + self::$lexer = new Lexer(['usedAttributes' => [ + 'comments', + 'startLine', + 'endLine', + 'startTokenPos', + 'endTokenPos', + 'startFilePos', + 'endFilePos' + ]]); + $refParser = new \ReflectionClass(Parser::class); $isNewParser = $refParser->isInterface(); if (!$isNewParser) { - self::$parser = new Parser(new Lexer(['usedAttributes' => [ - 'comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos', 'startFilePos', 'endFilePos' - ]])); + self::$parser = new Parser(self::$lexer); } else { - self::$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7); + self::$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7, self::$lexer); } self::$traverser = $traverser = new NodeTraverser();
Configure lexer to capture token positions for new parser too
goaop_parser-reflection
train
67a4f331cf4f9553269766a657c78ad783880d18
diff --git a/tests/test_forms.py b/tests/test_forms.py index <HASH>..<HASH> 100644 --- a/tests/test_forms.py +++ b/tests/test_forms.py @@ -1162,3 +1162,16 @@ def test_show_prevents_read_from_instance(): foo = Field(show=False) MyForm(data=Struct(), instance=object()) + + +def test_choice_post_validation_not_overwritten(): + def my_post_validation(field, **_): + raise Exception('foobar') + + class MyForm(Form): + foo = Field.choice(post_validation=my_post_validation, choices=[1, 2, 3]) + + with pytest.raises(Exception) as e: + MyForm() + + assert str(e.value) == 'foobar'
Added test for the bug where post_validation of Field.choice was overwritten (fixes #9)
TriOptima_tri.form
train
766e8957bed9e2d140615f354d3f63f780fe98a3
diff --git a/openquake/server/views.py b/openquake/server/views.py index <HASH>..<HASH> 100644 --- a/openquake/server/views.py +++ b/openquake/server/views.py @@ -350,9 +350,10 @@ def calc_list(request, id=None): Responses are in JSON. """ base_url = _get_base_url(request) + # always filter calculation list unless user is a superuser calc_data = logs.dbcmd('get_calcs', request.GET, utils.get_valid_users(request), - utils.get_acl_on(request), id) + not request.user.is_superuser, id) response_data = [] username = psutil.Process(os.getpid()).username()
Always filter calculation unless request comes from a superuser
gem_oq-engine
train
be3c6c87ff7281064cfb68cf7f3c872ed06a7eed
diff --git a/Application/Config/config.cache.php b/Application/Config/config.cache.php index <HASH>..<HASH> 100644 --- a/Application/Config/config.cache.php +++ b/Application/Config/config.cache.php @@ -1,7 +1,7 @@ <?php return array( - 'cache_path' => '', + 'cache_file_path' => '', 'memcached' => array( 'default' => array( 'hostname' => '127.0.0.1', diff --git a/Application/Config/config.core.php b/Application/Config/config.core.php index <HASH>..<HASH> 100644 --- a/Application/Config/config.core.php +++ b/Application/Config/config.core.php @@ -2,6 +2,8 @@ return array( 'enable_composer' => true, + 'enable_modules' => true, + 'enable_events' => true, 'composer_autoloader' => '', 'registry_caching' => false, 'registry_caching_method' => 'file', diff --git a/Core/Libraries/Cache/drivers/Cache_file.php b/Core/Libraries/Cache/drivers/Cache_file.php index <HASH>..<HASH> 100644 --- a/Core/Libraries/Cache/drivers/Cache_file.php +++ b/Core/Libraries/Cache/drivers/Cache_file.php @@ -66,7 +66,7 @@ class FW_Cache_file extends FW_Driver { Helpers::load('file'); Helpers::load('common'); - $path = Config::get('cache')->cache_path; + $path = Config::get('cache')->cache_file_path; $this->_cache_path = ($path === '') ? 'Application'.DS.'Cache/' : $path; } diff --git a/Core/System/class.core.php b/Core/System/class.core.php index <HASH>..<HASH> 100644 --- a/Core/System/class.core.php +++ b/Core/System/class.core.php @@ -92,11 +92,14 @@ class Core // And initialize the router paths Router::init(); - // Build all the registers for correct operation - Modules::buildRegister($config->registry_caching, - $config->registry_caching_method, - $config->registry_caching_time - ); + // Build all the registers for correct operation, if modules are enabled + if ($config->enable_modules) + { + Modules::buildRegister($config->registry_caching, + $config->registry_caching_method, + $config->registry_caching_time + ); + } // Load Composer if ($config->enable_composer) { @@ -104,6 +107,11 @@ class Core self::loadComposer($file); } + if (!$config->enable_events) + { + Events::disable(); + } + // And fire the coreStartEvent $event = Events::fireEvent('coreStartEvent'); if ($event->isCancelled()) { diff --git a/Core/System/class.events.php b/Core/System/class.events.php index <HASH>..<HASH> 100644 --- a/Core/System/class.events.php +++ b/Core/System/class.events.php @@ -183,8 +183,12 @@ class Events return false; } - Logger::newLevel("Firing Event: '".$eventName."'"); - Logger::log('Initializing Event'); + if (self::$enabled) + { + Logger::newLevel("Firing Event: '".$eventName."'"); + Logger::log('Initializing Event'); + } + if (func_num_args() > 1) { call_user_func_array(array($event, 'init'), array_slice(func_get_args(), 1)); @@ -192,9 +196,6 @@ class Events // Do not run if the event system is disabled if (!self::$enabled) { - Logger::log('Event system is disabled'); - Logger::stopLevel(); - return $event; }
Implemented new config.core.php variables. It is now possible to disable the modules and the events system using the config file. This will completely turn the system off. The event system will still load the event classes but it will not send them around.
FuzeWorks_Core
train
ac7128c03691b59637d0073ec226ecaf2f902de1
diff --git a/src/frontend/org/voltdb/RealVoltDB.java b/src/frontend/org/voltdb/RealVoltDB.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/RealVoltDB.java +++ b/src/frontend/org/voltdb/RealVoltDB.java @@ -353,6 +353,9 @@ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback, HostM */ String m_terminusNonce = null; + // m_durable means commandlogging is enabled. + boolean m_durable = false; + private int m_maxThreadsCount; @Override @@ -1038,15 +1041,15 @@ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback, HostM VoltZK.createStartActionNode(m_messenger.getZK(), m_messenger.getHostId(), m_config.m_startAction); validateStartAction(); - // durable means commandlogging is enabled. - boolean durable = readDeploymentAndCreateStarterCatalogContext(config); + m_durable = readDeploymentAndCreateStarterCatalogContext(config); + if (config.m_isEnterprise && m_config.m_startAction.doesRequireEmptyDirectories() - && !config.m_forceVoltdbCreate && durable) { + && !config.m_forceVoltdbCreate && m_durable) { managedPathsEmptyCheck(config); } //If we are not durable and we are not rejoining we backup auto snapshots if present. //If terminus is present we will recover from shutdown save so dont move. - if (!durable && m_config.m_startAction.doesRecover() && determination.terminusNonce == null) { + if (!m_durable && m_config.m_startAction.doesRecover() && determination.terminusNonce == null) { if (m_nodeSettings.clean()) { String msg = "Archiving old snapshots to " + m_nodeSettings.getSnapshoth() + ".1 and starting an empty database." + @@ -1228,7 +1231,7 @@ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback, HostM } // do the many init tasks in the Inits class - Inits inits = new Inits(m_statusTracker, this, 1, durable); + Inits inits = new Inits(m_statusTracker, this, 1, m_durable); inits.doInitializationWork(); // Need the catalog so that we know how many tables so we can guess at the necessary heap size @@ -1359,7 +1362,7 @@ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback, HostM (ProducerDRGateway) ndrgwConstructor.newInstance( new VoltFile(VoltDB.instance().getDROverflowPath()), new VoltFile(VoltDB.instance().getSnapshotPath()), - (m_config.m_startAction.doesRecover() && (durable || determination.terminusNonce != null)), + willDoActualRecover(), m_config.m_startAction.doesRejoin(), m_replicationActive.get(), m_configuredNumberOfPartitions, @@ -1571,6 +1574,17 @@ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback, HostM } /** + * Check if actual recover is needed + * Return false if we need to start new, + * or command log is disabled, + * or there is no complete snapshot + */ + private boolean willDoActualRecover() + { + return (m_config.m_startAction.doesRecover() && + (m_durable || getTerminusNonce() != null)); + } + /** * recover the partition assignment from one of lost hosts in the same placement group for rejoin * Use the placement group of the recovering host to find a matched host from the lost nodes in the topology * If the partition count from the lost node is the same as the site count of the recovering host, @@ -4075,7 +4089,8 @@ public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback, HostM m_consumerDRGateway.setInitialConversationMembership(expectedClusterMembers.getFirst(), expectedClusterMembers.getSecond()); } - m_consumerDRGateway.initialize(m_config.m_startAction != StartAction.CREATE); + + m_consumerDRGateway.initialize(m_config.m_startAction.doesRejoin() || willDoActualRecover()); } if (m_producerDRGateway != null) { m_producerDRGateway.startListening(m_catalogContext.cluster.getDrproducerenabled(),
ENG-<I> do not resume replication for DR consumer if durability is off (#<I>) ENG-<I>: Do not resume replication for DR consumer if durability is off
VoltDB_voltdb
train
752c860ba058f06e5ac9b7a1a411aaa4373a54b5
diff --git a/spec/project_spec.rb b/spec/project_spec.rb index <HASH>..<HASH> 100644 --- a/spec/project_spec.rb +++ b/spec/project_spec.rb @@ -96,6 +96,7 @@ describe 'RuboCop Project' do let(:bodies) do entries.map do |entry| entry + .gsub(/`[^`]+`/, '``') .sub(/^\*\s*(?:\[.+?\):\s*)?/, '') .sub(/\s*\([^\)]+\)$/, '') end
Ignore contents of backticks in changelog spec
rubocop-hq_rubocop
train
8a85626a710056dfd23cb4560e43d16b206655c5
diff --git a/context.go b/context.go index <HASH>..<HASH> 100644 --- a/context.go +++ b/context.go @@ -3,6 +3,7 @@ package echo import ( "encoding/json" "encoding/xml" + "fmt" "io" "mime" "mime/multipart" @@ -140,6 +141,10 @@ type ( // client to save the file. Attachment(io.ReadSeeker, string) error + // Inline sends a response from `io.ReaderSeeker` as inline, opening + // the file in the browser. + Inline(io.ReadSeeker, string) error + // NoContent sends a response with no body and a status code. NoContent(int) error @@ -417,8 +422,16 @@ func (c *echoContext) File(file string) error { } func (c *echoContext) Attachment(r io.ReadSeeker, name string) (err error) { + return c.contentDisposition(r, name, "attachment") +} + +func (c *echoContext) Inline(r io.ReadSeeker, name string) (err error) { + return c.contentDisposition(r, name, "inline") +} + +func (c *echoContext) contentDisposition(r io.ReadSeeker, name, dispositionType string) (err error) { c.response.Header().Set(HeaderContentType, ContentTypeByExtension(name)) - c.response.Header().Set(HeaderContentDisposition, "attachment; filename="+name) + c.response.Header().Set(HeaderContentDisposition, fmt.Sprintf("%s; filename=%s", dispositionType, name)) c.response.WriteHeader(http.StatusOK) _, err = io.Copy(c.response, r) return diff --git a/context_test.go b/context_test.go index <HASH>..<HASH> 100644 --- a/context_test.go +++ b/context_test.go @@ -145,6 +145,19 @@ func TestContext(t *testing.T) { } } + // Inline + rec = test.NewResponseRecorder() + c = e.NewContext(req, rec).(*echoContext) + file, err = os.Open("_fixture/images/walle.png") + if assert.NoError(t, err) { + err = c.Inline(file, "walle.png") + if assert.NoError(t, err) { + assert.Equal(t, http.StatusOK, rec.Status()) + assert.Equal(t, "inline; filename=walle.png", rec.Header().Get(HeaderContentDisposition)) + assert.Equal(t, 219885, rec.Body.Len()) + } + } + // NoContent rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext)
Inline feature (#<I>)
labstack_echo
train
999620a7d5cad90167c181d8b8d29e4747f7caae
diff --git a/dist/signature-form.tpl.html.js b/dist/signature-form.tpl.html.js index <HASH>..<HASH> 100644 --- a/dist/signature-form.tpl.html.js +++ b/dist/signature-form.tpl.html.js @@ -1,8 +1,8 @@ var ngModule; try { - ngModule = angular.module('wfm.component.signature'); + ngModule = angular.module('wfm.signature'); } catch (e) { - ngModule = angular.module('wfm.component.signature', []); + ngModule = angular.module('wfm.signature', []); } ngModule.run(['$templateCache', function ($templateCache) { diff --git a/dist/signature.tpl.html.js b/dist/signature.tpl.html.js index <HASH>..<HASH> 100644 --- a/dist/signature.tpl.html.js +++ b/dist/signature.tpl.html.js @@ -1,8 +1,8 @@ var ngModule; try { - ngModule = angular.module('wfm.component.signature'); + ngModule = angular.module('wfm.signature'); } catch (e) { - ngModule = angular.module('wfm.component.signature', []); + ngModule = angular.module('wfm.signature', []); } ngModule.run(['$templateCache', function ($templateCache) { diff --git a/lib/angular/signature-ng.js b/lib/angular/signature-ng.js index <HASH>..<HASH> 100644 --- a/lib/angular/signature-ng.js +++ b/lib/angular/signature-ng.js @@ -7,9 +7,9 @@ var canvasDrawr = require('../canvas-drawr'); -module.exports = 'wfm.component.signature'; +module.exports = 'wfm.signature'; -var ngModule = angular.module('wfm.component.signature', ['wfm.core.mediator']) +var ngModule = angular.module('wfm.signature', ['wfm.core.mediator']) require('../../dist'); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,14 @@ { - "name": "fh-wfm-component-signature", + "name": "fh-wfm-signature", "version": "0.0.8", "description": "A signature component for FeedHenry WFM.", "main": "lib/angular/signature-ng.js", "scripts": { - "build": "wfm-template-build -m 'wfm.component.signature'", - "watch": "wfm-template-build -w -m 'wfm.component.signature'" + "build": "wfm-template-build -m 'wfm.signature'", + "watch": "wfm-template-build -w -m 'wfm.signature'" }, "keywords": [ "wfm", - "component", "signature" ], "author": "Brian Leathem",
Rename to fh-wfm-signature
raincatcher-beta_raincatcher-signature
train
29931635f5a6bd58814d77fd519439a015c01adb
diff --git a/src/Models/AdminModel.php b/src/Models/AdminModel.php index <HASH>..<HASH> 100644 --- a/src/Models/AdminModel.php +++ b/src/Models/AdminModel.php @@ -9,7 +9,7 @@ use Symfony\Component\HttpFoundation\File\File; /** * Class AdminModel. */ -class AdminModel extends Model +abstract class AdminModel extends Model { /** * @var array Files to save. @@ -105,6 +105,11 @@ class AdminModel extends Model return $this->files; } + public function setFiles($files) + { + $this->files = $files; + } + /** * @return bool */
Make AdminModel abstract and add method to manually set uploaded files.
despark_ignicms
train
f8ae20c061bc99833f65d5965b25bae58343fc99
diff --git a/dask_ml/_partial.py b/dask_ml/_partial.py index <HASH>..<HASH> 100644 --- a/dask_ml/_partial.py +++ b/dask_ml/_partial.py @@ -7,6 +7,7 @@ import dask import numpy as np import sklearn.utils from dask.delayed import Delayed +from dask.highlevelgraph import HighLevelGraph from toolz import partial logger = logging.getLogger(__name__) @@ -120,19 +121,10 @@ def fit( } ) - graphs = {x_name: x.__dask_graph__(), name: dsk} - if hasattr(y, "__dask_graph__"): - graphs[y_name] = y.__dask_graph__() - - try: - from dask.highlevelgraph import HighLevelGraph - - new_dsk = HighLevelGraph.merge(*graphs.values()) - except ImportError: - from dask import sharedict - - new_dsk = sharedict.merge(*graphs.values()) - + dependencies = [x] + if y is not None: + dependencies.append(y) + new_dsk = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies) value = Delayed((name, nblocks - 1), new_dsk) if compute:
Fix `Delayed` optimization issue (#<I>)
dask_dask-ml
train
8615b3e88bee3cac37661e2279a72a9ae1c68582
diff --git a/src/test/java/org/bff/javampd/MPDPlayerTest.java b/src/test/java/org/bff/javampd/MPDPlayerTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/bff/javampd/MPDPlayerTest.java +++ b/src/test/java/org/bff/javampd/MPDPlayerTest.java @@ -54,6 +54,7 @@ public class MPDPlayerTest extends BaseTest { } @Test + @Ignore public void testSetVolume() throws MPDException, IOException { getPlayer().setVolume(0);
Issue <I>: Isolate unit tests
finnyb_javampd
train
f0c0688524b2783d3c9ec651619569afb15b0e77
diff --git a/zappa/cli.py b/zappa/cli.py index <HASH>..<HASH> 100755 --- a/zappa/cli.py +++ b/zappa/cli.py @@ -2000,6 +2000,7 @@ class ZappaCLI(object): self.profile_name = self.stage_config.get('profile_name', None) self.log_level = self.stage_config.get('log_level', "DEBUG") self.domain = self.stage_config.get('domain', None) + self.base_path = self.stage_config.get('base_path', None) self.timeout_seconds = self.stage_config.get('timeout_seconds', 30) dead_letter_arn = self.stage_config.get('dead_letter_arn', '') self.dead_letter_config = {'TargetArn': dead_letter_arn} if dead_letter_arn else {} @@ -2266,6 +2267,11 @@ class ZappaCLI(object): else: settings_s = settings_s + "DOMAIN=None\n" + if self.base_path: + settings_s = settings_s + "BASE_PATH='{0!s}'\n".format((self.base_path)) + else: + settings_s = settings_s + "BASE_PATH=None\n" + # Pass through remote config bucket and path if self.remote_env: settings_s = settings_s + "REMOTE_ENV='{0!s}'\n".format( diff --git a/zappa/core.py b/zappa/core.py index <HASH>..<HASH> 100644 --- a/zappa/core.py +++ b/zappa/core.py @@ -2180,7 +2180,7 @@ class Zappa(object): patchOperations=[ {"op" : "replace", "path" : "/basePath", - "value" : base_path} + "value" : '' if base_path is None else base_path} ]) if not found: self.apigateway_client.create_base_path_mapping( diff --git a/zappa/handler.py b/zappa/handler.py index <HASH>..<HASH> 100644 --- a/zappa/handler.py +++ b/zappa/handler.py @@ -492,6 +492,7 @@ class LambdaHandler(object): script_name=script_name, trailing_slash=self.trailing_slash, binary_support=settings.BINARY_SUPPORT, + base_path=settings.BASE_PATH, context_header_mappings=settings.CONTEXT_HEADER_MAPPINGS ) diff --git a/zappa/wsgi.py b/zappa/wsgi.py index <HASH>..<HASH> 100644 --- a/zappa/wsgi.py +++ b/zappa/wsgi.py @@ -32,6 +32,7 @@ def create_wsgi_request(event_info, script_name=None, trailing_slash=True, binary_support=False, + base_path=None, context_header_mappings={} ): """ @@ -87,6 +88,11 @@ def create_wsgi_request(event_info, headers = titlecase_keys(headers) path = urls.url_unquote(event_info['path']) + if base_path: + script_name = '/' + base_path + + if path.startswith(script_name): + path = path[len(script_name):] if query: query_string = urlencode(query)
Add base_path stripping and fix unsetting of base_path
Miserlou_Zappa
train
b3ac14a6490d63c37d9e56c598fb7f936b62b671
diff --git a/lib/discordrb/data.rb b/lib/discordrb/data.rb index <HASH>..<HASH> 100644 --- a/lib/discordrb/data.rb +++ b/lib/discordrb/data.rb @@ -3021,13 +3021,11 @@ module Discordrb @avatar = data['avatar'] # Will not exist if the data was requested through a webhook token - if data['user'] - @owner = @server.member(data['user']['id'].to_i) - unless @owner - Discordrb::LOGGER.debug("Member with ID #{data['user']['id']} not cached (possibly left the server).") - @owner = @bot.ensure_user(data['user']) - end - end + return unless data['user'] + @owner = @server.member(data['user']['id'].to_i) + return if @owner + Discordrb::LOGGER.debug("Member with ID #{data['user']['id']} not cached (possibly left the server).") + @owner = @bot.ensure_user(data['user']) end # Sets the webhook's avatar
Rework Webhook to fit guard clauses
meew0_discordrb
train
6889353fa2fc38ec214cfb259b6a40d97780ba93
diff --git a/src/Helpers/ColorHelper.php b/src/Helpers/ColorHelper.php index <HASH>..<HASH> 100644 --- a/src/Helpers/ColorHelper.php +++ b/src/Helpers/ColorHelper.php @@ -54,6 +54,25 @@ class ColorHelper } /** + * Converts a hex color to rgba + * @param string $hexColor eg. '#00ffff' + * @param int $alpha 0.00 - 1.00 + * @return string eg. 'rgba(0, 255, 255, 0.5)' + */ + public function rgba(string $hexColor, float $alpha = 1): string + { + // fall back to 1 if out of range + $alpha = (0 <= $alpha) && ($alpha <= 1) ? $alpha : 1; + return sprintf( + 'rgba(%d, %d, %d, %.2f', + $this->red($hexColor), + $this->green($hexColor), + $this->blue($hexColor), + $alpha + ); + } + + /** * Returns the luminosity difference between two colors. * Values above ~4.5 can be considered as good contrast * diff --git a/src/Support/theme.php b/src/Support/theme.php index <HASH>..<HASH> 100644 --- a/src/Support/theme.php +++ b/src/Support/theme.php @@ -20,6 +20,11 @@ function theme_widget(string $widgetName): string return theme()->viewNamespace() . '::widgets.' . $widgetName; } +function theme_color(string $semanticColorName): string +{ + return theme()->themeColorToHex($semanticColorName); +} + function theme(): Theme { return app('appshell.theme'); diff --git a/src/resources/views/customer/show.blade.php b/src/resources/views/customer/show.blade.php index <HASH>..<HASH> 100644 --- a/src/resources/views/customer/show.blade.php +++ b/src/resources/views/customer/show.blade.php @@ -14,7 +14,7 @@ {{ $customer->getName() }} @if (!$customer->is_active) <small> - <span class="badge badge-default"> + <span class="badge badge-secondary"> {{ __('inactive') }} </span> </small> @@ -29,7 +29,7 @@ 'type' => $customer->last_purchase_at ? 'success' : null ]) {{ __('Last purchase') }} - <span title="{{ show_datetime($customer->last_purchase_at, '', 'Y-m-d H:i') }}">{{ show_datetime($customer->last_purchase_at, __('never')) }}</span> + {{ show_datetime($customer->last_purchase_at, __('never')) }} @slot('subtitle') {{ __('Customer since') }} diff --git a/src/resources/views/settings/index.blade.php b/src/resources/views/settings/index.blade.php index <HASH>..<HASH> 100644 --- a/src/resources/views/settings/index.blade.php +++ b/src/resources/views/settings/index.blade.php @@ -6,7 +6,7 @@ @section('content') -<div class="card"><div class="card-body"> + {!! Form::open(['route' => 'appshell.settings.update', 'method' => 'PUT']) !!} <ul class="nav nav-tabs" role="tablist"> @foreach($tree->nodes() as $tab) @@ -24,7 +24,7 @@ @component(theme_widget('group'), ['accent' => 'secondary']) @slot('title'){{ $group->label() }}@endslot @foreach($group->items() as $item) - @component(theme_widget('form' . $item->getWidget()->component()), + @component(theme_widget('form.' . $item->getWidget()->component()), array_merge([ 'name' => sprintf('settings[%s]', $item->getKey()), 'value' => $item->getValue(), @@ -48,5 +48,5 @@ </div> </div> {!! Form::close() !!} -</div></div> + @stop diff --git a/src/resources/views/widgets/card_with_icon.blade.php b/src/resources/views/widgets/card_with_icon.blade.php index <HASH>..<HASH> 100644 --- a/src/resources/views/widgets/card_with_icon.blade.php +++ b/src/resources/views/widgets/card_with_icon.blade.php @@ -1,15 +1,16 @@ <div class="card{{ isset($type) ? " text-white bg-$type" : '' }}"> - <div class="card-body"> - <div class="h1 text-muted text-right m-b-2"> + <div class="card-body {{ $cardBodyClass ?? '' }}"> + <div class="h1 text-muted text-right {{ $iconClass ?? '' }}"> @if (isset($iconSlot)) {{ $iconSlot }} @elseif (isset($icon)) <i class="zmdi zmdi-{{ $icon }}"></i> @endif </div> - <div class="h4 m-b-0 text-uppercase"> + <div class="h4 mb-0 text-uppercase {{ $titleClass ?? '' }}"> {{ $slot }} </div> <small class="text-muted text-uppercase font-weight-bold">{{ $subtitle }}</small> + {{ $body ?? '' }} </div> </div>
Added rgba and theme_color helpers, extended the card_with_icon component
artkonekt_appshell
train
c8871aabb76c5b548b639da6d82c3c18cab1c1f8
diff --git a/src/Model/ModelTrait.php b/src/Model/ModelTrait.php index <HASH>..<HASH> 100644 --- a/src/Model/ModelTrait.php +++ b/src/Model/ModelTrait.php @@ -58,9 +58,7 @@ trait ModelTrait $getter = "get" . ucfirst($prop); if (method_exists($this, $getter)) { $value = $this->{$getter}(); - if (!is_null($value)) { - $data[$prop] = $this->getValueData($value); - } + $data[$prop] = $this->getValueData($value); } } return $data;
Null is a valid data type that we shouldn't discard
lexide_clay
train
7d55bea900cc7813277ff4266dcbc4077d9e107b
diff --git a/lib/sassc/import_handler.rb b/lib/sassc/import_handler.rb index <HASH>..<HASH> 100644 --- a/lib/sassc/import_handler.rb +++ b/lib/sassc/import_handler.rb @@ -22,7 +22,10 @@ module SassC private def import_function - @import_function ||= FFI::Function.new(:pointer, [:string, :string, :pointer]) do |path, parent_path, cookie| + @import_function ||= FFI::Function.new(:pointer, [:string, :pointer, :pointer]) do |path, importer_entry, compiler| + last_import = Native::compiler_get_last_import(compiler) + parent_path = Native::import_get_path(last_import) + imports = [*@importer.imports(path, parent_path)] imports_to_native(imports) end diff --git a/lib/sassc/native/native_context_api.rb b/lib/sassc/native/native_context_api.rb index <HASH>..<HASH> 100644 --- a/lib/sassc/native/native_context_api.rb +++ b/lib/sassc/native/native_context_api.rb @@ -138,5 +138,8 @@ module SassC def self.context_get_included_files(*args) return_string_array _context_get_included_files(*args) end + + # ADDAPI Sass_Import_Entry ADDCALL sass_compiler_get_last_import(struct Sass_Compiler* compiler); + attach_function :sass_compiler_get_last_import, [:pointer], :pointer end end diff --git a/lib/sassc/native/native_functions_api.rb b/lib/sassc/native/native_functions_api.rb index <HASH>..<HASH> 100644 --- a/lib/sassc/native/native_functions_api.rb +++ b/lib/sassc/native/native_functions_api.rb @@ -65,6 +65,7 @@ module SassC # Getters for import entry # ADDAPI const char* ADDCALL sass_import_get_path (struct Sass_Import*); + attach_function :sass_import_get_path, [:sass_import_ptr], :string # ADDAPI const char* ADDCALL sass_import_get_base (struct Sass_Import*); # ADDAPI const char* ADDCALL sass_import_get_source (struct Sass_Import*); attach_function :sass_import_get_source, [:sass_import_ptr], :string diff --git a/test/custom_importer_test.rb b/test/custom_importer_test.rb index <HASH>..<HASH> 100644 --- a/test/custom_importer_test.rb +++ b/test/custom_importer_test.rb @@ -29,6 +29,12 @@ module SassC end end + class ParentImporter < Importer + def imports(path, parent_path) + Import.new("name.scss", source: ".#{parent_path} { color: red; }") + end + end + def test_custom_importer_works temp_file("styles2.scss", ".hi { color: $var1; }") temp_file("fonts.scss", ".font { color: $var1; }") @@ -106,7 +112,15 @@ CSS end def test_parent_path_is_accessible - skip "TBD" + engine = Engine.new("@import 'parent.scss';", { + importer: ParentImporter, + filename: "import-parent-filename.scss" + }) + + assert_equal <<CSS, engine.render +.import-parent-filename.scss { + color: red; } +CSS end end end
parent/base filename is properly passed to importer
sass_sassc-ruby
train
68b1424ef37e8b8c0b0a4175689328fca2055b70
diff --git a/ryu/controller/controller.py b/ryu/controller/controller.py index <HASH>..<HASH> 100644 --- a/ryu/controller/controller.py +++ b/ryu/controller/controller.py @@ -13,11 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. +import contextlib import gflags import logging import gevent import random -import weakref from gevent.server import StreamServer from gevent.queue import Queue @@ -85,17 +85,25 @@ class Datapath(object): self.recv_q = Queue() self.send_q = Queue() - # weakref: qv_q.aux refers to aux = self - # self.ev_q.aux == weakref.ref(self) + # circular reference self.ev_q.aux == self self.ev_q = dispatcher.EventQueue(handler.QUEUE_NAME_OFP_MSG, handler.HANDSHAKE_DISPATCHER, - weakref.ref(self)) + self) self.set_version(max(self.supported_ofp_version)) self.xid = random.randint(0, self.ofproto.MAX_XID) self.id = None # datapath_id is unknown yet self.ports = None + def close(self): + """ + Call this before discarding this datapath object + The circular refernce as self.ev_q.aux == self must be broken. + """ + # tell this datapath is dead + self.ev_q.set_dispatcher(handler.DEAD_DISPATCHER) + self.ev_q.close() + def set_version(self, version): assert version in self.supported_ofp_version self.ofproto, self.ofproto_parser = self.supported_ofp_version[version] @@ -218,10 +226,5 @@ class Datapath(object): def datapath_connection_factory(socket, address): LOG.debug('connected socket:%s address:%s', socket, address) - - datapath = Datapath(socket, address) - try: + with contextlib.closing(Datapath(socket, address)) as datapath: datapath.serve() - finally: - # tell this datapath is dead - datapath.ev_q.set_dispatcher(handler.DEAD_DISPATCHER) diff --git a/ryu/controller/dispatcher.py b/ryu/controller/dispatcher.py index <HASH>..<HASH> 100644 --- a/ryu/controller/dispatcher.py +++ b/ryu/controller/dispatcher.py @@ -63,10 +63,22 @@ class EventQueue(TrackInstances): # This can be called when python interpreter exiting. # At that time, other object like EventQueueCreate can be # already destructed. So we can't call it blindly. + assert self.aux == None ev_q = self._get_ev_q() if ev_q is not None and self != ev_q: self._queue_q_ev(EventQueueCreate(self, False)) + def close(self): + """ + Call this function before discarding this object. + This function unset self.aux in order to break potential circular + reference. + + Sometimes self.aux results in cyclic reference. + So we need to break it explicitly. (Or use weakref) + """ + self.aux = None + def set_dispatcher(self, dispatcher): old = self.dispatcher new = dispatcher.clone() diff --git a/ryu/controller/dpset.py b/ryu/controller/dpset.py index <HASH>..<HASH> 100644 --- a/ryu/controller/dpset.py +++ b/ryu/controller/dpset.py @@ -93,7 +93,7 @@ class DPSet(object): if ev.ev_q.name != handler.QUEUE_NAME_OFP_MSG: return - datapath = ev.ev_q.aux() + datapath = ev.ev_q.aux assert datapath is not None if ev.new_dispatcher.name == handler.DISPATCHER_NAME_OFP_MAIN: LOG.debug('DPSET: register datapath %s', datapath)
controller: eliminate weakref of datapath.ev_q.aux
osrg_ryu
train
8a7e3b6c7c9c5846dd16ca836a54e104f9194f8f
diff --git a/testsuite/test_workflows.py b/testsuite/test_workflows.py index <HASH>..<HASH> 100644 --- a/testsuite/test_workflows.py +++ b/testsuite/test_workflows.py @@ -35,29 +35,6 @@ TEST_PACKAGES = [ ] -class WorkflowViewTest(InvenioTestCase): - - """ Test search view functions. """ - - def test_main_admin_availability(self): - """Test if admin view is avaiable.""" - from flask import url_for - - response = self.client.get(url_for('workflows.index'), - follow_redirects=True) - # FIXME: tmp 401 due to missing file - self.assert401(response) - - def test_workflow_list_availability(self): - """Test if workflow list view is avaiable.""" - from flask import url_for - - response = self.client.get(url_for('workflows.show_workflows'), - follow_redirects=True) - # FIXME: tmp 401 due to missing file - self.assert401(response) - - class WorkflowTasksTestCase(InvenioTestCase): """ Workflow class for testing.""" @@ -695,7 +672,7 @@ class TestWorkflowTasks(WorkflowTasksTestCase): start_by_wid(workflow.uuid) test_object.delete(test_object.id) -TEST_SUITE = make_test_suite(WorkflowViewTest, WorkflowTasksTestAPI, +TEST_SUITE = make_test_suite(WorkflowTasksTestAPI, TestWorkflowTasks) if __name__ == "__main__":
workflows: remove view test * Removes the view test as it does not test anything as the page requires login and it has different behavior if DEBUG mode is available and thus fails (<I> vs <I>). This can create confusion when developing.
inveniosoftware-contrib_invenio-workflows
train
6bff81ae84aef9a4c71edfaab5e1cf55e2839b84
diff --git a/src/sap.ui.core/src/sap/ui/core/dnd/DragDropBase.js b/src/sap.ui.core/src/sap/ui/core/dnd/DragDropBase.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.core/src/sap/ui/core/dnd/DragDropBase.js +++ b/src/sap.ui.core/src/sap/ui/core/dnd/DragDropBase.js @@ -25,6 +25,7 @@ sap.ui.define(['../Element', '../library', 'sap/base/Log', './DragAndDrop'], * <li>A custom dragging ghost element is not possible in Internet Explorer.</li> * <li>Transparency of the drag ghost element and the cursor during drag-and-drop operations depends on the browser implementation.</li> * <li>Internet Explorer does only support plain text MIME type for the DataTransfer Object.</li> + * <li>In Internet Explorer, default visual drop effect is <code>copy</code> and <code>dropEffect</code> property of the <code>DropInfo</code> has no effect. * <li>Constraining a drag position is not possible, therefore there is no snap-to-grid or snap-to-element feature possible.</li> * <li>Texts in draggable controls cannot be selected.</li> * <li>The text of input fields in draggable controls can be selected, but not dragged.</li> diff --git a/src/sap.ui.core/src/sap/ui/core/dnd/DragDropInfo.js b/src/sap.ui.core/src/sap/ui/core/dnd/DragDropInfo.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.core/src/sap/ui/core/dnd/DragDropInfo.js +++ b/src/sap.ui.core/src/sap/ui/core/dnd/DragDropInfo.js @@ -2,8 +2,8 @@ * ${copyright} */ -sap.ui.define(["./DragInfo", "./DropInfo", "sap/base/Log"], - function(DragInfo, DropInfo, Log) { +sap.ui.define(["./DragInfo", "./DropInfo", "sap/ui/Device", "sap/base/Log"], + function(DragInfo, DropInfo, Device, Log) { "use strict"; /** @@ -87,7 +87,15 @@ sap.ui.define(["./DragInfo", "./DropInfo", "sap/base/Log"], // Mixin the DragInfo implementation DragDropInfo.prototype.isDraggable = DragInfo.prototype.isDraggable; DragDropInfo.prototype.fireDragEnd = DragInfo.prototype.fireDragEnd; - DragDropInfo.prototype.fireDragStart = DragInfo.prototype.fireDragStart; + + DragDropInfo.prototype.fireDragStart = function(oEvent) { + // In IE, we can only control the cursor by setting effectAllowed in the dragstart. + if (Device.browser.msie) { + oEvent.originalEvent.dataTransfer.effectAllowed = this.getDropEffect().toLowerCase(); + } + + return DragInfo.prototype.fireDragStart.apply(this, arguments); + }; DragDropInfo.prototype.getDropTarget = function() { var sTargetElement = this.getTargetElement(); diff --git a/src/sap.ui.core/src/sap/ui/core/dnd/DropInfo.js b/src/sap.ui.core/src/sap/ui/core/dnd/DropInfo.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.core/src/sap/ui/core/dnd/DropInfo.js +++ b/src/sap.ui.core/src/sap/ui/core/dnd/DropInfo.js @@ -41,6 +41,8 @@ sap.ui.define(["./DragDropBase"], /** * Defines the visual drop effect. + * + * In Internet Explorer, default visual drop effect is <code>Copy</code> and this property has no effect. */ dropEffect: {type: "sap.ui.core.dnd.DropEffect", defaultValue: "Move", invalidate: false},
[INTERNAL] DragDropInfo: dropEffect workaround for IE - In IE, we can only control the cursor image by setting effectAllowed in the dragstart event. Setting dropEffect in the dragover handler has no effect and it does not change the cursor. Change-Id: I7edca<I>d<I>d<I>d4fc<I>dbbf<I>f<I>
SAP_openui5
train
3ababa264dc404e9f8eae01045a4531b0b5bd692
diff --git a/setuptools/command/easy_install.py b/setuptools/command/easy_install.py index <HASH>..<HASH> 100755 --- a/setuptools/command/easy_install.py +++ b/setuptools/command/easy_install.py @@ -1862,6 +1862,19 @@ class CommandSpec(list): launcher = os.environ.get('__PYVENV_LAUNCHER__', _default) @classmethod + def from_param(cls, param): + """ + Construct a CommandSpec from a parameter to build_scripts, which may + be None. + """ + if isinstance(param, cls): + return param + if param is None: + return cls.from_environment() + # otherwise, assume it's a string. + return cls.from_string(param) + + @classmethod def from_environment(cls): return cls.from_string(cls.launcher) diff --git a/setuptools/command/install_scripts.py b/setuptools/command/install_scripts.py index <HASH>..<HASH> 100755 --- a/setuptools/command/install_scripts.py +++ b/setuptools/command/install_scripts.py @@ -13,9 +13,8 @@ class install_scripts(orig.install_scripts): self.no_ep = False def run(self): - from setuptools.command.easy_install import ( - ScriptWriter, sys_executable, nt_quote_arg, - ) + from setuptools.command.easy_install import ScriptWriter, CommandSpec + self.run_command("egg_info") if self.distribution.scripts: orig.install_scripts.run(self) # run first to set up self.outfiles @@ -31,15 +30,14 @@ class install_scripts(orig.install_scripts): ei_cmd.egg_name, ei_cmd.egg_version, ) bs_cmd = self.get_finalized_command('build_scripts') - executable = getattr(bs_cmd, 'executable', sys_executable) + cmd = CommandSpec.from_param(getattr(bs_cmd, 'executable', None)) is_wininst = getattr( self.get_finalized_command("bdist_wininst"), '_is_running', False ) if is_wininst: - executable = "python.exe" + cmd = CommandSpec.from_string("python.exe") writer = ScriptWriter.get_writer(force_windows=is_wininst) - header = ScriptWriter.get_header("", nt_quote_arg(executable)) - for args in writer.get_args(dist, header): + for args in writer.get_args(dist, cmd.as_header()): self.write_script(*args) def write_script(self, script_name, contents, mode="t", *ignored):
Update install_scripts to use CommandSpec for generating script headers.
pypa_setuptools
train
fba9377c69a2ac8e1a6483251b681e9c033b1ade
diff --git a/src/js/client/ajaxCapable.js b/src/js/client/ajaxCapable.js index <HASH>..<HASH> 100644 --- a/src/js/client/ajaxCapable.js +++ b/src/js/client/ajaxCapable.js @@ -7,18 +7,26 @@ 1. The request data, which is the result of transforming the model according to the rules specified in `options.rules.modelToRequestPayload`. - 2. The ajax options, which is the result of transforming `options.ajaxOptions` according to the rules specified in + 2. The ajax options, which are the result of transforming `options.ajaxOptions` according to the rules specified in `options.rules.ajaxOptions`. - The remaining request options are controlled using `options.ajaxOptions`, which are options in the format used by - `jQuery.ajax()`. Once the request is sent, the following workflow applies: + The end result is expected to contain options in the format used by `jQuery.ajax()`, + with the exception of the `json: true` option, which is a nicety to improve handling of JSON data payloads. - 1. If the AJAX request returns an error or the result contains a "falsy" `ok` variable, the error is transformed + The rules used to prepare the final AJAX options are expanded before each request, so that you can use IoC + references that refer to the current state of the component. + + Once the request is sent, the following workflow applies: + + 1. If the AJAX request returns an error, the `handleError` invoker is called. The error is transformed using the rules found in `options.rules.errorResponseToModel`, and the results are applied to the component's model using the change applier. - 2. If the AJAX request is successful, the results are transformed using the rules found in - `options.rules.successResponseToModel`, and applied to the model using the change applier. + 2. If the AJAX request is successful, the `handleSuccess` invoker is called. The response data is transformed + using the rules found in `options.rules.successResponseToModel`, and applied to the model using the change + applier. + + All model changes are batched, i.e. the entire set of changes results in a single transaction. This component does not handle any rendering, you are expected to do that yourself, or use a grade that handles that. @@ -49,17 +57,18 @@ }; gpii.templates.ajaxCapable.makeRequest = function (that) { - var options = fluid.model.transformWithRules(that, that.options.rules.ajaxOptions); + var rules = fluid.expandOptions(that.options.rules.ajaxOptions, that); + var transformedAjaxOptions = fluid.model.transformWithRules(that.options.ajaxOptions, rules); var transformedModel = fluid.model.transformWithRules(that.model, that.options.rules.modelToRequestPayload); // We have added a `json` option not supported by `jQuery.ajax()` itself, which makes it easier to pass JSON data. - if (options.json) { - options.contentType = "application/json"; + if (transformedAjaxOptions.json) { + transformedAjaxOptions.contentType = "application/json"; } - options.data = options.json ? JSON.stringify(transformedModel) : transformedModel; - $.ajax(options); + transformedAjaxOptions.data = transformedAjaxOptions.json ? JSON.stringify(transformedModel) : transformedModel; + $.ajax(transformedAjaxOptions); }; gpii.templates.ajaxCapable.handleSuccess = function (that, data) { @@ -107,7 +116,7 @@ // Rules to control how the raw ajaxOptions are permuted before sending to the server. This allows things // like adding model data to the url. ajaxOptions: { - "": "options.ajaxOptions" // By default, pass the full list of options from `options.ajaxOptions` on to `jQuery.ajax()` + "": "" // By default, pass the full list of options from `options.ajaxOptions` on to `jQuery.ajax()` } },
GPII-<I>: Streamlined processing of AJAX options and updated documentation to reflect recent changes.
GPII_gpii-handlebars
train
44b0dae8e1d24f12d044240853c276b9ce3e1f86
diff --git a/examples/test_categories.php b/examples/test_categories.php index <HASH>..<HASH> 100644 --- a/examples/test_categories.php +++ b/examples/test_categories.php @@ -6,6 +6,7 @@ include("../Market/MarketSession.php"); $session = new MarketSession(); $session->login(GOOGLE_EMAIL, GOOGLE_PASSWD); +$session->setAndroidId(ANDROID_DEVICEID); $cr = new CategoriesRequest(); diff --git a/examples/test_screenshot.php b/examples/test_screenshot.php index <HASH>..<HASH> 100644 --- a/examples/test_screenshot.php +++ b/examples/test_screenshot.php @@ -6,6 +6,7 @@ include("../Market/MarketSession.php"); $session = new MarketSession(); $session->login(GOOGLE_EMAIL, GOOGLE_PASSWD); +$session->setAndroidId(ANDROID_DEVICEID); $appId = "7059973813889603239"; $imageId = 1; diff --git a/examples/test_search.php b/examples/test_search.php index <HASH>..<HASH> 100644 --- a/examples/test_search.php +++ b/examples/test_search.php @@ -6,6 +6,7 @@ include("../Market/MarketSession.php"); $session = new MarketSession(); $session->login(GOOGLE_EMAIL, GOOGLE_PASSWD); +$session->setAndroidId(ANDROID_DEVICEID); $ar = new AppsRequest(); $ar->setQuery($_GET["search"] ? $_GET["search"] : "froyo");
Added setAndroidId call
koconder_android-market-api-php
train
b3587a8874910f25a338e19191e10f2982fc52f9
diff --git a/servers/src/test/java/tachyon/master/file/meta/InodeFileTest.java b/servers/src/test/java/tachyon/master/file/meta/InodeFileTest.java index <HASH>..<HASH> 100644 --- a/servers/src/test/java/tachyon/master/file/meta/InodeFileTest.java +++ b/servers/src/test/java/tachyon/master/file/meta/InodeFileTest.java @@ -88,10 +88,10 @@ public final class InodeFileTest extends AbstractInodeTest { InodeFile inodeFile = createInodeFile(1); List<Long> blockIds = Lists.newArrayList(); final int NUM_BLOCKS = 3; - for (int i = 0; i < NUM_BLOCKS; i++) { + for (int i = 0; i < NUM_BLOCKS; i ++) { blockIds.add(inodeFile.getNewBlockId()); } - for (int i = 0; i < NUM_BLOCKS; i++) { + for (int i = 0; i < NUM_BLOCKS; i ++) { Assert.assertEquals(blockIds.get(i), (Long) inodeFile.getBlockIdByIndex(i)); } try {
[SMALLFIX] space before ++
Alluxio_alluxio
train
8c9557b316eec5f971af62299c531e3dc9e57b57
diff --git a/test/gir_ffi/in_out_pointer_test.rb b/test/gir_ffi/in_out_pointer_test.rb index <HASH>..<HASH> 100644 --- a/test/gir_ffi/in_out_pointer_test.rb +++ b/test/gir_ffi/in_out_pointer_test.rb @@ -1,7 +1,5 @@ require 'gir_ffi_test_helper' -require 'gir_ffi/in_out_pointer' - describe GirFFI::InOutPointer do describe ".new" do it "wraps an existing pointer and a type" do
Trust test helper to require all of GirFFI
mvz_gir_ffi
train
6c1f77ff79caf4a1484c4da5c2535c09ca6d3c16
diff --git a/src/java/voldemort/server/protocol/admin/AsyncOperationRunner.java b/src/java/voldemort/server/protocol/admin/AsyncOperationRunner.java index <HASH>..<HASH> 100644 --- a/src/java/voldemort/server/protocol/admin/AsyncOperationRunner.java +++ b/src/java/voldemort/server/protocol/admin/AsyncOperationRunner.java @@ -65,8 +65,7 @@ public class AsyncOperationRunner extends AbstractService { if(operations.get(requestId).getStatus().isComplete()) { logger.debug("Operation complete " + requestId); - // TODO: HIGH talk to alex, we should not remove values if complete - // operations.remove(requestId); + operations.remove(requestId); return true; }
reverted asyncRunner change to Not remove operations after completion.
voldemort_voldemort
train
aabd11dd8d746e59ff25f5ccd27011d9171991af
diff --git a/great_expectations/datasource/generator/batch_generator.py b/great_expectations/datasource/generator/batch_generator.py index <HASH>..<HASH> 100644 --- a/great_expectations/datasource/generator/batch_generator.py +++ b/great_expectations/datasource/generator/batch_generator.py @@ -25,7 +25,48 @@ class BatchGenerator(object): Batches include metadata that identifies how they were constructed--the same “batch_kwargs” assembled by the generator, While not every datasource will enable re-fetching a specific batch of data, GE can store snapshots of batches or store metadata from an - external data version control system. + external data version control system. + + Example Generator Configurations follow:: + + my_datasource_1: + class_name: PandasDatasource + generators: + # This generator will provide two data assets, corresponding to the globs defined under the "file_logs" + # and "data_asset_2" keys. The file_logs asset will be partitioned according to the match group + # defined in partition_regex + default: + class_name: GlobReaderGenerator + base_directory: /var/logs + reader_options: + sep: " + globs: + file_logs: + glob: logs/*.gz + partition_regex: logs/file_(\d{0,4})_\.log\.gz + data_asset_2: + glob: data/*.csv + + my_datasource_2: + class_name: PandasDatasource + generators: + # This generator will create one data asset per subdirectory in /data + # Each asset will have partitions corresponding to the filenames in that subdirectory + default: + class_name: SubdirReaderGenerator + reader_options: + sep: " + base_directory: /data + + my_datasource_3: + class_name: SqlalchemyDatasource + generators: + # This generator will search for a file named with the name of the requested generator asset and the + # .sql suffix to open with a query to use to generate data + default: + class_name: QueryGenerator + + """ _batch_kwargs_type = BatchKwargs
Add additional batch_generator documentation
great-expectations_great_expectations
train
dc0a97cfb04233cdd619972513fd1bc520d102c2
diff --git a/src/Finder.php b/src/Finder.php index <HASH>..<HASH> 100644 --- a/src/Finder.php +++ b/src/Finder.php @@ -33,9 +33,9 @@ class Finder private $type; /** - * @var string|null + * @var string[] */ - private $conditions; + private $where = []; /** * @var string @@ -103,12 +103,29 @@ class Finder $conditions_to_prepare = array_merge($conditions_to_prepare, $arguments); } - $this->conditions = $this->connection->prepareConditions($conditions_to_prepare); + $this->where[] = $this->connection->prepareConditions($conditions_to_prepare); return $this; } /** + * Return where part of the query + */ + public function getWhere() + { + switch (count($this->where)) { + case 0: + return ''; + case 1: + return $this->where[0]; + default: + return implode(' AND ', array_map(function($condition) { + return "($condition)"; + }, $this->where)); + } + } + + /** * @param string $order_by * @return $this */ @@ -190,8 +207,8 @@ class Finder $sql .= " $this->join"; } - if ($this->conditions) { - $sql .= " WHERE $this->conditions"; + if ($where = $this->getWhere()) { + $sql .= " WHERE $where"; } return $this->connection->executeFirstCell($sql); @@ -234,7 +251,9 @@ class Finder */ public function ids() { - return $this->connection->executeFirstColumn($this->getSelectIdsSql()); + $ids = $this->connection->executeFirstColumn($this->getSelectIdsSql()); + + return empty($ids) ? [] : $ids; } /** @@ -314,8 +333,8 @@ class Finder $result .= " $this->join"; } - if ($this->conditions) { - $result .= " WHERE $this->conditions"; + if ($where = $this->getWhere()) { + $result .= " WHERE $where"; } if ($this->order_by) { diff --git a/test/src/FindTest.php b/test/src/FindTest.php index <HASH>..<HASH> 100644 --- a/test/src/FindTest.php +++ b/test/src/FindTest.php @@ -89,6 +89,17 @@ class FindTest extends WritersTypeTestCase } /** + * Test if ids() returns an empty array on empty result set + */ + public function testFindIdsAlwaysReturnsArray() + { + $ids = $this->pool->find(Writer::class)->where('id = ?', -1)->ids(); + + $this->assertInternalType('array', $ids); + $this->assertCount(0, $ids); + } + + /** * Test count using finder object */ public function testCountUsingFinder() @@ -110,6 +121,32 @@ class FindTest extends WritersTypeTestCase } /** + * Test find using multiple calls to where() method + */ + public function testFindByMultipleConditions() + { + $finder_1 = $this->pool->find(Writer::class)->where('`birthday` > ?', '1800-01-01'); + $this->assertEquals("`birthday` > '1800-01-01'", $finder_1->getWhere()); + + /** @var Writer[] $should_be_fyodor */ + $should_be_fyodor_and_leo = $finder_1->all(); + + $this->assertCount(2, $should_be_fyodor_and_leo); + + $finder_2 = $this->pool->find(Writer::class)->where('`birthday` > ?', '1800-01-01')->where('birthday < ?', '1825-01-01'); + $this->assertEquals("(`birthday` > '1800-01-01') AND (birthday < '1825-01-01')", $finder_2->getWhere()); + + /** @var Writer[] $should_be_fyodor */ + $should_be_fyodor = $finder_2->all(); + + $this->assertCount(1, $should_be_fyodor); + + $this->assertInstanceOf(Writer::class, $should_be_fyodor[0]); + $this->assertTrue($should_be_fyodor[0]->isLoaded()); + $this->assertEquals('Fyodor Dostoyevsky', $should_be_fyodor[0]->getName()); + } + + /** * @expectedException \InvalidArgumentException */ public function testConditionsPatternNeedsToBeString()
Support multiple calls to where() in finder
activecollab_databaseobject
train
1ce1abf216dd61098579bd61d764fed9b601d479
diff --git a/lib/express/static.js b/lib/express/static.js index <HASH>..<HASH> 100644 --- a/lib/express/static.js +++ b/lib/express/static.js @@ -41,13 +41,17 @@ exports.File = Class({ */ send: function(request) { - var file = this.path + var cache, file = this.path + if (cache = request.cache.get(file)) + request.contentType(cache.type), + request.halt(200, cache.content) path.exists(file, function(exists){ if (!exists) request.halt() posix.stat(file).addCallback(function(stats){ if (!stats.isFile()) request.halt() posix.cat(file, 'binary').addCallback(function(content){ request.contentType(file) + request.cache.set(file, { type: file, content: content }) request.halt(200, content, 'binary') }) })
Static file caching. Closes #<I> Boosts performance of static file serving roughly %<I>
expressjs_express
train
54b17850262ae5775544e6c763bf192442ba0a9e
diff --git a/billy/importers/names.py b/billy/importers/names.py index <HASH>..<HASH> 100644 --- a/billy/importers/names.py +++ b/billy/importers/names.py @@ -111,7 +111,8 @@ class NameMatcher(object): if (term == self._term or not term) and leg_id: self._manual[chamber][name] = leg_id - if name in self._manual[None]: + # if the name is already in _manual[None] and isn't leg_id + if self._manual[None].get(name, False) not in (False, leg_id): self._manual[None][name] = None else: self._manual[None][name] = leg_id
fix importer if name is already manually matched in lower/upper
openstates_billy
train
06be60abec0c68f7efaa37e2b0b579403ff1c548
diff --git a/Form/Extension/Field/Type/FormTypeFieldExtension.php b/Form/Extension/Field/Type/FormTypeFieldExtension.php index <HASH>..<HASH> 100644 --- a/Form/Extension/Field/Type/FormTypeFieldExtension.php +++ b/Form/Extension/Field/Type/FormTypeFieldExtension.php @@ -16,6 +16,8 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormViewInterface; +use Symfony\Component\OptionsResolver\OptionsResolverInterface; + use Sonata\AdminBundle\Admin\FieldDescriptionInterface; use Sonata\AdminBundle\Exception\NoValueException; @@ -135,28 +137,16 @@ class FormTypeFieldExtension extends AbstractTypeExtension } /** - * Overrides the default options form the extended type. - * - * @param array $options - * - * @return array + * Sets the default options + * + * @param OptionsResolverInterface $resolver Options Resolver */ - public function getDefaultOptions() + public function setDefaultOptions(OptionsResolverInterface $resolver) { - return array( + $resolver->setDefaults(array( 'sonata_admin' => null, 'sonata_field_description' => null, - ); - } - - /** - * Returns the allowed option values for each option (if any). - * - * @return array The allowed option values - */ - public function getAllowedOptionValues() - { - return array(); + )); } /**
Refs #<I> : Follows the BC Break of the default form options in the extension
sonata-project_SonataAdminBundle
train
745c127a6549961cd2a63920b9e6467008411200
diff --git a/losantrest/client.py b/losantrest/client.py index <HASH>..<HASH> 100644 --- a/losantrest/client.py +++ b/losantrest/client.py @@ -26,7 +26,10 @@ SOFTWARE. # pylint: disable=E0401 import requests -import collections +try: + from collections.abc import Mapping +except ImportError: + from collections import Mapping import sys from .application import Application from .application_api_token import ApplicationApiToken @@ -243,7 +246,7 @@ class Client(object): return result map_data = None - if not isinstance(data, collections.Mapping): + if not isinstance(data, Mapping): map_data = [] for idx, val in enumerate(data): map_data.append([str(idx), val])
accidentally overwrote that mapping change again
Losant_losant-rest-python
train
b3d90ccc975605e58604521b054291e55cf0daf7
diff --git a/python/phonenumbers/__init__.py b/python/phonenumbers/__init__.py index <HASH>..<HASH> 100644 --- a/python/phonenumbers/__init__.py +++ b/python/phonenumbers/__init__.py @@ -146,7 +146,7 @@ from .phonenumbermatcher import PhoneNumberMatch, PhoneNumberMatcher, Leniency # Version number is taken from the upstream libphonenumber version # together with an indication of the version of the Python-specific code. -__version__ = "8.12.4" +__version__ = "8.12.5" __all__ = ['PhoneNumber', 'CountryCodeSource', 'FrozenPhoneNumber', 'REGION_CODE_FOR_NON_GEO_ENTITY', 'NumberFormat', 'PhoneNumberDesc', 'PhoneMetadata',
Prep for <I> release
daviddrysdale_python-phonenumbers
train
00417acdaf9952c645a2fa53ff83c8f6dc376aa4
diff --git a/centinel/primitives/tls.py b/centinel/primitives/tls.py index <HASH>..<HASH> 100644 --- a/centinel/primitives/tls.py +++ b/centinel/primitives/tls.py @@ -32,6 +32,8 @@ def get_fingerprint(host, port=443, external=None, log_prefix=''): except ssl.SSLError: # exception could also happen here try: + # this uses the highest version SSL or TLS that both + # endpoints support cert = ssl.get_server_certificate((host, port), ssl_version=ssl.PROTOCOL_SSLv23) except Exception as exp:
add comment to TLS primitive to clarify the logic
iclab_centinel
train
e9f041356860998e77e9bf2f670379b26c386d33
diff --git a/vault/activity_log.go b/vault/activity_log.go index <HASH>..<HASH> 100644 --- a/vault/activity_log.go +++ b/vault/activity_log.go @@ -1498,6 +1498,9 @@ func (a *ActivityLog) loadConfigOrDefault(ctx context.Context) (activityConfig, return config, nil } +// HandleTokenCreation adds the TokenEntry to the current fragment of the activity log. +// This currently occurs on token creation (for tokens without entities) +// or token usage (for tokens associated with entities) func (a *ActivityLog) HandleTokenCreation(entry *logical.TokenEntry) { // enabled state is checked in both of these functions, // because we have to grab a mutex there anyway. diff --git a/vault/request_handling.go b/vault/request_handling.go index <HASH>..<HASH> 100644 --- a/vault/request_handling.go +++ b/vault/request_handling.go @@ -383,6 +383,11 @@ func (c *Core) checkToken(ctx context.Context, req *logical.Request, unauth bool return auth, te, retErr } + // If it is an authenticated ( i.e with vault token ) request + // associated with an entity, increment client count + if !unauth && c.activityLog != nil && te.EntityID != "" { + c.activityLog.HandleTokenCreation(te) + } return auth, te, nil } diff --git a/vault/token_store.go b/vault/token_store.go index <HASH>..<HASH> 100644 --- a/vault/token_store.go +++ b/vault/token_store.go @@ -878,8 +878,8 @@ func (ts *TokenStore) create(ctx context.Context, entry *logical.TokenEntry) err return err } - // Update the activity log - if ts.activityLog != nil { + // Update the activity log in case the token has no entity + if ts.activityLog != nil && entry.EntityID == "" { ts.activityLog.HandleTokenCreation(entry) } @@ -926,8 +926,8 @@ func (ts *TokenStore) create(ctx context.Context, entry *logical.TokenEntry) err entry.ID = fmt.Sprintf("%s.%s", entry.ID, tokenNS.ID) } - // Update the activity log - if ts.activityLog != nil { + // Update the activity log in case the token has no entity + if ts.activityLog != nil && entry.EntityID == "" { ts.activityLog.HandleTokenCreation(entry) }
[VAULT-<I>] Count entity tokens on use (#<I>)
hashicorp_vault
train
d3c10471fb565ddb287c6d18b8176864149a80c3
diff --git a/internetarchive/iacli/ia.py b/internetarchive/iacli/ia.py index <HASH>..<HASH> 100755 --- a/internetarchive/iacli/ia.py +++ b/internetarchive/iacli/ia.py @@ -92,7 +92,7 @@ def main(): globals()['ia_module'] = __import__(module, fromlist=['internetarchive.iacli']) except ImportError: sys.stderr.write('error: "{0}" is not an `ia` command!\n'.format(cmd)) - sys.exit(1) + sys.exit(127) ia_module.main(argv)
Exit with <I> if subcommand does not exist.
jjjake_internetarchive
train
1250312287a8cb4cfff33fda56e64c9767d8b135
diff --git a/cmd/gateway-main.go b/cmd/gateway-main.go index <HASH>..<HASH> 100644 --- a/cmd/gateway-main.go +++ b/cmd/gateway-main.go @@ -301,9 +301,6 @@ func StartGateway(ctx *cli.Context, gw Gateway) { logger.FatalIf(globalNotificationSys.Init(GlobalContext, buckets, newObject), "Unable to initialize notification system") } - // Initialize users credentials and policies in background. - globalIAMSys.InitStore(newObject) - go globalIAMSys.Init(GlobalContext, newObject) if globalCacheConfig.Enabled { diff --git a/cmd/healthcheck-handler.go b/cmd/healthcheck-handler.go index <HASH>..<HASH> 100644 --- a/cmd/healthcheck-handler.go +++ b/cmd/healthcheck-handler.go @@ -95,6 +95,17 @@ func ReadinessCheckHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set(xhttp.MinIOServerStatus, unavailable) } + if globalIsGateway && globalEtcdClient != nil { + // Borrowed from https://github.com/etcd-io/etcd/blob/main/etcdctl/ctlv3/command/ep_command.go#L118 + ctx, cancel := context.WithTimeout(r.Context(), defaultContextTimeout) + defer cancel() + // etcd unreachable throw an error for readiness. + if _, err := globalEtcdClient.Get(ctx, "health"); err != nil { + writeErrorResponse(r.Context(), w, toAPIError(r.Context(), err), r.URL) + return + } + } + writeResponse(w, http.StatusOK, nil, mimeNone) } @@ -104,5 +115,17 @@ func LivenessCheckHandler(w http.ResponseWriter, r *http.Request) { // Service not initialized yet w.Header().Set(xhttp.MinIOServerStatus, unavailable) } + + if globalIsGateway && globalEtcdClient != nil { + // Borrowed from https://github.com/etcd-io/etcd/blob/main/etcdctl/ctlv3/command/ep_command.go#L118 + ctx, cancel := context.WithTimeout(r.Context(), defaultContextTimeout) + defer cancel() + // etcd unreachable throw an error for readiness. + if _, err := globalEtcdClient.Get(ctx, "health"); err != nil { + writeErrorResponse(r.Context(), w, toAPIError(r.Context(), err), r.URL) + return + } + } + writeResponse(w, http.StatusOK, nil, mimeNone) } diff --git a/docs/metrics/healthcheck/README.md b/docs/metrics/healthcheck/README.md index <HASH>..<HASH> 100644 --- a/docs/metrics/healthcheck/README.md +++ b/docs/metrics/healthcheck/README.md @@ -4,7 +4,7 @@ MinIO server exposes three un-authenticated, healthcheck endpoints liveness prob ### Liveness probe -This probe always responds with '200 OK'. When liveness probe fails, Kubernetes like platforms restart the container. +This probe always responds with '200 OK'. Only fails if 'etcd' is configured and unreachable. This behavior is specific to gateway. When liveness probe fails, Kubernetes like platforms restart the container. ``` livenessProbe: @@ -13,6 +13,23 @@ livenessProbe: port: 9000 scheme: HTTP initialDelaySeconds: 120 + periodSeconds: 30 + timeoutSeconds: 10 + successThreshold: 1 + failureThreshold: 3 +``` + +### Readiness probe + +This probe always responds with '200 OK'. Only fails if 'etcd' is configured and unreachable. This behavior is specific to gateway. When readiness probe fails, Kubernetes like platforms turn-off routing to the container. + +``` +readinessProbe: + httpGet: + path: /minio/health/ready + port: 9000 + scheme: HTTP + initialDelaySeconds: 120 periodSeconds: 15 timeoutSeconds: 10 successThreshold: 1
fail ready/liveness if etcd is unhealthy in gateway mode (#<I>)
minio_minio
train
da0a48dc9494af3c9e2fabe53e5724ecf0f50a45
diff --git a/lib/emir/recipes/aiv/slits.py b/lib/emir/recipes/aiv/slits.py index <HASH>..<HASH> 100644 --- a/lib/emir/recipes/aiv/slits.py +++ b/lib/emir/recipes/aiv/slits.py @@ -34,6 +34,9 @@ from numina.array.fwhm import compute_fwhm_2d_simple from numina.array.utils import expand_region import matplotlib.pyplot as plt +from matplotlib.figure import Figure +import matplotlib.patches +from emir.dataproducts import ArrayType # import math # @@ -101,6 +104,7 @@ class TestSlitDetectionRecipeRequirements(RecipeRequirements): class TestSlitDetectionRecipeResult(RecipeResult): frame = Product(DataFrameType) + slitstable = Product(ArrayType) @define_requirements(TestSlitDetectionRecipeRequirements) @@ -193,66 +197,76 @@ class TestSlitDetectionRecipe(BaseRecipe): regions = ndimage.find_objects(relabel_objects) centers = ndimage.center_of_mass(data2, labels=relabel_objects, index=ids) - char_slit(data2, regions, centers) + table = char_slit(data2, regions, centers) - result = self.create_result(frame=hdulist) + result = self.create_result(frame=hdulist, slitstable=table) return result def char_slit(data, regions, centers, box_increase=3, slit_size_ratio=4.0): - for r, c_alt in zip(regions, centers): - print 'initial region', r + result = [] + + for r in regions: + _logger.debug('initial region %s', r) oshape = shape_of_slices(r) ratio = oshape[0] / oshape[1] if ratio < slit_size_ratio: - print "this is not a slit, ratio=", ratio + _logger.debug("this is not a slit, ratio=%f", ratio) continue - print 'initial shape', oshape - print 'ratio', ratio + _logger.debug('initial shape %s', oshape) + _logger.debug('ratio %f', ratio) rp = expand_region(r, box_increase, box_increase, start=0, stop=2048) - print 'expanded region', rp + _logger.debug('expanded region %r', rp) ref = rp[0].start, rp[1].start - print 'reference point', ref + _logger.debug('reference point %r', ref) datas = data[rp] - shape = datas.shape - - print 'data, shape', shape - print 'orig shape', - print 'data, shape', shape_of_slices(rp) - c = ndimage.center_of_mass(datas) fc = datas.shape[0] // 2 cc = datas.shape[1] // 2 - print fc, cc, c[0], c[1] + _logger.debug("%d %d %d %d", fc, cc, c[0], c[1]) peak, fwhm_x, fwhm_y = compute_fwhm_2d_simple(datas, c[1], c[0]) - print 'center', 'y=',c[0] + ref[0], 'x=',c[1] + ref[1] - print 'center', 'y=',c_alt[0], 'x=',c_alt[1] - print 'fwhm_x', fwhm_x - print 'fwhm_y', fwhm_y + _logger.debug('x=%f y=%f', c[1] + ref[1], c[0] + ref[0]) + _logger.debug('fwhm_x %f fwhm_y %f', fwhm_x, fwhm_y) + + colrow = ref[1] + cc + 1, ref[0] + fc + 1 + + _logger.debug('Save figures slit-%d-%d', *colrow) fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(datas) - circle1 = plt.Circle(c[::-1], 0.6, color='r', fill=False) + circle1 = matplotlib.patches.Circle(c[::-1], 0.6, color='r', fill=False) ax.add_artist(circle1) - plt.show() - - plt.title('left-rigth') - plt.plot(datas[fc,:], 'r*-', label='%s' % (ref[0] + fc + 1)) - plt.legend() - plt.show() - - plt.title('top-bottom') - plt.plot(datas[:,cc], 'r*-', label='%s' % (ref[1] + cc + 1)) - plt.legend() - plt.show() + fig.savefig('slit-%d-%d-2d.png' % colrow) + plt.close() + + fig = plt.figure() + ax = fig.add_subplot(111) + ax.set_title('left-rigth') + ax.plot(datas[fc,:], 'r*-', label='%s' % colrow[0]) + ax.legend() + fig.savefig('slit-%d-%d-lr.png' % colrow) + plt.close() + + fig = plt.figure() + ax = fig.add_subplot(111) + ax.set_title('top-bottom') + ax.plot(datas[:,cc], 'r*-', label='%s' % colrow[1]) + ax.legend() + fig.savefig('slit-%d-%d-tb.png'% colrow) + plt.close() + _logger.debug('Label filtered objects') + + result.append([c[1] + ref[1] + 1, c[0] + ref[0] + 1, fwhm_x, fwhm_y]) + + return result
Return the table with center and FWHM
guaix-ucm_pyemir
train
aa5dfd8b28a61951c9eb749c2f199bd1aa6cf535
diff --git a/cmd/kubeadm/app/cmd/upgrade/common.go b/cmd/kubeadm/app/cmd/upgrade/common.go index <HASH>..<HASH> 100644 --- a/cmd/kubeadm/app/cmd/upgrade/common.go +++ b/cmd/kubeadm/app/cmd/upgrade/common.go @@ -163,24 +163,6 @@ func enforceRequirements(flags *applyPlanFlags, args []string, dryRun bool, upgr newK8sVersion = cfg.KubernetesVersion } - ignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(flags.ignorePreflightErrors, cfg.NodeRegistration.IgnorePreflightErrors) - if err != nil { - return nil, nil, nil, err - } - // Also set the union of pre-flight errors to InitConfiguration, to provide a consistent view of the runtime configuration: - cfg.NodeRegistration.IgnorePreflightErrors = ignorePreflightErrorsSet.List() - - // Ensure the user is root - klog.V(1).Info("running preflight checks") - if err := runPreflightChecks(client, ignorePreflightErrorsSet, &cfg.ClusterConfiguration, printer); err != nil { - return nil, nil, nil, err - } - - // Run healthchecks against the cluster - if err := upgrade.CheckClusterHealth(client, &cfg.ClusterConfiguration, ignorePreflightErrorsSet); err != nil { - return nil, nil, nil, errors.Wrap(err, "[upgrade/health] FATAL") - } - // The version arg is mandatory, during upgrade apply, unless it's specified in the config file if upgradeApply && newK8sVersion == "" { if err := cmdutil.ValidateExactArgNumber(args, []string{"version"}); err != nil { @@ -202,6 +184,24 @@ func enforceRequirements(flags *applyPlanFlags, args []string, dryRun bool, upgr } } + ignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(flags.ignorePreflightErrors, cfg.NodeRegistration.IgnorePreflightErrors) + if err != nil { + return nil, nil, nil, err + } + // Also set the union of pre-flight errors to InitConfiguration, to provide a consistent view of the runtime configuration: + cfg.NodeRegistration.IgnorePreflightErrors = ignorePreflightErrorsSet.List() + + // Ensure the user is root + klog.V(1).Info("running preflight checks") + if err := runPreflightChecks(client, ignorePreflightErrorsSet, &cfg.ClusterConfiguration, printer); err != nil { + return nil, nil, nil, err + } + + // Run healthchecks against the cluster + if err := upgrade.CheckClusterHealth(client, &cfg.ClusterConfiguration, ignorePreflightErrorsSet); err != nil { + return nil, nil, nil, errors.Wrap(err, "[upgrade/health] FATAL") + } + // If features gates are passed to the command line, use it (otherwise use featureGates from configuration) if flags.featureGatesString != "" { cfg.FeatureGates, err = features.NewFeatureGate(&features.InitFeatureGates, flags.featureGatesString) diff --git a/cmd/kubeadm/app/phases/upgrade/health.go b/cmd/kubeadm/app/phases/upgrade/health.go index <HASH>..<HASH> 100644 --- a/cmd/kubeadm/app/phases/upgrade/health.go +++ b/cmd/kubeadm/app/phases/upgrade/health.go @@ -65,7 +65,6 @@ func (c *healthCheck) Name() string { // CheckClusterHealth makes sure: // - the API /healthz endpoint is healthy // - all control-plane Nodes are Ready -// - (if self-hosted) that there are DaemonSets with at least one Pod for all control plane components // - (if static pod-hosted) that all required Static Pod manifests exist on disk func CheckClusterHealth(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration, ignoreChecksErrors sets.String) error { fmt.Println("[upgrade] Running cluster health checks")
kubeadm: fail faster when the version is not provided
kubernetes_kubernetes
train
c77c9280c96199b00f65c46a7b2bce46bb1944d1
diff --git a/spec/integration/string_querying_spec.rb b/spec/integration/string_querying_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/string_querying_spec.rb +++ b/spec/integration/string_querying_spec.rb @@ -206,7 +206,7 @@ ScopedSearch::RSpec::Database.test_databases.each do |db| end it "group by explicit" do - @class.search_for('',:group => 'explicit').should have(2).items + @class.search_for('',:group => 'explicit').all.should have(2).items end end end
Fix test to make sure the database query actually gets executed.
wvanbergen_scoped_search
train
20e48bb3e7a34d7c30212b4ba83bed58492f12bd
diff --git a/django-openstack/django_openstack/auth/views.py b/django-openstack/django_openstack/auth/views.py index <HASH>..<HASH> 100644 --- a/django-openstack/django_openstack/auth/views.py +++ b/django-openstack/django_openstack/auth/views.py @@ -35,6 +35,9 @@ class Login(forms.SelfHandlingForm): except api_exceptions.Unauthorized as e: messages.error(request, 'Error authenticating: %s' % e.message) + except api_exceptions.ApiException as e: + messages.error(request, 'Error authenticating with keystone: %s' % + e.message) def login(request): @@ -68,6 +71,3 @@ def switch_tenants(request, tenant_id): def logout(request): request.session.clear() return shortcuts.redirect('splash') - - - diff --git a/django-openstack/django_openstack/context_processors.py b/django-openstack/django_openstack/context_processors.py index <HASH>..<HASH> 100644 --- a/django-openstack/django_openstack/context_processors.py +++ b/django-openstack/django_openstack/context_processors.py @@ -1,8 +1,15 @@ - from django_openstack import api +from django.contrib import messages +from openstackx.api import exceptions as api_exceptions def tenants(request): if not request.user or not request.user.is_authenticated(): return {} - return {'tenants': api.token_list_tenants(request, request.user.token)} + + try: + return {'tenants': api.token_list_tenants(request, request.user.token)} + except api_exceptions.ApiException, e: + messages.error(request, "Unable to retrieve tenant list from\ + keystone: %s" % e.message) + return {'tenants': []} diff --git a/django-openstack/django_openstack/dash/views/images.py b/django-openstack/django_openstack/dash/views/images.py index <HASH>..<HASH> 100644 --- a/django-openstack/django_openstack/dash/views/images.py +++ b/django-openstack/django_openstack/dash/views/images.py @@ -114,7 +114,14 @@ class LaunchForm(forms.SelfHandlingForm): @login_required def index(request, tenant_id): - tenant = api.token_get_tenant(request, request.user.tenant) + tenant = {} + + try: + tenant = api.token_get_tenant(request, request.user.tenant) + except api_exceptions.ApiException, e: + messages.error(request, "Unable to retrienve tenant info\ + from keystone: %s" % e.message) + all_images = [] try: all_images = api.image_list_detailed(request) @@ -166,8 +173,19 @@ def launch(request, tenant_id, image_id): except: return [] - image = api.image_get(request, image_id) - tenant = api.token_get_tenant(request, request.user.tenant) + try: + image = api.image_get(request, image_id) + except Exception, e: + messages.error(request, 'Unable to retrieve image %s: %s' % + (image_id, e.message)) + return redirect('dash_instances', tenant_id) + + try: + tenant = api.token_get_tenant(request, request.user.tenant) + except api_exceptions.ApiException, e: + messages.error(request, 'Unable to retrieve tenant %s: %s' % + (request.user.tenant, e.message)) + return redirect('dash_instances', tenant_id) form, handled = LaunchForm.maybe_handle( request, initial={'flavorlist': flavorlist(), diff --git a/django-openstack/django_openstack/syspanel/views/users.py b/django-openstack/django_openstack/syspanel/views/users.py index <HASH>..<HASH> 100644 --- a/django-openstack/django_openstack/syspanel/views/users.py +++ b/django-openstack/django_openstack/syspanel/views/users.py @@ -39,9 +39,9 @@ class UserDeleteForm(forms.SelfHandlingForm): def handle(self, request, data): user_id = data['user'] api.user_delete(request, user_id) - messages.info(request, - '%s was successfully deleted.' - % user_id) + messages.info(request, '%s was successfully deleted.' + % user_id) + return redirect(request.build_absolute_uri()) @@ -52,7 +52,12 @@ def index(request): if handled: return handled - users = api.user_list(request) + users = [] + try: + users = api.user_list(request) + except api_exceptions.ApiException, e: + messages.error(request, 'Unable to list users: %s' % + e.message) user_delete_form = UserDeleteForm() return render_to_response('syspanel_users.html',{ @@ -119,7 +124,12 @@ def update(request, user_id): @login_required def create(request): - tenants = api.tenant_list(request) + try: + tenants = api.tenant_list(request) + except api_exceptions.ApiException, e: + messages.error(request, 'Unable to retrieve tenant list: %s' % + e.message) + return redirect('syspanel_users') if request.method == "POST": form = UserForm(request.POST, tenant_list=tenants)
improve error handling when keystone and other services are down
openstack_horizon
train
3657e96df273041c9f7f001ba6fb5dde2b2cb1e2
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -162,7 +162,7 @@ TuyaCloud.prototype.request = async function (options) { debug(apiResult.body); if (data.success === false) { - throw new TuyaCloudRequestError({code: data.errorCode, message: data.errorMsg}) + throw new TuyaCloudRequestError({code: data.errorCode, message: data.errorMsg}); } return data.result;
Formatting: fix lack of semicolon
TuyaAPI_cloud
train
a23c3e345b5b7d951fb557bfe393209e70a2d69b
diff --git a/src/streamlink/plugins/artetv.py b/src/streamlink/plugins/artetv.py index <HASH>..<HASH> 100644 --- a/src/streamlink/plugins/artetv.py +++ b/src/streamlink/plugins/artetv.py @@ -1,16 +1,14 @@ """Plugin for Arte.tv, bi-lingual art and culture channel.""" +import logging import re +from operator import itemgetter -from itertools import chain - -from streamlink.compat import urlparse from streamlink.plugin import Plugin from streamlink.plugin.api import validate -from streamlink.stream import HDSStream from streamlink.stream import HLSStream -from streamlink.stream import HTTPStream +log = logging.getLogger(__name__) JSON_VOD_URL = "https://api.arte.tv/api/player/v1/config/{0}/{1}?platform=ARTE_NEXT" JSON_LIVE_URL = "https://api.arte.tv/api/player/v1/livestream/{0}" @@ -32,7 +30,8 @@ _video_schema = validate.Schema({ "height": int, "mediaType": validate.text, "url": validate.text, - "versionShortLibelle": validate.text + "versionProg": int, + "versionLibelle": validate.text }, }, ) @@ -45,44 +44,21 @@ class ArteTV(Plugin): def can_handle_url(cls, url): return _url_re.match(url) - def _create_stream(self, stream, language): - stream_name = "{0}p".format(stream["height"]) - stream_type = stream["mediaType"] - stream_url = stream["url"] - stream_language = stream["versionShortLibelle"] - - if language == "de": - language = ["DE", "VOST-DE", "VA", "VOA", "Dt. Live", "OV", "OmU"] - elif language == "en": - language = ["ANG", "VOST-ANG"] - elif language == "es": - language = ["ESP", "VOST-ESP"] - elif language == "fr": - language = ["FR", "VOST-FR", "VF", "VOF", "Frz. Live", "VO", "ST mal"] - elif language == "pl": - language = ["POL", "VOST-POL"] - - if stream_language in language: - if stream_type in ("hls", "mp4"): - if urlparse(stream_url).path.endswith("m3u8"): + def _create_stream(self, streams): + variant, variantname = min([(stream["versionProg"], stream["versionLibelle"]) for stream in streams.values()], + key=itemgetter(0)) + log.debug(u"Using the '{0}' stream variant".format(variantname)) + for sname, stream in streams.items(): + if stream["versionProg"] == variant: + if stream["mediaType"] == "hls": try: - streams = HLSStream.parse_variant_playlist(self.session, stream_url) - - for stream in streams.items(): - yield stream + streams = HLSStream.parse_variant_playlist(self.session, stream["url"]) + for s in streams.items(): + yield s except IOError as err: - self.logger.error("Failed to extract HLS streams: {0}", err) - else: - yield stream_name, HTTPStream(self.session, stream_url) - - elif stream_type == "f4m": - try: - streams = HDSStream.parse_manifest(self.session, stream_url) - - for stream in streams.items(): - yield stream - except IOError as err: - self.logger.error("Failed to extract HDS streams: {0}", err) + log.warning(u"Failed to extract HLS streams for {0}/{1}: {2}".format(sname, + stream["versionLibelle"], + err)) def _get_streams(self): match = _url_re.match(self.url) @@ -98,10 +74,8 @@ class ArteTV(Plugin): if not video["videoJsonPlayer"]["VSR"]: return - vsr = video["videoJsonPlayer"]["VSR"].values() - streams = (self._create_stream(stream, language) for stream in vsr) - - return chain.from_iterable(streams) + vsr = video["videoJsonPlayer"]["VSR"] + return self._create_stream(vsr) __plugin__ = ArteTV
plugins.artetv: only pick the first variant of the stream (#<I>)
streamlink_streamlink
train
8b9a673748c12f5ffb893603424ebed9cbabd04f
diff --git a/contrib/py_stress/stress.py b/contrib/py_stress/stress.py index <HASH>..<HASH> 100644 --- a/contrib/py_stress/stress.py +++ b/contrib/py_stress/stress.py @@ -67,7 +67,7 @@ parser.add_option('-c', '--columns', type="int", dest="columns", help="Number of columns per key", default=5) parser.add_option('-d', '--nodes', type="string", dest="nodes", help="Host nodes (comma separated)", default="localhost") -parser.add_option('-s', '--stdev', type="int", dest="stdev", default=0.1, +parser.add_option('-s', '--stdev', type="float", dest="stdev", default=0.1, help="standard deviation factor") parser.add_option('-r', '--random', action="store_true", dest="random", help="use random key generator (stdev will have no effect)")
stress.py stdev accepts float instead of int. Patch by Oren Benjamin; revied by brandonwilliams for CASSANDRA-<I> git-svn-id: <URL>
Stratio_stratio-cassandra
train
366d2169fbc0e0f803b68c042b77b6b480836dbc
diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index <HASH>..<HASH> 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -95,7 +95,7 @@ func (abi ABI) getArguments(name string, data []byte) (Arguments, error) { args = event.Inputs } if args == nil { - return nil, errors.New("abi: could not locate named method or event") + return nil, fmt.Errorf("abi: could not locate named method or event: %s", name) } return args, nil }
accounts/abi: display name in "method/event not found" error (#<I>)
ethereum_go-ethereum
train
94120a0fdca7150c6aa99a038a535eb8b92c7464
diff --git a/.travis.yml b/.travis.yml index <HASH>..<HASH> 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,9 +25,8 @@ before_install: - if [[ $TRAVIS_PYTHON_VERSION == 3.6 ]]; then pip install -r requirements-dev-py3.txt; fi - travis_wait travis_retry pip install -r requirements-dev.txt - - travis_wait travis_retry pip install --upgrade "tensorflow>=1.11.0" + - travis_wait travis_retry pip install --upgrade tensorflow - python -c 'import tensorflow; print(tensorflow.__version__)' - - python -c 'import tensorflow; print(tensorflow.executing_eagerly())' - travis_wait travis_retry pip install --upgrade theano - python -c 'import theano; print(theano.__version__)' - travis_wait travis_retry pip install --upgrade https://github.com/Lasagne/Lasagne/archive/master.zip @@ -65,10 +64,8 @@ install: script: - pytest --collect-only # tf eager cannot be run in the same process as standard tf - - python -c 'import tensorflow; import torch; print(tensorflow.__version__); print(torch.__version__)' - pytest --ignore=foolbox/tests/test_models_tensorflow_eager.py - - python -c 'import tensorflow; import torch; print(tensorflow.__version__); print(torch.__version__)' - - pytest -v foolbox/tests/test_models_tensorflow_eager.py + - pytest foolbox/tests/test_models_tensorflow_eager.py - flake8 --ignore E402,E741 . after_success: - coveralls diff --git a/foolbox/models/base.py b/foolbox/models/base.py index <HASH>..<HASH> 100644 --- a/foolbox/models/base.py +++ b/foolbox/models/base.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import + import numpy as np import sys import abc diff --git a/foolbox/models/keras.py b/foolbox/models/keras.py index <HASH>..<HASH> 100644 --- a/foolbox/models/keras.py +++ b/foolbox/models/keras.py @@ -1,4 +1,5 @@ from __future__ import absolute_import + import numpy as np import logging diff --git a/foolbox/models/lasagne.py b/foolbox/models/lasagne.py index <HASH>..<HASH> 100644 --- a/foolbox/models/lasagne.py +++ b/foolbox/models/lasagne.py @@ -1,6 +1,6 @@ from __future__ import absolute_import -import numpy as np +import numpy as np from .base import DifferentiableModel diff --git a/foolbox/models/pytorch.py b/foolbox/models/pytorch.py index <HASH>..<HASH> 100644 --- a/foolbox/models/pytorch.py +++ b/foolbox/models/pytorch.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import + import numpy as np import warnings diff --git a/foolbox/models/tensorflow_eager.py b/foolbox/models/tensorflow_eager.py index <HASH>..<HASH> 100644 --- a/foolbox/models/tensorflow_eager.py +++ b/foolbox/models/tensorflow_eager.py @@ -37,7 +37,6 @@ class TensorFlowEagerModel(DifferentiableModel): # delay import until class is instantiated import tensorflow as tf - print(tf.__version__) assert tf.executing_eagerly() super(TensorFlowEagerModel, self).__init__( diff --git a/foolbox/models/theano.py b/foolbox/models/theano.py index <HASH>..<HASH> 100644 --- a/foolbox/models/theano.py +++ b/foolbox/models/theano.py @@ -1,5 +1,7 @@ from __future__ import absolute_import + import numpy as np + from .base import DifferentiableModel diff --git a/foolbox/models/wrappers.py b/foolbox/models/wrappers.py index <HASH>..<HASH> 100644 --- a/foolbox/models/wrappers.py +++ b/foolbox/models/wrappers.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import + from .base import Model from .base import DifferentiableModel
removed debugging statements and added absolute_import future to models
bethgelab_foolbox
train
6e3a799be3532927438494cf1f74a2bb81a50948
diff --git a/raccoon/lib/tls.py b/raccoon/lib/tls.py index <HASH>..<HASH> 100644 --- a/raccoon/lib/tls.py +++ b/raccoon/lib/tls.py @@ -76,9 +76,9 @@ class TLSHandler(TLSCipherSuiteChecker): result_lines = cert_details.split("\n") for i, line in enumerate(result_lines): - if "Subject Alternative Name" in line: + if "DNS:" in line: result_lines.pop(i) - result_lines.pop(i+1) + result_lines.pop(i-1) cert_details = "\n".join(result_lines) return cert_details diff --git a/raccoon/utils/helper_utils.py b/raccoon/utils/helper_utils.py index <HASH>..<HASH> 100644 --- a/raccoon/utils/helper_utils.py +++ b/raccoon/utils/helper_utils.py @@ -36,6 +36,7 @@ class HelperUtilities: @classmethod def validate_proxy_arguments(cls, *args): + """No more than 1 of the following can be specified: tor_routing, proxy, proxy_list""" if Counter((not arg for arg in (*args,))).get(False) > 1: raise RaccoonException("Must specify only one of the following:\n" "--tor-routing, --proxy-list, --proxy") @@ -52,6 +53,7 @@ class HelperUtilities: @classmethod def create_output_directory(cls, outdir): + """Tries to create base output directory""" cls.PATH = outdir try: os.mkdir(outdir)
fixed SAN dupes in TLS report
evyatarmeged_Raccoon
train
9708ff95fdbaf416104db29946cc7256e092c9b1
diff --git a/lib/setuplib.php b/lib/setuplib.php index <HASH>..<HASH> 100644 --- a/lib/setuplib.php +++ b/lib/setuplib.php @@ -63,7 +63,14 @@ define('MEMORY_HUGE', -4); * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @deprecated since 2.0 */ -class object extends stdClass {}; +class object extends stdClass { + /** + * Constructor. + */ + public function __construct() { + debugging("'object' class has been deprecated, please use stdClass instead.", DEBUG_DEVELOPER); + } +}; /** * Base Moodle Exception class diff --git a/lib/tests/setuplib_test.php b/lib/tests/setuplib_test.php index <HASH>..<HASH> 100644 --- a/lib/tests/setuplib_test.php +++ b/lib/tests/setuplib_test.php @@ -460,4 +460,10 @@ class core_setuplib_testcase extends advanced_testcase { return get_exception_info($e); } } + + public function test_object() { + $obj = new object(); + $this->assertDebuggingCalled("'object' class has been deprecated, please use stdClass instead."); + $this->assertInstanceOf('stdClass', $obj); + } }
MDL-<I> setuplib: depreciate class object properly Previously was marked depricated but not throwwing debugging
moodle_moodle
train