hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
8993062efd46f6fecb61b330a45e75b0ee9b2d4f
diff --git a/src/web3/Web3Service.js b/src/web3/Web3Service.js index <HASH>..<HASH> 100644 --- a/src/web3/Web3Service.js +++ b/src/web3/Web3Service.js @@ -36,14 +36,13 @@ export default class Web3Service extends PrivateService { static buildDeauthenticatingService(deauthenticateAfter = 50){ const service = Web3Service.buildTestService(); - service.manager().onAuthenticated(()=> { - service.get('timer').createTimer('deauthenticate', deauthenticateAfter, false, ()=> - {service._web3.version.getAccounts = - () => { - throw new Error('deauthenticated'); - }; + + service.manager().onAuthenticated(() => { + service.get('timer').createTimer('deauthenticate', deauthenticateAfter, false, () => { + service._web3.version.getAccounts = (cb) => cb(undefined, []); }); }); + return service; } @@ -158,12 +157,7 @@ export default class Web3Service extends PrivateService { } _isStillConnected() { - return _web3Promise(_ => this._web3.version.getNode(_)) - .then( - () => { - return true;}, - () => { - return false;}); + return _web3Promise(_ => this._web3.version.getNode(_)).then(() => true, () => false); } authenticate() { @@ -194,12 +188,10 @@ export default class Web3Service extends PrivateService { } _isStillAuthenticated() { - return _web3Promise(_ => this._web3.version.getAccounts(_)) - .then( - () => { - return true;}, - () => { - return false;}); + return _web3Promise(_ => this._web3.version.getAccounts(_)).then( + accounts => (accounts instanceof Array && accounts.length > 0), + () => false + ); } //using same dummy data as in the web3 documentation: https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethestimategas
Bugfix: spoof web3.version.getAccounts() with node.js style dummy function, and correctly signal deauthentication on empty accounts array.
makerdao_dai.js
train
5337096d5fce9d4d8751614279987979e7172e65
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,14 @@ Your balance: Please see the other examples for a complete overview of all the available API calls. +Conversations WhatsApp Sandbox +------------- +To use the whatsapp sandbox you need to add `messagebird.Feature.ENABLE_CONVERSATIONSAPI_WHATSAPP_SANDBOX` to the list of features you want enabled. Don't forget to replace `YOUR_ACCESS_KEY` with your actual access key. + +```python + client = messagebird.Client('1ekjMs368KTRlP0z6zfG9P70z', features=[messagebird.Feature.ENABLE_CONVERSATIONSAPI_WHATSAPP_SANDBOX]) +``` + Documentation ------------- Complete documentation, instructions, and examples are available at: diff --git a/messagebird/__init__.py b/messagebird/__init__.py index <HASH>..<HASH> 100644 --- a/messagebird/__init__.py +++ b/messagebird/__init__.py @@ -1,2 +1,2 @@ -from messagebird.client import Client, ErrorException +from messagebird.client import Client, ErrorException, Feature from messagebird.signed_request import SignedRequest diff --git a/messagebird/client.py b/messagebird/client.py index <HASH>..<HASH> 100644 --- a/messagebird/client.py +++ b/messagebird/client.py @@ -1,5 +1,6 @@ import sys import json +import enum from messagebird.balance import Balance from messagebird.contact import Contact, ContactList @@ -16,6 +17,7 @@ from messagebird.conversation_message import ConversationMessage, ConversationMe from messagebird.conversation import Conversation, ConversationList from messagebird.conversation_webhook import ConversationWebhook, ConversationWebhookList + ENDPOINT = 'https://rest.messagebird.com' CLIENT_VERSION = '1.4.1' PYTHON_VERSION = '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) @@ -23,6 +25,10 @@ USER_AGENT = 'MessageBird/ApiClient/%s Python/%s' % (CLIENT_VERSION, PYTHON_VERS REST_TYPE = 'rest' CONVERSATION_API_ROOT = 'https://conversations.messagebird.com/v1/' +CONVERSATION_API_WHATSAPP_SANDBOX_ROOT = 'https://whatsapp-sandbox.messagebird.com/v1/' + + + CONVERSATION_PATH = 'conversations' CONVERSATION_MESSAGES_PATH = 'messages' CONVERSATION_WEB_HOOKS_PATH = 'webhooks' @@ -35,20 +41,25 @@ class ErrorException(Exception): message = ' '.join([str(e) for e in self.errors]) super(ErrorException, self).__init__(message) +class Feature(enum.Enum): + ENABLE_CONVERSATIONSAPI_WHATSAPP_SANDBOX = 1 class Client(object): - def __init__(self, access_key, http_client=None): + + def __init__(self, access_key, http_client=None, features=[]): self.access_key = access_key self.http_client = http_client + + self.conversation_api_root = CONVERSATION_API_WHATSAPP_SANDBOX_ROOT if Feature.ENABLE_CONVERSATIONSAPI_WHATSAPP_SANDBOX in features else CONVERSATION_API_ROOT def _get_http_client(self, type=REST_TYPE): if self.http_client: return self.http_client - if type == REST_TYPE: - return HttpClient(ENDPOINT, self.access_key, USER_AGENT) - - return HttpClient(CONVERSATION_API_ROOT, self.access_key, USER_AGENT) + if type == CONVERSATION_TYPE: + return HttpClient(self.conversation_api_root, self.access_key, USER_AGENT) + + return HttpClient(ENDPOINT, self.access_key, USER_AGENT) def request(self, path, method='GET', params=None, type=REST_TYPE): """Builds a request, gets a response and decodes it."""
Added Feature Flag to enable Whatsapp Sandbox
messagebird_python-rest-api
train
f399545f3853055b21865b47e27dd2a36688bfde
diff --git a/worker/provisioner/export_test.go b/worker/provisioner/export_test.go index <HASH>..<HASH> 100644 --- a/worker/provisioner/export_test.go +++ b/worker/provisioner/export_test.go @@ -50,7 +50,7 @@ func GetCopyAvailabilityZoneMachines(p ProvisionerTask) []AvailabilityZoneMachin task.machinesMutex.RLock() defer task.machinesMutex.RUnlock() // sort to make comparisons in the tests easier. - sort.Sort(azMachineFilterSort(task.availabilityZoneMachines)) + sort.Sort(azMachineSort(task.availabilityZoneMachines)) retvalues := make([]AvailabilityZoneMachine, len(task.availabilityZoneMachines)) for i := range task.availabilityZoneMachines { retvalues[i] = *task.availabilityZoneMachines[i] diff --git a/worker/provisioner/provisioner_task.go b/worker/provisioner/provisioner_task.go index <HASH>..<HASH> 100644 --- a/worker/provisioner/provisioner_task.go +++ b/worker/provisioner/provisioner_task.go @@ -874,9 +874,9 @@ func (task *provisionerTask) machineAvailabilityZoneDistribution( // If the machine has a distribution group, assign based on lowest zone // population of the distribution group machine. var machineZone string - zoneMap := azMachineFilterSort(task.availabilityZoneMachines) + zoneMap := azMachineSort(task.availabilityZoneMachines) if len(distGroupMachineIds) > 0 { - zoneMap = azMachineFilterSort(task.populateDistributionGroupZoneMap(distGroupMachineIds)) + zoneMap = azMachineSort(task.populateDistributionGroupZoneMap(distGroupMachineIds)) } sort.Sort(zoneMap) @@ -913,16 +913,15 @@ func (task *provisionerTask) machineAvailabilityZoneDistribution( return machineZone, nil } -// azMachineFilterSort extends a slice of AvailabilityZoneMachine references -// with a sort implementation by zone population and name, -// and filtration based on zones expressed in constraints. -type azMachineFilterSort []*AvailabilityZoneMachine +// azMachineSort extends a slice of AvailabilityZoneMachine references +// with a sort implementation by zone population and name. +type azMachineSort []*AvailabilityZoneMachine -func (a azMachineFilterSort) Len() int { +func (a azMachineSort) Len() int { return len(a) } -func (a azMachineFilterSort) Less(i, j int) bool { +func (a azMachineSort) Less(i, j int) bool { switch { case a[i].MachineIds.Size() < a[j].MachineIds.Size(): return true @@ -932,7 +931,7 @@ func (a azMachineFilterSort) Less(i, j int) bool { return false } -func (a azMachineFilterSort) Swap(i, j int) { +func (a azMachineSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] } @@ -1275,8 +1274,7 @@ func (task *provisionerTask) markMachineFailedInAZ(machine apiprovisioner.Machin } // Check if there are any zones left to try (that also match constraints). - zoneMap := azMachineFilterSort(task.availabilityZoneMachines) - for _, zoneMachines := range zoneMap { + for _, zoneMachines := range task.availabilityZoneMachines { if zoneMachines.MatchesConstraints(cons) && !zoneMachines.FailedMachineIds.Contains(machine.Id()) && !zoneMachines.ExcludedMachineIds.Contains(machine.Id()) { @@ -1294,18 +1292,6 @@ func (task *provisionerTask) clearMachineAZFailures(machine apiprovisioner.Machi } } -func (task *provisionerTask) addMachineToAZMap(machine *apiprovisioner.Machine, zoneName string) { - task.machinesMutex.Lock() - defer task.machinesMutex.Unlock() - for _, zoneMachines := range task.availabilityZoneMachines { - if zoneName == zoneMachines.ZoneName { - zoneMachines.MachineIds.Add(machine.Id()) - break - } - } - return -} - // removeMachineFromAZMap removes the specified machine from availabilityZoneMachines. // It is assumed this is called when the machines are being deleted from state, or failed // provisioning.
Drive-by: rename azMachineFilterSort as it doesn't filter any more
juju_juju
train
42a6d4384656096ccb309128f4df6a6a845a5a37
diff --git a/spec/lib/myfinance/resources/receivable_account_spec.rb b/spec/lib/myfinance/resources/receivable_account_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/myfinance/resources/receivable_account_spec.rb +++ b/spec/lib/myfinance/resources/receivable_account_spec.rb @@ -6,7 +6,6 @@ describe Myfinance::Resources::ReceivableAccount do let(:page) { 2 } let(:url) { subject.response.request.base_url } - describe "#find_all", vcr: true do before :each do subject.build
Update receivable_account_spec.rb
myfreecomm_myfinance-client-ruby
train
d0d81e15326ddfb74bf837653e0312bb90b3ef78
diff --git a/translator/expressions.go b/translator/expressions.go index <HASH>..<HASH> 100644 --- a/translator/expressions.go +++ b/translator/expressions.go @@ -142,21 +142,19 @@ func (c *pkgContext) translateExpr(expr ast.Expr) *expression { } case *ast.FuncLit: - return c.formatExpr("%s", strings.TrimSpace(string(c.CatchOutput(0, func() { - c.newFuncContext(e.Type, exprType.(*types.Signature), func() { - closurePrefix := "(" - closureSuffix := ")" - if len(c.f.escapingVars) != 0 { - list := strings.Join(c.f.escapingVars, ", ") - closurePrefix = "(function(" + list + ") { return " - closureSuffix = "; })(" + list + ")" - } - c.Printf("%sfunction(%s) {", closurePrefix, strings.Join(c.f.params, ", ")) - c.Indent(func() { - c.translateFunctionBody(e.Body.List) - }) - c.Printf("}%s", closureSuffix) + return c.formatExpr("%s", strings.TrimSpace(string(c.newFunction(e.Type, exprType.(*types.Signature), func() { + closurePrefix := "(" + closureSuffix := ")" + if len(c.f.escapingVars) != 0 { + list := strings.Join(c.f.escapingVars, ", ") + closurePrefix = "(function(" + list + ") { return " + closureSuffix = "; })(" + list + ")" + } + c.Printf("%sfunction(%s) {", closurePrefix, strings.Join(c.f.params, ", ")) + c.Indent(func() { + c.translateFunctionBody(e.Body.List) }) + c.Printf("}%s", closureSuffix) })))) case *ast.UnaryExpr: diff --git a/translator/package.go b/translator/package.go index <HASH>..<HASH> 100644 --- a/translator/package.go +++ b/translator/package.go @@ -56,7 +56,7 @@ type flowData struct { endCase int } -func (c *pkgContext) newFuncContext(t *ast.FuncType, sig *types.Signature, f func()) { +func (c *pkgContext) newFunction(t *ast.FuncType, sig *types.Signature, f func()) []byte { outerFuncContext := c.f vars := make(map[string]int, len(c.f.allVars)) for k, v := range c.f.allVars { @@ -82,9 +82,9 @@ func (c *pkgContext) newFuncContext(t *ast.FuncType, sig *types.Signature, f fun } c.f.localVars = nil - f() - + output := c.CatchOutput(0, f) c.f = outerFuncContext + return output } func (c *pkgContext) Write(b []byte) (int, error) { @@ -340,7 +340,9 @@ func TranslatePackage(importPath string, files []*ast.File, fileSet *token.FileS native := natives[funName] delete(natives, funName) - d.BodyCode = c.CatchOutput(1, func() { c.translateFunction(fun, native) }) + c.Indent(func() { + d.BodyCode = c.translateFunction(fun, native) + }) archive.Declarations = append(archive.Declarations, d) if strings.HasPrefix(fun.Name.String(), "Test") { archive.Tests = append(archive.Tests, fun.Name.String()) @@ -515,9 +517,9 @@ func (c *pkgContext) initArgs(ty types.Type) string { } } -func (c *pkgContext) translateFunction(fun *ast.FuncDecl, native string) { +func (c *pkgContext) translateFunction(fun *ast.FuncDecl, native string) []byte { sig := c.info.Objects[fun.Name].(*types.Func).Type().(*types.Signature) - c.newFuncContext(fun.Type, sig, func() { + return c.newFunction(fun.Type, sig, func() { var recv *ast.Ident if fun.Recv != nil && fun.Recv.List[0].Names != nil { recv = fun.Recv.List[0].Names[0]
turned newFuncContext into newFunction
gopherjs_gopherjs
train
b106e0a3088c5bd85ce0ec7ccb959100a64ebd7e
diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/UndertowEventListener.java b/undertow/src/main/java/org/wildfly/extension/undertow/UndertowEventListener.java index <HASH>..<HASH> 100644 --- a/undertow/src/main/java/org/wildfly/extension/undertow/UndertowEventListener.java +++ b/undertow/src/main/java/org/wildfly/extension/undertow/UndertowEventListener.java @@ -27,31 +27,33 @@ package org.wildfly.extension.undertow; import io.undertow.servlet.api.DeploymentInfo; /** + * TODO: implement commented out Undertow events + * * @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author Radoslav Husar */ public interface UndertowEventListener { void onShutdown(); - void onDeploymentAdd(DeploymentInfo deploymentInfo, Host host); + //void onDeploymentAdd(DeploymentInfo deploymentInfo, Host host); void onDeploymentStart(DeploymentInfo deploymentInfo, Host host); void onDeploymentStop(DeploymentInfo deploymentInfo, Host host); - void onDeploymentRemove(DeploymentInfo deploymentInfo, Host host); + //void onDeploymentRemove(DeploymentInfo deploymentInfo, Host host); - void onHostAdd(Host host); + //void onHostAdd(Host host); - void onHostRemove(Host host); + //void onHostRemove(Host host); void onHostStart(Host host); void onHostStop(Host host); - void onServerAdd(Server server); + //void onServerAdd(Server server); - void onServerRemove(Server server); + //void onServerRemove(Server server); void onServerStart(Server server);
WFLY-<I> lets not falsely expose events that never ever happen
wildfly_wildfly
train
401ede63791d7130fd6b97b1ce646e7fae28d0c0
diff --git a/build_config.php b/build_config.php index <HASH>..<HASH> 100644 --- a/build_config.php +++ b/build_config.php @@ -2,7 +2,7 @@ $buildConfig = array ( 'major' => 2, 'minor' => 9, - 'build' => 26, + 'build' => 27, 'shopgate_library_path' => "", 'plugin_name' => "library", 'display_name' => "Shopgate Library 2.9.x", diff --git a/classes/core.php b/classes/core.php index <HASH>..<HASH> 100644 --- a/classes/core.php +++ b/classes/core.php @@ -24,7 +24,7 @@ ################################################################################### # define constants ################################################################################### -define('SHOPGATE_LIBRARY_VERSION', '2.9.26'); +define('SHOPGATE_LIBRARY_VERSION', '2.9.27'); define('SHOPGATE_LIBRARY_ENCODING' , 'UTF-8'); define('SHOPGATE_BASE_DIR', realpath(dirname(__FILE__).'/../'));
Increased Shopgate Library <I>.x to version <I>.
shopgate_cart-integration-sdk
train
ba08a5bb55dd7766417e1f7446107efd3966d038
diff --git a/event/modifier.go b/event/modifier.go index <HASH>..<HASH> 100644 --- a/event/modifier.go +++ b/event/modifier.go @@ -18,6 +18,7 @@ import ( "github.com/hajimehoshi/ebiten/internal/driver" ) +// Modifier is a bit set of modifier keys on a keyboard. type Modifier int const (
event: Add a comment at Modifier Updates #<I>
hajimehoshi_ebiten
train
40e370ec51eb60a1350838354fd3765b7da53962
diff --git a/lib/module.js b/lib/module.js index <HASH>..<HASH> 100644 --- a/lib/module.js +++ b/lib/module.js @@ -6,6 +6,7 @@ let extractPayload = function(html, route){ let pre = chunks[0] let payload = chunks[1].split('</script>').shift() let post = chunks[1].split('</script>').slice(1).join('</script>') + if(route === '/') route = '' //hack for home page return { html: pre + '<script defer src="' + route + '/payload.js"></script>' + post,
fix for home page payload.js
DreaMinder_nuxt-payload-extractor
train
654e8b41fa789874bc9b2bb427fbfff7978a9eae
diff --git a/src/interactive-auth.js b/src/interactive-auth.js index <HASH>..<HASH> 100644 --- a/src/interactive-auth.js +++ b/src/interactive-auth.js @@ -55,6 +55,12 @@ const MSISDN_STAGE_TYPE = "m.login.msisdn"; * promise which resolves to the successful response or rejects with a * MatrixError. * + * @param {function(bool): module:client.Promise} opts.setBusy + * called whenever the interactive auth logic is busy submitting + * information provided by the user. After this has been called with + * true the UI should indicate that a request is in progress until it + * is called again with false. + * * @param {function(string, object?)} opts.stateUpdated * called when the status of the UI auth changes, ie. when the state of * an auth stage changes of when the auth flow moves to a new stage. @@ -101,6 +107,7 @@ function InteractiveAuth(opts) { this._matrixClient = opts.matrixClient; this._data = opts.authData || {}; this._requestCallback = opts.doRequest; + this._setBusyCallback = opts.setBusy; // startAuthStage included for backwards compat this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage; this._resolveFunc = null; @@ -117,7 +124,9 @@ function InteractiveAuth(opts) { this._chosenFlow = null; this._currentStage = null; - this._polling = false; + // if we are currently trying to submit an auth dict (which includes polling) + // the promise the will resolve/reject when it completes + this._submitPromise = false; } InteractiveAuth.prototype = { @@ -138,7 +147,10 @@ InteractiveAuth.prototype = { // if we have no flows, try a request (we'll have // just a session ID in _data if resuming) if (!this._data.flows) { - this._doRequest(this._data); + this._setBusyCallback(true); + this._doRequest(this._data).finally(() => { + this._setBusyCallback(false); + }); } else { this._startNextAuthStage(); } @@ -152,7 +164,9 @@ InteractiveAuth.prototype = { */ poll: async function() { if (!this._data.session) return; - if (this._polling) return; + // if we currently have a request in flight, there's no point making + // another just to check what the status is + if (this._submitPromise) return; let authDict = {}; if (this._currentStage == EMAIL_STAGE_TYPE) { @@ -173,12 +187,7 @@ InteractiveAuth.prototype = { } } - this._polling = true; - try { - await this.submitAuthDict(authDict, true); - } finally { - this._polling = false; - } + this.submitAuthDict(authDict, true); }, /** @@ -235,13 +244,37 @@ InteractiveAuth.prototype = { throw new Error("submitAuthDict() called before attemptAuth()"); } + if (!background && this._setBusyCallback) { + this._setBusyCallback(true); + } + + // if we're currently trying a request, wait for it to finish + // as otherwise we can get multiple 200 responses which can mean + // things like multiple logins for register requests. + // (but discard any expections as we only care when its done, + // not whether it worked or not) + while (this._submitPromise) { + try { + await this._submitPromise; + } catch (e) { + } + } + // use the sessionid from the last request. const auth = { session: this._data.session, }; utils.extend(auth, authData); - await this._doRequest(auth, background); + try { + // NB. the 'background' flag is deprecated by the setBusy + // callback and is here for backwards compat + this._submitPromise = this._doRequest(auth, background); + await this._submitPromise; + } finally { + this._submitPromise = null; + if (!background) this._setBusyCallback(false); + } }, /**
Don't overlap auth submissions with polls Wait for polls to complete before submitting auth dicts, otherwise we risk the requests overlapping and both returning a <I>. Also introduces a setBusy interface to interactive-auth to explicitly set the busy status, since otherwise it doesn't get set until the request actually starts.
matrix-org_matrix-js-sdk
train
3e9df7f9b3b575ba9f78803b588793a562d69091
diff --git a/lyricsgenius/api.py b/lyricsgenius/api.py index <HASH>..<HASH> 100644 --- a/lyricsgenius/api.py +++ b/lyricsgenius/api.py @@ -24,9 +24,9 @@ class API(object): """Genius API""" # Create a persistent requests connection - userAgent = 'LyricsGenius' session = requests.Session() - session.headers = {'application': userAgent, 'User-Agent': userAgent} + session.headers = {'application': 'LyricsGenius', + 'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'} def __init__(self, client_access_token, response_format='plain', timeout=5, sleep_time=0.5): @@ -138,10 +138,20 @@ class Genius(API): def _clean_str(self, s): return s.translate(str.maketrans('', '', punctuation)).replace('\u200b', " ").strip().lower() - def _result_is_lyrics(self, song_title): + def _result_is_lyrics(self, song_title, extra_terms=[]): """Returns False if result from Genius is not actually song lyrics""" - regex = re.compile( - r"(tracklist)|(track list)|(album art(work)?)|(liner notes)|(booklet)|(credits)|(remix)|(interview)|(skit)", re.IGNORECASE) + + excluded_terms = ['track\\s?list', 'album art(work)?', 'liner notes', + 'booklet', 'credits', 'interview', + 'skit', 'instrumental'] + if extra_terms: + if isinstance(extra_terms, list): + excluded_terms.extend(extra_terms) + else: + excluded_terms.append(extra_terms) + + expression = r"".join(["({})|".format(term) for term in excluded_terms]).strip('|') + regex = re.compile(expression, re.IGNORECASE) return not regex.search(song_title) def search_song(self, song_title, artist_name=""): diff --git a/tests/test_genius.py b/tests/test_genius.py index <HASH>..<HASH> 100644 --- a/tests/test_genius.py +++ b/tests/test_genius.py @@ -134,6 +134,10 @@ class TestSong(unittest.TestCase): msg = "The returned song does not have a media attribute." self.assertTrue(hasattr(self.song, 'media'), msg) + def test_result_is_lyrics(self): + msg = "Did not reject a false-song." + self.assertFalse(api._result_is_lyrics('Beatles Tracklist'), msg) + def test_saving_json_file(self): print('\n') format_ = 'json'
Add option for additional terms in result_is_lyrics check
johnwmillr_LyricsGenius
train
1efbdd16315cbbc1b0a4ab57eb2274afc1e14d57
diff --git a/server.go b/server.go index <HASH>..<HASH> 100644 --- a/server.go +++ b/server.go @@ -1453,8 +1453,8 @@ func (s *Server) applySetPrivilege(m *messaging.Message) error { // RetentionPolicy returns a retention policy by name. // Returns an error if the database doesn't exist. func (s *Server) RetentionPolicy(database, name string) (*RetentionPolicy, error) { - s.mu.Lock() - defer s.mu.Unlock() + s.mu.RLock() + defer s.mu.RUnlock() // Lookup database. db := s.databases[database]
Use a read lock to look up a retention policy
influxdata_influxdb
train
a964802c248f54f7e3203000fb11251e5249dbe1
diff --git a/pysra/output.py b/pysra/output.py index <HASH>..<HASH> 100644 --- a/pysra/output.py +++ b/pysra/output.py @@ -419,6 +419,8 @@ class ResponseSpectrumRatioOutput(RatioBasedOutput): class ProfileBasedOutput(Output): + ylabel = 'Depth (m)' + def __init__(self): super().__init__() @@ -429,12 +431,14 @@ class ProfileBasedOutput(Output): class MaxStrainProfile(ProfileBasedOutput): + xlabel = 'Max. Strain (dec)' + def __init__(self): super().__init__() def __call__(self, calc, name=None): ProfileBasedOutput.__call__(self, calc, name) - values = [0] + [l.strain for l in calc.profile[:-1]] + values = [0] + [l.strain_max for l in calc.profile[:-1]] self._add_values(values)
Added labels to max strain. Changed from strain to strain_max.
arkottke_pysra
train
769040e16a0dbef5fad1e6adbb745f7487c15b60
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -73,23 +73,6 @@ class Service extends AdapterService { return schema ? knex.withSchema(schema).table(table) : knex(table); } - init (opts, cb) { - const k = this.Model; - const { table, schema, fullName } = this; - - return k.schema.hasTable(fullName).then(exists => { - if (!exists) { - debug(`creating ${fullName}`); - return (schema) - ? k.schema.withSchema(schema).createTable(table, cb).then(res => res) - : k.schema.createTable(table, cb).then(res => res); - } else { - debug(`${fullName} already exists`); - return null; - } - }); - } - knexify (query, params, parentKey) { Object.keys(params || {}).forEach(key => { const value = params[key]; diff --git a/test/index.test.js b/test/index.test.js index <HASH>..<HASH> 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -116,7 +116,7 @@ const users = service({ function clean () { return Promise.all([ db.schema.dropTableIfExists(people.fullName).then(() => { - return people.init({}, (table) => { + return db.schema.createTable(people.fullName, (table) => { table.increments('id'); table.string('name').notNullable(); table.integer('age'); @@ -126,7 +126,7 @@ function clean () { }); }), db.schema.dropTableIfExists(peopleId.fullName).then(() => { - return peopleId.init({}, table => { + return db.schema.createTable(peopleId.fullName, (table) => { table.increments('customid'); table.string('name'); table.integer('age'); @@ -136,7 +136,7 @@ function clean () { }); }), db.schema.dropTableIfExists(users.fullName).then(() => { - return users.init({}, table => { + return db.schema.createTable(users.fullName, (table) => { table.increments('id'); table.string('name'); table.integer('age'); diff --git a/test/service-method-overrides.test.js b/test/service-method-overrides.test.js index <HASH>..<HASH> 100644 --- a/test/service-method-overrides.test.js +++ b/test/service-method-overrides.test.js @@ -53,7 +53,7 @@ const animals = new Animal({ function clean () { return db.schema.dropTableIfExists(animals.fullName).then(() => { - return animals.init({}, (table) => { + return db.schema.createTable(animals.fullName, (table) => { table.increments('id'); table.integer('ancestor_id'); table.string('name').notNullable();
Remove init method (#<I>)
feathersjs-ecosystem_feathers-knex
train
a6ed0b3241929d651a213bedb7a2495c4042d0f3
diff --git a/src/util/childProcess.js b/src/util/childProcess.js index <HASH>..<HASH> 100644 --- a/src/util/childProcess.js +++ b/src/util/childProcess.js @@ -59,6 +59,22 @@ module.exports = class ChildProcess { transform(data, encoding, callback) { let text = data.toString().trim(); if (text.length > 0 && self.isTextWhiteListed(text)) { + if (text.includes("✔")) { + // for successful chunks we really only want to keep specific lines + const lines = text.split("\n"); + const buff = []; + const startWithTerms = ["Running:", " ✔", "OK."]; + const processLine = (line) => { + for (const term of startWithTerms) { + // line could have an ERROR or WARN tag that is whitelisted we want to keep + if (self.isTextWhiteListed(line) || line.startsWith(term)) { + buff.push(line); + } + } + }; + lines.forEach(line => processLine(line)); + text = buff.join("\n"); + } text = text .split("\n") .filter((line) => !_.isEmpty(line.trim())) @@ -75,6 +91,7 @@ module.exports = class ChildProcess { this.emitter = new EventEmitter(); this.emitter.stdout = stdoutFilter; this.emitter.stderr = handler.stderr; + this.emitter.infoSlicer = infoSlicer; // pipe the stdout stream into the slicer and then into the filter this.handler.stdout.pipe(infoSlicer).pipe(stdoutFilter);
add extra filter on success (check) chunks
TestArmada_magellan
train
34b8fa83af9579e72e0465354fdcbac8a62141eb
diff --git a/src/lib/Herrera/Box/Box.php b/src/lib/Herrera/Box/Box.php index <HASH>..<HASH> 100644 --- a/src/lib/Herrera/Box/Box.php +++ b/src/lib/Herrera/Box/Box.php @@ -162,6 +162,13 @@ class Box foreach ($iterator as $key => $value) { if (is_string($value)) { + if (false === is_string($key)) { + throw UnexpectedValueException::create( + 'The key returned by the iterator (%s) is not a string.', + gettype($key) + ); + } + $key = canonical_path($key); $value = canonical_path($value); diff --git a/src/tests/Herrera/Box/Tests/BoxTest.php b/src/tests/Herrera/Box/Tests/BoxTest.php index <HASH>..<HASH> 100644 --- a/src/tests/Herrera/Box/Tests/BoxTest.php +++ b/src/tests/Herrera/Box/Tests/BoxTest.php @@ -258,6 +258,16 @@ SOURCE; )), __DIR__); } + public function testBuildFromIteratorInvalidKey() + { + $this->setExpectedException( + 'Herrera\\Box\\Exception\\UnexpectedValueException', + 'The key returned by the iterator (integer) is not a string.' + ); + + $this->box->buildFromIterator(new ArrayIterator(array('test'))); + } + public function testBuildFromIteratorInvalid() { $this->setExpectedException( @@ -265,7 +275,9 @@ SOURCE; 'The iterator value "resource" was not expected.' ); - $this->box->buildFromIterator(new ArrayIterator(array(STDOUT))); + $this->box->buildFromIterator(new ArrayIterator(array( + 'stream' => STDOUT + ))); } /**
Properly checking iterator returned key.
box-project_box2-lib
train
ac728bc385b7328787d6294adcfe43c1505d5920
diff --git a/Classes/Logger.php b/Classes/Logger.php index <HASH>..<HASH> 100644 --- a/Classes/Logger.php +++ b/Classes/Logger.php @@ -135,14 +135,13 @@ class Logger extends \Xinc\Core\Singleton while (strlen($prioritystr) < 7) { $prioritystr .= ' '; } - $message = ' ' . $prioritystr . ' ' . $timestr . ' ' . $msg."\n"; + $message = $prioritystr . ' ' . $timestr . ' ' . $msg . "\n"; + $message = getmypid() . ': ' . $message; - if ($this->logLevel == self::LOG_LEVEL_VERBOSE) { - if (defined('STDERR')) { - fputs(STDERR, $message); - } else { - echo '<!-- LogMessage: ' . $message . " -->\n"; - } + if (defined('STDERR')) { + fputs(STDERR, getmypid() . ': ' . $prioritystr . ' ' . $msg . "\n"); + } else { + echo '<!-- LogMessage: ' . $message . " -->\n"; } if ($this->file != null) {
Issue <I>: Let Logger output to screen
xinc-develop_xinc-core
train
fea631953bcf2e276c50df7af32af50519a4ca8c
diff --git a/lib/WAAClock.js b/lib/WAAClock.js index <HASH>..<HASH> 100644 --- a/lib/WAAClock.js +++ b/lib/WAAClock.js @@ -3,12 +3,8 @@ var _ = require('underscore') , inherits = require('util').inherits , isBrowser = (typeof window !== 'undefined') -if (isBrowser && !AudioContext) { - if (window.webkitAudioContext) - console.error('This browser uses a prefixed version of web audio API') - else - console.error('This browser doesn\'t seem to support web audio API') -} +if (isBrowser && !AudioContext) + throw new Error('This browser doesn\'t seem to support web audio API') // ==================== Event ==================== // var Event = function(clock, time, func) {
removed test for prefixed AudioContext
sebpiq_WAAClock
train
4c64efc081aebb8d163c213130df50576f03160a
diff --git a/lib/active_type/virtual_attributes.rb b/lib/active_type/virtual_attributes.rb index <HASH>..<HASH> 100644 --- a/lib/active_type/virtual_attributes.rb +++ b/lib/active_type/virtual_attributes.rb @@ -144,28 +144,47 @@ module ActiveType @virtual_attributes_cache ||= {} end - def [](name) + def read_existing_virtual_attribute(name, &block_when_not_virtual) if self.singleton_class._has_virtual_column?(name) read_virtual_attribute(name) else - super + yield end end - # ActiveRecord 4.2.1 - def _read_attribute(name) + def write_existing_virtual_attribute(name, value, &block_when_not_virtual) if self.singleton_class._has_virtual_column?(name) - read_virtual_attribute(name) + write_virtual_attribute(name, value) else - super + yield + end + end + + def [](name) + read_existing_virtual_attribute(name) { super } + end + + if ActiveRecord::VERSION::STRING >= '4.2.0' + def _read_attribute(name) + read_existing_virtual_attribute(name) { super } + end + else + def read_attribute(name) + read_existing_virtual_attribute(name) { super } end end def []=(name, value) - if self.singleton_class._has_virtual_column?(name) - write_virtual_attribute(name, value) - else - super + write_existing_virtual_attribute(name, value) { super } + end + + if ActiveRecord::VERSION::STRING >= '5.2.0' + def _write_attribute(name, value) + write_existing_virtual_attribute(name, value) { super } + end + else + def write_attribute(name, value) + write_existing_virtual_attribute(name, value) { super } end end diff --git a/spec/shared_examples/accessors.rb b/spec/shared_examples/accessors.rb index <HASH>..<HASH> 100644 --- a/spec/shared_examples/accessors.rb +++ b/spec/shared_examples/accessors.rb @@ -21,4 +21,42 @@ shared_examples_for "ActiveRecord-like accessors" do |attributes| end end + it 'allows reading via read_attribute' do + attributes.each do |key, value| + subject.send("#{key}=", value) + expect(subject.send(:read_attribute, key)).to eq(value) + end + end + + if ActiveRecord::VERSION::STRING >= '4.2.0' + # Rails 4.2 introduced this internal reader method for performance reasons. + # https://github.com/rails/rails/commit/08576b94ad4f19dfc368619d7751e211d23dcad8 + # It is called by `read_attribute` and other ActiveRecord methods, so we test its behavior explicitly. + it 'allows reading via _read_attribute' do + attributes.each do |key, value| + subject.send("#{key}=", value) + expect(subject._read_attribute(key)).to eq(value) + end + end + end + + it 'allows writing via write_attribute' do + attributes.each do |key, value| + subject.send(:write_attribute, key, value) + expect(subject.send(key)).to eq(value) + end + end + + if ActiveRecord::VERSION::STRING >= '5.2.0' + # Rails 5.2 introduced this internal writer method for performance reasons. + # https://github.com/rails/rails/commit/c879649a733d982fba9e70f5a280d13636b67c37 + # It is called by `write_attribute` and other ActiveRecord methods, so we test its behavior explicitly. + it 'allows writing via _write_attribute' do + attributes.each do |key, value| + subject._write_attribute(key, value) + expect(subject.send(key)).to eq(value) + end + end + end + end
Support virtual attributes in internal ActiveRecord readers/writers
makandra_active_type
train
f399fbf9f4ca705949534e78419b9c21aeb2959c
diff --git a/packages/cozy-stack-client/src/querystring.js b/packages/cozy-stack-client/src/querystring.js index <HASH>..<HASH> 100644 --- a/packages/cozy-stack-client/src/querystring.js +++ b/packages/cozy-stack-client/src/querystring.js @@ -4,6 +4,7 @@ import pickBy from 'lodash/pickBy' * Encode an object as querystring, values are encoded as * URI components, keys are not. * + * @function * @private */ export const encode = data => { @@ -23,6 +24,7 @@ export const encode = data => { * Returns a URL from base url and a query parameter object. * Any undefined parameter is removed. * + * @function * @private */ export const buildURL = (url, params) => {
docs: Constant functions recognized as functions
cozy_cozy-client
train
f0651239b61b1262c91686a497892c406708b1a8
diff --git a/skyfield/positionlib.py b/skyfield/positionlib.py index <HASH>..<HASH> 100644 --- a/skyfield/positionlib.py +++ b/skyfield/positionlib.py @@ -476,7 +476,6 @@ class Astrometric(ICRF): bcrs_position = bcrs_position.reshape(shape) bcrs_velocity = bcrs_velocity.reshape(shape) if gcrs_position is not None: - asdfff gcrs_position = gcrs_position.reshape(shape) if gcrs_position is None:
Remove errant line from positionlib
skyfielders_python-skyfield
train
7a44cc7d64addb6df0da0c7ec4e5792431204a51
diff --git a/lib/output.js b/lib/output.js index <HASH>..<HASH> 100644 --- a/lib/output.js +++ b/lib/output.js @@ -15,7 +15,7 @@ function render(moduleName, data) { var status = _([ !data.isInstalled ? chalk.bgGreen.white.bold(' ' + emoji.get('worried') + ' MISSING! ') + ' In package.json but not installed.' : '', data.bump && data.easyUpgrade ? [ - chalk.bgGreen.white.bold(' ' + emoji.get('heart_eyes') + ' UPDATE! ') + ' Your local install is out of date. ', + chalk.bgGreen.white.bold(' ' + emoji.get('heart_eyes') + ' UPDATE! ') + ' Your local install is out of date. ' + chalk.blue.underline(data.homepage), ' ' + chalk.green('npm install ' + moduleName) + ' to go from ' + data.installed + ' to ' + data.latest ] : '', data.bump && !data.easyUpgrade ? [
show homepage when it's a simple semver update
dylang_npm-check
train
c2261bf962dae017fb31bf783ca609d88f6b2b4e
diff --git a/test/collection.js b/test/collection.js index <HASH>..<HASH> 100644 --- a/test/collection.js +++ b/test/collection.js @@ -542,8 +542,8 @@ $(document).ready(function() { equal(col.length, 0); }); - test("#861, adding models to a collection which do not pass validation", 1, function() { - raises(function() { + test("#861, adding models to a collection which do not pass validation", 2, function() { + var fired = null; var Model = Backbone.Model.extend({ validate: function(attrs) { if (attrs.id == 3) return "id can't be 3"; @@ -555,25 +555,26 @@ $(document).ready(function() { }); var col = new Collection; + col.on("error", function() { fired = true; }); col.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}]); - }, function(e) { - return e.message === "Can't add an invalid model to a collection"; - }); + equal(fired, true); + equal(col.length, 5); }); - test("throwing during add leaves consistent state", 4, function() { + test("invalid models are discarded and only valid models are added to a collection", 5, function() { var col = new Backbone.Collection(); - col.on('test', function() { ok(false); }); + col.on('test', function() { ok(true); }); col.model = Backbone.Model.extend({ validate: function(attrs){ if (!attrs.valid) return 'invalid'; } }); var model = new col.model({id: 1, valid: true}); - raises(function() { col.add([model, {id: 2}]); }); + col.add([model, {id: 2}]);; model.trigger('test'); - ok(!col.getByCid(model.cid)); - ok(!col.get(1)); - equal(col.length, 0); + ok(col.getByCid(model.cid)); + ok(col.get(1)); + ok(!col.get(2)); + equal(col.length, 1); }); test("multiple copies of the same model", 3, function() {
Modified two tests to listen for error events rather than catching exceptions when adding an invalid model to a collection
jashkenas_backbone
train
595b7785052eba5dec734c8c4d7426f069800ffc
diff --git a/bugwarrior/db.py b/bugwarrior/db.py index <HASH>..<HASH> 100644 --- a/bugwarrior/db.py +++ b/bugwarrior/db.py @@ -247,14 +247,21 @@ def synchronize(issue_generator, conf): ) if notify: send_notification(issue, 'Created', conf) - tw.task_add(**issue) + + try: + tw.task_add(**issue) + except taskw.TaskwarriorError as e: + log.name('db').trace(e) for issue in issue_updates['changed']: log.name('db').info( "Updating task {0}", issue['description'].encode("utf-8") ) - tw.task_update(issue) + try: + tw.task_update(issue) + except taskw.TaskwarriorError as e: + log.name('db').trace(e) for issue in issue_updates['closed']: task_info = tw.get_task(uuid=issue) @@ -264,7 +271,11 @@ def synchronize(issue_generator, conf): ) if notify: send_notification(task_info, 'Completed', conf) - tw.task_done(uuid=issue) + + try: + tw.task_done(uuid=issue) + except taskw.TaskwarriorError as e: + log.name('db').trace(e) # Send notifications if notify:
Proceed along happily if taskwarrior shellout fails at something.
ralphbean_bugwarrior
train
d6d8726cd6aecbeb7443234e420fd8887cd236ef
diff --git a/src/org/opencms/ade/containerpage/CmsModelGroupHelper.java b/src/org/opencms/ade/containerpage/CmsModelGroupHelper.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/ade/containerpage/CmsModelGroupHelper.java +++ b/src/org/opencms/ade/containerpage/CmsModelGroupHelper.java @@ -53,6 +53,7 @@ import org.opencms.xml.containerpage.CmsContainerElementBean; import org.opencms.xml.containerpage.CmsContainerPageBean; import org.opencms.xml.containerpage.CmsXmlContainerPage; import org.opencms.xml.containerpage.CmsXmlContainerPageFactory; +import org.opencms.xml.containerpage.I_CmsFormatterBean; import java.io.IOException; import java.util.ArrayList; @@ -81,6 +82,12 @@ public class CmsModelGroupHelper { /** Static reference to the log. */ private static final Log LOG = CmsLog.getLog(CmsModelGroupHelper.class); + /** Settings to keep when resetting. */ + private static final String[] KEEP_SETTING_IDS = new String[] { + CmsContainerElement.MODEL_GROUP_STATE, + CmsContainerElement.ELEMENT_INSTANCE_ID, + CmsContainerElement.USE_AS_COPY_MODEL}; + /** The current cms context. */ private CmsObject m_cms; @@ -824,7 +831,7 @@ public class CmsModelGroupHelper { } /** - * Collects the page containers by parent instance id + * Collects the page containers by parent instance id.<p> * * @param page the page * @@ -897,20 +904,46 @@ public class CmsModelGroupHelper { CmsContainerElementBean baseElement, boolean allowCopyModel) { - Map<String, String> settings = new HashMap<String, String>(element.getIndividualSettings()); - if (!(baseElement.isCopyModel() && allowCopyModel)) { - // skip the model id in case of copy models + boolean resetSettings = false; + if (!baseElement.isCopyModel() && !element.getFormatterId().equals(baseElement.getFormatterId())) { + I_CmsFormatterBean formatter = m_configData.getCachedFormatters().getFormatters().get( + element.getFormatterId()); + resetSettings = (formatter == null) + || !formatter.getResourceTypeNames().contains( + OpenCms.getResourceManager().getResourceType(baseElement.getResource())); + } + Map<String, String> settings; + if (resetSettings) { + settings = new HashMap<String, String>(); + for (String id : KEEP_SETTING_IDS) { + if (element.getIndividualSettings().containsKey(id)) { + settings.put(id, element.getIndividualSettings().get(id)); + } + } settings.put(CmsContainerElement.MODEL_GROUP_ID, element.getId().toString()); - if (allowCopyModel) { - // transfer all other settings - for (Entry<String, String> settingEntry : baseElement.getIndividualSettings().entrySet()) { - if (!settings.containsKey(settingEntry.getKey())) { - settings.put(settingEntry.getKey(), settingEntry.getValue()); + // transfer all other settings + for (Entry<String, String> settingEntry : baseElement.getIndividualSettings().entrySet()) { + if (!settings.containsKey(settingEntry.getKey())) { + settings.put(settingEntry.getKey(), settingEntry.getValue()); + } + } + } else { + settings = new HashMap<String, String>(element.getIndividualSettings()); + if (!(baseElement.isCopyModel() && allowCopyModel)) { + // skip the model id in case of copy models + settings.put(CmsContainerElement.MODEL_GROUP_ID, element.getId().toString()); + if (allowCopyModel) { + // transfer all other settings + for (Entry<String, String> settingEntry : baseElement.getIndividualSettings().entrySet()) { + if (!settings.containsKey(settingEntry.getKey())) { + settings.put(settingEntry.getKey(), settingEntry.getValue()); + } } } + + } else if (baseElement.isCopyModel()) { + settings.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.wasModelGroup.name()); } - } else if (baseElement.isCopyModel()) { - settings.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.wasModelGroup.name()); } return CmsContainerElementBean.cloneWithSettings(baseElement, settings); }
Fixing issue where changing model group root element could lead to invalid formatter settings.
alkacon_opencms-core
train
bb5f88b360ee146bdd45484bf5e4da45dc878c82
diff --git a/satpy/resample.py b/satpy/resample.py index <HASH>..<HASH> 100644 --- a/satpy/resample.py +++ b/satpy/resample.py @@ -27,7 +27,7 @@ import hashlib import json import os from logging import getLogger -from weakref import WeakValueDictionary +from collections import OrderedDict import numpy as np import xarray as xr @@ -88,7 +88,7 @@ class BaseResampler(object): The base resampler class. Abstract. """ - caches = WeakValueDictionary() + caches = OrderedDict() def __init__(self, source_geo_def, target_geo_def): """ @@ -192,6 +192,8 @@ class BaseResampler(object): def _update_caches(self, hash_str, cache_dir, filename): """Update caches and dump new resampling parameters to disk""" + while len(self.caches.keys()) > 2: + self.caches.popitem() self.caches[hash_str] = self.cache if cache_dir: # XXX: Look in to doing memmap-able files instead @@ -269,6 +271,8 @@ class KDTreeResampler(BaseResampler): self._update_caches(kd_hash, cache_dir, filename) return self.cache + else: + del valid_input_index, valid_output_index, index_array, distance_array def compute(self, data, weight_funcs=None, fill_value=None, with_uncert=False, **kwargs): @@ -604,7 +608,19 @@ RESAMPLERS = {"kd_tree": KDTreeResampler, "native": NativeResampler, } -RESAMPLER_CACHE = WeakValueDictionary() + +def prepare_resampler(source_area, destination_area, resampler=None): + """Instanciate and return a resampler.""" + if resampler is None: + LOG.info("Using default KDTree resampler") + resampler = 'kd_tree' + + if isinstance(resampler, str): + resampler_class = RESAMPLERS[resampler] + else: + resampler_class = resampler + + return resampler_class(source_area, destination_area) def resample(source_area, data, destination_area, @@ -616,25 +632,17 @@ def resample(source_area, data, destination_area, DeprecationWarning) resampler = kwargs.pop('resampler_class') - key = (source_area, destination_area) - if key in RESAMPLER_CACHE: - resampler = RESAMPLER_CACHE[key] - else: - if resampler is None: - LOG.info("Using default KDTree resampler") - resampler = 'kd_tree' - - if isinstance(resampler, str): - resampler_class = RESAMPLERS[resampler] - else: - resampler_class = resampler - resampler = resampler_class(source_area, destination_area) - RESAMPLER_CACHE[key] = resampler + if not isinstance(resampler, BaseResampler): + resampler_instance = prepare_resampler(source_area, + destination_area, + resampler) if isinstance(data, list): - return [resampler.resample(ds, **kwargs) for ds in data] + res = [resampler_instance.resample(ds, **kwargs) for ds in data] else: - return resampler.resample(data, **kwargs) + res = resampler_instance.resample(data, **kwargs) + + return res def resample_dataset(dataset, destination_area, **kwargs): @@ -667,7 +675,7 @@ def resample_dataset(dataset, destination_area, **kwargs): def mask_source_lonlats(source_def, mask): - """Mask source longitudes and latitudes to match data mask""" + """Mask source longitudes and latitudes to match data mask.""" source_geo_def = source_def # the data may have additional masked pixels
Start removing caching for resampling
pytroll_satpy
train
efde954697cb4798da050f72c9924eef3cc893bf
diff --git a/tests/test_pl.py b/tests/test_pl.py index <HASH>..<HASH> 100644 --- a/tests/test_pl.py +++ b/tests/test_pl.py @@ -64,6 +64,22 @@ class Num2WordsPLTest(TestCase): "osiemdziesiąt cztery miliony dwieście dwadzieścia " "tysięcy dwieście dziewięćdzisiąt jeden" ) + self.assertEqual( + num2words( + 963301000001918264129471042047146102350812074235000101020000120324, + lang='pl' + ), + "dziewięćset sześćdziesiąt trzy decyliardy trzysta jeden " + "decylionów nonylion dziewięćset osiemnaście oktyliardów dwieście " + "sześćdziesiąt cztery oktyliony sto dwadzieścia dziewięć " + "septyliardów czterysta siedemdziesiąt jeden septylionów " + "czterdzieści dwa sekstyliardy czterdzieści siedem sekstylionów " + "sto czterdzieści sześć kwintyliardów sto dwa kwintyliony trzysta " + "pięćdziesiąt kwadryliardów osiemset dwanaście kwadrylionów " + "siedemdziesiąt cztery tryliardy dwieście trzydzieści pięć " + "trylionów sto jeden bilionów dwadzieścia miliardów sto " + "dwadzieścia tysięcy trzysta dwadzieścia cztery" + ) def test_to_ordinal(self): # @TODO: implement to_ordinal
Update test_pl.py added test for a really big number in Polish
savoirfairelinux_num2words
train
f8435d022aaf0a4942a08dd84feaceb6b2e67d8d
diff --git a/cairo/fontoptions_since_1_16.go b/cairo/fontoptions_since_1_16.go index <HASH>..<HASH> 100644 --- a/cairo/fontoptions_since_1_16.go +++ b/cairo/fontoptions_since_1_16.go @@ -1,4 +1,4 @@ -// +build !cairo_1_10,!cairo_1_12,!cairo_1_14 +// +build !cairo_1_9,!cairo_1_10,!cairo_1_11,!cairo_1_12,!cairo_1_13,!cairo_1_14,!cairo_1_15 package cairo
It turns out Cairo release numberings are only even on the patch number, not the minor number, so we neet to include more Cairo releases
gotk3_gotk3
train
6b1d64d484b8cbf035eab575d8b194dbc250c8e1
diff --git a/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php b/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php index <HASH>..<HASH> 100644 --- a/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php +++ b/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php @@ -357,9 +357,6 @@ class UnitOfWorkTest extends OrmTestCase $entity = new Country(456, 'United Kingdom'); - $this->_unitOfWork->persist($entity); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity)); - $this->_unitOfWork->clear($entity); } @@ -367,9 +364,6 @@ class UnitOfWorkTest extends OrmTestCase { $entity = new Country(456, 'United Kingdom'); - $this->_unitOfWork->persist($entity); - $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity)); - $this->_unitOfWork->clear(); $this->assertFalse($this->_unitOfWork->isInIdentityMap($entity));
Remove unecessary persist in tests
doctrine_orm
train
8379e6bc70ca3849e973ccd99a907ab3744788c3
diff --git a/test/unit/token-model.test.js b/test/unit/token-model.test.js index <HASH>..<HASH> 100644 --- a/test/unit/token-model.test.js +++ b/test/unit/token-model.test.js @@ -151,6 +151,10 @@ suite('Token Model', function() { }); }).then(done, done); }); + + test.only('remove a non existing key', function(done) { + tokenModel.del('zit').then(done, done); + }); }); suite('MaxTokens Policy', function() {
write test to illustarte delete non existing key bug
thanpolas_kansas
train
2f7b8fa6744dd4276fa19e010062456c2817ce2b
diff --git a/server/index.js b/server/index.js index <HASH>..<HASH> 100644 --- a/server/index.js +++ b/server/index.js @@ -19,14 +19,11 @@ function register (server, options, next) { server.ext('onPreResponse', corsHeaders) - registerPlugins(server, options, function (error) { + server.register({register: hoodieServer, options: options}, function (error) { if (error) { return next(error) } - server.register({ - register: hoodieServer, - options: options - }, function (error) { + registerPlugins(server, options, function (error) { if (error) { return next(error) }
fix: register `@hoodie/server` before plugins
hoodiehq_hoodie
train
686fb20713479c166d29a0712dbaf8c3a14cc530
diff --git a/structr-core/src/test/java/org/structr/common/CypherNotInTransactionTest.java b/structr-core/src/test/java/org/structr/common/CypherNotInTransactionTest.java index <HASH>..<HASH> 100644 --- a/structr-core/src/test/java/org/structr/common/CypherNotInTransactionTest.java +++ b/structr-core/src/test/java/org/structr/common/CypherNotInTransactionTest.java @@ -32,17 +32,14 @@ import static junit.framework.TestCase.assertNotNull; import org.neo4j.cypher.javacompat.ExecutionEngine; import org.neo4j.cypher.javacompat.ExecutionResult; import org.neo4j.graphdb.GraphDatabaseService; -import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; import org.structr.common.error.FrameworkException; import org.structr.core.GraphObject; -import org.structr.core.entity.AbstractNode; import org.structr.core.entity.SixOneOneToOne; import org.structr.core.entity.TestOne; import org.structr.core.entity.TestSix; -import org.structr.core.graph.NodeInterface; /** * @@ -63,19 +60,16 @@ public class CypherNotInTransactionTest extends StructrTest { try { - final NodeInterface testNode1 = this.createTestNode(TestSix.class); - final NodeInterface testNode2 = this.createTestNode(TestOne.class); + final TestSix testSix = this.createTestNode(TestSix.class); + final TestOne testOne = this.createTestNode(TestOne.class); SixOneOneToOne rel = null; - assertNotNull(testNode1); - assertNotNull(testNode2); - - assertNotNull(testOne); assertNotNull(testSix); + assertNotNull(testOne); try { app.beginTx(); - rel = app.create(testNode1, testNode2, SixOneOneToOne.class); + rel = app.create(testSix, testOne, SixOneOneToOne.class); app.commitTx(); } finally { diff --git a/structr-rest/src/test/java/org/structr/rest/common/StructrRestTest.java b/structr-rest/src/test/java/org/structr/rest/common/StructrRestTest.java index <HASH>..<HASH> 100644 --- a/structr-rest/src/test/java/org/structr/rest/common/StructrRestTest.java +++ b/structr-rest/src/test/java/org/structr/rest/common/StructrRestTest.java @@ -200,7 +200,7 @@ public class StructrRestTest extends TestCase { for (int i = 0; i < number; i++) { - rels.add(app.create(startNode, endNode, relType)); + rels.add((T)app.create(startNode, endNode, relType)); } app.commitTx(); diff --git a/structr-ui/src/test/java/org/structr/web/common/StructrTest.java b/structr-ui/src/test/java/org/structr/web/common/StructrTest.java index <HASH>..<HASH> 100644 --- a/structr-ui/src/test/java/org/structr/web/common/StructrTest.java +++ b/structr-ui/src/test/java/org/structr/web/common/StructrTest.java @@ -256,7 +256,7 @@ public class StructrTest extends TestCase { for (int i = 0; i < number; i++) { - rels.add(app.create(startNode, endNode, relType)); + rels.add((T)app.create(startNode, endNode, relType)); } app.commitTx(); @@ -274,7 +274,7 @@ public class StructrTest extends TestCase { try { app.beginTx(); - final T rel = app.create(startNode, endNode, relType); + final T rel = (T)app.create(startNode, endNode, relType); app.commitTx();
Fixed tests according to new typesafe relationship creation in StructrApp, work in progress.
structr_structr
train
7a8b4a9d02c949a45460b66f8813a52520148673
diff --git a/examples/src/java/com/twitter/heron/examples/api/StatefulSlidingWindowTopology.java b/examples/src/java/com/twitter/heron/examples/api/StatefulSlidingWindowTopology.java index <HASH>..<HASH> 100644 --- a/examples/src/java/com/twitter/heron/examples/api/StatefulSlidingWindowTopology.java +++ b/examples/src/java/com/twitter/heron/examples/api/StatefulSlidingWindowTopology.java @@ -58,11 +58,14 @@ public final class StatefulSlidingWindowTopology { private OutputCollector collector; @Override - public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { + @SuppressWarnings("HiddenField") + public void prepare(Map<String, Object> topoConf, TopologyContext context, + OutputCollector collector) { this.collector = collector; } @Override + @SuppressWarnings("HiddenField") public void initState(State<String, Long> state) { this.state = state; sum = state.getOrDefault("sum", 0L); @@ -87,7 +90,8 @@ public final class StatefulSlidingWindowTopology { } } - public static class IntegerSpout extends BaseRichSpout implements IStatefulComponent<String, Long> { + public static class IntegerSpout extends BaseRichSpout + implements IStatefulComponent<String, Long> { private static final Logger LOG = Logger.getLogger(IntegerSpout.class.getName()); private static final long serialVersionUID = 5454291010750852782L; private SpoutOutputCollector collector; @@ -130,6 +134,7 @@ public final class StatefulSlidingWindowTopology { } @Override + @SuppressWarnings("HiddenField") public void initState(State<String, Long> state) { this.state = state; this.msgId = this.state.getOrDefault("msgId", 0L); @@ -144,7 +149,8 @@ public final class StatefulSlidingWindowTopology { public static void main(String[] args) throws Exception { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("integer", new IntegerSpout(), 1); - builder.setBolt("sumbolt", new WindowSumBolt().withWindow(BaseWindowedBolt.Count.of(5), BaseWindowedBolt.Count.of(3)), 1).shuffleGrouping("integer"); + builder.setBolt("sumbolt", new WindowSumBolt().withWindow(BaseWindowedBolt.Count.of(5), + BaseWindowedBolt.Count.of(3)), 1).shuffleGrouping("integer"); builder.setBolt("printer", new PrinterBolt()).shuffleGrouping("sumbolt"); Config conf = new Config(); conf.setDebug(true); diff --git a/examples/src/java/com/twitter/heron/examples/api/WindowedWordCountTopology.java b/examples/src/java/com/twitter/heron/examples/api/WindowedWordCountTopology.java index <HASH>..<HASH> 100644 --- a/examples/src/java/com/twitter/heron/examples/api/WindowedWordCountTopology.java +++ b/examples/src/java/com/twitter/heron/examples/api/WindowedWordCountTopology.java @@ -33,10 +33,13 @@ import com.twitter.heron.api.tuple.Fields; import com.twitter.heron.api.tuple.Tuple; import com.twitter.heron.api.tuple.Values; import com.twitter.heron.api.windowing.TupleWindow; -import com.twitter.heron.api.bolt.BaseWindowedBolt.Count; -public class WindowedWordCountTopology { - public static class SentenceSpout extends BaseRichSpout { +public final class WindowedWordCountTopology { + + private WindowedWordCountTopology() { + } + + private static class SentenceSpout extends BaseRichSpout { private static final long serialVersionUID = 2879005791639364028L; private SpoutOutputCollector collector; @@ -46,7 +49,7 @@ public class WindowedWordCountTopology { } @Override - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes", "HiddenField"}) public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) { collector = spoutOutputCollector; @@ -78,9 +81,10 @@ public class WindowedWordCountTopology { private static class WindowSumBolt extends BaseWindowedBolt { private static final long serialVersionUID = 8458595466693183050L; private OutputCollector collector; - Map<String, Integer> counts = new HashMap<String, Integer>(); + private Map<String, Integer> counts = new HashMap<String, Integer>(); @Override + @SuppressWarnings("HiddenField") public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; @@ -108,7 +112,8 @@ public class WindowedWordCountTopology { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("sentence", new SentenceSpout(), parallelism); builder.setBolt("split", new SplitSentence(), parallelism).shuffleGrouping("sentence"); - builder.setBolt("consumer", new WindowSumBolt().withWindow(Count.of(10)), parallelism) + builder.setBolt("consumer", new WindowSumBolt() + .withWindow(BaseWindowedBolt.Count.of(10)), parallelism) .fieldsGrouping("split", new Fields("word")); Config conf = new Config();
fixing formating in examples (#<I>)
apache_incubator-heron
train
aa8fdf50a6ee4916ced2ab23eda833467477885c
diff --git a/dshelpers.py b/dshelpers.py index <HASH>..<HASH> 100644 --- a/dshelpers.py +++ b/dshelpers.py @@ -31,7 +31,7 @@ __all__ = ["update_status", "install_cache", "download_url", "rate_limit_disabled", 'BatchProcessor'] -def BatchProcessor(object): +class BatchProcessor(object): """ You can push items here and they'll be stored in a queue. When batch_size items have been pushed, the given callback is called with the list of
BatchProcessor is a class not a function...
scraperwiki_data-services-helpers
train
6a78e064ffd5c4c3194a9a46c773c1c28980185b
diff --git a/bddrest/authoring/manipulation.py b/bddrest/authoring/manipulation.py index <HASH>..<HASH> 100644 --- a/bddrest/authoring/manipulation.py +++ b/bddrest/authoring/manipulation.py @@ -61,7 +61,7 @@ def when(*args, **kwargs): for k, v in kwargs.items(): if isinstance(v, Manipulator): - clone = getattr(story.base_call,k) + clone = getattr(story.base_call, k).copy() v.apply(clone) kwargs[k] = clone diff --git a/bddrest/tests/test_form_manipulation.py b/bddrest/tests/test_form_manipulation.py index <HASH>..<HASH> 100644 --- a/bddrest/tests/test_form_manipulation.py +++ b/bddrest/tests/test_form_manipulation.py @@ -46,14 +46,14 @@ def test_append_form_field(): def test_remove_from_fields(): call = dict( - title='test remove form fields', - url='/apiv1/devices/name: SM-12345678/id: 1', - verb='POST', - form=dict( - activationCode='746727', - phone='+9897654321', - email='user@example.com' - ) + title='test remove form fields', + url='/apiv1/devices/name: SM-12345678/id: 1', + verb='POST', + form=dict( + activationCode='746727', + phone='+9897654321', + email='user@example.com' + ) ) with Given(wsgi_application, **call): @@ -71,20 +71,25 @@ def test_remove_from_fields(): def test_update_from_fields(): call = dict( - title='test remove form fields', - url='/apiv1/devices/name: SM-12345678/id: 1', - verb='POST', - form=dict( - activationCode='746727', - email='user@example.com' - ) + title='test remove form fields', + url='/apiv1/devices/name: SM-12345678/id: 1', + verb='POST', + form=dict( + activationCode='746727', + email='user@example.com' + ) ) with Given(wsgi_application, **call): assert response.status =='200 OK' + assert response.json == dict( + activationCode='746727', + email='user@example.com' + ) + when( - 'Updating fields', + 'Updating email and phone fields', form=Update(email='test@example.com', phone='+98123456789') ) assert response.json == dict( @@ -93,3 +98,18 @@ def test_update_from_fields(): email='test@example.com' ) + when( + 'Updating only acitvation code', + form=Update(activationCode='666') + ) + assert response.json == dict( + activationCode='666', + email='user@example.com' + ) + + when('Not updating at all') + assert response.json == dict( + activationCode='746727', + email='user@example.com' + ) +
Copy the base collection before manipulation, closes #<I>
Carrene_bddrest
train
284b2a1313c2ee1fefbbebab7394bdc68e655099
diff --git a/cluster/kubernetes/images.go b/cluster/kubernetes/images.go index <HASH>..<HASH> 100644 --- a/cluster/kubernetes/images.go +++ b/cluster/kubernetes/images.go @@ -152,7 +152,10 @@ func (c *Cluster) ImagesToFetch() registry.ImageCreds { for imageID, creds := range imageCreds { existingCreds, ok := allImageCreds[imageID] if ok { - existingCreds.Merge(creds) + mergedCreds := registry.NoCredentials() + mergedCreds.Merge(existingCreds) + mergedCreds.Merge(creds) + allImageCreds[imageID] = mergedCreds } else { allImageCreds[imageID] = creds }
Merge existing image credentials into a fresh set With the previous merging strategy the set of credentials which got mutated could be assigned to other images, resulting in overwrites where we would (and did) not expect them. This new approach is the most direct fix to work around mutating the credentials of other images. It creates a fresh set of (empty) credentials and merges the others into it before assigning it to the image.
weaveworks_flux
train
a5dde4c21ddd7edc9c56fe8b403484e995c56008
diff --git a/app/controllers/elements_controller.rb b/app/controllers/elements_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/elements_controller.rb +++ b/app/controllers/elements_controller.rb @@ -2,7 +2,7 @@ class ElementsController < AlchemyController filter_access_to [:show], :attribute_check => true layout false - + # Returns the element partial as HTML or as JavaScript that tries to replace a given +container_id+ with the partial content via jQuery. def show @element = Element.find(params[:id]) diff --git a/app/helpers/pages_helper.rb b/app/helpers/pages_helper.rb index <HASH>..<HASH> 100644 --- a/app/helpers/pages_helper.rb +++ b/app/helpers/pages_helper.rb @@ -1,5 +1,7 @@ module PagesHelper + include ElementsHelper + def render_classes classes=[] s = classes.uniq.delete_if{|x| x == nil || x.blank?}.join(" ") s.blank? ? "" : "class='#{s}'" diff --git a/spec/element_spec.rb b/spec/element_spec.rb index <HASH>..<HASH> 100644 --- a/spec/element_spec.rb +++ b/spec/element_spec.rb @@ -19,4 +19,6 @@ describe Element do FileUtils.mv(File.join(File.dirname(__FILE__), '..', 'config', 'alchemy', 'elements.yml.bak'), File.join(File.dirname(__FILE__), '..', 'config', 'alchemy', 'elements.yml')) end + it "should return an ingredient by name" + end diff --git a/spec/factories.rb b/spec/factories.rb index <HASH>..<HASH> 100644 --- a/spec/factories.rb +++ b/spec/factories.rb @@ -32,16 +32,25 @@ FactoryGirl.define do page_layout 'intro' public true end - + factory :page do - name "A Public Page" + language { Language.find_by_code('kl') || Factory(:language) } + name "A Page" + parent_id { Factory(:language_root_page).id } page_layout "standard" - language :language - + + factory :language_root_page do + name 'Klingonian' + page_layout 'intro' + language_root true + parent_id { Page.root.id } + end + factory :public_page do + name "A Public Page" public true end - + end factory :element do diff --git a/spec/integration/standardset_spec.rb b/spec/integration/standardset_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/standardset_spec.rb +++ b/spec/integration/standardset_spec.rb @@ -2,15 +2,19 @@ require 'spec_helper' describe 'Alchemy Standard Set' do - it "should show the sitename ingredient as page title prefix" do - pending "because we should spec creation of Page and Language first" - header_page = Factory(:public_page) - sitename = Factory(:element, :name => 'sitename', :page => header_page) - sitename.content_by_name('name').essence.update_attributes(:body => 'Peters Petshop') - visit '/' - within('head title') { page.should have_content('Peters Petshop') } - end + before(:each) do + # We need an user or the signup view will show up + Factory(:registered_user) + end - it "should render a whole page including all its elements and contents" + it "should show the sitename ingredient as page title prefix" + + it "should render a whole page including all its elements and contents" do + page = Factory(:public_page) + article = Factory(:element, :name => 'article', :page => page) + article.content_by_name('intro').essence.update_attributes(:body => 'Welcome to Peters Petshop') + visit '/a-public-page' + within('#content') { page.should have_content('Welcome to Peters Petshop') } + end end
Fixes Factories to get all examples passing
AlchemyCMS_alchemy_cms
train
8c128e1dcc36b472b43eb136adf49dd630986ec3
diff --git a/spec/ruby_speech/grxml_spec.rb b/spec/ruby_speech/grxml_spec.rb index <HASH>..<HASH> 100644 --- a/spec/ruby_speech/grxml_spec.rb +++ b/spec/ruby_speech/grxml_spec.rb @@ -275,6 +275,34 @@ module RubySpeech item.children(:item, :weight => 0.5).should == [item1] end + + describe "manually created documents" do + it "should be able to traverse up the tree" do + item = GRXML::Item.new + item1 = GRXML::Item.new :weight => 0.5 + item2 = GRXML::Item.new :weight => 0.5 + item1 << item2 + item << item1 + + item2.parent.should == item1 + item1.parent.should == item + end + end + + describe "DSL created documents" do + it "should be able to traverse up the tree" do + grammar = GRXML.draw do + rule :id => 'one' do + item + end + end + + two = grammar.children.first.children.first + two.should be_a GRXML::Item + two.parent.should be_a GRXML::Rule + two.parent.id.should == 'one' + end + end end # draw end # GRXML end # RubySpeech
[BUGFIX] Failing tests for parent attribute on contracted documents
adhearsion_ruby_speech
train
6d95bf72a4d0eba7e77df05ab9380835eefbd86a
diff --git a/src/SetDataCapableTrait.php b/src/SetDataCapableTrait.php index <HASH>..<HASH> 100644 --- a/src/SetDataCapableTrait.php +++ b/src/SetDataCapableTrait.php @@ -2,8 +2,8 @@ namespace Dhii\Data\Object; +use ArrayAccess; use Dhii\Util\String\StringableInterface as Stringable; -use Traversable; use Exception as RootException; use InvalidArgumentException; @@ -15,64 +15,46 @@ use InvalidArgumentException; trait SetDataCapableTrait { /** - * Assign data. + * Assign a single piece of data. * * @since [*next-version*] * - * @param iterable $data The data to set. Existing keys will be overwritten. - * The rest of the data remains unaltered. + * @param string|int|float|bool|Stringable $key The key, for which to assign the data. + * Unless an integer is given, this will be normalized to string. + * @param mixed $value The value to assign. + * + * @throws InvalidArgumentException If key is invalid. + * @throws RootException If a problem occurs while writing data. */ - protected function _setData($data) + protected function _setData($key, $value) { - if (!is_array($data) && !($data instanceof Traversable)) { - throw $this->_createInvalidArgumentException($this->__('Data must be iterable'), null, null, $data); - } - + $key = $this->_normalizeKey($key); $store = $this->_getDataStore(); - foreach ($data as $_key => $_value) { - $store->{(string) $_key} = $_value; - } + $store->offsetSet($key, $value); } /** - * Retrieves the data store obeject. + * Retrieves a pointer to the data store. * * @since [*next-version*] * - * @return object The data store. + * @return ArrayAccess The data store. */ abstract protected function _getDataStore(); /** - * Creates a new invalid argument exception. + * Normalizes an array key. * - * @since [*next-version*] - * - * @param string|Stringable|null $message The error message, if any. - * @param int|null $code The error code, if any. - * @param RootException|null $previous The inner exception for chaining, if any. - * @param mixed|null $argument The invalid argument, if any. - * - * @return InvalidArgumentException The new exception. - */ - abstract protected function _createInvalidArgumentException( - $message = null, - $code = null, - RootException $previous = null, - $argument = null - ); - - /** - * Translates a string, and replaces placeholders. + * If key is not an integer (strict type check), it will be normalized to string. + * Otherwise it is left as is. * * @since [*next-version*] - * @see sprintf() * - * @param string $string The format string to translate. - * @param array $args Placeholder values to replace in the string. - * @param mixed $context The context for translation. + * @param string|int|float|bool|Stringable $key The key to normalize. + * + * @throws InvalidArgumentException If the value cannot be normalized. * - * @return string The translated string. + * @return string|int The normalized key. */ - abstract protected function __($string, $args = [], $context = null); + abstract protected function _normalizeKey($key); }
Changed behaviour of `SetDataCapableTrait` - Now works with `ArrayAccess`. - Now sets a single piece of data.
Dhii_data-object-abstract
train
137116eb124a9e271d56d19c48a7bd99d8413098
diff --git a/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/FileIndex.java b/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/FileIndex.java index <HASH>..<HASH> 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/FileIndex.java +++ b/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/FileIndex.java @@ -113,7 +113,7 @@ public class FileIndex implements BatchComponent { // Index only provided files indexFiles(fileSystem, progress, fileSystem.sourceFiles(), InputFile.TYPE_MAIN); indexFiles(fileSystem, progress, fileSystem.testFiles(), InputFile.TYPE_TEST); - } else { + } else if (fileSystem.baseDir() != null) { // index from basedir indexDirectory(fileSystem, progress, fileSystem.baseDir(), InputFile.TYPE_MAIN); indexDirectory(fileSystem, progress, fileSystem.baseDir(), InputFile.TYPE_TEST);
SONAR-<I> fix support of non-fs projects
SonarSource_sonarqube
train
cffe01c60373c33f03fc8985bfae608dbf6536df
diff --git a/snap7/client.py b/snap7/client.py index <HASH>..<HASH> 100644 --- a/snap7/client.py +++ b/snap7/client.py @@ -67,8 +67,9 @@ class Client(object): rack, slot)) self.set_param(snap7.snap7types.RemotePort, tcpport) - return self.library.Cli_ConnectTo(self.pointer, c_char_p(six.b(address)), - c_int(rack), c_int(slot)) + return self.library.Cli_ConnectTo( + self.pointer, c_char_p(six.b(address)), + c_int(rack), c_int(slot)) def db_read(self, db_number, start, size): """This is a lean function of Cli_ReadArea() to read PLC DB. @@ -80,8 +81,9 @@ class Client(object): type_ = snap7.snap7types.wordlen_to_ctypes[snap7.snap7types.S7WLByte] data = (type_ * size)() - result = (self.library.Cli_DBRead(self.pointer, db_number, start, size, - byref(data))) + result = (self.library.Cli_DBRead( + self.pointer, db_number, start, size, + byref(data))) check_error(result, context="client") return bytearray(data) @@ -119,7 +121,6 @@ class Client(object): check_error(result, context="client") return bytearray(_buffer), size.value - def upload(self, block_num): """ Uploads a block body from AG @@ -161,8 +162,9 @@ class Client(object): """ logging.debug("db_get db_number: %s" % db_number) _buffer = buffer_type() - result = self.library.Cli_DBGet(self.pointer, db_number, byref(_buffer), - byref(c_int(buffer_size))) + result = self.library.Cli_DBGet( + self.pointer, db_number, byref(_buffer), + byref(c_int(buffer_size))) check_error(result, context="client") return bytearray(_buffer) @@ -183,7 +185,7 @@ class Client(object): result = self.library.Cli_ReadArea(self.pointer, area, dbnumber, start, size, wordlen, byref(data)) check_error(result, context="client") - return data + return bytearray(data) @error_wrap def write_area(self, area, dbnumber, start, data): @@ -223,9 +225,10 @@ class Client(object): (blocktype, size)) data = (c_int * 10)() count = c_int(size) - result = self.library.Cli_ListBlocksOfType(self.pointer, blocktype, - byref(data), - byref(count)) + result = self.library.Cli_ListBlocksOfType( + self.pointer, blocktype, + byref(data), + byref(count)) logging.debug("number of items found: %s" % count) check_error(result, context="client") @@ -297,14 +300,16 @@ class Client(object): def ab_write(self, start, data): """ - This is a lean function of Cli_WriteArea() to Write PLC process outputs. + This is a lean function of Cli_WriteArea() to write PLC process + outputs """ wordlen = snap7.snap7types.S7WLByte type_ = snap7.snap7types.wordlen_to_ctypes[wordlen] size = len(data) cdata = (type_ * size).from_buffer(data) logging.debug("ab write: start: %s: size: %s: " % (start, size)) - return self.library.Cli_ABWrite(self.pointer, start, size, byref(cdata)) + return self.library.Cli_ABWrite( + self.pointer, start, size, byref(cdata)) def as_ab_read(self, start, size): """ @@ -328,7 +333,8 @@ class Client(object): size = len(data) cdata = (type_ * size).from_buffer(data) logging.debug("ab write: start: %s: size: %s: " % (start, size)) - return self.library.Cli_AsABWrite(self.pointer, start, size, byref(cdata)) + return self.library.Cli_AsABWrite( + self.pointer, start, size, byref(cdata)) @error_wrap def as_compress(self, time): @@ -399,8 +405,9 @@ class Client(object): cdata = (type_ * size).from_buffer(data) logger.debug("db_write db_number:%s start:%s size:%s data:%s" % (db_number, start, size, data)) - return self.library.Cli_AsDBWrite(self.pointer, db_number, start, size, - byref(cdata)) + return self.library.Cli_AsDBWrite( + self.pointer, db_number, start, size, + byref(cdata)) @error_wrap def as_download(self, data, block_num=-1):
flake8 issue <I>
gijzelaerr_python-snap7
train
3960b9f1bb59338204bea40aaa76a7a4fb90c63f
diff --git a/src/moneyed/test_moneyed_classes.py b/src/moneyed/test_moneyed_classes.py index <HASH>..<HASH> 100644 --- a/src/moneyed/test_moneyed_classes.py +++ b/src/moneyed/test_moneyed_classes.py @@ -175,9 +175,9 @@ class TestMoney: assert self.one_million_bucks != x def test_equality_to_other_types(self): - x = Money(amount=1, currency=self.USD) - assert self.one_million_bucks != None - assert self.one_million_bucks != {} + x = Money(amount=0, currency=self.USD) + assert x != None + assert x != {} def test_not_equal_to_decimal_types(self): assert self.one_million_bucks != self.one_million_decimal
Modified test_equality_to_other_types to make sure $0 is not the same as None or an empty dict. The previous version didn't make sense.
limist_py-moneyed
train
15bc351e5611a3534dc4d2a1d3fe3d0d24991d73
diff --git a/src/Statement.php b/src/Statement.php index <HASH>..<HASH> 100644 --- a/src/Statement.php +++ b/src/Statement.php @@ -11,7 +11,6 @@ final class Statement extends \PDOStatement public function __construct(\PDOStatement $statement) { $this->stmt = $statement; - $this->queryString = $statement->queryString; } private function except() @@ -19,6 +18,15 @@ final class Statement extends \PDOStatement throw new \Exception($this->stmt->errorCode() . implode('. ', $this->stmt->errorInfo())); } + public function __get($name) + { + if ($name === 'queryString') { + return $this->stmt->queryString; + } + + return null; + } + /** * @param mixed $column * @param mixed $param @@ -136,7 +144,13 @@ final class Statement extends \PDOStatement */ public function fetchAll($fetch_style = null, $fetch_argument = null, $ctor_args = null) { - return $this->stmt->fetchAll($fetch_style, $fetch_argument, $ctor_args); + if ($fetch_style === \PDO::FETCH_CLASS) { + return $this->stmt->fetchAll($fetch_style, $fetch_argument, $ctor_args); + } elseif ($fetch_style === \PDO::FETCH_FUNC || $fetch_style === \PDO::FETCH_COLUMN) { + return $this->stmt->fetchAll($fetch_style, $fetch_argument); + } else { + return $this->stmt->fetchAll($fetch_style); + } } public function fetchColumn($column_number = 0)
Fix access to PDOStatement::queryString
royallthefourth_smooth-pdo
train
b0017f0e5a5124b5f6f1ce50cac48bbeb7b7ca50
diff --git a/tests/saltunittest.py b/tests/saltunittest.py index <HASH>..<HASH> 100644 --- a/tests/saltunittest.py +++ b/tests/saltunittest.py @@ -61,6 +61,7 @@ class TestsLoggingHandler(object): self.level = level self.format = format self.activated = False + self.prev_logging_level = None def activate(self): class Handler(logging.Handler): @@ -76,11 +77,20 @@ class TestsLoggingHandler(object): self.handler.setFormatter(formatter) logging.root.addHandler(self.handler) self.activated = True + # Make sure we're running with the lowest logging level with our + # tests logging handler + current_logging_level = logging.root.getEffectiveLevel() + if current_logging_level > logging.DEBUG: + self.prev_logging_level = current_logging_level + logging.root.setLevel(0) def deactivate(self): if not self.activated: return logging.root.removeHandler(self.handler) + # Restore previous logging level if changed + if self.prev_logging_level is not None: + logging.root.setLevel(self.prev_logging_level) @property def messages(self):
Make sure the tests logging handler catches all messages when active.
saltstack_salt
train
abc165c152ffd1cd46d899b0ede1ac7cd5702c6a
diff --git a/src/test/java/com/spotify/docker/client/DefaultDockerClientTest.java b/src/test/java/com/spotify/docker/client/DefaultDockerClientTest.java index <HASH>..<HASH> 100755 --- a/src/test/java/com/spotify/docker/client/DefaultDockerClientTest.java +++ b/src/test/java/com/spotify/docker/client/DefaultDockerClientTest.java @@ -1413,8 +1413,8 @@ public class DefaultDockerClientTest { assertThat(createEvent.time(), notNullValue()); Event startEvent = eventStream.next(); - if (!dockerApiVersionLessThan("1.22")) { - // For some reason, version 1.22 has an extra null Event. So we read the next one. + if (dockerApiVersionAtLeast("1.22") && eventStream.hasNext()) { + // For some reason, version 1.22 has an extra null Event sometimes. So we read the next one. startEvent = eventStream.next(); }
testEventStream: Only read the next event if it exists
spotify_docker-client
train
c67d5bf88ab972da97ef10845a0df59284f250dc
diff --git a/core-bundle/tests/EventListener/UserSessionListenerTest.php b/core-bundle/tests/EventListener/UserSessionListenerTest.php index <HASH>..<HASH> 100644 --- a/core-bundle/tests/EventListener/UserSessionListenerTest.php +++ b/core-bundle/tests/EventListener/UserSessionListenerTest.php @@ -257,6 +257,11 @@ class UserSessionListenerTest extends TestCase $request->attributes->set('_contao_referer_id', 'dummyTestRefererId'); $request->server->set('REQUEST_URI', '/path/of/contao?having&query&string=1'); + $requestWithRefInUrl = new Request(); + $requestWithRefInUrl->attributes->set('_contao_referer_id', 'dummyTestRefererId'); + $requestWithRefInUrl->server->set('REQUEST_URI', '/path/of/contao?having&query&string=1'); + $requestWithRefInUrl->query->set('ref', 'dummyTestRefererId'); + return [ 'Test current referer null returns correct new referer for back end scope' => [ ContaoCoreBundle::SCOPE_BACKEND, @@ -274,6 +279,27 @@ class UserSessionListenerTest extends TestCase ] ] ], + 'Test referer returns correct new referer for back end scope' => [ + ContaoCoreBundle::SCOPE_BACKEND, + 'contao_backend', + 'Contao\\BackendUser', + 'tl_user', + $requestWithRefInUrl, + 'referer', + [ + 'dummyTestRefererId' => [ + 'last' => '', + 'current' => 'hi/I/am/your_current_referer.html' + ] + ], + [ + 'dummyTestRefererId' => [ + 'last' => 'hi/I/am/your_current_referer.html', + // Make sure this one never contains a / at the beginning + 'current' => 'path/of/contao?having&query&string=1' + ] + ] + ], 'Test current referer null returns null for front end scope' => [ ContaoCoreBundle::SCOPE_FRONTEND, 'contao_frontend',
[Core] Test if the referer is correctly replaced on already existing referer in back end scope
contao_contao
train
158eea33a1cc59a961fb937bbe4d7b4d0221b060
diff --git a/actions/class.TaoModule.php b/actions/class.TaoModule.php index <HASH>..<HASH> 100644 --- a/actions/class.TaoModule.php +++ b/actions/class.TaoModule.php @@ -412,35 +412,6 @@ abstract class tao_actions_TaoModule extends tao_actions_CommonModule { } /** - * Download versioned file - * @param resourceUri {uri} Uri of the resource to download - */ - public function downloadVersionedFile() - { - if($this->hasRequestParameter('uri')){ - - $uri = tao_helpers_Uri::decode($this->getRequestParameter('uri')); - $file = new core_kernel_versioning_File($uri); - $fileName = $file->getOnePropertyValue(new core_kernel_classes_Property(PROPERTY_FILE_FILENAME)); - if(core_kernel_versioning_File::isVersionedFile($file)){ - - $content = $file->getFileContent(); - $size = strlen($content); - $mimeType = tao_helpers_File::getMimeType($file->getAbsolutePath()); - $this->setContentHeader($mimeType); - header("Content-Length: $size"); - header("Content-Disposition: attachment; filename=\"{$fileName}\""); - header("Expires: 0"); - header("Cache-Control: no-cache, must-revalidate"); - header("Pragma: no-cache"); - print $content; - return; - } - } - return; - } - - /** * Edit a versioned file * @todo refactor */ diff --git a/actions/form/class.VersionedFile.php b/actions/form/class.VersionedFile.php index <HASH>..<HASH> 100644 --- a/actions/form/class.VersionedFile.php +++ b/actions/form/class.VersionedFile.php @@ -127,7 +127,7 @@ class tao_actions_form_VersionedFile // if the file is yet versioned add a way to download it if($versioned){ - $downloadUrl = _url('downloadVersionedFile', 'Items', 'taoItems', array( + $downloadUrl = _url('downloadFile', 'File', 'tao', array( 'uri' => tao_helpers_Uri::encode($instance->uriResource), //'classUri' => tao_helpers_Uri::encode($this->clazz->uriResource) ));
delete the downloadVersionedFile action from the tao taoModule controler the deleted action is replaced with the downloadFile action from the tao file controler git-svn-id: <URL>
oat-sa_tao-core
train
73e08e7fcb9ca1df1f44260427ca745c9f20dbe4
diff --git a/jarjar-core/src/main/java/com/tonicsystems/jarjar/transform/config/PatternUtils.java b/jarjar-core/src/main/java/com/tonicsystems/jarjar/transform/config/PatternUtils.java index <HASH>..<HASH> 100644 --- a/jarjar-core/src/main/java/com/tonicsystems/jarjar/transform/config/PatternUtils.java +++ b/jarjar-core/src/main/java/com/tonicsystems/jarjar/transform/config/PatternUtils.java @@ -49,7 +49,7 @@ public class PatternUtils { regex = replaceAllLiteral(regex, dstar, "(.+?)"); // One wildcard test requires the argument to be allowably empty. regex = replaceAllLiteral(regex, star, "([^/]+)"); regex = replaceAllLiteral(regex, estar, "*\\??)"); // Although we replaced with + above, we mean * - regex = replaceAllLiteral(regex, internal, "\\\\$"); // Convert internal class symbols to regular expressions + regex = replaceAllLiteral(regex, internal, "\\$"); // Convert internal class symbols to regular expressions return Pattern.compile("\\A" + regex + "\\Z"); // this.count = this.pattern.matcher("foo").groupCount(); }
fix internal class symbols to regular expressions error
shevek_jarjar
train
1cf356daea5acd6fc9d42fe8e9df966b3a7d2a04
diff --git a/src/com/esri/core/geometry/GeometryCursor.java b/src/com/esri/core/geometry/GeometryCursor.java index <HASH>..<HASH> 100644 --- a/src/com/esri/core/geometry/GeometryCursor.java +++ b/src/com/esri/core/geometry/GeometryCursor.java @@ -47,5 +47,5 @@ public abstract class GeometryCursor { *This method is to be used together with the tick() method on the ListeningGeometryCursor. *Call tock() for each tick() on the ListeningGeometryCursor. */ - protected boolean tock() { return true; } + public boolean tock() { return true; } }
GeometryCursor: make tock method public
Esri_geometry-api-java
train
43f8f9f99a6bf1e60709b77c37c35fdab527daa8
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,9 @@ A 'swiss army knife' solution for merging two or more objects. It supports deep - `options:object` - `deep:boolean` (optional): If true, it performs deep merge operation. **Default:** `false` - `clone:boolean` (optional): If true, clones object properties rather than assigning references. **Default:** `false` + - `adjunct:boolean`(optional): If true, it copies only non-existing properties. **Default:** `false` - `descriptor:boolean`(optional): If true, copies property descriptors. **Default:** `false` + - `functions:boolean`(optional): If true, copies function values, else functions will be ignored. **Default:** `false` - `filter:function` (optional): A callback function to test if source property will be merged to target. - `arrayMerge:boolean|function` (optional): If true, it combines array values. It this is a function, result of call will be assigned to target. @@ -111,7 +113,9 @@ Performs merge with more than two objects. - `options:object` - `deep:boolean` (optional): If true, it performs deep merge operation. **Default:** `false` - `clone:boolean` (optional): If true, clones object properties rather than assigning references. **Default:** `false` + - `adjunct:boolean`(optional): If true, it copies only non-existing properties. **Default:** `false` - `descriptor:boolean`(optional): If true, copies property descriptors. **Default:** `false` + - `functions:boolean`(optional): If true, copies function values, else functions will be ignored. **Default:** `false` - `filter:function` (optional): A callback function to test if source property will be merged to target. - `arrayMerge:boolean|function` (optional): If true, it combines array values. It this is a function, result of call will be assigned to target. diff --git a/lib/merge.js b/lib/merge.js index <HASH>..<HASH> 100644 --- a/lib/merge.js +++ b/lib/merge.js @@ -16,6 +16,7 @@ const isObject = (item) => * @param {boolean} [options.clone] * @param {boolean} [options.adjunct] * @param {boolean} [options.descriptor] + * @param {boolean} [options.functions] * @param {Function} [options.filter] * @param {Function|Boolean} [options.arrayMerge] * @return {Object} @@ -35,21 +36,32 @@ function merge(target, source, options = {}) { if (options.adjunct && target.hasOwnProperty(key)) continue; - const src = Object.getOwnPropertyDescriptor(source, key); - if (options.descriptor) { - if (src.get || src.set || typeof src.value === 'function') { - Object.defineProperty(target, key, src); - continue; - } - } else if (typeof src.value === 'function') + const descriptor = Object.getOwnPropertyDescriptor(source, key); + + if (typeof descriptor.value === 'function' && !options.functions) continue; - let srcVal = src.value; + if (options.descriptor && (descriptor.get || descriptor.set)) { + Object.defineProperty(target, key, descriptor); + continue; + } + + delete descriptor.get; + delete descriptor.set; + if (!options.descriptor) { + descriptor.enumerable = true; + descriptor.configurable = true; + descriptor.writable = true; + } + + let srcVal = source[key]; let trgVal = target[key]; if (isObject(srcVal)) { if (options.deep) { - if (!isObject(trgVal)) - trgVal = target[key] = {}; + if (!isObject(trgVal)) { + descriptor.value = trgVal = {}; + Object.defineProperty(target, key, descriptor); + } merge(trgVal, srcVal, options); continue; } @@ -64,17 +76,8 @@ function merge(target, source, options = {}) { } else if (options.clone) srcVal = srcVal.slice(); } - - if (options.descriptor) { - const src = Object.getOwnPropertyDescriptor(source, key); - Object.defineProperty(target, key, { - configurable: src.configurable, - enumerable: src.enumerable, - writable: src.writable, - value: srcVal - }); - } else - target[key] = srcVal; + descriptor.value = srcVal; + Object.defineProperty(target, key, descriptor); } return target; } diff --git a/test/merge.js b/test/merge.js index <HASH>..<HASH> 100644 --- a/test/merge.js +++ b/test/merge.js @@ -169,7 +169,7 @@ describe('merge', function() { return ++this.bar; } }; - let o = merge({}, a, {descriptor: true}); + let o = merge({}, a, {functions: true}); assert.strictEqual(a.getFoo(), 1); assert.strictEqual(o.getFoo(), 1); assert.strictEqual(o.getFoo(), 2);
[*] Added "functions" options to allow copying functions or not
panates_putil-merge
train
ee61d6ecd06c253f12b9243e673d80ff1814e922
diff --git a/src/Guzzle/Http/Plugin/LogPlugin.php b/src/Guzzle/Http/Plugin/LogPlugin.php index <HASH>..<HASH> 100644 --- a/src/Guzzle/Http/Plugin/LogPlugin.php +++ b/src/Guzzle/Http/Plugin/LogPlugin.php @@ -225,8 +225,10 @@ class LogPlugin implements EventSubscriberInterface // Send the log message to the adapter, adding a category and host $priority = $response && !$response->isSuccessful() ? LOG_ERR : LOG_DEBUG; $this->logAdapter->log(trim($message), $priority, array( - 'category' => 'guzzle.request', - 'host' => $this->hostname + 'category' => 'guzzle.request', + 'host' => $this->hostname, + 'request' => $request, + 'response' => $response )); }
[LogPlugin] #<I> Expose request and response details through extras
guzzle_guzzle3
train
feeb6b8b5cada3322ae7e11428f34bd92995f1c0
diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java index <HASH>..<HASH> 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java @@ -482,7 +482,7 @@ public class DefaultKubernetesClient extends BaseClient implements NamespacedKub */ @Override public VersionInfo getVersion() { - return new ClusterOperationsImpl(httpClient, getConfiguration(), ClusterOperationsImpl.KUBERNETES_VERSION_ENDPOINT).fetchVersion(); + return getVersion(this); } public static VersionInfo getVersion(BaseClient client) {
refactor: use newly introduced method! :facepalm:
fabric8io_kubernetes-client
train
dd630501b05539991c0a2537cca3e62ce713e51d
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexAbstract.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexAbstract.java @@ -71,21 +71,18 @@ public abstract class OIndexAbstract<T> implements OIndexInternal<T> { protected static final String CONFIG_CLUSTERS = "clusters"; protected final String type; protected final OLockManager<Object> keyLockManager; - protected volatile IndexConfiguration configuration; - protected final ODocument metadata; protected final OAbstractPaginatedStorage storage; private final String databaseName; private final String name; - private final OReadersWriterSpinLock rwLock = new OReadersWriterSpinLock(); private final AtomicLong rebuildVersion = new AtomicLong(); - private final int version; + protected volatile IndexConfiguration configuration; protected String valueContainerAlgorithm; protected int indexId = -1; + protected Set<String> clustersToIndex = new HashSet<String>(); private String algorithm; - private Set<String> clustersToIndex = new HashSet<String>(); private volatile OIndexDefinition indexDefinition; private volatile boolean rebuilding = false; private Map<String, String> engineProperties = new HashMap<String, String>(); @@ -610,6 +607,12 @@ public abstract class OIndexAbstract<T> implements OIndexInternal<T> { } @Override + public void setType(OType type) { + indexDefinition = new OSimpleKeyIndexDefinition(version, type); + updateConfiguration(); + } + + @Override public String getAlgorithm() { acquireSharedLock(); try { @@ -904,12 +907,6 @@ public abstract class OIndexAbstract<T> implements OIndexInternal<T> { } @Override - public void setType(OType type) { - indexDefinition = new OSimpleKeyIndexDefinition(version, type); - updateConfiguration(); - } - - @Override public String getIndexNameByKey(final Object key) { final OIndexEngine engine = storage.getIndexEngine(indexId); return engine.getIndexNameByKey(key); @@ -1027,6 +1024,10 @@ public abstract class OIndexAbstract<T> implements OIndexInternal<T> { }); } + protected IndexConfiguration indexConfigurationInstance(final ODocument document) { + return new IndexConfiguration(document); + } + public static final class IndexTxSnapshot { public Map<Object, Object> indexSnapshot = new HashMap<Object, Object>(); public boolean clear = false; @@ -1039,10 +1040,6 @@ public abstract class OIndexAbstract<T> implements OIndexInternal<T> { } } - protected IndexConfiguration indexConfigurationInstance(final ODocument document) { - return new IndexConfiguration(document); - } - protected static class IndexConfiguration { protected final ODocument document;
changes visibility of clustersToindexes to protected to enable subclasses access to it
orientechnologies_orientdb
train
ba134cc5b73b6caec16b7d2c9f4cf77d4ed968af
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -7,11 +7,9 @@ **/ "use strict"; -var Request = require("request"); -var Api = require("./api/v3.0.0/index"); +var Google = require('googleapis'); -var Client = module.exports = function(config) { -}; +var Client = module.exports = function(config) {}; (function() { var config = {}; @@ -34,17 +32,15 @@ var Client = module.exports = function(config) { return; } - // TODO Does Youtube API support basic auth? - options.type = options.type || "oauth"; + var authObj = null; + switch (options.type) { + case "oauth": + authObj = options.token; - if (!options.type || "basic|oauth|key".indexOf(options.type) === -1) { - throw new Error("Invalid authentication type must be 'oauth' or 'key'"); - } else if (options.type == "key" && !options.key) { - throw new Error("Key authentication requires a key to be set"); - } else if (options.type == "oauth" && !options.token) { - throw new Error("OAuth2 authentication requires a token to be set"); + break; } + Google.options({ auth: authObj }); config.auth = options; }; @@ -66,62 +62,9 @@ var Client = module.exports = function(config) { return config = conf; }; - /** - * Client#request(options, callback) -> null - * - options (Object): parameters to send as the request body - * - callback (Function): function to be called when the request returns. - * If the the request returns with an error, the error is passed to - * the callback as its first argument (NodeJS-style). - * - * Send an HTTP request to the server and pass the result to a callback. - **/ - this.request = function(options, callback) { - - var reqOptions = {}; - - if (typeof options === "string") { - reqOptions.url = options; - } - - for (var option in options) { - reqOptions[option] = options[option]; - } + var GoogleYoutube = Google.youtube("v3"); + for (var f in GoogleYoutube) { + this[f] = GoogleYoutube[f]; + } - if (reqOptions.json == undefined) { - reqOptions.json = true; - } - - Request(reqOptions, function (err, res, body) { - - if (!err && res.statusCode == 200) { - return callback(null, body); - } - - // no content - if (res.statusCode === 204) { - return callback(null, ""); - } - - if (body && body.error) { - err = body.error.message || body.error; - } - - if (err) { - return callback(err); - } - - // unknown error - callback("Something wrong happened in the request (index.js:this.request) function. Check the logs for more information."); - console.error( - "\n---- Submit an issue with the following information ----" + - "\nIssues: https://github.com/IonicaBizau/youtube-api/issues" + - "\nDate: " + new Date().toString() + - "\nError: " + JSON.stringify(err) + - "\nStatus Code:: " + JSON.stringify(res.statusCode) + - "\nBody: " + JSON.stringify(body) + - "\n------------------" - ); - }); - }; }).call(Client); -Api.call(Client);
First try to integrate Google APIs NodeJS client
IonicaBizau_youtube-api
train
b13fa112369ef26760be52fce81ac7b366703010
diff --git a/lib/fog/aws/models/storage/file.rb b/lib/fog/aws/models/storage/file.rb index <HASH>..<HASH> 100644 --- a/lib/fog/aws/models/storage/file.rb +++ b/lib/fog/aws/models/storage/file.rb @@ -50,7 +50,7 @@ module Fog requires :directory, :key connection.copy_object(directory.key, key, target_directory_key, target_file_key, options) target_directory = connection.directories.new(:key => target_directory_key) - target_directory.files.get(target_file_key) + target_directory.files.head(target_file_key) end def destroy
Only do a 'head' on the file that we've copied - no need to go download it now, that would defeat the purpose
fog_fog
train
9a4904d7d301b6125f6e50d705d644c6a910e507
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -365,6 +365,7 @@ module ActiveRecord def load_schema(db_config, format = ActiveRecord.schema_format, file = nil) # :nodoc: file ||= schema_dump_path(db_config, format) + return unless file verbose_was, Migration.verbose = Migration.verbose, verbose? && ENV["VERBOSE"] check_schema_file(file) @@ -390,7 +391,7 @@ module ActiveRecord file ||= schema_dump_path(db_config) - return true unless File.exist?(file) + return true unless file && File.exist?(file) ActiveRecord::Base.establish_connection(db_config) @@ -403,7 +404,7 @@ module ActiveRecord def reconstruct_from_schema(db_config, format = ActiveRecord.schema_format, file = nil) # :nodoc: file ||= schema_dump_path(db_config, format) - check_schema_file(file) + check_schema_file(file) if file ActiveRecord::Base.establish_connection(db_config) @@ -421,6 +422,8 @@ module ActiveRecord def dump_schema(db_config, format = ActiveRecord.schema_format) # :nodoc: require "active_record/schema_dumper" filename = schema_dump_path(db_config, format) + return unless filename + connection = ActiveRecord::Base.connection FileUtils.mkdir_p(db_dir) diff --git a/railties/test/application/rake/multi_dbs_test.rb b/railties/test/application/rake/multi_dbs_test.rb index <HASH>..<HASH> 100644 --- a/railties/test/application/rake/multi_dbs_test.rb +++ b/railties/test/application/rake/multi_dbs_test.rb @@ -1024,6 +1024,27 @@ module ApplicationTests end end + test "db:test:prepare don't raise errors when schema_dump is false" do + app_file "config/database.yml", <<~EOS + development: &development + primary: + adapter: sqlite3 + database: dev_db + schema_dump: false + secondary: + adapter: sqlite3 + database: secondary_dev_db + schema_dump: false + test: + <<: *development + EOS + + Dir.chdir(app_path) do + output = rails("db:test:prepare", "--trace") + assert_match(/Execute db:test:prepare/, output) + end + end + test "db:create and db:drop don't raise errors when loading YAML containing multiple ERB statements on the same line" do app_file "config/database.yml", <<-YAML development:
Fix handling disabled schema dumping for test environment
rails_rails
train
8c72464692e4db19e09221a50f38125b09f874dc
diff --git a/src/java/voldemort/store/socket/clientrequest/AbstractClientRequest.java b/src/java/voldemort/store/socket/clientrequest/AbstractClientRequest.java index <HASH>..<HASH> 100644 --- a/src/java/voldemort/store/socket/clientrequest/AbstractClientRequest.java +++ b/src/java/voldemort/store/socket/clientrequest/AbstractClientRequest.java @@ -21,6 +21,7 @@ import java.io.DataOutputStream; import java.io.IOException; import voldemort.VoldemortException; +import voldemort.store.UnreachableStoreException; /** * AbstractClientRequest implements ClientRequest to provide some basic @@ -37,6 +38,8 @@ public abstract class AbstractClientRequest<T> implements ClientRequest<T> { private volatile boolean isComplete = false; + private volatile boolean isParsed = false; + protected abstract void formatRequestInternal(DataOutputStream outputStream) throws IOException; protected abstract T parseResponseInternal(DataInputStream inputStream) throws IOException; @@ -62,6 +65,8 @@ public abstract class AbstractClientRequest<T> implements ClientRequest<T> { error = e; } catch(VoldemortException e) { error = e; + } finally { + isParsed = true; } } @@ -69,6 +74,9 @@ public abstract class AbstractClientRequest<T> implements ClientRequest<T> { if(!isComplete) throw new IllegalStateException("Client response not complete, cannot determine result"); + if(!isParsed) + throw new UnreachableStoreException("Client response not read/parsed, cannot determine result"); + if(error instanceof IOException) throw (IOException) error; else if(error instanceof VoldemortException) diff --git a/src/java/voldemort/store/socket/clientrequest/ClientRequestExecutor.java b/src/java/voldemort/store/socket/clientrequest/ClientRequestExecutor.java index <HASH>..<HASH> 100644 --- a/src/java/voldemort/store/socket/clientrequest/ClientRequestExecutor.java +++ b/src/java/voldemort/store/socket/clientrequest/ClientRequestExecutor.java @@ -59,6 +59,9 @@ public class ClientRequestExecutor extends SelectorManagerWorker { } public boolean isValid() { + if(isClosed()) + return false; + Socket s = socketChannel.socket(); return !s.isClosed() && s.isBound() && s.isConnected(); } @@ -111,8 +114,15 @@ public class ClientRequestExecutor extends SelectorManagerWorker { @Override public void close() { - super.close(); + // Due to certain code paths, close may be called in a recursive + // fashion. Rather than trying to handle all of the cases, simply keep + // track of whether we've been called before and only perform the logic + // once. + if(!isClosed.compareAndSet(false, true)) + return; + completeClientRequest(); + closeInternal(); } @Override diff --git a/src/java/voldemort/utils/SelectorManagerWorker.java b/src/java/voldemort/utils/SelectorManagerWorker.java index <HASH>..<HASH> 100644 --- a/src/java/voldemort/utils/SelectorManagerWorker.java +++ b/src/java/voldemort/utils/SelectorManagerWorker.java @@ -24,6 +24,7 @@ import java.nio.channels.ClosedByInterruptException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Level; import org.apache.log4j.Logger; @@ -55,6 +56,8 @@ public abstract class SelectorManagerWorker implements Runnable { protected final long createTimestamp; + protected final AtomicBoolean isClosed; + protected final Logger logger = Logger.getLogger(getClass()); public SelectorManagerWorker(Selector selector, @@ -67,6 +70,7 @@ public abstract class SelectorManagerWorker implements Runnable { this.inputStream = new ByteBufferBackedInputStream(ByteBuffer.allocate(socketBufferSize)); this.outputStream = new ByteBufferBackedOutputStream(ByteBuffer.allocate(socketBufferSize)); this.createTimestamp = System.nanoTime(); + this.isClosed = new AtomicBoolean(false); if(logger.isDebugEnabled()) logger.debug("Accepting remote connection from " + socketChannel.socket()); @@ -115,6 +119,17 @@ public abstract class SelectorManagerWorker implements Runnable { } public void close() { + // Due to certain code paths, close may be called in a recursive + // fashion. Rather than trying to handle all of the cases, simply keep + // track of whether we've been called before and only perform the logic + // once. + if(!isClosed.compareAndSet(false, true)) + return; + + closeInternal(); + } + + protected void closeInternal() { if(logger.isInfoEnabled()) logger.info("Closing remote connection from " + socketChannel.socket()); @@ -145,6 +160,10 @@ public abstract class SelectorManagerWorker implements Runnable { } } + public boolean isClosed() { + return isClosed.get(); + } + /** * Flips the output buffer, and lets the Selector know we're ready to write. *
No longer checking a closed socket is checked back into the pool
voldemort_voldemort
train
5d944e7ccf55e3474242347e6c49776cb1eef794
diff --git a/src/Components/Database/Installer.php b/src/Components/Database/Installer.php index <HASH>..<HASH> 100644 --- a/src/Components/Database/Installer.php +++ b/src/Components/Database/Installer.php @@ -55,7 +55,8 @@ final class Installer extends AbstractInstaller if (File::exists(database_path('database.sqlite'))) { return false; } - File::makeDirectory($this->app->databasePath('migrations'), 0755, true, true); + + File::makeDirectory($this->app->databasePath(), 0755, true, true); File::put( $this->app->databasePath('database.sqlite'), @@ -65,6 +66,17 @@ final class Installer extends AbstractInstaller ); $this->task( + 'Creating migrations folder', + function () { + if (File::exists($this->app->databasePath('migrations'))) { + return false; + } + + File::makeDirectory($this->app->databasePath('migrations'), 0755, true, true); + } + ); + + $this->task( 'Creating seeds folders and files', function () { if (File::exists($this->app->databasePath('seeds'.DIRECTORY_SEPARATOR.'DatabaseSeeder.php'))) {
Move migrations dir step to a separate task
laravel-zero_framework
train
a14a144fe9ca0ba36318ba2c6743b4abdc91b957
diff --git a/libkbfs/md_ops.go b/libkbfs/md_ops.go index <HASH>..<HASH> 100644 --- a/libkbfs/md_ops.go +++ b/libkbfs/md_ops.go @@ -100,7 +100,6 @@ func (md *MDOpsStandard) decryptMerkleLeaf( } currRmd := rmd - //var fetched []*RootMetadataSigned for { // If currRmd isn't readable, keep fetching MDs until it can // be read. Then try currRmd.data.TLFPrivateKey to decrypt @@ -504,7 +503,7 @@ func (md *MDOpsStandard) processMetadata(ctx context.Context, irmd := MakeImmutableRootMetadata(rmd, key, mdID, localTimestamp, true) // Then, verify the verifying keys. We do this after decrypting - // the MD and making the ImmutableRootMetadata, since we way need + // the MD and making the ImmutableRootMetadata, since we may need // access to the private metadata when checking the merkle roots, // and we also need access to the `mdID`. if err := md.verifyWriterKey(
md_ops: address revoked device write verification review feedback Suggested by jzila. Issue: #<I>
keybase_client
train
8d94a6e72ed86b4b3cb33d4fd2c5752eda3711c1
diff --git a/src/Library/Configs.php b/src/Library/Configs.php index <HASH>..<HASH> 100644 --- a/src/Library/Configs.php +++ b/src/Library/Configs.php @@ -136,7 +136,7 @@ class Configs { foreach ( self::get( 'plugins' ) as $plugin ) { // If no filters, add the plugin. Else, only add the plugin if all filters match. if ( empty( $filters ) ) { - $plugins[] = Factory::create( $plugin['file'] ); + $plugins[] = \Boldgrid\Library\Library\Plugin\Factory::create( $plugin['file'] ); } else { $addPlugin = true; @@ -147,7 +147,7 @@ class Configs { } if ( $addPlugin ) { - $plugins[] = Factory::create( $plugin['file'] ); + $plugins[] = \Boldgrid\Library\Library\Plugin\Factory::create( $plugin['file'] ); } } }
Corrected class not fouind error on L<I> & <I>
BoldGrid_library
train
9971a9f49388ca21cc0671fc4c4af2c76fc6729f
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -44,6 +44,13 @@ class IOpipeWrapperClass { ) { this.startTime = process.hrtime(); this.startTimestamp = Date.now(); + this.config = config; + this.metrics = []; + this.originalIdentity = originalIdentity; + this.event = originalEvent; + this.originalContext = originalContext; + this.originalCallback = originalCallback; + this.userFunc = userFunc; // setup any included plugins this.plugins = plugins.map((pluginFn = defaultPluginFunction) => { @@ -63,9 +70,6 @@ class IOpipeWrapperClass { this.log.apply(this, logArgs); }; - this.config = config; - this.metrics = []; - // assign a new dnsPromise if it's not a coldstart because dns could have changed if (!globals.COLDSTART) { this.dnsPromise = getDnsPromise(this.config.host); @@ -73,12 +77,6 @@ class IOpipeWrapperClass { this.dnsPromise = dnsPromise; } - this.originalIdentity = originalIdentity; - this.event = originalEvent; - this.originalContext = originalContext; - this.originalCallback = originalCallback; - this.userFunc = userFunc; - this.setupContext(); // assign modified methods and objects here
Move config and metrics setup so they are on 'this' for plugins
iopipe_iopipe-js-core
train
94e269cbc98e774630426aa0a0dc70c1db82502d
diff --git a/lib/puppet/file_serving/mount/file.rb b/lib/puppet/file_serving/mount/file.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/file_serving/mount/file.rb +++ b/lib/puppet/file_serving/mount/file.rb @@ -25,7 +25,7 @@ class Puppet::FileServing::Mount::File < Puppet::FileServing::Mount file = ::File.join(full_path, relative_path) - if !(FileTest.exist?(file) )# or FileTest.symlink?(file)) + if !(FileTest.exist?(file) or FileTest.symlink?(file)) Puppet.info("File does not exist or is not accessible: #{file}") return nil end
Uncommeniting the fix for #<I>
puppetlabs_puppet
train
8f68bb0a3f6fb605d85c4c2686c61ea2989f2501
diff --git a/source/rafcon/statemachine/storage/storage.py b/source/rafcon/statemachine/storage/storage.py index <HASH>..<HASH> 100644 --- a/source/rafcon/statemachine/storage/storage.py +++ b/source/rafcon/statemachine/storage/storage.py @@ -57,7 +57,6 @@ class StateMachineStorage(Observable): FILE_NAME_CORE_DATA_OLD = 'meta.json' SCRIPT_FILE = 'script.py' STATEMACHINE_FILE = 'statemachine.yaml' - LIBRARY_FILE = 'library.yaml' def __init__(self, base_path=RAFCON_TEMP_PATH_STORAGE): Observable.__init__(self)
Remove unused constant LIBRARY_FILE
DLR-RM_RAFCON
train
502d8d3277ef501e7b6ff31543f4d54bb8257bb9
diff --git a/Octo/Event/Manager.php b/Octo/Event/Manager.php index <HASH>..<HASH> 100644 --- a/Octo/Event/Manager.php +++ b/Octo/Event/Manager.php @@ -40,13 +40,17 @@ class Manager } } - public function registerListener($event, $callback) + public function registerListener($event, $callback, $priority = false) { if (!array_key_exists($event, $this->listeners)) { $this->listeners[$event] = []; } - $this->listeners[$event][] = $callback; + if ($priority) { + array_unshift($this->listeners[$event], $callback); + } else { + array_push($this->listeners[$event], $callback); + } } public function triggerEvent($event, &$data = null) @@ -58,9 +62,15 @@ class Manager $rtn = true; foreach ($this->listeners[$event] as $callback) { - if (!$callback($data)) { + $continue = true; + + if (!$callback($data, $continue)) { $rtn = false; } + + if (!$continue) { + break; + } } return $rtn;
Adding rudimentary prioritisation, and allow events to stop further propagation.
Block8_Octo
train
553889874c2ba904004c9b14a246ec38f724b295
diff --git a/examples/stock_server.js b/examples/stock_server.js index <HASH>..<HASH> 100644 --- a/examples/stock_server.js +++ b/examples/stock_server.js @@ -85,4 +85,4 @@ if (require.main === module) { stockServer.listen(); } -exports.module = stockServer; +module.exports = stockServer;
Fixed typo in stock_server.js0
grpc_grpc-node
train
39c15d3bf98227d769b0bbf6dae61f590873e420
diff --git a/karld/loadump.py b/karld/loadump.py index <HASH>..<HASH> 100644 --- a/karld/loadump.py +++ b/karld/loadump.py @@ -42,7 +42,8 @@ def ensure_file_path_dir(file_path): def i_get_csv_data(file_name, *args, **kwargs): """A generator for reading a csv file. """ - with open(file_name, 'rb') as csv_file: + buffering = kwargs.get('buffering', FILE_BUFFER_SIZE) + with open(file_name, 'rb', buffering=buffering) as csv_file: reader = csv.reader(csv_file, *args, **kwargs) for row in reader: yield row
Add buffering to csv getting
johnwlockwood_iter_karld_tools
train
35a344dbae2d96012336c0b7c299f1e69ad148cb
diff --git a/lib/cieloz/requisicao_transacao/dados_portador.rb b/lib/cieloz/requisicao_transacao/dados_portador.rb index <HASH>..<HASH> 100644 --- a/lib/cieloz/requisicao_transacao/dados_portador.rb +++ b/lib/cieloz/requisicao_transacao/dados_portador.rb @@ -37,8 +37,9 @@ class Cieloz::RequisicaoTransacao def mascara num = numero.to_s - mask_size = num.length - 6 - ("*" * mask_size) + num[mask_size..-1] + digits = num[0..5] + mask_size = num.length - digits.length + digits + ("*" * mask_size) end def codigo_seguranca= codigo
Refactor dados_portador#mascara to use six first digits, like bin does
fabiolnm_cieloz
train
87209c799c27cdbd5e1e8608d17ba6822edfe453
diff --git a/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/common/executor/CommandExecutorSelector.java b/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/common/executor/CommandExecutorSelector.java index <HASH>..<HASH> 100644 --- a/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/common/executor/CommandExecutorSelector.java +++ b/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/common/executor/CommandExecutorSelector.java @@ -24,7 +24,7 @@ import org.apache.shardingsphere.transaction.core.TransactionType; import java.util.concurrent.ExecutorService; /** - * Executor group. + * Command executor selector. * * @author zhangliang * @author zhaojun @@ -36,7 +36,7 @@ public final class CommandExecutorSelector { * Get executor service. * * @param transactionType transaction type - * @param channelId channel id + * @param channelId channel ID * @return executor service */ public static ExecutorService getExecutor(final TransactionType transactionType, final ChannelId channelId) {
for #<I>, update java doc for CommandExecutorSelector
apache_incubator-shardingsphere
train
dfcabc50c478364e5def9ef0ab29232f68a24e33
diff --git a/Code/Version1.2.mf/apogeedata.py b/Code/Version1.2.mf/apogeedata.py index <HASH>..<HASH> 100644 --- a/Code/Version1.2.mf/apogeedata.py +++ b/Code/Version1.2.mf/apogeedata.py @@ -60,10 +60,10 @@ def continuum_normalize_Chebyshev(lambdas, fluxes, flux_errs, ivars, array of fluxes flux_errs: ndarray - measurement uncertainties on fluxes + array of measurement uncertainties on fluxes ivars: ndarray - inverse variance matrix + array of inverse variances pixtest_fname: str filename against which testing continuum subtraction @@ -74,13 +74,13 @@ def continuum_normalize_Chebyshev(lambdas, fluxes, flux_errs, ivars, Returns ------- norm_flux: ndarray - 3D continuum-normalized spectra (nstars, npixels, 3) + array of continuum-normalized fluxes norm_ivar: ndarray - normalized inverse variance + array of continuum-normalized inverse variances continua: ndarray - 2D continuum array (nstars, npixels) + array corresponding to the fitted continuum """ continua = np.zeros(lambdas.shape) norm_flux = np.zeros(fluxes.shape)
documentation on continuum_normalize_Chebyshev method fixed
annayqho_TheCannon
train
8601703f9d2f8248f152530fd70a5382a21535d3
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -65,8 +65,6 @@ function getElementProperties(el) { props.forEach(function(propName) { if(!el[propName]) return - if(el[propName] instanceof Element) return - // Special case: style // .style is a DOMStyleDeclaration, thus we need to iterate over all // rules to create a hash of applied css properties. @@ -140,6 +138,8 @@ function getElementProperties(el) { // ref: https://github.com/Matt-Esch/virtual-dom/issues/176 if("contentEditable" == propName && el[propName] === 'inherit') return + if('object' === typeof el[propName]) return + // default: just copy the property obj[propName] = el[propName] return
Make it usable in node.js
marcelklehr_vdom-virtualize
train
f11e59eb04aa8c8645e08d50ef0ce98a938b9fc2
diff --git a/openquake/hazardlib/gsim/base.py b/openquake/hazardlib/gsim/base.py index <HASH>..<HASH> 100644 --- a/openquake/hazardlib/gsim/base.py +++ b/openquake/hazardlib/gsim/base.py @@ -147,7 +147,7 @@ def _get_poes_site(mean_std, loglevels, truncation_level, ampfun, ctxs): # Get the values of ground-motion used to compute the probability # of exceedance on soil. - soillevels = loglevels[imt] # shape S + soillevels = loglevels[imt] # shape L1 # Here we set automatically the IMLs that will be used to compute # the probability of occurrence of GM on rock within discrete @@ -187,11 +187,11 @@ def _get_poes_site(mean_std, loglevels, truncation_level, ampfun, ctxs): # Computing the probability of exceedance of the levels of # ground-motion loglevels on soil - logaf = numpy.log(numpy.exp(soillevels) / iml_mid) # shape S - for c in range(C): + logaf = numpy.log(numpy.exp(soillevels) / iml_mid) # shape L1 + for l in range(L1): poex_af = 1. - norm.cdf( - logaf, numpy.log(median_af[c]), std_af[c]) # shape S - out_s[c, m * L1: (m + 1) * L1] += poex_af * pocc_rock[c] # S + logaf[l], numpy.log(median_af), std_af) # shape C + out_s[:, m * L1 + l] += poex_af * pocc_rock # shape C return out_s
Vectorized by contexts in _get_poes_site
gem_oq-engine
train
6348786067e112ca371a02c722401309459a039f
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index <HASH>..<HASH> 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -33,7 +33,7 @@ def _skip_if_mpl_14_or_dev_boxplot(): # Boxplot failures on 1.4 and 1.4.1 # Don't need try / except since that's done at class level import matplotlib - if matplotlib.__version__ in ('1.4.0', '1.5.x'): + if matplotlib.__version__ >= LooseVersion('1.4'): raise nose.SkipTest("Matplotlib Regression in 1.4 and current dev.") @@ -72,6 +72,11 @@ class TestPlotBase(tm.TestCase): 'weight': random.normal(161, 32, size=n), 'category': random.randint(4, size=n)}) + if mpl.__version__ >= LooseVersion('1.4'): + self.bp_n_objects = 7 + else: + self.bp_n_objects = 8 + def tearDown(self): tm.close() @@ -1799,7 +1804,6 @@ class TestDataFramePlots(TestPlotBase): @slow def test_boxplot(self): - _skip_if_mpl_14_or_dev_boxplot() df = self.hist_df series = df['height'] numeric_cols = df._get_numeric_data().columns @@ -1807,15 +1811,19 @@ class TestDataFramePlots(TestPlotBase): ax = _check_plot_works(df.plot, kind='box') self._check_text_labels(ax.get_xticklabels(), labels) - assert_array_equal(ax.xaxis.get_ticklocs(), np.arange(1, len(numeric_cols) + 1)) - self.assertEqual(len(ax.lines), 8 * len(numeric_cols)) + assert_array_equal(ax.xaxis.get_ticklocs(), + np.arange(1, len(numeric_cols) + 1)) + self.assertEqual(len(ax.lines), + self.bp_n_objects * len(numeric_cols)) - axes = _check_plot_works(df.plot, kind='box', subplots=True, logy=True) + with tm.assert_produces_warning(UserWarning): + axes = _check_plot_works(df.plot, kind='box', + subplots=True, logy=True) self._check_axes_shape(axes, axes_num=3, layout=(1, 3)) self._check_ax_scales(axes, yaxis='log') for ax, label in zip(axes, labels): self._check_text_labels(ax.get_xticklabels(), [label]) - self.assertEqual(len(ax.lines), 8) + self.assertEqual(len(ax.lines), self.bp_n_objects) axes = series.plot(kind='box', rot=40) self._check_ticks_props(axes, xrot=40, yrot=0) @@ -1829,13 +1837,11 @@ class TestDataFramePlots(TestPlotBase): labels = [com.pprint_thing(c) for c in numeric_cols] self._check_text_labels(ax.get_xticklabels(), labels) assert_array_equal(ax.xaxis.get_ticklocs(), positions) - self.assertEqual(len(ax.lines), 8 * len(numeric_cols)) + self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols)) @slow def test_boxplot_vertical(self): - _skip_if_mpl_14_or_dev_boxplot() df = self.hist_df - series = df['height'] numeric_cols = df._get_numeric_data().columns labels = [com.pprint_thing(c) for c in numeric_cols] @@ -1843,7 +1849,7 @@ class TestDataFramePlots(TestPlotBase): ax = df.plot(kind='box', rot=50, fontsize=8, vert=False) self._check_ticks_props(ax, xrot=0, yrot=50, ylabelsize=8) self._check_text_labels(ax.get_yticklabels(), labels) - self.assertEqual(len(ax.lines), 8 * len(numeric_cols)) + self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols)) axes = _check_plot_works(df.plot, kind='box', subplots=True, vert=False, logx=True) @@ -1851,13 +1857,13 @@ class TestDataFramePlots(TestPlotBase): self._check_ax_scales(axes, xaxis='log') for ax, label in zip(axes, labels): self._check_text_labels(ax.get_yticklabels(), [label]) - self.assertEqual(len(ax.lines), 8) + self.assertEqual(len(ax.lines), self.bp_n_objects) positions = np.array([3, 2, 8]) ax = df.plot(kind='box', positions=positions, vert=False) self._check_text_labels(ax.get_yticklabels(), labels) assert_array_equal(ax.yaxis.get_ticklocs(), positions) - self.assertEqual(len(ax.lines), 8 * len(numeric_cols)) + self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols)) @slow def test_boxplot_return_type(self):
TST: Adjust boxplot tests following MPL API change fliers on a boxplot are now 1 object instead of 2.
pandas-dev_pandas
train
a94d6ec5d07c772fc4b7838d13029256c11b38e6
diff --git a/structr-ui/src/main/resources/structr/js/editors.js b/structr-ui/src/main/resources/structr/js/editors.js index <HASH>..<HASH> 100644 --- a/structr-ui/src/main/resources/structr/js/editors.js +++ b/structr-ui/src/main/resources/structr/js/editors.js @@ -365,6 +365,7 @@ let _Editors = { model: storageContainer.model, value: editorText, language: language, + readOnly: customConfig.readOnly }); // dispose previously existing editors (with the exception of editors for this id - required for multiple editors per element, like function property) diff --git a/structr-ui/src/main/resources/structr/js/init.js b/structr-ui/src/main/resources/structr/js/init.js index <HASH>..<HASH> 100644 --- a/structr-ui/src/main/resources/structr/js/init.js +++ b/structr-ui/src/main/resources/structr/js/init.js @@ -275,8 +275,6 @@ $(function() { for (let el of elements) { - _Schema.showGeneratedSource(el); - if (el.classList.contains('tab')) { el.dispatchEvent(new Event('click')); }
Bugfix: Respect monaco editor config "readOnly" setting and prevent duplicate loading of editor in one case
structr_structr
train
d25f9a14b444ce5c2a31ba901f76ee20745dd8cd
diff --git a/spec/brewery_db/resource_spec.rb b/spec/brewery_db/resource_spec.rb index <HASH>..<HASH> 100644 --- a/spec/brewery_db/resource_spec.rb +++ b/spec/brewery_db/resource_spec.rb @@ -3,17 +3,13 @@ require 'spec_helper' describe BreweryDB::Resource, :resource do - context '#get', vcr: cassette_options do + context '#get', :vcr do let(:resource) do Class.new(BreweryDB::Resource) { def ok get('breweries', name: 'Rogue Ales').data end - def bad_request - get('breweries').data - end - def not_found get('brewery/NOT_FOUND').data end @@ -26,17 +22,6 @@ describe BreweryDB::Resource, :resource do its(:name) { should == 'Rogue Ales' } end - context 'a bad request' do - it 'raises an exception' do - expect { resource.bad_request }.to raise_error(BreweryDB::BadRequest) - end - - it 'sets the exception message to the error message in the response' do - exception = resource.bad_request rescue $! - exception.message.should match /data.*invalid/ - end - end - context 'a not found request' do it 'raises an exception' do expect { resource.not_found }.to raise_error(BreweryDB::NotFound)
Remove redundant and API-Key specific test. This case is better covered by the middleware specs. Also, the test is tightly coupled to the API key being used - a "Premium" key does not have the restriction, so the request goes through fine.
tylerhunt_brewery_db
train
8fa03922d813f954381138a00d02c7913c7b0749
diff --git a/lib/tabula/entities/spreadsheet.rb b/lib/tabula/entities/spreadsheet.rb index <HASH>..<HASH> 100644 --- a/lib/tabula/entities/spreadsheet.rb +++ b/lib/tabula/entities/spreadsheet.rb @@ -134,12 +134,14 @@ module Tabula def to_csv out = StringIO.new + out.set_encoding("utf-8") Tabula::Writers.CSV(rows, out) out.string end def to_tsv out = StringIO.new + out.set_encoding("utf-8") Tabula::Writers.TSV(rows, out) out.string end diff --git a/lib/tabula/entities/table.rb b/lib/tabula/entities/table.rb index <HASH>..<HASH> 100644 --- a/lib/tabula/entities/table.rb +++ b/lib/tabula/entities/table.rb @@ -79,12 +79,14 @@ module Tabula def to_csv out = StringIO.new + out.set_encoding("utf-8") Tabula::Writers.CSV(rows, out) out.string end def to_tsv out = StringIO.new + out.set_encoding("utf-8") Tabula::Writers.TSV(rows, out) out.string end
fixes UTF-8 to IBM<I> encoding error turns out StringIO needs an encoding set explicitly (StringIO takes the system encoding, like any other IO, but strings are (by default) UTF-8, so chucking UTF-8 strings into an IBM<I> IO obviously breaks stuff.)
tabulapdf_tabula-extractor
train
0a5d93e7b32dc27fd2ceb3c5141225f750fa8b6b
diff --git a/mollie/api/client.py b/mollie/api/client.py index <HASH>..<HASH> 100644 --- a/mollie/api/client.py +++ b/mollie/api/client.py @@ -2,14 +2,13 @@ import json import platform import re import ssl -import warnings from collections import OrderedDict from urllib.parse import urlencode import requests from requests_oauthlib import OAuth2Session -from .error import RemovedIn23Warning, RequestError, RequestSetupError +from .error import RequestError, RequestSetupError from .resources.captures import Captures from .resources.chargebacks import Chargebacks from .resources.customer_mandates import CustomerMandates @@ -72,7 +71,7 @@ class Client(object): access_token=access_token)) return access_token - def __init__(self, api_key=None, api_endpoint=None, timeout=10): + def __init__(self, api_endpoint=None, timeout=10): self.api_endpoint = self.validate_api_endpoint(api_endpoint or self.API_ENDPOINT) self.api_version = self.API_VERSION self.timeout = timeout @@ -120,15 +119,6 @@ class Client(object): self.set_user_agent_component('OpenSSL', ssl.OPENSSL_VERSION.split(' ')[1], sanitize=False) # keep legacy formatting of this component - if api_key: - # There is no clean way for supporting both API key and access token acceptance and validation - # in __init__(). Furthermore the naming of the parameter would be inconsistent. - # Using class methods is way cleaner. - msg = "Setting the API key during init will be removed in the future. " \ - "Use Client.set_api_key() or Client.set_access_token() instead." - warnings.warn(msg, RemovedIn23Warning) - self.api_key = self.validate_api_key(api_key) - def set_api_endpoint(self, api_endpoint): self.api_endpoint = self.validate_api_endpoint(api_endpoint) diff --git a/tests/test_client.py b/tests/test_client.py index <HASH>..<HASH> 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -92,14 +92,6 @@ def test_client_invalid_api_key(): client.set_access_token('test_123') -def test_client_api_key_during_init_deprecated(recwarn): - """Setting the api key during init should work but raise a warning.""" - with pytest.warns(DeprecationWarning, - match='Setting the API key during init will be removed in the future'): - client = Client(api_key='test_123') - assert client.api_key == 'test_123' - - def test_client_broken_cert_bundle(monkeypatch): """A request should raise an error when the certificate bundle is not available.
Remove support for setting api_key during client init.
mollie_mollie-api-python
train
c395adf3f51886f29a621c6289a1546525a63fff
diff --git a/base.php b/base.php index <HASH>..<HASH> 100644 --- a/base.php +++ b/base.php @@ -1543,7 +1543,7 @@ final class Base extends Prefab implements ArrayAccess { * @param $args array * @param $timeout int **/ - function until($func,$args=NULL,$timeout=60) { +function until($func,$args=NULL,$timeout=60) { if (!$args) $args=array(); $time=time(); @@ -1557,10 +1557,18 @@ final class Base extends Prefab implements ArrayAccess { !connection_aborted() && // Got time left? (time()-$time+1<$limit) && + // Turn output buffering on + ob_start() && + // Restart session + @session_start() && // CAUTION: Callback will kill host if it never becomes truthy! - !($out=$this->call($func,$args))) + !($out=$this->call($func,$args))) { + session_commit(); + ob_flush(); + flush(); // Hush down sleep(1); + } return $out; }
Restore automatic session handling by until()
bcosca_fatfree-core
train
1d1c5f7dca802bc2fc94446d3d2f222714430409
diff --git a/lib/rets.js b/lib/rets.js index <HASH>..<HASH> 100644 --- a/lib/rets.js +++ b/lib/rets.js @@ -54,41 +54,59 @@ var Session = require('./session'); * @throws {Error} If an invalid URL object or string is passed. */ util.inherits(RETS, EventEmitter); -function RETS(options) { +function RETS(config, options) { /** * @todo Document this pattern. */ if (!(this instanceof RETS)) { - return new RETS(options); + return new RETS(config, options); } /** - * Holds the original options passed by the user. - * - * @member {object|string} + * If config is a string, the user passed a url so move it into config.url + * as a parsed url. */ - this.options = options; - - if (typeof this.options === 'undefined') { - throw new Error('options is required.'); + if (typeof config === 'string') { + config = {url: url.parse(config)}; } - if (typeof this.options.url === 'undefined') { - throw new Error('options.url is required.'); + + /** + * If config is not an object, throw an error. + */ + if (typeof config !== 'object') { + throw new Error('config is required and must be a string or an object.'); } - if (typeof this.options.url !== 'string' && typeof this.options.url !== 'object') { - throw new Error('options.url is not a string or an object.'); + + /** + * If config is not an object, throw an error. + */ + if (typeof config.url === 'string') { + config.url = url.parse(config.url); } - if (typeof this.options.url === 'string') { - this.url = this.options.url = url.parse(this.options.url); - } else { - this.url = this.options.url; + + /** + * If config.url.auth is not null, parse it to extract the user and + * password and assign these to config.user and config.pass respectively. + */ + if (config.url.auth !== null) { + var auth = config.url.auth.split(':'); + config.user = auth[0]; + if (auth.length > 1) { + config.pass = auth[1]; + } } - if (typeof this.url.host !== 'string' || this.url.host.length < 1) { - throw new Error('invalid options.url.host.'); + + /** + * If by now config.host is null, throw an error as we need at least that + * to connect to a rets server. + */ + if (config.url.host === null) { + throw Error("config.url.host is not valid"); } - if (typeof this.url.auth !== 'string' || this.url.auth.length < 2 || this.url.auth.indexOf(':') < 0 ) { - throw new Error('invalid options.url.auth.'); + + if (config.user === null) { + throw Error("config.user is required"); } /** @@ -102,20 +120,30 @@ function RETS(options) { */ this.defaults = { url: null, + user: null, + pass: null, ua: { - name: 'RETS-Connector1/2', - pass: '' + name: 'RETS.JS@0.0.1', + pass: null }, version: 'RETS/1.7.2' }; /** - * Holds the final configuration for the instance - * after processing, defaults, validation, etc. + * Holds the original options passed by the user. + * + * @member {object|string} + */ + this.options = options || {}; + + /** + * Holds the original options passed by the user. + * + * @member {object|string} */ - this.config = {}; - util._extend(this.config, this.defaults); - util._extend(this.config, this.options); + this.config = extend(true, {}, this.defaults, config, this.options); + + // debug("config: \n%s", util.inspect(this.config, {colors:true})); /** * Hold reference to Session instance.
Digesting options with new function signature.
retsr_rets.js
train
4c8f36275aa17e535475f5e645ad0a2044007a68
diff --git a/lib/htmlToXlsx.js b/lib/htmlToXlsx.js index <HASH>..<HASH> 100644 --- a/lib/htmlToXlsx.js +++ b/lib/htmlToXlsx.js @@ -111,7 +111,6 @@ module.exports = function (reporter, definition) { if (reporter.compilation) { reporter.compilation.resourceInTemp('htmlToXlsxConversionScript.js', path.join(path.dirname(require.resolve('html-to-xlsx')), 'lib', 'scripts', 'conversionScript.js')) - reporter.compilation.resourceDirectoryInTemp('xlsxTemplate', path.join(path.dirname(require.resolve('msexcel-builder-extended')), 'tmpl')) } definition.options.tmpDir = reporter.options.tempAutoCleanupDirectory @@ -122,7 +121,6 @@ module.exports = function (reporter, definition) { if (reporter.execution) { options.conversionScriptPath = reporter.execution.resourceTempPath('htmlToXlsxConversionScript.js') - options.xlsxTemplatePath = reporter.execution.resourceTempPath('xlsxTemplate') } if (reporter.compilation) {
don’t require msexcel-builder-extended (it is not used)
jsreport_jsreport-html-to-xlsx
train
712debcc74ff0a6c977aabee3e41c9f0829896c7
diff --git a/lib/fluent/plugin/out_aws-elasticsearch-service.rb b/lib/fluent/plugin/out_aws-elasticsearch-service.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/plugin/out_aws-elasticsearch-service.rb +++ b/lib/fluent/plugin/out_aws-elasticsearch-service.rb @@ -192,14 +192,14 @@ class FaradayMiddleware::AwsSigV4 begin if credentials.is_a?(Proc) signer = lambda do - Aws::Signers::V4.new(credentials.call, service_name, region) + Aws::Sigv4::Signer.new(service: service_name, region: region, credentials: credentials.call) end - def signer.sign(req) - self.call.sign(req) + def signer.sign_request(req) + self.call.sign_request(req) end signer else - Aws::Signers::V4.new(credentials, service_name, region) + Aws::Sigv4::Signer.new(service: service_name, region: region, credentials: credentials) end end
fix api changes for aws sdk v3 - replacing previously used internal API with the normal one
atomita_fluent-plugin-aws-elasticsearch-service
train
b42657d891e2c882d76dae5decd2a02fb36934fc
diff --git a/tests/integration/GraphQL/GraphQLQueryTest.php b/tests/integration/GraphQL/GraphQLQueryTest.php index <HASH>..<HASH> 100644 --- a/tests/integration/GraphQL/GraphQLQueryTest.php +++ b/tests/integration/GraphQL/GraphQLQueryTest.php @@ -94,6 +94,6 @@ GRAPHQL; $response = $this->execute($client, $request); $data = json_decode((string)$response->getBody(), true); - $this->assertSame(0, $data['data']['products']['count']); + $this->assertNotEmpty($data['data']['products']['count']); } }
test(GraphQL): fix assertion
commercetools_commercetools-php-sdk
train
b9077e0ae899bf8955e571e0c61df50aad13ad3c
diff --git a/pharen.php b/pharen.php index <HASH>..<HASH> 100755 --- a/pharen.php +++ b/pharen.php @@ -174,7 +174,7 @@ class Lexer{ }else if($this->char == "{"){ $this->tok = new OpenBraceToken; }else if($this->char == "}"){ - $this->char = new CloseBraceToken; + $this->tok = new CloseBraceToken; }else if($this->char == '"'){ $this->tok = new StringToken; $this->state = "string"; @@ -198,7 +198,7 @@ class Lexer{ $this->tok = new NameToken($this->char); $this->state = "append"; } - } + } } } @@ -1463,7 +1463,6 @@ class Parser{ $lookahead = $this->tokens[$i+1]; } $node; - if($tok instanceof OpenParenToken or $tok instanceof OpenBracketToken or $tok instanceof OpenBraceToken){ $expected_state = $this->get_expected($state); if($this->is_literal($expected_state)){ @@ -1504,7 +1503,7 @@ class Parser{ else if($tok->value == '@' && $this->tokens[$i-1]->value == ','){ $lookahead->unquote_spliced = True; } - }else if($tok instanceof CloseParenToken or $tok instanceof CloseBracketToken){ + }else if($tok instanceof CloseParenToken or $tok instanceof CloseBracketToken or $tok instanceof CloseBraceToken){ $curnode = $curnode->parent; array_pop($state); if(count($state) === 0){
Fix bug where CloseBraceToken was not being read.
Scriptor_pharen
train
dc02663c6689d91ee0d2c73623196160c213e47e
diff --git a/pipenv/cli.py b/pipenv/cli.py index <HASH>..<HASH> 100644 --- a/pipenv/cli.py +++ b/pipenv/cli.py @@ -551,10 +551,16 @@ def do_init(dev=False, requirements=False, skip_virtualenv=False, allow_global=F def pip_install(package_name=None, r=None, allow_global=False): - if r: - c = delegator.run('{0} install -r {1} --require-hashes -i {2}'.format(which_pip(allow_global=allow_global), r, project.source['url'])) - else: - c = delegator.run('{0} install "{1}" -i {2}'.format(which_pip(allow_global=allow_global), package_name, project.source['url'])) + # try installing for each source in project.sources + for source in project.sources: + if r: + c = delegator.run('{0} install -r {1} --require-hashes -i {2}'.format(which_pip(allow_global=allow_global), r, source['url'])) + else: + c = delegator.run('{0} install "{1}" -i {2}'.format(which_pip(allow_global=allow_global), package_name, source['url'])) + + if c.return_code == 0: + break + # return the result of the first one that runs ok or the last one that didn't work return c
making `cli.proper_case` use a new method that runs through all sources in project.sources, and return the Request's return for the first one that hit OK, or neither did ok, then raise an exception. Also doing something similar to `cli.pip_install` so that it will try to pip install for all the sources and return the first cmd that worked or the last that didn't work.
pypa_pipenv
train
6df9dae3170c1bf4bfb24e9e311bb2124893faaa
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index <HASH>..<HASH> 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -65,13 +65,16 @@ class TestNumericComparisons: # GH#8932, GH#22163 ts = pd.Timestamp.now() df = pd.DataFrame({"x": range(5)}) - with pytest.raises(TypeError): + + msg = "Invalid comparison between dtype=int64 and Timestamp" + + with pytest.raises(TypeError, match=msg): df > ts - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): df < ts - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): ts < df - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): ts > df assert not (df == ts).any().any() diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index <HASH>..<HASH> 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -66,8 +66,11 @@ ignore_natural_naming_warning = pytest.mark.filterwarnings( class TestHDFStore: def test_format_kwarg_in_constructor(self, setup_path): # GH 13291 + + msg = "format is not a defined argument for HDFStore" + with ensure_clean_path(setup_path) as path: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): HDFStore(path, format="table") def test_context(self, setup_path): @@ -203,21 +206,27 @@ class TestHDFStore: # Invalid. df = tm.makeDataFrame() - with pytest.raises(ValueError): + msg = "Can only append to Tables" + + with pytest.raises(ValueError, match=msg): df.to_hdf(path, "df", append=True, format="f") - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df.to_hdf(path, "df", append=True, format="fixed") - with pytest.raises(TypeError): + msg = r"invalid HDFStore format specified \[foo\]" + + with pytest.raises(TypeError, match=msg): df.to_hdf(path, "df", append=True, format="foo") - with pytest.raises(TypeError): - df.to_hdf(path, "df", append=False, format="bar") + with pytest.raises(TypeError, match=msg): + df.to_hdf(path, "df", append=False, format="foo") # File path doesn't exist path = "" - with pytest.raises(FileNotFoundError): + msg = f"File {path} does not exist" + + with pytest.raises(FileNotFoundError, match=msg): read_hdf(path, "df") def test_api_default_format(self, setup_path): @@ -230,7 +239,10 @@ class TestHDFStore: _maybe_remove(store, "df") store.put("df", df) assert not store.get_storer("df").is_table - with pytest.raises(ValueError): + + msg = "Can only append to Tables" + + with pytest.raises(ValueError, match=msg): store.append("df2", df) pd.set_option("io.hdf.default_format", "table") @@ -251,7 +263,7 @@ class TestHDFStore: df.to_hdf(path, "df") with HDFStore(path) as store: assert not store.get_storer("df").is_table - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df.to_hdf(path, "df2", append=True) pd.set_option("io.hdf.default_format", "table") @@ -384,7 +396,10 @@ class TestHDFStore: # this is an error because its table_type is appendable, but no # version info store.get_node("df2")._v_attrs.pandas_version = None - with pytest.raises(Exception): + + msg = "'NoneType' object has no attribute 'startswith'" + + with pytest.raises(Exception, match=msg): store.select("df2") def test_mode(self, setup_path): @@ -428,7 +443,11 @@ class TestHDFStore: # conv read if mode in ["w"]: - with pytest.raises(ValueError): + msg = ( + "mode w is not allowed while performing a read. " + r"Allowed modes are r, r\+ and a." + ) + with pytest.raises(ValueError, match=msg): read_hdf(path, "df", mode=mode) else: result = read_hdf(path, "df", mode=mode)
TST: Removed some bare pytest raises (#<I>)
pandas-dev_pandas
train
eb967cc7561b76b510636d7aab7b2b0aca4e95f1
diff --git a/api/auth.go b/api/auth.go index <HASH>..<HASH> 100644 --- a/api/auth.go +++ b/api/auth.go @@ -283,7 +283,7 @@ func addUserToTeam(w http.ResponseWriter, r *http.Request, t auth.Token) error { } if !team.ContainsUser(u) { msg := fmt.Sprintf("You are not authorized to add new users to the team %s", team.Name) - return &errors.HTTP{Code: http.StatusUnauthorized, Message: msg} + return &errors.HTTP{Code: http.StatusForbidden, Message: msg} } user, err := auth.GetUserByEmail(email) if err != nil { diff --git a/api/auth_test.go b/api/auth_test.go index <HASH>..<HASH> 100644 --- a/api/auth_test.go +++ b/api/auth_test.go @@ -770,7 +770,7 @@ func (s *AuthSuite) TestAddUserToTeamShouldReturnNotFoundIfThereIsNoTeamWithTheG c.Assert(e, gocheck.ErrorMatches, "^Team not found$") } -func (s *AuthSuite) TestAddUserToTeamShouldReturnUnauthorizedIfTheGivenUserIsNotInTheGivenTeam(c *gocheck.C) { +func (s *AuthSuite) TestAddUserToTeamShouldReturnForbiddenIfTheGivenUserIsNotInTheGivenTeam(c *gocheck.C) { h := testHandler{} ts := testing.StartGandalfTestServer(&h) defer ts.Close() @@ -790,7 +790,7 @@ func (s *AuthSuite) TestAddUserToTeamShouldReturnUnauthorizedIfTheGivenUserIsNot c.Assert(err, gocheck.NotNil) e, ok := err.(*errors.HTTP) c.Assert(ok, gocheck.Equals, true) - c.Assert(e.Code, gocheck.Equals, http.StatusUnauthorized) + c.Assert(e.Code, gocheck.Equals, http.StatusForbidden) c.Assert(e, gocheck.ErrorMatches, "^You are not authorized to add new users to the team tsuruteam$") }
api/auth: return forbidden instead of unauthorized in addUserToTeam The client is properly detecting errors, but we're returning the wrong error. We should not return "unauthorized" when the user is actually "forbidden" to execute the request. Well, that's confusing. Related to #<I>.
tsuru_tsuru
train
2ed0995244f9abd3e1ceae19b3f87ecabcb3f19b
diff --git a/test/access.js b/test/access.js index <HASH>..<HASH> 100644 --- a/test/access.js +++ b/test/access.js @@ -164,12 +164,13 @@ exports.load_file = { exports.load_re_file = { setUp : _set_up, 'whitelist': function (test) { - test.expect(3); + test.expect(4); this.plugin.load_re_file('white', 'mail'); test.ok(this.plugin.list_re); // console.log(this.plugin.temp); test.equal(true, this.plugin.in_re_list('white', 'mail', 'list@harakamail.com')); test.equal(false, this.plugin.in_re_list('white', 'mail', 'list@harail.com')); + test.equal(false, this.plugin.in_re_list('white', 'mail', 'LIST@harail.com')); test.done(); }, };
test that load_re_file and in_re_list work in a case-insensitive manner
haraka_haraka-plugin-access
train
48586eda4b1e16c573eace31c546d6e7ec866862
diff --git a/tests/FiniteStateMachine/VerifyLogTest.php b/tests/FiniteStateMachine/VerifyLogTest.php index <HASH>..<HASH> 100644 --- a/tests/FiniteStateMachine/VerifyLogTest.php +++ b/tests/FiniteStateMachine/VerifyLogTest.php @@ -263,23 +263,6 @@ class Fsm_VerifyLogTest extends FsmTestCase $this->assertExceptionMessage($stateSet, $log, 'index', $logRecordIndex); } - protected function _provideLogsWithSpecificValues($key, $values) - { - $argumentSets = array(); - $templateArgumentSets = $this->provideValidLogs(); - foreach ($values as $value) { - $templateArgumentSetIndex = rand(0, sizeof($templateArgumentSets) - 1); - $argumentSet = $templateArgumentSets[$templateArgumentSetIndex]; - $log = &$argumentSet['log']; - $logIndex = rand(0, sizeof($log) - 1); - $log[$logIndex][$key] = $value; - unset($log); - $argumentSet['logRecordIndex'] = $logIndex; - $argumentSets[] = $argumentSet; - } - return $argumentSets; - } - public function provideValidLogs() { $stateSet = $this->_getBillingStateSet();
#<I>: Fsm_VerifyLogTest::_provideLogsWithSpecificValues() has been eliminated
tourman_fsm
train
d8817bea50a1562d37341a82467b8d99d9bd75c6
diff --git a/panels/_version.py b/panels/_version.py index <HASH>..<HASH> 100644 --- a/panels/_version.py +++ b/panels/_version.py @@ -1,2 +1,2 @@ # Versions compliant with PEP 440 https://www.python.org/dev/peps/pep-0440 -__version__ = "0.0.39" +__version__ = "0.0.40"
Update version number to <I>
chaoss_grimoirelab-sigils
train
4c1490dcb9ab7959fc05e36be2632db046048201
diff --git a/routes/index.js b/routes/index.js index <HASH>..<HASH> 100644 --- a/routes/index.js +++ b/routes/index.js @@ -112,7 +112,7 @@ router.get('/app/:conn', function (req, res, next){ var MongoURI = require('mongo-uri'); // if no connection found - if(Object.keys(connection_list).length === 0){ + if(!connection_list || Object.keys(connection_list).length === 0){ res.redirect(req.app_context + '/app'); return; }
Cannot convert undefined or null to object if there is no connection_list, it is not object
mrvautin_adminMongo
train
f2e9d08d330d91040503176e31f489cda4921646
diff --git a/pkg/blobinfocache/memory.go b/pkg/blobinfocache/memory.go index <HASH>..<HASH> 100644 --- a/pkg/blobinfocache/memory.go +++ b/pkg/blobinfocache/memory.go @@ -18,7 +18,8 @@ type locationKey struct { // memoryCache implements an in-memory-only BlobInfoCache type memoryCache struct { - mutex sync.Mutex // synchronizes concurrent accesses + mutex sync.Mutex + // The following fields can only be accessed with mutex held. uncompressedDigests map[digest.Digest]digest.Digest digestsByUncompressed map[digest.Digest]map[digest.Digest]struct{} // stores a set of digests for each uncompressed digest knownLocations map[locationKey]map[types.BICLocationReference]time.Time // stores last known existence time for each location reference @@ -42,13 +43,11 @@ func NewMemoryCache() types.BlobInfoCache { func (mem *memoryCache) UncompressedDigest(anyDigest digest.Digest) digest.Digest { mem.mutex.Lock() defer mem.mutex.Unlock() - return mem.uncompressedDigest(anyDigest) + return mem.uncompressedDigestLocked(anyDigest) } -// uncompressedDigest returns an uncompressed digest corresponding to anyDigest. -// May return anyDigest if it is known to be uncompressed. -// Returns "" if nothing is known about the digest (it may be compressed or uncompressed). -func (mem *memoryCache) uncompressedDigest(anyDigest digest.Digest) digest.Digest { +// uncompressedDigestLocked implements types.BlobInfoCache.UncompressedDigest, but must be called only with mem.mutex held. +func (mem *memoryCache) uncompressedDigestLocked(anyDigest digest.Digest) digest.Digest { if d, ok := mem.uncompressedDigests[anyDigest]; ok { return d } @@ -124,7 +123,7 @@ func (mem *memoryCache) CandidateLocations(transport types.ImageTransport, scope res = mem.appendReplacementCandidates(res, transport, scope, primaryDigest) var uncompressedDigest digest.Digest // = "" if canSubstitute { - if uncompressedDigest = mem.uncompressedDigest(primaryDigest); uncompressedDigest != "" { + if uncompressedDigest = mem.uncompressedDigestLocked(primaryDigest); uncompressedDigest != "" { otherDigests := mem.digestsByUncompressed[uncompressedDigest] // nil if not present in the map for d := range otherDigests { if d != primaryDigest && d != uncompressedDigest {
Be even more explicit about the rules for holding mem.mutex Document that field accesses must be done with the mutex held, and rename uncompressedDigest to uncompressedDigestLocked.
containers_image
train
f8e40cd2f2674326524f4229a143043c6bb62490
diff --git a/src/utils/async.js b/src/utils/async.js index <HASH>..<HASH> 100644 --- a/src/utils/async.js +++ b/src/utils/async.js @@ -1,7 +1,19 @@ // @flow +const getGlob = () => { + if ( + typeof window !== 'undefined' && + window.setImmediate && + window.setTimeout && + window.setTimeout.apply + ) { + return window; + } + return global; +}; + const setImmediate = (glob => glob.setImmediate || ((fn, ...args) => glob.setTimeout(fn, 0, ...args)))( - typeof window !== 'undefined' ? window : global, + getGlob(), ); export function schedule(fn: Function, args?: any[] = []): Promise<any> {
Fix issue #<I> Issue was caused by window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ that override some window fn Make sur the needed functions are available now
jfairbank_redux-saga-test-plan
train
f95b27ee1b74952317280f751c59c0ff32d2ffea
diff --git a/redis/client.py b/redis/client.py index <HASH>..<HASH> 100755 --- a/redis/client.py +++ b/redis/client.py @@ -2517,6 +2517,12 @@ class PubSub(object): return self.handle_message(response, ignore_subscribe_messages) return None + def ping(self): + """ + Ping the Redis server + """ + return self.execute_command('PING') + def handle_message(self, response, ignore_subscribe_messages=False): """ Parses a pub/sub message. If the channel or pattern was subscribed to @@ -2531,6 +2537,13 @@ class PubSub(object): 'channel': response[2], 'data': response[3] } + elif message_type == 'pong': + message = { + 'type': message_type, + 'pattern': None, + 'channel': None, + 'data': response[1] + } else: message = { 'type': message_type,
Allow pings in PubSub According to <URL>
andymccurdy_redis-py
train
bde56649b4d1ade4b6861a141e3d73bd2c61afd5
diff --git a/build/webpack.dev.config.js b/build/webpack.dev.config.js index <HASH>..<HASH> 100644 --- a/build/webpack.dev.config.js +++ b/build/webpack.dev.config.js @@ -10,6 +10,10 @@ const webpack = require('webpack') // Helpers const resolve = file => require('path').resolve(__dirname, file) +const extractPlugin = ExtractTextPlugin.extract({ + use: ['css-loader', 'postcss-loader', 'stylus-loader'] +}) + module.exports = { devtool: '#cheap-module-eval-source-map', entry: ['babel-polyfill', './dev/index.js'], @@ -30,7 +34,14 @@ module.exports = { rules: [ { test: /\.vue$/, - loaders: ['vue-loader', 'eslint-loader'], + loaders: [{ + loader: 'vue-loader', + options: { + loaders: { + stylus: extractPlugin + } + } + }, 'eslint-loader'], exclude: /node_modules/ }, { @@ -40,9 +51,7 @@ module.exports = { }, { test: /\.styl$/, - loaders: ExtractTextPlugin.extract({ - use: ['css-loader', 'postcss-loader', 'stylus-loader'] - }), + loaders: extractPlugin, exclude: /node_modules/ } ] @@ -55,7 +64,10 @@ module.exports = { publicPath: '/dev/' }, plugins: [ - new ExtractTextPlugin('[name].css'), + new ExtractTextPlugin({ + filename: '[name].css', + allChunks: true + }), new OptimizeCssAssetsPlugin({ assetNameRegExp: /\.css$/ }),
fixed css deduplication in dev
vuetifyjs_vuetify
train
2577f6a2cb25cbb65fdc437a30fcfddc0ca0d298
diff --git a/test/PredisShared.php b/test/PredisShared.php index <HASH>..<HASH> 100644 --- a/test/PredisShared.php +++ b/test/PredisShared.php @@ -25,7 +25,8 @@ class RC { private static $_connection; private static function createConnection() { - $connection = new Predis\Client(array('host' => RC::SERVER_HOST, 'port' => RC::SERVER_PORT)); + $serverProfile = new Predis\RedisServer__Futures(); + $connection = new Predis\Client(array('host' => RC::SERVER_HOST, 'port' => RC::SERVER_PORT), $serverProfile); $connection->connect(); $connection->selectDatabase(RC::DEFAULT_DATABASE); return $connection; @@ -45,6 +46,22 @@ class RC { } } + public static function helperForBlockingPops($op) { + // TODO: I admit that this helper is kinda lame and it does not run + // in a separate process to properly test BLPOP/BRPOP + $redisUri = sprintf('redis://%s:%d/?database=%d', RC::SERVER_HOST, RC::SERVER_PORT, RC::DEFAULT_DATABASE); + $handle = popen('php', 'w'); + fwrite($handle, "<?php + require '../lib/Predis.php'; + \$redis = Predis\Client::create('$redisUri'); + \$redis->rpush('{$op}1', 'a'); + \$redis->rpush('{$op}2', 'b'); + \$redis->rpush('{$op}3', 'c'); + \$redis->rpush('{$op}1', 'd'); + ?>"); + pclose($handle); + } + public static function getArrayOfNumbers() { return array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } diff --git a/test/RedisCommandsTest.php b/test/RedisCommandsTest.php index <HASH>..<HASH> 100644 --- a/test/RedisCommandsTest.php +++ b/test/RedisCommandsTest.php @@ -535,6 +535,60 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase { }); } + function testListBlockingPopFirst() { + // TODO: this test does not cover all the aspects of BLPOP/BRPOP as it + // does not run with a concurrent client pushing items on lists. + RC::helperForBlockingPops('blpop'); + + // BLPOP on one key + $start = time(); + $item = $this->redis->blpop('blpop3', 5); + $this->assertEquals((float)(time() - $start), 0, '', 1); + $this->assertEquals($item, array('blpop3', 'c')); + + // BLPOP on more than one key + $poppedItems = array(); + while ($item = $this->redis->blpop('blpop1', 'blpop2', 1)) { + $poppedItems[] = $item; + } + $this->assertEquals( + array(array('blpop1', 'a'), array('blpop1', 'd'), array('blpop2', 'b')), + $poppedItems + ); + + // check if BLPOP timeouts as expected on empty lists + $start = time(); + $this->redis->blpop('blpop4', 2); + $this->assertEquals((float)(time() - $start), 2, '', 1); + } + + function testListBlockingPopLast() { + // TODO: this test does not cover all the aspects of BLPOP/BRPOP as it + // does not run with a concurrent client pushing items on lists. + RC::helperForBlockingPops('brpop'); + + // BRPOP on one key + $start = time(); + $item = $this->redis->brpop('brpop3', 5); + $this->assertEquals((float)(time() - $start), 0, '', 1); + $this->assertEquals($item, array('brpop3', 'c')); + + // BRPOP on more than one key + $poppedItems = array(); + while ($item = $this->redis->brpop('brpop1', 'brpop2', 1)) { + $poppedItems[] = $item; + } + $this->assertEquals( + array(array('brpop1', 'd'), array('brpop1', 'a'), array('brpop2', 'b')), + $poppedItems + ); + + // check if BRPOP timeouts as expected on empty lists + $start = time(); + $this->redis->brpop('brpop4', 2); + $this->assertEquals((float)(time() - $start), 2, '', 1); + } + /* commands operating on sets */
Added tests for BLPOP and BRPOP. They are not really that great as they are missing a concurrent RPUSHing client, but they are enough for now.
nrk_predis
train
5a4ca3cd02ed8242495b27d9b04f8d0217ddd1ce
diff --git a/test/cookbooks/poise-python_test/recipes/default.rb b/test/cookbooks/poise-python_test/recipes/default.rb index <HASH>..<HASH> 100644 --- a/test/cookbooks/poise-python_test/recipes/default.rb +++ b/test/cookbooks/poise-python_test/recipes/default.rb @@ -27,12 +27,12 @@ python_runtime_test 'pypy' # Ignoring CentOS 6 because system Python there is 2.6 which doesn't support -m. if platform_family?('rhel') && node['platform_version'].start_with?('6') + file '/no_system' +else python_runtime_test 'system' do version '' runtime_provider :system end -else - file '/no_system' end if platform_family?('rhel')
Err, did that backwards.
poise_poise-python
train
0715668f60f78b63fc2beeea35a60f173f936dee
diff --git a/Swat/SwatNavBar.php b/Swat/SwatNavBar.php index <HASH>..<HASH> 100644 --- a/Swat/SwatNavBar.php +++ b/Swat/SwatNavBar.php @@ -140,7 +140,6 @@ class SwatNavBar extends SwatControl if (count($this->entries == 0)) throw new SwatException('Navbar is empty.'); - reset($this->entries); return end($this->entries); }
On Mon, <I>-<I>-<I> at <I>:<I> -<I>, Michael Gauthier wrote: I don't think the reset() call is necessary here. svn commit r<I>
silverorange_swat
train
5b9ddebbce30babce5f6c6a6038c2c78d5e830f0
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,7 @@ import io import os from setuptools import setup, find_packages +from sys import version_info def parse_requirements(file): @@ -12,6 +13,17 @@ def parse_requirements(file): return required_packages +def get_main_requirements(): + """ Collects requirements from a file and adds additional requirement for Python 3.6 + """ + requirements = parse_requirements('requirements.txt') + + if version_info.major == 3 and version_info.minor == 6: + requirements.append('dataclasses') + + return requirements + + def get_version(): for line in open(os.path.join(os.path.dirname(__file__), 'sentinelhub', '_version.py')): if line.find("__version__") >= 0: @@ -69,7 +81,7 @@ setup( packages=find_packages(), package_data={'sentinelhub': ['sentinelhub/config.json', 'sentinelhub/.utmzones.geojson']}, include_package_data=True, - install_requires=parse_requirements('requirements.txt'), + install_requires=get_main_requirements(), extras_require={ 'DEV': parse_requirements('requirements-dev.txt'), 'DOCS': parse_requirements('requirements-docs.txt')
In case of Python <I> install dataclasses package
sentinel-hub_sentinelhub-py
train
8d24dfb58003a2a04339aca2e0af59ecb9c7673d
diff --git a/seaglass/trunk/seaglass/src/main/java/com/seaglass/util/PlatformUtils.java b/seaglass/trunk/seaglass/src/main/java/com/seaglass/util/PlatformUtils.java index <HASH>..<HASH> 100644 --- a/seaglass/trunk/seaglass/src/main/java/com/seaglass/util/PlatformUtils.java +++ b/seaglass/trunk/seaglass/src/main/java/com/seaglass/util/PlatformUtils.java @@ -51,7 +51,7 @@ public class PlatformUtils { * @return true if this JVM is running on a Mac. */ public static boolean isMac() { - return false && System.getProperty("os.name").startsWith("Mac OS"); + return System.getProperty("os.name").startsWith("Mac OS"); } /**
Accidently checked in the fake non-Mac version.
khuxtable_seaglass
train
ed772fb406de84da3bcdc27ed507337a3481ffbb
diff --git a/thumbor/transformer.py b/thumbor/transformer.py index <HASH>..<HASH> 100644 --- a/thumbor/transformer.py +++ b/thumbor/transformer.py @@ -39,17 +39,21 @@ class Transformer(object): def adjust_focal_points(self): source_width, source_height = self.engine.size - self.focal_points = [] + self.focal_points = None if self.context.request.focal_points: - crop = self.context.request.crop - for point in self.context.request.focal_points: - point.x -= crop['left'] or 0 - point.y -= crop['top'] or 0 - if point.x < 0 or point.x > self.target_width or \ - point.y < 0 or point.y > self.target_height: - continue - self.focal_points.append(point) + if self.context.request.should_crop: + self.focal_points = [] + crop = self.context.request.crop + for point in self.context.request.focal_points: + if point.x < crop['left'] or point.x > crop['right'] or \ + point.y < crop['top'] or point.y > crop['bottom']: + continue + point.x -= crop['left'] or 0 + point.y -= crop['top'] or 0 + self.focal_points.append(point) + else: + self.focal_points = self.context.request.focal_points if not self.focal_points: self.focal_points = [
Making sure to only ignore focal points if we're receiving crop coordinates. Fixes #<I>
thumbor_thumbor
train
da34100b700d508c2184fd943e22140740b3be01
diff --git a/lib/rake/rake_test_loader.rb b/lib/rake/rake_test_loader.rb index <HASH>..<HASH> 100644 --- a/lib/rake/rake_test_loader.rb +++ b/lib/rake/rake_test_loader.rb @@ -19,6 +19,7 @@ argv = ARGV.select do |argument| false end rescue LoadError => e + raise unless e.path abort "\nFile does not exist: #{e.path}\n\n" end end diff --git a/test/test_rake_rake_test_loader.rb b/test/test_rake_rake_test_loader.rb index <HASH>..<HASH> 100644 --- a/test/test_rake_rake_test_loader.rb +++ b/test/test_rake_rake_test_loader.rb @@ -24,7 +24,7 @@ class TestRakeRakeTestLoader < Rake::TestCase $:.replace orig_loaded_features end - def test_load_error + def test_load_error_from_require out, err = capture_io do ARGV.replace %w[no_such_test_file.rb] @@ -44,4 +44,18 @@ class TestRakeRakeTestLoader < Rake::TestCase assert_match expected, err end + + def test_load_error_raised_explicitly + File.write("error_test.rb", "raise LoadError, 'explicitly raised'") + out, err = capture_io do + ARGV.replace %w[error_test.rb] + + exc = assert_raises(LoadError) do + load @loader + end + assert_equal "explicitly raised", exc.message + end + assert_empty out + assert_empty err + end end
Re-raise a LoadError that didn't come from require in the test loader
ruby_rake
train