hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
c3083fbba95ec47ad5c37e742395355721cdb68a
diff --git a/Neos.SiteKickstarter/Classes/Command/KickstartCommandController.php b/Neos.SiteKickstarter/Classes/Command/KickstartCommandController.php index <HASH>..<HASH> 100644 --- a/Neos.SiteKickstarter/Classes/Command/KickstartCommandController.php +++ b/Neos.SiteKickstarter/Classes/Command/KickstartCommandController.php @@ -36,7 +36,7 @@ class KickstartCommandController extends CommandController /** * Kickstart a new site package * - * This command generates a new site package with basic TypoScript and Sites.xml + * This command generates a new site package with basic Fusion and Sites.xml * * @param string $packageKey The packageKey for your site * @param string $siteName The siteName of your site
BUGFIX: Remove "TypoScript" from method explanation
neos_neos-development-collection
train
d96685289a7a5ce74a3dc0ece745f9c26236c9bd
diff --git a/src/tests/tests.py b/src/tests/tests.py index <HASH>..<HASH> 100644 --- a/src/tests/tests.py +++ b/src/tests/tests.py @@ -8,7 +8,7 @@ Windows, Linux, Mac Os X. **Description:** - Tests Suite Module. + This module runs the tests suite. **Others:** @@ -38,6 +38,12 @@ __status__ = "Production" #*** Module classes and definitions. #*********************************************************************************************** def testsSuite(): + """ + This definitions runs the tests suite. + + :return: Tests suite. ( TestSuite ) + """ + testsLoader = unittest.TestLoader() return testsLoader.discover(os.path.dirname(__file__)) diff --git a/src/tests/utilities.py b/src/tests/utilities.py index <HASH>..<HASH> 100644 --- a/src/tests/utilities.py +++ b/src/tests/utilities.py @@ -8,7 +8,7 @@ Windows, Linux, Mac Os X. **Description:** - Tests utilities Module. + This module defines tests suite logging configuration. **Others:** @@ -41,4 +41,4 @@ LOGGER = logging.getLogger(Constants.logger) # Starting The Console Handler. LOGGING_CONSOLE_HANDLER = logging.StreamHandler(sys.__stdout__) LOGGING_CONSOLE_HANDLER.setFormatter(core.LOGGING_DEFAULT_FORMATTER) -LOGGER.addHandler(LOGGING_CONSOLE_HANDLER) \ No newline at end of file +LOGGER.addHandler(LOGGING_CONSOLE_HANDLER)
Update "tests" and "tests.utilities" modules docstrings.
KelSolaar_Foundations
train
95ddaa816870b03ca1e34960952062a5ca904652
diff --git a/esteid/config.py b/esteid/config.py index <HASH>..<HASH> 100644 --- a/esteid/config.py +++ b/esteid/config.py @@ -7,7 +7,7 @@ def wsdl_url(): """Url of the DigidocService wsdl Test: https://tsp.demo.sk.ee/dds.wsdl - Live: https://www.sk.ee/DigiDocService/DigiDocService_2_3.wsdl + Live: https://digidocservice.sk.ee/dds.wsdl :return: str """ diff --git a/esteid/digidocservice/models.py b/esteid/digidocservice/models.py index <HASH>..<HASH> 100644 --- a/esteid/digidocservice/models.py +++ b/esteid/digidocservice/models.py @@ -154,7 +154,7 @@ class Signer(BaseDigidocServiceObject): @staticmethod def parse_common_name(common_name, id_code): - # FIXME: This parses legacy common name format, however we should also parse RFC2253 + # FIXME: This parses legacy common name format, however we should also add a method for parsing RFC2253 # see $ssl_client_i_dn vs $ssl_client_i_dn_legacy in nginx docs: # http://nginx.org/en/docs/http/ngx_http_ssl_module.html#variables common_name = common_name.replace(str(id_code), '') diff --git a/esteid/digidocservice/service.py b/esteid/digidocservice/service.py index <HASH>..<HASH> 100644 --- a/esteid/digidocservice/service.py +++ b/esteid/digidocservice/service.py @@ -118,9 +118,12 @@ class DigiDocService(object): def start_session(self, b_hold_session, signing_profile=None, sig_doc_xml=None, datafile=None): response = self.__invoke('StartSession', { 'bHoldSession': b_hold_session, - 'SigningProfile': signing_profile or self.get_signingprofile(), 'SigDocXML': sig_doc_xml or SkipValue, 'datafile': datafile or SkipValue, + + # This parameter is deprecated and exists only due to historical reasons. We need to specify it as + # SkipValue to keep zeep happy + 'SigningProfile': SkipValue, }) if response['Sesscode']: @@ -372,7 +375,8 @@ class DigiDocService(object): # Some service methods use the status field for other things (e.g. MobileAuthenticate) return response - # This should usually not happen, hence the over-the-top raise Exception + # This should usually not happen, hence the over-the-top raise Exception which gets re-raised as + # DigiDocException below raise Exception(response) except Fault as e:
Update wording of some docstrings/comments - Update live wsdl url in `config.wsdl_url` docstring
thorgate_django-esteid
train
ddb7993924091051cd58cb5cfcd0de5de054c9f6
diff --git a/mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioSelector.java b/mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioSelector.java index <HASH>..<HASH> 100644 --- a/mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioSelector.java +++ b/mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioSelector.java @@ -248,7 +248,7 @@ abstract class AbstractNioSelector implements NioSelector { long beforeSelect = System.nanoTime(); int selected = select(selector, quickSelect); // The SelectorUtil.EPOLL_BUG_WORKAROUND condition was removed in Netty 3.10.5 and instead - // put in the if (selectReturnsImmediately == 1024) condition later on. This seems inefficient + // added to the if (selectReturnsImmediately == 1024) condition later on. This seems inefficient // for the (common) case where the workaround is not enabled since in that case there's no point // in looping through the selector keys, so we are keeping the condition here. There's no risk // of a busy loop (https://github.com/netty/netty/issues/2426) when the workaround is not enabled.
(mina.netty) Minor change to a comment in AbstractNioSelector.
kaazing_gateway
train
9e7857c2ff596f6decba4b89dd7d0206e18ff88a
diff --git a/tests/DockerAsyncTest.php b/tests/DockerAsyncTest.php index <HASH>..<HASH> 100644 --- a/tests/DockerAsyncTest.php +++ b/tests/DockerAsyncTest.php @@ -7,6 +7,7 @@ namespace Docker\Tests; use Amp\Delayed; use Amp\Loop; use Docker\API\Model\ContainersCreatePostBody; +use Docker\API\Model\ContainersCreatePostResponse201; use Docker\API\Model\EventsGetResponse200; use Docker\DockerAsync; use Docker\Stream\ArtaxCallbackStream; @@ -64,6 +65,7 @@ class DockerAsyncTest extends \PHPUnit\Framework\TestCase $containerConfig->setImage('busybox:latest'); $containerConfig->setCmd(['echo', '-n', 'output']); + /** @var ContainersCreatePostResponse201 $containerCreate */ $containerCreate = yield $docker->containerCreate($containerConfig); // Let a chance for the container create event to be dispatched to the consumer @@ -71,9 +73,19 @@ class DockerAsyncTest extends \PHPUnit\Framework\TestCase $events->cancel(); - $this->assertCount(1, $receivedEvents); - $this->assertInstanceOf(EventsGetResponse200::class, current($receivedEvents)); - $this->assertSame(current($receivedEvents)->getActor()->getId(), $containerCreate->getId()); + $matchedEvents = array_filter( + $receivedEvents, + function ($event) use ($containerCreate) { + return \is_object($event) + && $event instanceof EventsGetResponse200 + && $event->getAction() === 'create' + && $event->getType() === 'container' + && $event->getActor() !== null + && $event->getActor()->getID() === $containerCreate->getId(); + } + ); + + $this->assertCount(1, $matchedEvents); }); } }
fix: attempt to catch the proper event using a macther (docker may not run in isolation in Travis CI)
docker-php_docker-php
train
6baffe345538a6e257a2fb476cf7aac2fdd91e0a
diff --git a/example/e2e/renderItems.e2e.js b/example/e2e/renderItems.e2e.js index <HASH>..<HASH> 100644 --- a/example/e2e/renderItems.e2e.js +++ b/example/e2e/renderItems.e2e.js @@ -37,47 +37,44 @@ describe('example with renderItems and data', () => { it('should execute autoplay every 2.0s', async () => { // 0s => screen with zero - await expect(element(by.id(SCREENS.zero))).toBeVisible(); + await waitFor(element(by.id(SCREENS.zero))).toBeVisible().withTimeout(DELAY); + await expect(element(by.id(SCREENS.one))).toBeNotVisible(); await expect(element(by.id(SCREENS.two))).toBeNotVisible(); await expect(element(by.id(SCREENS.three))).toBeNotVisible(); await expect(element(by.id(SCREENS.fourth))).toBeNotVisible(); // after 2s => screen with one - await new Promise((_) => setTimeout(_, DELAY)); + await waitFor(element(by.id(SCREENS.one))).toBeVisible().withTimeout(DELAY); await expect(element(by.id(SCREENS.zero))).toBeNotVisible(); - await expect(element(by.id(SCREENS.one))).toBeVisible(); await expect(element(by.id(SCREENS.two))).toBeNotVisible(); await expect(element(by.id(SCREENS.three))).toBeNotVisible(); await expect(element(by.id(SCREENS.fourth))).toBeNotVisible(); // after 4s => screen with two - await new Promise((_) => setTimeout(_, DELAY)); + await waitFor(element(by.id(SCREENS.two))).toBeVisible().withTimeout(DELAY); await expect(element(by.id(SCREENS.zero))).toBeNotVisible(); await expect(element(by.id(SCREENS.one))).toBeNotVisible(); - await expect(element(by.id(SCREENS.two))).toBeVisible(); await expect(element(by.id(SCREENS.three))).toBeNotVisible(); await expect(element(by.id(SCREENS.fourth))).toBeNotVisible(); // after 6s => screen with three - await new Promise((_) => setTimeout(_, DELAY)); + await waitFor(element(by.id(SCREENS.three))).toBeVisible().withTimeout(DELAY); await expect(element(by.id(SCREENS.zero))).toBeNotVisible(); await expect(element(by.id(SCREENS.one))).toBeNotVisible(); await expect(element(by.id(SCREENS.two))).toBeNotVisible(); - await expect(element(by.id(SCREENS.three))).toBeVisible(); await expect(element(by.id(SCREENS.fourth))).toBeNotVisible(); // after 8s => screen with fourth - await new Promise((_) => setTimeout(_, DELAY)); + await waitFor(element(by.id(SCREENS.fourth))).toBeVisible().withTimeout(DELAY); await expect(element(by.id(SCREENS.zero))).toBeNotVisible(); await expect(element(by.id(SCREENS.one))).toBeNotVisible(); await expect(element(by.id(SCREENS.two))).toBeNotVisible(); await expect(element(by.id(SCREENS.three))).toBeNotVisible(); - await expect(element(by.id(SCREENS.fourth))).toBeVisible(); }); // https://github.com/wix/Detox/blob/master/docs/APIRef.ActionsOnElement.md#swipedirection-speed-percentage
Increase delay for tests (#<I>) * Increase delay for tests * Update renderItems.e2e.js * Update renderItems.e2e.js * Update renderItems.e2e.js * Update renderItems.e2e.js
gusgard_react-native-swiper-flatlist
train
74013b3abafe0258dbefee92128a1e0dcc0b954f
diff --git a/lib/jasmine_dom_matchers.js b/lib/jasmine_dom_matchers.js index <HASH>..<HASH> 100644 --- a/lib/jasmine_dom_matchers.js +++ b/lib/jasmine_dom_matchers.js @@ -179,7 +179,7 @@ }), toHaveClass: withSingleElement(function(actual, expected) { - var pass = actual.classList.contains(expected); + var pass = (Array.isArray(expected) ? expected : Array(expected)).every(function(a) { return actual.classList.contains(a); }); return generateResults(pass, prettify(actual), expected, 'have class', actual.classList); }), diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "jasmine_dom_matchers", "description": "dom matchers for Jasmine", "main": "lib/jasmine_dom_matchers.js", - "version": "0.1.2", + "version": "0.1.3", "keywords": ["jasmine"], "homepage": "http://github.com/charleshansen/jasmine_dom_matchers", "author": "Charles Hansen <[email protected]>", diff --git a/spec/javascripts/MatchersSpec.js b/spec/javascripts/MatchersSpec.js index <HASH>..<HASH> 100644 --- a/spec/javascripts/MatchersSpec.js +++ b/spec/javascripts/MatchersSpec.js @@ -84,13 +84,21 @@ describe("Matchers", function() { }); }); - it('tests classes', function() { - expect($('<div class="foo bar"></div>')).toHaveClass('foo'); - expect($('<div class="foo bar"></div>')).toHaveClass('bar'); - expect($('<div class="foo"></div>')).not.toHaveClass('bar'); - expect($('<div><div class="foo"></div></div>')).not.toHaveClass('foo'); - }); + describe('toHaveClass', function() { + it('tests classes when given a single class', function() { + expect($('<div class="foo bar"></div>')).toHaveClass('foo'); + expect($('<div class="foo bar"></div>')).toHaveClass('bar'); + expect($('<div class="foo"></div>')).not.toHaveClass('bar'); + expect($('<div><div class="foo"></div></div>')).not.toHaveClass('foo'); + }); + it('works with arrays', function() { + expect($('<div class="foo bar baz"></div>')).toHaveClass(['foo', 'bar']); + expect($('<div class="foo bar"></div>')).not.toHaveClass(['foo', 'zebra']); + expect($('<div></div>')).not.toHaveClass(['foo']); + }); + }); + describe("toHaveText", function() { it('matches text exactly', function() { expect($('<div>foo</div>')).toHaveText('foo');
toHaveClass can now take arrays
charleshansen_jasmine_dom_matchers
train
9e3653dfa02ea377724e1d0e0c6dd8175277b5c4
diff --git a/lib/Promise.js b/lib/Promise.js index <HASH>..<HASH> 100644 --- a/lib/Promise.js +++ b/lib/Promise.js @@ -38,7 +38,10 @@ function Promise(resolver){ var then; try{ then = value.then; - }catch(_){} + }catch(exception){ + adoptRejectedState(exception); + return; + } if(typeof then !== "function"){ adoptFulfilledState(value); diff --git a/lib/ResolutionPropagator.js b/lib/ResolutionPropagator.js index <HASH>..<HASH> 100644 --- a/lib/ResolutionPropagator.js +++ b/lib/ResolutionPropagator.js @@ -16,11 +16,7 @@ function extractThenMethod(x){ return null; } - var then; - try{ - then = x.then; - }catch(_){} - + var then = x.then; return typeof then === "function" ? then : null; } @@ -50,7 +46,12 @@ function ResolutionPropagator(transforms){ module.exports = ResolutionPropagator; ResolutionPropagator.valueOrPromise = function(value){ - var then = extractThenMethod(value); + var then; + try{ + then = extractThenMethod(value); + }catch(exception){ + return new ResolutionPropagator().settle(false, exception).promise; + } if(!then || value instanceof Promise){ return value; } @@ -121,6 +122,16 @@ ResolutionPropagator.prototype.settle = function(fulfilled, value, handledReject } } + var valueThen = null; + if(fulfilled && !this._resolvePromise){ + try{ + valueThen = extractThenMethod(value); + }catch(exception){ + value = exception; + fulfilled = false; + } + } + this._transforms = null; this._settled = true; this._fulfilled = fulfilled; @@ -133,9 +144,8 @@ ResolutionPropagator.prototype.settle = function(fulfilled, value, handledReject } }else{ this.value = value; - if(fulfilled){ - this._valueThen = extractThenMethod(value); - }else{ + this._valueThen = valueThen; + if(!fulfilled){ this._handledRejection = handledRejection || legendary.unhandledRejection(value); } }
Reject promise when 'x.then' throws
novemberborn_legendary
train
93513d2a8eb55e1ee9ce405cd6f122af885cca0c
diff --git a/sdk/storage/azure-storage-blob-cryptography/src/main/java/com/azure/storage/blob/specialized/cryptography/EncryptedBlobClientBuilder.java b/sdk/storage/azure-storage-blob-cryptography/src/main/java/com/azure/storage/blob/specialized/cryptography/EncryptedBlobClientBuilder.java index <HASH>..<HASH> 100644 --- a/sdk/storage/azure-storage-blob-cryptography/src/main/java/com/azure/storage/blob/specialized/cryptography/EncryptedBlobClientBuilder.java +++ b/sdk/storage/azure-storage-blob-cryptography/src/main/java/com/azure/storage/blob/specialized/cryptography/EncryptedBlobClientBuilder.java @@ -33,6 +33,7 @@ import com.azure.storage.common.implementation.policy.SasTokenCredentialPolicy; import com.azure.storage.common.policy.RequestRetryOptions; import com.azure.storage.common.policy.RequestRetryPolicy; import com.azure.storage.common.policy.ResponseValidationPolicyBuilder; +import com.azure.storage.common.policy.ScrubEtagPolicy; import com.azure.storage.common.policy.SharedKeyCredentialPolicy; import java.net.MalformedURLException; @@ -151,6 +152,8 @@ public final class EncryptedBlobClientBuilder { policies.add(new HttpLoggingPolicy(logOptions)); + policies.add(new ScrubEtagPolicy()); + HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient)
Added the ScrubEtagPolicy to encryption (#<I>)
Azure_azure-sdk-for-java
train
6be473fd9fcbf4022fd17f031e905285716204b9
diff --git a/salt/states/pkg.py b/salt/states/pkg.py index <HASH>..<HASH> 100644 --- a/salt/states/pkg.py +++ b/salt/states/pkg.py @@ -180,7 +180,7 @@ def _fulfills_version_spec(versions, oper, desired_version, versions = versions['version'] for ver in versions: if (oper == '==' and fnmatch.fnmatch(ver, desired_version)) \ - or salt.utils.compare_versions(ver1=ver, + or salt.utils.versions.compare(ver1=ver, oper=oper, ver2=desired_version, cmp_func=cmp_func,
Fix missed reference to salt.utils.compare_versions
saltstack_salt
train
5f221f73971e7a3054f467e27adda623824aebab
diff --git a/satpy/readers/seviri_l1b_native.py b/satpy/readers/seviri_l1b_native.py index <HASH>..<HASH> 100644 --- a/satpy/readers/seviri_l1b_native.py +++ b/satpy/readers/seviri_l1b_native.py @@ -60,7 +60,8 @@ from satpy.readers.seviri_base import (SEVIRICalibrationHandler, dec10216, VISIR_NUM_COLUMNS, VISIR_NUM_LINES, HRV_NUM_COLUMNS, VIS_CHANNELS, add_scanline_acq_time, - get_cds_time) + get_cds_time, NoValidOrbitParams, + SatelliteLocatorFactory) from satpy.readers.seviri_l1b_native_hdr import (GSDTRecords, native_header, native_trailer) from satpy.readers._geos_area import get_area_definition @@ -90,6 +91,7 @@ class NativeMSGFileHandler(BaseFileHandler, SEVIRICalibrationHandler): self.mda = {} self.mda['is_full_disk'] = True self.trailer = {} + self.satpos = None # Read header, prepare dask-array, read trailer # Available channels are known only after the header has been read @@ -475,11 +477,26 @@ class NativeMSGFileHandler(BaseFileHandler, SEVIRICalibrationHandler): dataset.attrs['standard_name'] = dataset_info['standard_name'] dataset.attrs['platform_name'] = self.mda['platform_name'] dataset.attrs['sensor'] = 'seviri' - dataset.attrs['orbital_parameters'] = { - 'projection_longitude': self.mda['projection_parameters']['ssp_longitude'], - 'projection_latitude': 0., - 'projection_altitude': self.mda['projection_parameters']['h']} + # Orbital parameters + actual_lon, actual_lat, actual_alt = self._get_satpos() + orbital_parameters = { + 'projection_longitude': self.mda['projection_parameters'][ + 'ssp_longitude'], + 'projection_latitude': 0., + 'projection_altitude': self.mda['projection_parameters']['h'], + 'satellite_nominal_longitude': self.header['15_DATA_HEADER'][ + 'SatelliteStatus']['SatelliteDefinition'][ + 'NominalLongitude'], + 'satellite_nominal_latitude': 0.0 + } + if actual_lon is not None: + orbital_parameters.update({ + 'satellite_actual_longitude': actual_lon, + 'satellite_actual_latitude': actual_lat, + 'satellite_actual_altitude': actual_alt + }) + dataset.attrs['orbital_parameters'] = orbital_parameters return dataset def calibrate(self, data, dataset_id): @@ -566,6 +583,32 @@ class NativeMSGFileHandler(BaseFileHandler, SEVIRICalibrationHandler): i = self.mda['channel_list'].index(dataset_id['name']) return self.dask_array['visir']['acq_time'][:, i] + def _get_satpos(self): + """Get actual satellite position in geodetic coordinates (WGS-84). + + Evaluate orbit polynomials at the start time of the scan. + + Returns: Longitude [deg east], Latitude [deg north] and Altitude [m] + """ + if self.satpos is None: + a = self.mda['projection_parameters']['a'] + b = self.mda['projection_parameters']['b'] + time = self.start_time + factory = SatelliteLocatorFactory( + self.header['15_DATA_HEADER']['SatelliteStatus']['Orbit'][ + 'OrbitPolynomial'] + ) + sat_locator = factory.get_satellite_locator(time) + try: + lon, lat, alt = sat_locator.get_satpos_geodetic(time, a, b) + except NoValidOrbitParams as err: + logger.warning(err) + lon = lat = alt = None + + # Cache results + self.satpos = lon, lat, alt + return self.satpos + def get_available_channels(header): """Get the available channels from the header information."""
Make satellite position available in SEV native
pytroll_satpy
train
ea121d079426d47eb0280d1fb74a373ea5927ffe
diff --git a/bugzoo/core/patch.py b/bugzoo/core/patch.py index <HASH>..<HASH> 100644 --- a/bugzoo/core/patch.py +++ b/bugzoo/core/patch.py @@ -79,7 +79,7 @@ class Hunk(object): last_insertion_at = old_start_at - hunk_lines: List[HunkLine] = [] + hunk_lines = [] while True: # discarding the previous line ensures that we only consume lines # from the line buffer that belong to the hunk @@ -203,7 +203,7 @@ class Patch(object): Constructs a Patch from a provided unified format diff. """ lines = diff.split('\n') - file_patches: List[FilePatch] = [] + file_patches = [] while lines: if lines[0] == '' or lines[0].isspace(): lines.pop(0)
core: removed Python <I> code
squaresLab_BugZoo
train
c110c1b2c3400669fb207aaa8028b38e98bc9885
diff --git a/jf_agent/jira_download.py b/jf_agent/jira_download.py index <HASH>..<HASH> 100644 --- a/jf_agent/jira_download.py +++ b/jf_agent/jira_download.py @@ -46,9 +46,9 @@ def download_fields(jira_connection, include_fields, exclude_fields): filters = [] if include_fields: - filters.append(lambda field: field['key'] in include_fields) + filters.append(lambda field: field['id'] in include_fields) if exclude_fields: - filters.append(lambda field: field['key'] not in exclude_fields) + filters.append(lambda field: field['id'] not in exclude_fields) fields = [field for field in jira_connection.fields() if all(filt(field) for filt in filters)] @@ -144,13 +144,16 @@ def download_boards_and_sprints(jira_connection, project_ids): if not jira_boards: break b_start_at += len(jira_boards) - boards.extend([b for b in jira_boards if str(b.location.projectId) in project_ids]) + + # Some versions of Jira map boards to projects, some do not. + # If this includes a "location" for boards, then only + # include boards for the projects we're pulling + boards.extend([b for b in jira_boards if not hasattr(b, 'location') or str(getattr(b.location, 'projectId', '')) in project_ids]) print('✓') - print('downloading jira sprints... ', end='', flush=True) links = [] sprints = {} - for b in boards: + for b in tqdm(boards, desc='downloading jira sprints', file=sys.stdout): if b.raw['type'] != 'scrum': continue s_start_at = 0 @@ -163,10 +166,11 @@ def download_boards_and_sprints(jira_connection, project_ids): # JIRA returns 500 errors for various reasons: board is # misconfigured; "falied to execute search"; etc. Just # skip and move on - if e.status_code == 500: - logger.exception(f"Couldn't get sprints for board {b.id}. Skipping...") + if e.status_code == 500 or e.status_code == 404: + logger.warn(f"Couldn't get sprints for board {b.id}. Skipping...") else: raise + if not batch: break s_start_at += len(batch) @@ -175,7 +179,6 @@ def download_boards_and_sprints(jira_connection, project_ids): links.append({'board_id': b.id, 'sprint_ids': [s.id for s in sprints_for_board]}) sprints.update({s.id: s for s in sprints_for_board}) - print('✓') return [b.raw for b in boards], [s.raw for s in sprints.values()], links @@ -230,8 +233,9 @@ def download_issues(jira_connection, project_ids, include_fields, exclude_fields def download_worklogs(jira_connection, issue_ids): print(f'downloading jira worklogs... ', end='', flush=True) updated = [] + since = 0 while True: - worklog_ids_json = jira_connection._get_json('worklog/updated', params={'since': 0}) + worklog_ids_json = jira_connection._get_json('worklog/updated', params={'since': since}) updated_worklog_ids = [v['worklogId'] for v in worklog_ids_json['values']] resp = jira_connection._session.post( @@ -247,6 +251,8 @@ def download_worklogs(jira_connection, issue_ids): updated.extend([wl for wl in worklog_list_json if wl['issueId'] in issue_ids]) if worklog_ids_json['lastPage']: break + since = worklog_ids_json['until'] + print('✓') print(f'Finding old worklogs that have been deleted... ', end='', flush=True)
Support for Jira Server 6 and 7: (#7) * Support for Jira Server 6 and 7: Handle - Fields identified by 'id', not 'key' - Boards that are global, not tied to projects - Boards that are private to a user - worklog pagination
Jellyfish-AI_jf_agent
train
7123a22a383fe10c5571071d868e935c4dc16a84
diff --git a/client/my-sites/invites/controller.js b/client/my-sites/invites/controller.js index <HASH>..<HASH> 100644 --- a/client/my-sites/invites/controller.js +++ b/client/my-sites/invites/controller.js @@ -16,10 +16,15 @@ import { setSection } from 'state/ui/actions'; import { renderWithReduxStore } from 'lib/react-helpers'; import { getRedirectAfterAccept } from 'my-sites/invites/utils'; import { acceptInvite as acceptInviteAction } from 'lib/invites/actions'; +import _user from 'lib/user'; export function acceptInvite( context ) { const acceptedInvite = store.get( 'invite_accepted' ); if ( acceptedInvite ) { + const userModule = _user(); + if ( userModule.get().email === acceptedInvite.sentTo ) { + userModule.set( { email_verified: true } ); + } store.remove( 'invite_accepted' ); const acceptInviteCallback = error => { if ( error ) {
Invites: Set email_verified to true
Automattic_wp-calypso
train
5f4a522ec25ad196dae033cfe36bd17621a9ea18
diff --git a/src/utils/helper.js b/src/utils/helper.js index <HASH>..<HASH> 100644 --- a/src/utils/helper.js +++ b/src/utils/helper.js @@ -329,6 +329,7 @@ export const getSearchState = (state = {}, forHeaders = false) => { aggregations, isLoading, error, + promotedResults, } = state; const searchState = {}; @@ -342,6 +343,22 @@ export const getSearchState = (state = {}, forHeaders = false) => { populateState(props); + function computeResultStats() { + Object.keys(hits).forEach((componentId) => { + const { hidden, total, time } = hits[componentId]; + searchState[componentId] = { + ...searchState[componentId], + resultStats: { + ...searchState[componentId].resultStats, + numberOfResults: total, + time, + promoted: promotedResults[componentId].length, + hidden, + }, + }; + }); + } + Object.keys(selectedValues).forEach((componentId) => { const componentState = searchState[componentId]; const selectedValue = selectedValues[componentId]; @@ -366,6 +383,8 @@ export const getSearchState = (state = {}, forHeaders = false) => { populateState(aggregations, 'aggregations'); populateState(isLoading, 'isLoading'); populateState(error, 'error'); + populateState(promotedResults, 'promotedResults'); + computeResultStats(); } populateState(dependencyTree, 'react'); return searchState;
feat(web): provide promotedResults and resultStats for StateProvider and ReactiveList
appbaseio_reactivecore
train
5af70aef0bf6a7380e6938daea5c6b3301e7eb97
diff --git a/src/plotypus_scripts/plotypus.py b/src/plotypus_scripts/plotypus.py index <HASH>..<HASH> 100644 --- a/src/plotypus_scripts/plotypus.py +++ b/src/plotypus_scripts/plotypus.py @@ -182,7 +182,8 @@ def process_star(filename, periods={}, **ops): else: # file has wrong extension return - _period = periods.get(name) if name in periods else None + _period = periods.get(name) if periods is not None and \ + name in periods else None result = get_lightcurve_from_file(filename, period=_period, **ops) if result is not None:
Fixed bug from no period file being passed (2)
astroswego_plotypus
train
0625f1c2583c10eba6a624fad9463a7c5f565b51
diff --git a/tests/Calendar/CalendarTest.php b/tests/Calendar/CalendarTest.php index <HASH>..<HASH> 100644 --- a/tests/Calendar/CalendarTest.php +++ b/tests/Calendar/CalendarTest.php @@ -215,7 +215,7 @@ class CalendarTest extends \PHPUnit_Framework_TestCase } } - public function testOverriddenEventRemoval() + public function testOverriddenDailyEventRemoval() { $recurrenceFactory = new RecurrenceFactory(); $recurrenceFactory->addRecurrenceType('daily', 'Plummer\Calendarful\Recurrence\Type\Daily'); @@ -224,13 +224,93 @@ class CalendarTest extends \PHPUnit_Framework_TestCase $eventRegistry->shouldReceive('get') ->once() ->andReturn([ - new MockEvent(1, '2014-12-01 12:00:00', '2014-12-01 13:00:00', 'daily'), - new MockEvent(2, '2014-12-02 18:00:00', '2014-12-02 19:00:00', null, null, 1, '2014-12-02 18:00:00'), + new MockEvent(1, '2014-06-01 00:00:00', '2014-06-01 01:00:00', 'daily'), + new MockEvent(2, '2014-06-15 18:00:00', '2014-06-15 19:00:00', null, null, 1, '2014-06-15 00:00:00'), ]); $calendar = Calendar::create($recurrenceFactory) - ->populate($eventRegistry, new \DateTime('2014-12-01 00:00:00'), new \DateTime('2014-12-05 00:00:00')); + ->populate($eventRegistry, new \DateTime('2014-06-01 12:00:00'), new \DateTime('2014-06-30 20:00:00')); + + $overrideExists = false; + $overriddenExists = false; + + $this->assertEquals(29, $calendar->count()); + + foreach($calendar as $event) { + if($event->getStartDate() === '2014-06-15 18:00:00') { + $overrideExists = true; + } + else if($event->getStartDate() === '2014-06-15 00:00:00') { + $overriddenExists = true; + } + } + + $this->assertTrue($overrideExists && !$overriddenExists); + } + + public function testOverriddenWeeklyEventRemoval() + { + $recurrenceFactory = new RecurrenceFactory(); + $recurrenceFactory->addRecurrenceType('weekly', 'Plummer\Calendarful\Recurrence\Type\Weekly'); + + $eventRegistry = m::mock('\Plummer\Calendarful\RegistryInterface'); + $eventRegistry->shouldReceive('get') + ->once() + ->andReturn([ + new MockEvent(1, '2014-06-01 00:00:00', '2014-06-01 01:00:00', 'weekly'), + new MockEvent(2, '2014-06-22 18:00:00', '2014-06-22 19:00:00', null, null, 1, '2014-06-22 00:00:00'), + ]); + + $calendar = Calendar::create($recurrenceFactory) + ->populate($eventRegistry, new \DateTime('2014-06-01 12:00:00'), new \DateTime('2014-06-30 20:00:00')); + + $overrideExists = false; + $overriddenExists = false; + + $this->assertEquals(4, $calendar->count()); + + foreach($calendar as $event) { + if($event->getStartDate() === '2014-06-22 18:00:00') { + $overrideExists = true; + } + else if($event->getStartDate() === '2014-06-22 00:00:00') { + $overriddenExists = true; + } + } + + $this->assertTrue($overrideExists && !$overriddenExists); + } + + public function testOverriddenMonthlyDateEventRemoval() + { + $recurrenceFactory = new RecurrenceFactory(); + $recurrenceFactory->addRecurrenceType('monthly', 'Plummer\Calendarful\Recurrence\Type\MonthlyDate'); + + $eventRegistry = m::mock('\Plummer\Calendarful\RegistryInterface'); + $eventRegistry->shouldReceive('get') + ->once() + ->andReturn([ + new MockEvent(1, '2014-05-31 00:00:00', '2014-05-31 01:00:00', 'monthly'), + new MockEvent(2, '2014-08-31 18:00:00', '2014-08-31 19:00:00', null, null, 1, '2014-08-31 00:00:00'), + ]); + + $calendar = Calendar::create($recurrenceFactory) + ->populate($eventRegistry, new \DateTime('2014-05-01 12:00:00'), new \DateTime('2014-10-31 20:00:00')); + + $overrideExists = false; + $overriddenExists = false; $this->assertEquals(4, $calendar->count()); + + foreach($calendar as $event) { + if($event->getStartDate() === '2014-08-31 18:00:00') { + $overrideExists = true; + } + else if($event->getStartDate() === '2014-08-31 00:00:00') { + $overriddenExists = true; + } + } + + $this->assertTrue($overrideExists && !$overriddenExists); } } \ No newline at end of file
Restructure and add more calendar tests for overridden event occurrences.
benplummer_calendarful
train
a5e4af782cb3575d660008c00b6fa873fb3d6c34
diff --git a/lib/chef/knife/bootstrap.rb b/lib/chef/knife/bootstrap.rb index <HASH>..<HASH> 100644 --- a/lib/chef/knife/bootstrap.rb +++ b/lib/chef/knife/bootstrap.rb @@ -865,6 +865,7 @@ class Chef def ssh_opts opts = {} return opts if winrm? + opts[:pty] = true # ensure we can talk to systems with requiretty set true in sshd config opts[:non_interactive] = true # Prevent password prompts from underlying net/ssh opts[:forward_agent] = (config_value(:ssh_forward_agent) === true) opts[:connection_timeout] = session_timeout diff --git a/spec/unit/knife/bootstrap_spec.rb b/spec/unit/knife/bootstrap_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/knife/bootstrap_spec.rb +++ b/spec/unit/knife/bootstrap_spec.rb @@ -1015,6 +1015,7 @@ describe Chef::Knife::Bootstrap do verify_host_key: false, port: 9999, non_interactive: true, + pty: true, } end @@ -1069,6 +1070,7 @@ describe Chef::Knife::Bootstrap do verify_host_key: false, # Config port: 12, # cli non_interactive: true, + pty: true, } end @@ -1120,6 +1122,7 @@ describe Chef::Knife::Bootstrap do sudo_password: "blah", verify_host_key: true, non_interactive: true, + pty: true, } end it "generates a config hash using the CLI options and pulling nothing from Chef::Config" do @@ -1143,6 +1146,7 @@ describe Chef::Knife::Bootstrap do sudo: false, verify_host_key: "always", non_interactive: true, + pty: true, connection_timeout: 60, } end @@ -1491,33 +1495,38 @@ describe Chef::Knife::Bootstrap do context "for ssh" do let(:connection_protocol) { "ssh" } + let(:default_opts) do + { + non_interactive: true, + pty: true, + forward_agent: false, + connection_timeout: 60, + } + end + + context "by default" do + it "returns a configuration hash with appropriate defaults" do + expect(knife.ssh_opts).to eq default_opts + end + end + context "when ssh_forward_agent has a value" do before do knife.config[:ssh_forward_agent] = true end - it "returns a configuration hash with forward_agent set to true. non-interactive is always true" do - expect(knife.ssh_opts).to eq({ forward_agent: true, non_interactive: true, connection_timeout: 60 }) - end - end - context "when ssh_forward_agent is not set" do - it "returns a configuration hash with forward_agent set to false. non-interactive is always true" do - expect(knife.ssh_opts).to eq({ forward_agent: false, non_interactive: true, connection_timeout: 60 }) + it "returns a default configuration hash with forward_agent set to true" do + expect(knife.ssh_opts).to eq(default_opts.merge(forward_agent: true)) end end context "when session_timeout has a value" do before do knife.config[:session_timeout] = 120 end - it "returns a configuration hash with connection_timeout value." do - expect(knife.ssh_opts).to eq({ forward_agent: false, non_interactive: true, connection_timeout: 120 }) + it "returns a default configuration hash with updated timeout value." do + expect(knife.ssh_opts).to eq(default_opts.merge(connection_timeout: 120)) end end - context "when session_timeout is not set" do - it "returns a configuration hash with connection_timeout default value." do - expect(knife.ssh_opts).to eq({ forward_agent: false, non_interactive: true, connection_timeout: 60 }) - end - end end context "for winrm" do
Enable pty for bootstrap ssh This will allow bootstrap to work with systems that have `requiretty` configured, and is consistent with the behavior of Chef <I> bootstrap
chef_chef
train
220b2652bede07304b4f5ed805eff523f507eb62
diff --git a/pyquil/quilbase.py b/pyquil/quilbase.py index <HASH>..<HASH> 100644 --- a/pyquil/quilbase.py +++ b/pyquil/quilbase.py @@ -174,6 +174,11 @@ class DefGate(AbstractInstruction): self.name = name self.matrix = np.asarray(matrix) + is_unitary = np.allclose(np.eye(rows), self.matrix.dot(self.matrix.T.conj())) + if not is_unitary: + raise AssertionError("Matrix must be unitary.") + + def out(self): """ Prints a readable Quil string representation of this gate. diff --git a/pyquil/tests/test_quil.py b/pyquil/tests/test_quil.py index <HASH>..<HASH> 100644 --- a/pyquil/tests/test_quil.py +++ b/pyquil/tests/test_quil.py @@ -23,9 +23,11 @@ from pyquil.gates import I, X, Y, Z, H, T, S, RX, RY, RZ, CNOT, CCNOT, PHASE, CP TRUE, FALSE, NOT, AND, OR, MOVE, EXCHANGE from pyquil.quilbase import InstructionGroup, DefGate, Gate, reset_label_counter, RawInstr, Addr +import pytest + import numpy as np from scipy.linalg import sqrtm -from math import pi +from math import pi, sqrt def test_make_connection(): @@ -38,17 +40,31 @@ def test_gate(): def test_defgate(): - dg = DefGate("TEST", np.array([[0 + 0.5j, 0.5], - [0.5, 0 - 0.5j]])) - assert dg.out() == "DEFGATE TEST:\n 0.0+0.5i, 0.5+0.0i\n 0.5+0.0i, 0.0-0.5i\n" + dg = DefGate("TEST", np.array([[1., 0.], + [0., 1.]])) + assert dg.out() == "DEFGATE TEST:\n 1.0, 0.0\n 0.0, 1.0\n" test = dg.get_constructor() tg = test(DirectQubit(1), DirectQubit(2)) assert tg.out() == "TEST 1 2" +def test_defgate_non_square_should_throw_error(): + with pytest.raises(AssertionError) as error_info: + DefGate("TEST", np.array([[0 + 0.5j, 0.5, 1], + [0.5, 0 - 0.5j, 1]])) + assert str(error_info.value) == "Matrix must be square." + + +def test_defgate_non_unitary_should_throw_error(): + with pytest.raises(AssertionError) as error_info: + DefGate("TEST", np.array([[0, 1], + [2, 3]])) + assert str(error_info.value) == "Matrix must be unitary." + + def test_defgate_param(): - dgp = DefGate("TEST", [[1., 1.], [0., 1.]]) - assert dgp.out() == "DEFGATE TEST:\n 1.0, 1.0\n 0.0, 1.0\n" + dgp = DefGate("TEST", [[1., 0.], [0., 1.]]) + assert dgp.out() == "DEFGATE TEST:\n 1.0, 0.0\n 0.0, 1.0\n" test = dgp.get_constructor() tg = test(DirectQubit(1)) assert tg.out() == "TEST 1" @@ -193,7 +209,7 @@ def test_rotations(): assert p.out() == 'RX(0.5) 0\nRY(0.1) 1\nRZ(1.4) 2\n' -def test_contolled_gates(): +def test_controlled_gates(): p = Program(CNOT(0, 1), CCNOT(0, 1, 2)) assert p.out() == 'CNOT 0 1\nCCNOT 0 1 2\n'
DefGate: validation for unitary matrix (#<I>)
rigetti_pyquil
train
f002ee2bee20f4a5ff019796f44e3b1cbc6e6ca2
diff --git a/aesh/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java b/aesh/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java index <HASH>..<HASH> 100644 --- a/aesh/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java +++ b/aesh/src/main/java/org/aesh/command/impl/AeshCommandRuntime.java @@ -224,11 +224,11 @@ public class AeshCommandRuntime<CI extends CommandInvocation> if (aeshLine.words().isEmpty()) { return null; } + final String name = aeshLine.firstWord().word(); CommandContainer<CI> container = - commandResolver.resolveCommand(aeshLine.words().get(0).word(), aeshLine.line()); + commandResolver.resolveCommand(name, aeshLine.line()); if (container == null) { - throw new CommandNotFoundException("No command handler for '"+ - aeshLine.words().get(0).word()+ "'.",aeshLine.words().get(0).word()); + throw new CommandNotFoundException("No command handler for '"+name+ "'.",name); } container.addLine(aeshLine); return container;
refactor: use firstWord method to simplify
aeshell_aesh
train
fcc9d79cfa4ebbf46dba404babf7ad34a8a6189f
diff --git a/api/api/search/search/substring_search.py b/api/api/search/search/substring_search.py index <HASH>..<HASH> 100644 --- a/api/api/search/search/substring_search.py +++ b/api/api/search/search/substring_search.py @@ -4,8 +4,8 @@ Search ~~~~~ - copyright: (c) 2014 by Halfmoon Labs, Inc. - copyright: (c) 2015 by Blockstack.org + copyright: (c) 2014-2017 by Blockstack Inc. + copyright: (c) 2017 by Blockstack.org This file is part of Search. @@ -27,13 +27,19 @@ This file is part of Search. usage: './substring_search --create_cache --search <query>' """ +import os import sys import json -from .db import search_db, search_profiles -from .db import search_cache -from .config import DEFAULT_LIMIT +current_dir = os.path.abspath(os.path.dirname(__file__)) +parent_dir = os.path.abspath(current_dir + "/../") +sys.path.insert(0, parent_dir) + +from search.db import search_db, search_profiles +from search.db import search_cache + +from search.config import DEFAULT_LIMIT def anyword_substring_search_inner(query_word, target_words):
make sure that relative imports work if not invoked as module
blockstack_blockstack-core
train
a47774d2fa258a04559598b214fea11afe1a1bf7
diff --git a/src/widgets/SimpleOperation.php b/src/widgets/SimpleOperation.php index <HASH>..<HASH> 100644 --- a/src/widgets/SimpleOperation.php +++ b/src/widgets/SimpleOperation.php @@ -91,7 +91,7 @@ class SimpleOperation extends Widget 'button' => [ 'label' => $this->buttonLabel, 'class' => $this->buttonClass, - 'disabled' => $this->getIsOperable(), + 'disabled' => !$this->getIsOperable(), 'position' => $this->buttonPosition, 'visible' => $this->buttonVisible === null ? true : $this->buttonVisible, ], @@ -121,7 +121,7 @@ class SimpleOperation extends Widget return true; } - return $this->model->isOperable; + return $this->model->isOperable(); } public function run()
fix expessin for disabling control button
hiqdev_hipanel-core
train
9d284a92a24a8ac7e6bfadb1d9a2b9eda792e481
diff --git a/value.go b/value.go index <HASH>..<HASH> 100644 --- a/value.go +++ b/value.go @@ -141,44 +141,46 @@ func NewValue(v interface{}) Value { // NullValue is an empty value. type NullValue struct{} +var nullValue NullValue + // NewNullValue generates a NullValue instance. -func NewNullValue() *NullValue { - return &NullValue{} +func NewNullValue() NullValue { + return nullValue } -func (vl *NullValue) estimateSize() int { +func (vl NullValue) estimateSize() int { return 0 } -func (vl *NullValue) write(buffer []byte, offset int) (int, error) { +func (vl NullValue) write(buffer []byte, offset int) (int, error) { return 0, nil } -func (vl *NullValue) pack(packer *packer) error { +func (vl NullValue) pack(packer *packer) error { packer.PackNil() return nil } // GetType returns wire protocol value type. -func (vl *NullValue) GetType() int { +func (vl NullValue) GetType() int { return ParticleType.NULL } // GetObject returns original value as an interface{}. -func (vl *NullValue) GetObject() interface{} { +func (vl NullValue) GetObject() interface{} { return nil } -// func (vl *NullValue) GetLuaValue() LuaValue { +// func (vl NullValue) GetLuaValue() LuaValue { // return LuaNil.NIL // } -func (vl *NullValue) reader() io.Reader { +func (vl NullValue) reader() io.Reader { return nil } // String implements Stringer interface. -func (vl *NullValue) String() string { +func (vl NullValue) String() string { return "" }
type alias instead of struct for NullValue
aerospike_aerospike-client-go
train
807ffc815bc7d9407450b69cb9b7f861c65b1198
diff --git a/fs/fs.go b/fs/fs.go index <HASH>..<HASH> 100644 --- a/fs/fs.go +++ b/fs/fs.go @@ -390,6 +390,24 @@ func (fs *fileSystem) mintInode(o *gcs.Object) (in inode.Inode) { return } +// Implementation detail of lookUpOrCreateInodeIfNotStale; do not use outside +// of that function. +// +// Return true if o should be treated as stale in comparison to an inode with +// the given source generation. +// +// Special case: we always treat implicit directories as authoritative, even +// though they would otherwise appear to be stale when an explicit placeholder +// object has once been seen (since the implicit generation is negative). This +// saves from an infinite loop when a placeholder object is deleted but the +// directory still implicitly exists -- the caller would otherwise attempt over +// and over again to get a fresh record and simply find the implicit record +// each time. +func staleComparedTo(o *gcs.Object, gen int64) bool { + isImplicit := o.Generation == inode.ImplicitDirGen + return o.Generation < gen && !isImplicit +} + // Attempt to find an inode for the given object record, or create one if one // has never yet existed and the record is newer than any inode we've yet // recorded. @@ -433,7 +451,7 @@ func (fs *fileSystem) lookUpOrCreateInodeIfNotStale( // TODO(jacobsa): Can we drop the cached generation and just use // existingInode.SourceGeneration()? If so, will want to document the // non-decreasing nature of calls to that function. - if o.Generation < cg.gen { + if staleComparedTo(o, cg.gen) { fs.mu.Unlock() return } @@ -451,13 +469,14 @@ func (fs *fileSystem) lookUpOrCreateInodeIfNotStale( fs.mu.Unlock() existingInode.Lock() - // Can we tell that we're exactly right or stale? + // Can we tell that we're exactly right? if o.Generation == existingInode.SourceGeneration() { in = existingInode return } - if o.Generation < existingInode.SourceGeneration() { + // Are we stale? + if staleComparedTo(o, existingInode.SourceGeneration()) { existingInode.Unlock() return } @@ -471,8 +490,6 @@ func (fs *fileSystem) lookUpOrCreateInodeIfNotStale( // Re-acquire the file system lock. If the cache entry still points at // existingInode, we have proven we can replace it with an entry for a a // newly-minted inode. - // - // TODO(jacobsa): There probably lurk implicit directory problems here! fs.mu.Lock() if fs.inodeIndex[o.Name].in == existingInode { in = fs.mintInode(o)
Fixed an infinite loop related to looking up implicit directories. As in d<I>f3e9ad<I>f6fa<I>cd2dbfc.
jacobsa_ratelimit
train
98b249af9499f13c482d9ffa4ce6f1367ddb4586
diff --git a/hazelcast/src/main/java/com/hazelcast/impl/FactoryImpl.java b/hazelcast/src/main/java/com/hazelcast/impl/FactoryImpl.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/impl/FactoryImpl.java +++ b/hazelcast/src/main/java/com/hazelcast/impl/FactoryImpl.java @@ -535,34 +535,58 @@ public class FactoryImpl implements HazelcastInstance { } public <K, V> IMap<K, V> getMap(String name) { + if (name == null) { + throw new NullPointerException("Retrieving a map instance with a null key is not allowed!"); + } return (IMap<K, V>) getOrCreateProxyByName(Prefix.MAP + name); } public <E> IQueue<E> getQueue(String name) { + if (name == null) { + throw new NullPointerException("Retrieving a queue instance with a null key is not allowed!"); + } return (IQueue) getOrCreateProxyByName(Prefix.QUEUE + name); } public <E> ITopic<E> getTopic(String name) { + if (name == null) { + throw new NullPointerException("Retrieving a topic instance with a null key is not allowed!"); + } return (ITopic<E>) getOrCreateProxyByName(Prefix.TOPIC + name); } public <E> ISet<E> getSet(String name) { + if (name == null) { + throw new NullPointerException("Retrieving a set instance with a null key is not allowed!"); + } return (ISet<E>) getOrCreateProxyByName(Prefix.SET + name); } public <E> IList<E> getList(String name) { + if (name == null) { + throw new NullPointerException("Retrieving a list instance with a null key is not allowed!"); + } return (IList<E>) getOrCreateProxyByName(Prefix.AS_LIST + name); } public <K, V> MultiMap<K, V> getMultiMap(String name) { + if (name == null) { + throw new NullPointerException("Retrieving a multi-map instance with a null key is not allowed!"); + } return (MultiMap<K, V>) getOrCreateProxyByName(Prefix.MULTIMAP + name); } public ILock getLock(Object key) { + if (key == null) { + throw new NullPointerException("Retrieving a lock instance with a null key is not allowed!"); + } return (ILock) getOrCreateProxy(new ProxyKey("lock", key)); } public Object getOrCreateProxyByName(final String name) { + if (name == null) { + throw new NullPointerException("Proxy name is required!"); + } Object proxy = proxiesByName.get(name); if (proxy == null) { proxy = getOrCreateProxy(new ProxyKey(name, null)); @@ -572,6 +596,9 @@ public class FactoryImpl implements HazelcastInstance { } public Object getOrCreateProxy(final ProxyKey proxyKey) { + if (proxyKey == null) { + throw new NullPointerException("Proxy key is required!"); + } initialChecks(); Object proxy = proxies.get(proxyKey); if (proxy == null) {
Fixes #<I>. Added null check before creating instance proxies.
hazelcast_hazelcast
train
7b84c93181eead84598b2b3e7a82bc68f39d84c6
diff --git a/jsreport.config.js b/jsreport.config.js index <HASH>..<HASH> 100644 --- a/jsreport.config.js +++ b/jsreport.config.js @@ -5,6 +5,9 @@ const chromeSchema = { strategy: { type: 'string', defaultNotInitialized: 'dedicated-process' }, numberOfWorkers: { type: 'number', defaultNotInitialized: '<The number of CPU cores in the machine>' }, timeout: { type: 'number' }, + puppeteerInstance: { + description: `Specifies a custom instance of puppeteer to use. you can pass here the export of require('puppeteer')` + }, launchOptions: { type: 'object', properties: { diff --git a/lib/chrome.js b/lib/chrome.js index <HASH>..<HASH> 100644 --- a/lib/chrome.js +++ b/lib/chrome.js @@ -7,7 +7,6 @@ const os = require('os') const url = require('url') const extend = require('node.extend.without.arrays') -const puppeteer = require('puppeteer') const dedicatedProcessStrategy = require('./dedicatedProcessStrategy') const chromePoolStrategy = require('./chromePoolStrategy') @@ -25,7 +24,7 @@ async function renderHeaderOrFooter (type, reporter, req, content) { return res.content.toString() } -function execute (reporter, definition, strategyCall, imageExecution) { +function execute (reporter, puppeteer, definition, strategyCall, imageExecution) { const strategy = definition.options.strategy return async (req, res) => { @@ -97,6 +96,8 @@ module.exports = function (reporter, definition) { definition.options = Object.assign({}, reporter.options.chrome, definition.options) + const puppeteer = definition.options.puppeteerInstance != null ? definition.options.puppeteerInstance : require('puppeteer') + if (definition.options.launchOptions == null) { definition.options.launchOptions = {} } @@ -142,12 +143,12 @@ module.exports = function (reporter, definition) { reporter.extensionsManager.recipes.push({ name: 'chrome-pdf', - execute: execute(reporter, definition, strategyCall) + execute: execute(reporter, puppeteer, definition, strategyCall) }) reporter.extensionsManager.recipes.push({ name: 'chrome-image', - execute: execute(reporter, definition, strategyCall, true) + execute: execute(reporter, puppeteer, definition, strategyCall, true) }) reporter.documentStore.registerComplexType('ChromeType', { diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,9 @@ "dependencies": { "node.extend.without.arrays": "1.1.6" }, + "peerDependencies": { + "puppeteer": "1.x.x" + }, "author": "Jan Blaha", "devDependencies": { "babel-eslint": "10.0.1",
move puppeteer to peer dep references jsreport/jsreport#<I>
jsreport_jsreport-chrome-pdf
train
052ba1dc79093723f77d8743229ed9a05f842d10
diff --git a/lib/factory.js b/lib/factory.js index <HASH>..<HASH> 100644 --- a/lib/factory.js +++ b/lib/factory.js @@ -10,7 +10,6 @@ 'use strict' var kindOf = require('kind-of') -var extend = require('extend-shallow') var isGenFn = require('is-es6-generator-function') var isPromise = require('is-promise') var asyncDone = require('async-done') @@ -27,6 +26,7 @@ module.exports = function factory (method) { throw new TypeError('benz: expect `fns` to be array, object or function') } if (kindOf(extensions) === 'object') { + var extend = require('extend-shallow') extensions = extend(this.option('extensions') || {}, extensions) } else { extensions = this.option('extensions')
require extend-shallow only if needed
hybridables_benz
train
9fd6668710ea31b89f392e344d92f861c6c77b7f
diff --git a/anythumbnailer/thumbnail_.py b/anythumbnailer/thumbnail_.py index <HASH>..<HASH> 100644 --- a/anythumbnailer/thumbnail_.py +++ b/anythumbnailer/thumbnail_.py @@ -34,7 +34,7 @@ class Thumbnailer(object): return False return True - def thumbnail(self, source_filename_or_fp, **kwargs): + def thumbnail(self, source_filename_or_fp, dimensions=None, **kwargs): raise NotImplementedError()
Thumbnailer.thumbnail() stub method must also accept "dimensions" as positional argument.
FelixSchwarz_anythumbnailer
train
f9001b97bb4fd75b6654009d93fae06f242a12bf
diff --git a/packages/next/taskfile-babel.js b/packages/next/taskfile-babel.js index <HASH>..<HASH> 100644 --- a/packages/next/taskfile-babel.js +++ b/packages/next/taskfile-babel.js @@ -52,15 +52,9 @@ const babelServerOpts = { { modules: 'commonjs', targets: { - node: '8.3', + node: '12.0', }, loose: true, - // This is handled by the Next.js webpack config that will run next/babel over the same code. - exclude: [ - 'transform-typeof-symbol', - 'transform-async-to-generator', - 'transform-spread', - ], }, ], ],
Bump babel target to Node.js <I> (#<I>) Next.js <I> supports Node.js <I> and newer. This PR updates babel to reflect this. Follow up to PR #<I>
zeit_next.js
train
cd2412fb3cd35a5e92e10e1c953b62bd1f77515c
diff --git a/code/control/Payment_Controller.php b/code/control/Payment_Controller.php index <HASH>..<HASH> 100755 --- a/code/control/Payment_Controller.php +++ b/code/control/Payment_Controller.php @@ -385,7 +385,16 @@ class Payment_Controller extends Controller { $order = Order::get() ->byID(Session::get("Checkout.OrderID")); - $cart = ShoppingCart::get(); + + // If an error with order, redirect back + if (!$order) { + $form->sessionMessage( + "Orders.ErrorCreatingOrder", + "Error creating order, please try again" + ); + + return $this->redirectBack(); + } // Map our order data to an array to omnipay $omnipay_data = []; @@ -403,7 +412,7 @@ class Payment_Controller extends Controller $payment = Payment::create() ->init( $this->getPaymentMethod(), - Checkout::round_up($cart->TotalCost, 2), + Checkout::round_up($order->Total->Value, 2), Checkout::config()->currency_code )->setSuccessUrl($this->Link('complete')) ->setFailureUrl(Controller::join_links( @@ -411,12 +420,8 @@ class Payment_Controller extends Controller "error" )); - // Map order ID - if ($order && $order->ID) { - $payment->OrderID = $order->ID; - } - - // Save it to the database to generate an ID + // Map order ID & save to generate an ID + $payment->OrderID = $order->ID; $payment->write(); // Add an extension before we finalise the payment
Use order total for payment submission and add error if order not set
silvercommerce_shoppingcart
train
171f4753bf2fdafb7c8b79daf396f758052da278
diff --git a/lib/cistern/attributes.rb b/lib/cistern/attributes.rb index <HASH>..<HASH> 100644 --- a/lib/cistern/attributes.rb +++ b/lib/cistern/attributes.rb @@ -8,7 +8,7 @@ module Cistern::Attributes boolean: ->(v, _) { TRUTHY.include?(v.to_s.downcase) }, float: ->(v, _) { v && v.to_f }, integer: ->(v, _) { v && v.to_i }, - string: ->(v, opts) { (opts[:allow_nil] && v.nil?) ? v : v.to_s }, + string: ->(v, _) { v && v.to_s }, time: ->(v, _) { v.is_a?(Time) ? v : v && Time.parse(v.to_s) }, } end diff --git a/spec/attributes_spec.rb b/spec/attributes_spec.rb index <HASH>..<HASH> 100644 --- a/spec/attributes_spec.rb +++ b/spec/attributes_spec.rb @@ -75,7 +75,7 @@ describe Cistern::Attributes, 'parsing' do it 'should parse string' do expect(TypeSpec.new(name: 1).name).to eq('1') expect(TypeSpec.new(name: "b").name).to eq('b') - expect(TypeSpec.new(name: nil).name).to eq("") + expect(TypeSpec.new(name: nil).name).to eq(nil) end it 'should allow nils in string types' do
fix(attributes): allow string types to be nil previous behavior was to convert all values #to_s (including nil). New behavior is to `allow_nil` by default. BREAKING CHANGE ? this will break installations that rely on the nil to emptry string conversions.
lanej_cistern
train
fc89c03b29ac45fb046a924d82c58a33f2fb3051
diff --git a/.travis.yml b/.travis.yml index <HASH>..<HASH> 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,7 @@ language: node_js node_js: +- '0.10' +- '0.12' - '4' - '5' - '6' diff --git a/bin/particle.js b/bin/particle.js index <HASH>..<HASH> 100755 --- a/bin/particle.js +++ b/bin/particle.js @@ -1,6 +1,7 @@ #!/usr/bin/env node /* eslint no-var: 0 */ global.verboseLevel = 1; +require('babel-polyfill'); var app = appForEnvironment(); app.default.run(process.argv); diff --git a/commands/CloudCommands.js b/commands/CloudCommands.js index <HASH>..<HASH> 100644 --- a/commands/CloudCommands.js +++ b/commands/CloudCommands.js @@ -679,7 +679,7 @@ CloudCommand.prototype = extend(BaseCommand.prototype, { //prompt for creds function () { if (password) { - return {username, password}; + return {username: username, password: password}; } return prompts.getCredentials(username, password); }, diff --git a/commands/HelpCommand.js b/commands/HelpCommand.js index <HASH>..<HASH> 100644 --- a/commands/HelpCommand.js +++ b/commands/HelpCommand.js @@ -114,7 +114,7 @@ HelpCommand.prototype = extend(BaseCommand.prototype, { return -1; } - const lines = this.commandText(name, subcmd, command); + var lines = this.commandText(name, subcmd, command); console.log(lines.join('\n')); }, diff --git a/oldlib/interpreter.js b/oldlib/interpreter.js index <HASH>..<HASH> 100644 --- a/oldlib/interpreter.js +++ b/oldlib/interpreter.js @@ -30,8 +30,6 @@ var fs = require('fs'); var path = require('path'); var when = require('when'); var settings = require('../settings.js'); -// I get Error: only one instance of babel-polyfill is allowed when adding this back -//require("babel-polyfill"); var Interpreter = function () { diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -86,7 +86,6 @@ "babel-plugin-add-module-exports": "^0.1.2", "babel-polyfill": "^6.9.1", "babel-preset-es2015": "^6.5.0", - "babel-preset-stage-3": "^6.11.0", "babel-register": "^6.5.2", "chai": "^3.5.0", "chai-as-promised": "^5.3.0", diff --git a/test/test-setup.js b/test/test-setup.js index <HASH>..<HASH> 100644 --- a/test/test-setup.js +++ b/test/test-setup.js @@ -1,7 +1,9 @@ // Set up the Mocha test framework with the Chai assertion library and // the testdouble library for mocks and stubs (previously Sinon mock library) -import 'babel-polyfill'; +if (!global._babelPolyfill) { + require('babel-polyfill'); +} import chai from 'chai'; import td from 'testdouble'; import tdChai from "testdouble-chai";
Add support back for node <I> and <I>
particle-iot_particle-cli
train
52b842dd29d5224010f2a8d52204c20d285019d0
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ BUG FIXES: + * consul/connect: Fixed a bug where gateway proxy connection default timeout not set [[GH-9851](https://github.com/hashicorp/nomad/pull/9851)] * scheduler: Fixed a bug where shared ports were not persisted during inplace updates for service jobs. [[GH-9830](https://github.com/hashicorp/nomad/issues/9830)] ## 1.0.2 (January 14, 2020) diff --git a/api/services.go b/api/services.go index <HASH>..<HASH> 100644 --- a/api/services.go +++ b/api/services.go @@ -335,6 +335,8 @@ type ConsulGatewayBindAddress struct { } var ( + // defaultConnectTimeout is the default amount of time a connect gateway will + // wait for a response from an upstream service (same as consul) defaultGatewayConnectTimeout = 5 * time.Second ) diff --git a/nomad/job_endpoint_hook_connect.go b/nomad/job_endpoint_hook_connect.go index <HASH>..<HASH> 100644 --- a/nomad/job_endpoint_hook_connect.go +++ b/nomad/job_endpoint_hook_connect.go @@ -12,6 +12,12 @@ import ( "github.com/pkg/errors" ) +const ( + // defaultConnectTimeout is the default amount of time a connect gateway will + // wait for a response from an upstream service (same as consul) + defaultConnectTimeout = 5 * time.Second +) + var ( // connectSidecarResources returns the set of resources used by default for // the Consul Connect sidecar task @@ -324,6 +330,11 @@ func gatewayProxyForBridge(gateway *structs.ConsulGateway) *structs.ConsulGatewa proxy.Config = gateway.Proxy.Config } + // set default connect timeout if not set + if proxy.ConnectTimeout == nil { + proxy.ConnectTimeout = helper.TimeToPtr(defaultConnectTimeout) + } + // magically set the fields where Nomad knows what to do proxy.EnvoyGatewayNoDefaultBind = true proxy.EnvoyGatewayBindTaggedAddresses = false diff --git a/nomad/job_endpoint_hook_connect_test.go b/nomad/job_endpoint_hook_connect_test.go index <HASH>..<HASH> 100644 --- a/nomad/job_endpoint_hook_connect_test.go +++ b/nomad/job_endpoint_hook_connect_test.go @@ -492,6 +492,7 @@ func TestJobEndpointConnect_gatewayProxyForBridge(t *testing.T) { }, }) require.Equal(t, &structs.ConsulGatewayProxy{ + ConnectTimeout: helper.TimeToPtr(defaultConnectTimeout), EnvoyGatewayNoDefaultBind: true, EnvoyGatewayBindTaggedAddresses: false, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ diff --git a/vendor/github.com/hashicorp/nomad/api/services.go b/vendor/github.com/hashicorp/nomad/api/services.go index <HASH>..<HASH> 100644 --- a/vendor/github.com/hashicorp/nomad/api/services.go +++ b/vendor/github.com/hashicorp/nomad/api/services.go @@ -335,6 +335,8 @@ type ConsulGatewayBindAddress struct { } var ( + // defaultConnectTimeout is the default amount of time a connect gateway will + // wait for a response from an upstream service (same as consul) defaultGatewayConnectTimeout = 5 * time.Second )
consul/connect: always set gateway proxy default timeout If the connect.proxy stanza is left unset, the connection timeout value is not set but is assumed to be, and may cause a non-fatal NPE on job submission.
hashicorp_nomad
train
ef1ce427cbd2e937d95573f15a6191eb6bb15d89
diff --git a/feedback.go b/feedback.go index <HASH>..<HASH> 100644 --- a/feedback.go +++ b/feedback.go @@ -3,6 +3,7 @@ package apns import ( "bytes" "encoding/binary" + "encoding/hex" "time" ) @@ -17,17 +18,22 @@ type FeedbackTuple struct { } func feedbackTupleFromBytes(b []byte) FeedbackTuple { - var ts uint32 - var tokLen uint16 - tok := make([]byte, 32) - r := bytes.NewReader(b) + var ts uint32 binary.Read(r, binary.BigEndian, &ts) + + var tokLen uint16 binary.Read(r, binary.BigEndian, &tokLen) + + tok := make([]byte, tokLen) binary.Read(r, binary.BigEndian, &tok) - return FeedbackTuple{Timestamp: time.Unix(int64(ts), 0), TokenLength: tokLen, DeviceToken: string(tok)} + return FeedbackTuple{ + Timestamp: time.Unix(int64(ts), 0), + TokenLength: tokLen, + DeviceToken: hex.EncodeToString(tok), + } } func NewFeedback(gw string, cert string, key string) (Feedback, error) {
Fix bug where feedback token was being returned as invalid string
timehop_apns
train
15282d1f9957ccb8f53a9e4b1948aabca999414b
diff --git a/mandrill_templates.go b/mandrill_templates.go index <HASH>..<HASH> 100644 --- a/mandrill_templates.go +++ b/mandrill_templates.go @@ -141,6 +141,8 @@ type Template struct { Code string `json:"code"` PublishName string `json:"publish_name"` PublishCode string `json:"publish_code"` + Slug string `json:"slug"` + Subject string `json:"subject"` CreatedAt APITime `json:"published_at"` UpdateAt APITime `json:"updated_at"` }
add slug and subject to mandrill templates
mattbaird_gochimp
train
bc9ed57e24f2dbf78e8d50338ed6fb0732862291
diff --git a/src/test/org/openscience/cdk/modeling/forcefield/ForceFieldTests.java b/src/test/org/openscience/cdk/modeling/forcefield/ForceFieldTests.java index <HASH>..<HASH> 100644 --- a/src/test/org/openscience/cdk/modeling/forcefield/ForceFieldTests.java +++ b/src/test/org/openscience/cdk/modeling/forcefield/ForceFieldTests.java @@ -20,6 +20,7 @@ */ package org.openscience.cdk.modeling.forcefield; +import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.util.Map; @@ -1026,11 +1027,12 @@ public class ForceFieldTests extends CDKTestCase { molecule = forceField.getMolecule(); //logger.debug("Molecule: ", molecule); - FileWriter fileWriter = new FileWriter("./" + input + "-output.mol"); - //stringWriter.write(input + "-output.mol"); - MDLWriter mdlWriter = new MDLWriter(fileWriter); - mdlWriter.write(molecule); - mdlWriter.close(); +// File output = File.createTempFile(input + "-output", "mol"); +// FileWriter fileWriter = new FileWriter(output); +// //stringWriter.write(input + "-output.mol"); +// MDLWriter mdlWriter = new MDLWriter(fileWriter); +// mdlWriter.write(molecule); +// mdlWriter.close(); Assert.assertEquals(34.01, forceField.getMinimumFunctionValueCGM(), 0.01); @@ -1116,12 +1118,12 @@ public class ForceFieldTests extends CDKTestCase { molecule = forceField.getMolecule(); //logger.debug("Molecule: ", molecule); - // Please don't write a file in the test cases. - FileWriter fileWriter = new FileWriter("./" + input + "-output.mol"); - //stringWriter.write(input + "-output.mol"); - MDLWriter mdlWriter = new MDLWriter(fileWriter); - mdlWriter.write(molecule); - mdlWriter.close(); +// File output = File.createTempFile(input + "-output", "mol"); +// FileWriter fileWriter = new FileWriter(output); +// //stringWriter.write(input + "-output.mol"); +// MDLWriter mdlWriter = new MDLWriter(fileWriter); +// mdlWriter.write(molecule); +// mdlWriter.close(); Assert.assertEquals(734.17, forceField.getMinimumFunctionValueCGM(), 0.01); @@ -1248,12 +1250,12 @@ public class ForceFieldTests extends CDKTestCase { molecule = forceField.getMolecule(); //logger.debug("Molecule: ", molecule); - // Please don't write a file in the test cases. - FileWriter fileWriter = new FileWriter("./" + input + "-output.mol"); - //stringWriter.write(input + "-output.mol"); - MDLWriter mdlWriter = new MDLWriter(fileWriter); - mdlWriter.write(molecule); - mdlWriter.close(); +// File output = File.createTempFile(input + "-output", "mol"); +// FileWriter fileWriter = new FileWriter(output); +// //stringWriter.write(input + "-output.mol"); +// MDLWriter mdlWriter = new MDLWriter(fileWriter); +// mdlWriter.write(molecule); +// mdlWriter.close(); Assert.assertEquals(33.32029777, forceField.getMinimumFunctionValueCGM(), 0.00001);
Force field unit tests no longer write output to disk. That was originally used for manual inspection, but commented out for now (closes #<I>) git-svn-id: <URL>
cdk_cdk
train
b001a4c9a0d3bd931829c53248b53ae35cf54e96
diff --git a/__init__.py b/__init__.py index <HASH>..<HASH> 100644 --- a/__init__.py +++ b/__init__.py @@ -52,12 +52,6 @@ except ImportError, why: __all__ = ['add_site_dir', 'patch'] -try: - environ_apply_diff() -except ImportError, why: - warnings.warn('Error while running sitecustomize.environ.apply_diff: %r' % why) - - # Where do we want to start inserting directories into sys.path? Just before # this module, of course. So determine where we were imported from. our_sys_path = os.path.abspath(os.path.join(__file__, @@ -65,6 +59,7 @@ our_sys_path = os.path.abspath(os.path.join(__file__, os.path.pardir, )) + # Setup the pseudo site-packages. sites = [x.strip() for x in os.environ.get('KS_PYTHON_SITES', '').split(':') if x] sites.append(our_sys_path) @@ -75,6 +70,13 @@ for site in sites: warnings.warn('Error while adding site-package %r: %r' % (site, why)) +# Restore frozen environment variables. +try: + environ_apply_diff() +except ImportError, why: + warnings.warn('Error while running sitecustomize.environ.apply_diff: %r' % why) + + # Monkey-patch chflags for Python2.6 since our NFS does not support it and # Python2.6 does not ignore that lack of support. # See: http://hg.python.org/cpython/rev/e12efebc3ba6/ diff --git a/environ.py b/environ.py index <HASH>..<HASH> 100644 --- a/environ.py +++ b/environ.py @@ -48,11 +48,12 @@ def freeze(environ, names): environ[VARIABLE_NAME] = _dumps(diff) def apply_diff(): + verbose('# %s.apply_diff()', __name__) blob = os.environ.pop(VARIABLE_NAME, None) diff = _loads(blob) if blob else {} for k, v in diff.iteritems(): - verbose('# %s.apply_diff(...): %r -> %r', __name__, k, v) + verbose('# %s.apply_diff(): %r -> %r', __name__, k, v) if v is None: os.environ.pop(k, None)
Apply environ diff after setting up sys.path Maya and its children can all find Qt.
mikeboers_sitetools
train
379bf2b4ec3402bb7e99d7839cd961e06f789d11
diff --git a/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/DisparityDisplayPanel.java b/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/DisparityDisplayPanel.java index <HASH>..<HASH> 100644 --- a/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/DisparityDisplayPanel.java +++ b/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/DisparityDisplayPanel.java @@ -152,15 +152,15 @@ public class DisparityDisplayPanel extends StandardAlgConfigPanel texture = ((Number) textureSpinner.getValue()).doubleValue(); } else if( e.getSource() == sliderPeriodColor ) { periodAdjust = sliderPeriodColor.getValue(); - listener.disparityRender(); + listener.changeView3D(); return; } else if( e.getSource() == sliderOffsetColor ) { offsetAdjust = sliderOffsetColor.getValue(); - listener.disparityRender(); + listener.changeView3D(); return; } else if( e.getSource() == sliderSpeed3D) { speedAdjust = sliderSpeed3D.getValue(); - listener.changeSpeed3D(); + listener.changeView3D(); return; } @@ -182,7 +182,7 @@ public class DisparityDisplayPanel extends StandardAlgConfigPanel listener.disparityGuiChange(); } else if( e.getSource() == comboColorizer) { colorScheme = comboColorizer.getSelectedIndex(); - listener.disparityGuiChange(); + listener.changeView3D(); } else if( e.getSource() == invalidToggle) { colorInvalid = invalidToggle.isSelected(); listener.disparityRender(); @@ -247,6 +247,6 @@ public class DisparityDisplayPanel extends StandardAlgConfigPanel void disparityGuiChange(); void disparityRender(); void changeInputScale(); - void changeSpeed3D(); + void changeView3D(); } } diff --git a/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/VisualizeStereoDisparity.java b/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/VisualizeStereoDisparity.java index <HASH>..<HASH> 100644 --- a/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/VisualizeStereoDisparity.java +++ b/demonstrations/src/main/java/boofcv/demonstrations/feature/disparity/VisualizeStereoDisparity.java @@ -179,11 +179,12 @@ public class VisualizeStereoDisparity <T extends ImageGray<T>, D extends ImageGr gui.setPreferredSize(new Dimension(origLeft.getWidth(), origLeft.getHeight())); comp = gui; } else { - double baseline = calib.getRightToLeft().getT().norm(); + if( !computedCloud ) { computedCloud = true; DisparityToColorPointCloud d2c = new DisparityToColorPointCloud(); + double baseline = calib.getRightToLeft().getT().norm(); d2c.configure(baseline, rectK,rectR, leftRectToPixel, control.minDisparity,control.maxDisparity); d2c.process(activeAlg.getDisparity(),colorLeft); @@ -192,23 +193,7 @@ public class VisualizeStereoDisparity <T extends ImageGray<T>, D extends ImageGr pcv.clearPoints(); pcv.setCameraHFov(PerspectiveOps.computeHFov(rectifiedPinhole)); pcv.addCloud(d2c.getCloud(),d2c.getCloudColor()); - changeSpeed3D(); - } - double periodColor = baseline*5*control.periodScale(); - PeriodicColorizer colorizer=null; - switch( control.colorScheme ) { - case 0: pcv.removeColorizer();break; - case 1: colorizer = new RainbowColorSingleAxis.X(); break; - case 2: colorizer = new RainbowColorSingleAxis.Y(); break; - case 3: colorizer = new RainbowColorSingleAxis.Z(); break; - case 4: colorizer = new RainbowColorAxisPlane.X_YZ(4.0); break; - case 5: colorizer = new RainbowColorAxisPlane.Y_XZ(4.0); break; - case 6: colorizer = new RainbowColorAxisPlane.Z_XY(4.0); break; - } - if( colorizer != null ) { - colorizer.setPeriod(periodColor); - colorizer.setOffset(control.offsetScale()); - pcv.setColorizer(colorizer); + changeView3D(); } comp = pcv.getComponent(); comp.requestFocusInWindow(); @@ -432,9 +417,27 @@ public class VisualizeStereoDisparity <T extends ImageGray<T>, D extends ImageGr } @Override - public void changeSpeed3D() { + public void changeView3D() { double baseline = calib.getRightToLeft().getT().norm(); + double periodColor = baseline*5*control.periodScale(); + PeriodicColorizer colorizer=null; + switch( control.colorScheme ) { + case 0: pcv.removeColorizer();break; + case 1: colorizer = new RainbowColorSingleAxis.X(); break; + case 2: colorizer = new RainbowColorSingleAxis.Y(); break; + case 3: colorizer = new RainbowColorSingleAxis.Z(); break; + case 4: colorizer = new RainbowColorAxisPlane.X_YZ(4.0); break; + case 5: colorizer = new RainbowColorAxisPlane.Y_XZ(4.0); break; + case 6: colorizer = new RainbowColorAxisPlane.Z_XY(4.0); break; + } + if( colorizer != null ) { + colorizer.setPeriod(periodColor); + colorizer.setOffset(control.offsetScale()); + pcv.setColorizer(colorizer); + } + pcv.setTranslationStep(control.speedScale()*baseline/30); + pcv.getComponent().repaint(); } /**
- fixed pointless rebuilding of Swing that resulted in File flashing when 3D stuff was modified
lessthanoptimal_BoofCV
train
2cd486d5c54201b3dec3958c9a76085ff6918d44
diff --git a/examples/main.py b/examples/main.py index <HASH>..<HASH> 100644 --- a/examples/main.py +++ b/examples/main.py @@ -19,6 +19,8 @@ source = ''' This is another line of the content. %p.warning This is a warning. + %< + This should not have whitespace. #footer &copy; The author, today. diff --git a/paml/codegen.py b/paml/codegen.py index <HASH>..<HASH> 100644 --- a/paml/codegen.py +++ b/paml/codegen.py @@ -17,6 +17,9 @@ class _GeneratorSentinal(object): self.__dict__.update(**kwargs) +class OuterCommand(str): + pass + class BaseGenerator(object): @@ -24,7 +27,7 @@ class BaseGenerator(object): dec_depth = _GeneratorSentinal(delta=-1) _increment_tokens = (inc_depth, dec_depth) - assert_newline = _GeneratorSentinal() + assert_newline = OuterCommand('assert_newline') no_whitespace = _GeneratorSentinal( indent_str = '', @@ -36,6 +39,8 @@ class BaseGenerator(object): pop_whitespace = _GeneratorSentinal() + lstrip = OuterCommand('lstrip') + rstrip = OuterCommand('rstrip') def __init__(self): self.whitespace_stack = [self.default_whitespace] @@ -49,9 +54,35 @@ class BaseGenerator(object): def generate_iter(self, node): generator = self._generate_string_tokens(node) buffer = [] + r_stripping = False try: while True: - yield next(generator) + x = next(generator) + if isinstance(x, OuterCommand): + if x == self.assert_newline: + if buffer and not buffer[-1].endswith('\n'): + buffer.append('\n') + elif x == self.lstrip: + print 'len', len(buffer) + for i in xrange(len(buffer) - 1, -1, -1): + print i, repr(buffer[i]) + buffer[i] = buffer[i].rstrip() + if buffer[i]: + for z in buffer: + yield z + buffer = [] + break + elif x == self.rstrip: + r_stripping = True + else: + raise ValueError('unexpected OuterCommand %r' % x) + else: + if r_stripping: + x = x.lstrip() + if x: + r_stripping = False + if x: + buffer.append(x) except StopIteration: for x in buffer: yield x @@ -67,9 +98,6 @@ class BaseGenerator(object): self.whitespace_stack.append(token) elif token is self.pop_whitespace: self.whitespace_stack.pop() - elif token is self.assert_newline: - if result and result[-1][-1] != '\n': - yield '\n' elif isinstance(token, basestring): if token: yield token diff --git a/paml/nodes.py b/paml/nodes.py index <HASH>..<HASH> 100644 --- a/paml/nodes.py +++ b/paml/nodes.py @@ -89,14 +89,18 @@ class Tag(Base): else: attr_str = '<%% __M_writer(__P_attrs(%r, %s)) %%>' % (const_attrs, self.kwargs_expr) + yield engine.indent() + if self.strip_outer: + yield engine.lstrip + if self.self_closing or self.name in self.self_closing_names: - yield engine.indent() yield '<%s%s />' % (self.name, attr_str) yield engine.endl else: - yield engine.indent() yield '<%s%s>' % (self.name, attr_str) if self.children: + if self.strip_inner: + yield engine.rstrip yield engine.endl yield engine.inc_depth @@ -111,7 +115,11 @@ class Tag(Base): if self.children: yield engine.dec_depth yield engine.indent() + if self.strip_inner: + yield engine.lstrip yield '</%s>' % self.name + if self.strip_outer: + yield engine.rstrip yield engine.endl def __repr__(self): diff --git a/paml/parse.py b/paml/parse.py index <HASH>..<HASH> 100644 --- a/paml/parse.py +++ b/paml/parse.py @@ -99,11 +99,11 @@ class Parser(object): line = line # Whitespace striping - m2 = re.match(r'[<>]+', line) + m2 = re.match(r'([<>]+)', line) strip_outer = strip_inner = False if m2: - strip_outer = '>' in m2.group(0) - strip_inner = '>' in m2.group(0) + strip_outer = '>' in m2.group(1) + strip_inner = '<' in m2.group(1) line = line[m2.end():] # Self closing tags
WIP: almost have whitespace control working.
mikeboers_PyHAML
train
d58e02136cd5d05ce45d4654dee028755e5ef1f5
diff --git a/src/org/openscience/cdk/applications/jchempaint/JChemPaintPanel.java b/src/org/openscience/cdk/applications/jchempaint/JChemPaintPanel.java index <HASH>..<HASH> 100755 --- a/src/org/openscience/cdk/applications/jchempaint/JChemPaintPanel.java +++ b/src/org/openscience/cdk/applications/jchempaint/JChemPaintPanel.java @@ -734,6 +734,14 @@ public abstract class JChemPaintPanel *@param chemModel The cheModel of the structure to be scaled and centered. */ public void scaleAndCenterMolecule(ChemModel chemModel) { + scaleAndCenterMolecule(chemModel, null); + } + /** + * Scales and centers the structure in the dimensions of the DrawingPanel. + * + *@param chemModel The cheModel of the structure to be scaled and centered. + */ + public void scaleAndCenterMolecule(ChemModel chemModel, Dimension dim) { JChemPaintModel jcpm = getJChemPaintModel(); Renderer2DModel rendererModel = jcpm.getRendererModel(); AtomContainer ac = ChemModelManipulator.getAllInOneContainer(chemModel); @@ -753,12 +761,18 @@ public abstract class JChemPaintPanel relocatedX=0; relocatedY=0; } else { - if(viewablePart.getWidth()==0 && viewablePart.getHeight()==0){ - relocatedX=0; - relocatedY=0; - GeometryTools.center(ac, model.getBackgroundDimension()); + if(dim==null){ + if(viewablePart.getWidth()==0 && viewablePart.getHeight()==0){ + relocatedX=0; + relocatedY=0; + GeometryTools.center(ac, model.getBackgroundDimension()); + }else{ + GeometryTools.center(ac, viewablePart); + } }else{ - GeometryTools.center(ac, viewablePart); + relocatedY = model.getBackgroundDimension().getSize().getHeight() - (dim.getHeight()); + relocatedX = 0; + GeometryTools.center(ac, dim); } } //fixing the coords regarding the position of the viewablePart diff --git a/src/org/openscience/cdk/applications/jchempaint/applet/JChemPaintAbstractApplet.java b/src/org/openscience/cdk/applications/jchempaint/applet/JChemPaintAbstractApplet.java index <HASH>..<HASH> 100644 --- a/src/org/openscience/cdk/applications/jchempaint/applet/JChemPaintAbstractApplet.java +++ b/src/org/openscience/cdk/applications/jchempaint/applet/JChemPaintAbstractApplet.java @@ -116,9 +116,7 @@ public abstract class JChemPaintAbstractApplet extends JApplet { public void initPanelAndModel(JChemPaintPanel jcpp) { getContentPane().removeAll(); getContentPane().setLayout(new BorderLayout()); - if(theJcpp.getJChemPaintModel()!=null) - jcpp.scaleAndCenterMolecule(theModel.getChemModel()); - theModel.setTitle("JCP Applet" /* getNewFrameName() */); + theModel.setTitle("JCP Applet" /* getNewFrameName() */); theModel.setAuthor(JCPPropertyHandler.getInstance().getJCPProperties().getProperty("General.UserName")); // Package self = Package.getPackage("org.openscience.cdk.applications.jchempaint"); // String version = self.getImplementationVersion(); @@ -127,7 +125,9 @@ public abstract class JChemPaintAbstractApplet extends JApplet { theModel.setGendate((Calendar.getInstance()).getTime().toString()); jcpp.setJChemPaintModel(theModel); jcpp.registerModel(theModel); - + if(theJcpp.getJChemPaintModel()!=null) + jcpp.scaleAndCenterMolecule(theModel.getChemModel(),new Dimension((int)this.getSize().getWidth()-100,(int)this.getSize().getHeight()-100)); + //embedded means that additional instances can't be created, which is // needed for applet as well jcpp.setEmbedded();
when loading a structure in editor applet at startup it centered in viewable part git-svn-id: <URL>
cdk_cdk
train
d811bd84b4e9ed99455a2dc6267ea57398759300
diff --git a/files/externallib.php b/files/externallib.php index <HASH>..<HASH> 100755 --- a/files/externallib.php +++ b/files/externallib.php @@ -100,7 +100,6 @@ throw new coding_exception('File browsing api function is not implemented yet, s $params = $child->get_params(); if ($child->is_directory()) { $node = array( - //TODO: this is wrong, you need to fetch info from the child node!!!! 'contextid' => $params['contextid'], 'component' => $params['component'], 'filearea' => $params['filearea'], @@ -113,7 +112,6 @@ throw new coding_exception('File browsing api function is not implemented yet, s $list[] = $node; } else { $node = array( - //TODO: this is wrong, you need to fetch info from the child node!!!! 'contextid' => $params['contextid'], 'component' => $params['component'], 'filearea' => $params['filearea'],
fixed incorrect comments, thanks Dongsheng
moodle_moodle
train
fc56c154479699652923ee1f9a064055365210bd
diff --git a/lib/wfc3Data.py b/lib/wfc3Data.py index <HASH>..<HASH> 100644 --- a/lib/wfc3Data.py +++ b/lib/wfc3Data.py @@ -195,16 +195,20 @@ class WFC3IRInputImage(WFC3InputImage): for chip in self.returnAllChips(extname=self.scienceExt): chip._effGain = 1. - # Multiply the values of the sci extension pixels by the gain. - print "Converting %s[%s,%d] from ELECTRONS/S to ELECTRONS"%(self._filename,self.scienceExt,chip._chip) - # Set the BUNIT keyword to 'electrons' - chip._bunit = 'ELECTRONS' - chip.header.update('BUNIT','ELECTRONS') - _handle[self.scienceExt,chip._chip].header.update('BUNIT','ELECTRONS') - - # If the exptime is 0 the science image will be zeroed out. - np.multiply(_handle[self.scienceExt,chip._chip].data,chip._exptime,_handle[self.scienceExt,chip._chip].data) - chip.data=_handle[self.scienceExt,chip._chip].data + if '/S' in chip._bunit: + # Multiply the values of the sci extension pixels by the gain. + print "Converting %s[%s,%d] from ELECTRONS/S to ELECTRONS"%(self._filename,self.scienceExt,chip._chip) + # Set the BUNIT keyword to 'electrons' + chip._bunit = 'ELECTRONS' + chip.header.update('BUNIT','ELECTRONS') + _handle[self.scienceExt,chip._chip].header.update('BUNIT','ELECTRONS') + + # If the exptime is 0 the science image will be zeroed out. + np.multiply(_handle[self.scienceExt,chip._chip].data,chip._exptime,_handle[self.scienceExt,chip._chip].data) + chip.data=_handle[self.scienceExt,chip._chip].data + else: + print "Input %s[%s,%d] already in units of ELECTRONS"%(self._filename,self.scienceExt,chip._chip) + _handle.close()
Logic was added to the wfc3Data module in betadrizzle to only convert IR data to units of electrons iff input units were electrons/s already. This will prevent the data from being scaled mutiple times by the exptime should the data be processed repeatedly by betadrizzle when 'workinplace' is set to True(yes). git-svn-id: <URL>
spacetelescope_drizzlepac
train
93a765178f2ff5c4e5db320641253098c6388c71
diff --git a/galpy/util/bovy_plot.py b/galpy/util/bovy_plot.py index <HASH>..<HASH> 100644 --- a/galpy/util/bovy_plot.py +++ b/galpy/util/bovy_plot.py @@ -871,8 +871,8 @@ def scatterplot(x,y,*args,**kwargs): for ii in range(len(plotx)): bovy_plot(plotx[ii],ploty[ii],overplot=True, color='%.2f'%(1.-w8[ii]),*args,**kwargs) - else: - bovy_plot(plotx,ploty,overplot=True,*args,**kwargs) + else: + bovy_plot(plotx,ploty,overplot=True,*args,**kwargs) #Add onedhists if not onedhists: return
fix outlier plotting in scatterplot
jobovy_galpy
train
4fcf8608c994fa721cee388fd4c0607b6791df26
diff --git a/lib/spaceship/certificate.rb b/lib/spaceship/certificate.rb index <HASH>..<HASH> 100644 --- a/lib/spaceship/certificate.rb +++ b/lib/spaceship/certificate.rb @@ -235,6 +235,9 @@ module Spaceship app_id = app.app_id end + # ensure csr is a OpenSSL::X509::Request + csr = OpenSSL::X509::Request.new(csr) if csr.is_a?(String) + # if this succeeds, we need to save the .cer and the private key in keychain access or wherever they go in linux response = client.create_certificate!(type, csr.to_pem, app_id) # munge the response to make it work for the factory diff --git a/spec/certificate_spec.rb b/spec/certificate_spec.rb index <HASH>..<HASH> 100644 --- a/spec/certificate_spec.rb +++ b/spec/certificate_spec.rb @@ -77,13 +77,28 @@ describe Spaceship::Certificate do expect(client).to receive(:create_certificate!).with('3BQKVH9I2X', /BEGIN CERTIFICATE REQUEST/, 'B7JBD8LHAA') { JSON.parse(read_fixture_file('certificateCreate.certRequest.json')) } - certificate = Spaceship::Certificate::ProductionPush.create!(csr: Spaceship::Certificate.create_certificate_signing_request.first, bundle_id: 'net.sunapps.151') + csr, pkey = Spaceship::Certificate.create_certificate_signing_request + certificate = Spaceship::Certificate::ProductionPush.create!(csr: csr, bundle_id: 'net.sunapps.151') expect(certificate).to be_instance_of(Spaceship::Certificate::ProductionPush) end + it 'should create a new certificate using a CSR from a file' do + expect(client).to receive(:create_certificate!).with('3BQKVH9I2X', /BEGIN CERTIFICATE REQUEST/, 'B7JBD8LHAA') { + JSON.parse(read_fixture_file('certificateCreate.certRequest.json')) + } + csr, pkey = Spaceship::Certificate.create_certificate_signing_request + Tempfile.open('csr') do |f| + f.write(csr.to_pem) + f.rewind + pem = f.read + Spaceship::Certificate::ProductionPush.create!(csr: pem, bundle_id: 'net.sunapps.151') + end + end + it 'raises an error if the user wants to create a certificate for a non-existing app' do expect { - Spaceship::Certificate::ProductionPush.create!(csr: Spaceship::Certificate.create_certificate_signing_request.first, bundle_id: 'notExisting') + csr, pkey = Spaceship::Certificate.create_certificate_signing_request + Spaceship::Certificate::ProductionPush.create!(csr: csr, bundle_id: 'notExisting') }.to raise_error "Could not find app with bundle id 'notExisting'" end end
fixes issue #<I> - passing a CSR from a file as a String
fastlane_fastlane
train
f2ebc8d8bb281ceab3080652a96cef940447d73c
diff --git a/testproject/tests/tests/files.py b/testproject/tests/tests/files.py index <HASH>..<HASH> 100644 --- a/testproject/tests/tests/files.py +++ b/testproject/tests/tests/files.py @@ -1,7 +1,5 @@ import os -from django.core.files.storage import default_storage from django.test.testcases import TestCase -from django.test.utils import override_settings from djet import files @@ -19,21 +17,21 @@ class InMemoryFilesTestCase(TestCase): self.assertEqual(file.name, 'test.jpg') -@override_settings(DEFAULT_FILE_STORAGE='djet.files.InMemoryStorage') class InMemoryStorageTestCase(TestCase): def setUp(self): + self.storage = files.InMemoryStorage() self.file_name = 'test.txt' self.file = files.make_inmemory_file(self.file_name, 'Avada Kedavra') - default_storage.save(self.file_name, self.file) + self.storage.save(self.file_name, self.file) def test_file_should_not_be_saved_on_disk_when_saved(self): self.assertFalse(os.path.exists(self.file_name)) def test_file_should_exist_when_saved(self): - self.assertTrue(default_storage.exists(self.file_name)) + self.assertTrue(self.storage.exists(self.file_name)) def test_file_should_be_the_same_when_opened(self): - uploaded_file = default_storage.open(self.file_name) + uploaded_file = self.storage.open(self.file_name) self.assertEqual(uploaded_file, self.file)
Changed tests to work on older DJango versions.
sunscrapers_djet
train
4bdcd60e12457d52b9a9fae41a96f1be416dde29
diff --git a/activiti-webapp-rest/src/main/java/org/activiti/rest/api/process/ProcessInstancePost.java b/activiti-webapp-rest/src/main/java/org/activiti/rest/api/process/ProcessInstancePost.java index <HASH>..<HASH> 100644 --- a/activiti-webapp-rest/src/main/java/org/activiti/rest/api/process/ProcessInstancePost.java +++ b/activiti-webapp-rest/src/main/java/org/activiti/rest/api/process/ProcessInstancePost.java @@ -46,7 +46,7 @@ public class ProcessInstancePost extends ActivitiWebScript { variables.remove("processDefinitionId"); variables.remove("businessKey"); - model.put("processInstance", getRuntimeService().startProcessInstanceByKey(processDefinitionId, businessKey, variables)); + model.put("processInstance", getRuntimeService().startProcessInstanceById(processDefinitionId, businessKey, variables)); } }
changing ProcessInstancePost webscript from startProcessInstanceByKey back to startProcessInstanceById
camunda_camunda-bpm-platform
train
13a27a185665d8608a9f9344f93678f5361ae5e2
diff --git a/lib/sass/script/literal.rb b/lib/sass/script/literal.rb index <HASH>..<HASH> 100644 --- a/lib/sass/script/literal.rb +++ b/lib/sass/script/literal.rb @@ -1,80 +1,82 @@ -class Sass::Script::Literal # :nodoc: - require 'sass/script/string' - require 'sass/script/number' - require 'sass/script/color' - require 'sass/script/bool' - - attr_reader :value - - def initialize(value = nil) - @value = value - end - - def perform(environment) - self - end - - def and(other) - to_bool ? other : self - end - - def or(other) - to_bool ? self : other - end - - def eq(other) - Sass::Script::Bool.new(self.class == other.class && self.value == other.value) - end - - def neq(other) - Sass::Script::Bool.new(!eq(other).to_bool) - end - - def unary_not - Sass::Script::Bool.new(!to_bool) - end - - def concat(other) - Sass::Script::String.new("#{self.to_s} #{other.to_s}") - end - - def comma(other) - Sass::Script::String.new("#{self.to_s}, #{other.to_s}") - end - - def plus(other) - Sass::Script::String.new(self.to_s + other.to_s) - end - - def minus(other) - Sass::Script::String.new("#{self.to_s}-#{other.to_s}") - end - - def div(other) - Sass::Script::String.new("#{self.to_s}/#{other.to_s}") - end - - def unary_minus - Sass::Script::String.new("-#{self.to_s}") - end - - def unary_div - Sass::Script::String.new("/#{self.to_s}") - end - - def inspect - value.inspect - end - - def to_bool - true - end - - def ==(other) - eq(other).to_bool - end - - def to_i - raise Sass::SyntaxError.new("#{self.inspect} is not an integer.") +module Sass::Script + class Literal # :nodoc: + require 'sass/script/string' + require 'sass/script/number' + require 'sass/script/color' + require 'sass/script/bool' + + attr_reader :value + + def initialize(value = nil) + @value = value + end + + def perform(environment) + self + end + + def and(other) + to_bool ? other : self + end + + def or(other) + to_bool ? self : other + end + + def eq(other) + Sass::Script::Bool.new(self.class == other.class && self.value == other.value) + end + + def neq(other) + Sass::Script::Bool.new(!eq(other).to_bool) + end + + def unary_not + Sass::Script::Bool.new(!to_bool) + end + + def concat(other) + Sass::Script::String.new("#{self.to_s} #{other.to_s}") + end + + def comma(other) + Sass::Script::String.new("#{self.to_s}, #{other.to_s}") + end + + def plus(other) + Sass::Script::String.new(self.to_s + other.to_s) + end + + def minus(other) + Sass::Script::String.new("#{self.to_s}-#{other.to_s}") + end + + def div(other) + Sass::Script::String.new("#{self.to_s}/#{other.to_s}") + end + + def unary_minus + Sass::Script::String.new("-#{self.to_s}") + end + + def unary_div + Sass::Script::String.new("/#{self.to_s}") + end + + def inspect + value.inspect + end + + def to_bool + true + end + + def ==(other) + eq(other).to_bool + end + + def to_i + raise Sass::SyntaxError.new("#{self.inspect} is not an integer.") + end end end
[Sass] Format Sass::Script::Literal like other similar classes.
sass_ruby-sass
train
6cca55dc175722d2ea62cb3aa80dd50806397472
diff --git a/angel/test/test.py b/angel/test/test.py index <HASH>..<HASH> 100644 --- a/angel/test/test.py +++ b/angel/test/test.py @@ -300,19 +300,6 @@ class AngelListTestCase(unittest.TestCase): t_ = s_['startup_roles'][0] self.assertEqual(e, sorted(list(t_.iterkeys()))) - def test_startup_roles_deprecated(self, id_=2674): - expected_keys = sorted(['per_page', 'last_page', 'total', 'startup_roles', 'page']) - directions = ['incoming', 'outgoing'] - for direction in directions: - r_ = angel.get_startup_roles_deprecated(id_, direction=direction) - self.assertEqual(type(r_), dict) - self.assertEqual(expected_keys, sorted(list(r_.iterkeys()))) - roles_ = r_['startup_roles'] - self.assertEqual(type(roles_), list) - p_ = roles_[0] - e = sorted(['confirmed', 'ended_at', 'title', 'created_at', 'startup', 'tagged', 'role', 'started_at', 'id']) - self.assertEqual(e, sorted(list(p_.iterkeys()))) - def test_status_updates(self, startup_id=ANGELLIST_ID): expected_keys = sorted(['total', 'per_page', 'last_page', 'status_updates', 'page']) u_ = angel.get_status_updates(startup_id)
removed test_startup_roles_deprecated test
bugra_angel-list
train
36c6bd89037815e1f409b647c78129996ebb43fc
diff --git a/cli/index.js b/cli/index.js index <HASH>..<HASH> 100755 --- a/cli/index.js +++ b/cli/index.js @@ -61,10 +61,23 @@ switch(cmd) { let args = slurm({ w: {list: true}, u: {list: true}, + x: {rest: true}, v: true, // verbose errors }) + + if (Array.isArray(args.x) && !args.w) + fatal('Cannot use -x without -w') + if (args.length || !args.w && !args.u) fatal('Unrecognized command') + + if (Array.isArray(args.x)) { + if (args.w.length > 1) { + fatal('Cannot use -x on multiple roots') + } + let root = path.resolve(args.w[0]) + return runAndWatch(root, args.x[0], args.x.slice(1)) + } if (args.w) args.w.forEach(watch) if (args.u) @@ -85,6 +98,54 @@ async function watch(root) { }).catch(fatal) } +// Restart a child process when files change. +function runAndWatch(root, cmd, args) { + let {spawn} = require('child_process') + + let proc = run() + let kill = debounce(100, () => { + if (!proc) return rerun() + proc.once('exit', rerun).kill() + }) + + wch.stream(root, { + exclude: [ + '.git', + '.git/**', + '.*.sw[a-z]', '*~', // vim temporary files + '.DS_Store', // macOS Finder metadata + ] + }).on('data', kill) + + function run() { + return spawn(cmd, args, { + stdio: ['ignore', 'inherit', 'inherit'] + }).on('error', fatal).on('exit', die) + } + + function die() { + proc = null + } + + function rerun() { + if (!args.v) { + // 1. Print empty lines until the screen is blank. + process.stdout.write('\033[2J') + // 2. Clear the scrollback. + process.stdout.write('\u001b[H\u001b[2J\u001b[3J') + } + proc = run() + } + + function debounce(delay, fn) { + let timer + return function() { + clearTimeout(timer) + timer = setTimeout(fn, delay) + } + } +} + function good(label, ...args) { log(huey.pale_green(label), ...args) }
feat(cli): add -x for executing a command when files change You must use -w and only 1 root can be watched.
aleclarson_wch
train
3c527d1a1a6f5fc970c63e604cf2fb33beee27f1
diff --git a/test/duplicated-extension.js b/test/duplicated-extension.js index <HASH>..<HASH> 100644 --- a/test/duplicated-extension.js +++ b/test/duplicated-extension.js @@ -55,3 +55,10 @@ test( '.one.two {} .two{&.one {}}', '.one.two {}' ); + +test( + 'nested selector grouping', + [nestedCSS, scss], + '.one {&.two, .two& {}} .one {.two&, &.two {}}', + '.one.two, .two.one {}' +); diff --git a/test/unique-css.js b/test/unique-css.js index <HASH>..<HASH> 100644 --- a/test/unique-css.js +++ b/test/unique-css.js @@ -163,3 +163,10 @@ test( '@keyframes a {0% {} 100% {}} @-webkit-keyframes a {0% {} 100% {}}', '@keyframes a {0% {} 100% {}} @-webkit-keyframes a {0% {} 100% {}}' ); + +test( + 'selector groups partially overlapping', + css, + '.one, .two {} .one, .two, .three {}', + '.one, .two {} .one, .two, .three {}' +);
test: check nested selector groupings and partial overlap cases
ChristianMurphy_postcss-combine-duplicated-selectors
train
128d53521f745fa6d05ca9ee9f8ad2073ee93b4b
diff --git a/test/cache.test.js b/test/cache.test.js index <HASH>..<HASH> 100644 --- a/test/cache.test.js +++ b/test/cache.test.js @@ -3,8 +3,8 @@ var assert = require('assert'); var helper = require('./support/helper'); describe('cache', function() { - before(function(done) { - helper.ensureExists('test/tmp',done); + before(function() { + helper.ensureExists('test/tmp'); }); it('should cache Database objects while opening', function(done) { diff --git a/test/null_error.test.js b/test/null_error.test.js index <HASH>..<HASH> 100644 --- a/test/null_error.test.js +++ b/test/null_error.test.js @@ -7,11 +7,9 @@ describe('null error', function() { var db; before(function(done) { - helper.ensureExists('test/tmp',function(err) { - if (err) throw err; - helper.deleteFile(filename); - db = new sqlite3.Database(filename, done); - }); + helper.ensureExists('test/tmp'); + helper.deleteFile(filename); + db = new sqlite3.Database(filename, done); }); it('should create a table', function(done) { diff --git a/test/open_close.test.js b/test/open_close.test.js index <HASH>..<HASH> 100644 --- a/test/open_close.test.js +++ b/test/open_close.test.js @@ -4,8 +4,8 @@ var fs = require('fs'); var helper = require('./support/helper'); describe('open/close', function() { - before(function(done) { - helper.ensureExists('test/tmp',done); + before(function() { + helper.ensureExists('test/tmp'); }); describe('open and close non-existant database', function() { diff --git a/test/parallel_insert.test.js b/test/parallel_insert.test.js index <HASH>..<HASH> 100644 --- a/test/parallel_insert.test.js +++ b/test/parallel_insert.test.js @@ -6,9 +6,8 @@ describe('parallel', function() { var db; before(function(done) { helper.deleteFile('test/tmp/test_parallel_inserts.db'); - helper.ensureExists('test/tmp',function(err){ - db = new sqlite3.Database('test/tmp/test_parallel_inserts.db', done); - }); + helper.ensureExists('test/tmp'); + db = new sqlite3.Database('test/tmp/test_parallel_inserts.db', done); }); var columns = []; diff --git a/test/support/helper.js b/test/support/helper.js index <HASH>..<HASH> 100644 --- a/test/support/helper.js +++ b/test/support/helper.js @@ -1,6 +1,6 @@ var assert = require('assert'); var fs = require('fs'); -var pathExists = require('fs').exists || require('path').exists; +var pathExists = require('fs').existsSync || require('path').existsSync; exports.deleteFile = function(name) { try { @@ -13,14 +13,9 @@ exports.deleteFile = function(name) { }; exports.ensureExists = function(name,cb) { - pathExists(name,function(exists) { - if (!exists) { - fs.mkdir(name,function(err) { - return cb(err); - }); - } - return cb(null); - }); + if (!pathExists(name)) { + fs.mkdirSync(name); + }; } assert.fileDoesNotExist = function(name) {
move test/tmp directory creation to sync to avoid race to create directory which will appear as'Error: done() called multiple times' - refs visionmedia/mocha#<I>
mapbox_node-sqlite3
train
ec90f781e81b09e2578815aa7c4a90651ddc70df
diff --git a/provider/openstack/config_test.go b/provider/openstack/config_test.go index <HASH>..<HASH> 100644 --- a/provider/openstack/config_test.go +++ b/provider/openstack/config_test.go @@ -14,6 +14,7 @@ import ( "launchpad.net/loggo" "launchpad.net/juju-core/environs" + envtesting "launchpad.net/juju-core/environs/testing" "launchpad.net/juju-core/environs/config" "launchpad.net/juju-core/testing" ) @@ -66,7 +67,7 @@ type configTest struct { authURL string accessKey string secretKey string - firewallMode config.FirewallMode + firewallMode string err string } @@ -491,13 +492,12 @@ func (t *testWriter) Write(level loggo.Level, module, filename string, line int, func (s *ConfigDeprecationSuite) setupEnv(c *gc.C, deprecatedKey, value string) { s.setupEnvCredentials() - attrs := map[string]interface{}{ + attrs := envtesting.FakeConfig.Merge(testing.Attrs{ "name": "testenv", "type": "openstack", "control-bucket": "x", - "authorized-keys": "fakekey", deprecatedKey: value, - } + }) _, err := environs.NewFromAttrs(attrs) c.Assert(err, gc.IsNil) } diff --git a/provider/openstack/live_test.go b/provider/openstack/live_test.go index <HASH>..<HASH> 100644 --- a/provider/openstack/live_test.go +++ b/provider/openstack/live_test.go @@ -37,21 +37,17 @@ func makeTestConfig(cred *identity.Credentials) map[string]interface{} { // access-key: $OS_USERNAME // secret-key: $OS_PASSWORD // - attrs := map[string]interface{}{ + attrs := envtesting.FakeConfig.Merge(coretesting.Attrs{ "name": "sample-" + randomName(), "type": "openstack", "auth-mode": "userpass", "control-bucket": "juju-test-" + randomName(), - "ca-cert": coretesting.CACert, - "ca-private-key": coretesting.CAKey, - "authorized-keys": "fakekey", - "admin-secret": "secret", "username": cred.User, "password": cred.Secrets, "region": cred.Region, "auth-url": cred.URL, "tenant-name": cred.TenantName, - } + }) return attrs } @@ -61,7 +57,7 @@ func registerLiveTests(cred *identity.Credentials) { gc.Suite(&LiveTests{ cred: cred, LiveTests: jujutest.LiveTests{ - TestConfig: jujutest.TestConfig{config}, + TestConfig: config, Attempt: *openstack.ShortAttempt, CanOpenState: true, HasProvisioner: true, @@ -89,7 +85,7 @@ func (t *LiveTests) SetUpSuite(c *gc.C) { c.Assert(err, gc.IsNil) publicBucketURL, err := cl.MakeServiceURL("object-store", nil) c.Assert(err, gc.IsNil) - t.TestConfig = t.TestConfig.Merge(testing.Attrs{ + t.TestConfig = t.TestConfig.Merge(coretesting.Attrs{ "public-bucket-url": publicBucketURL, "auth-url": t.cred.URL, }) diff --git a/provider/openstack/local_test.go b/provider/openstack/local_test.go index <HASH>..<HASH> 100644 --- a/provider/openstack/local_test.go +++ b/provider/openstack/local_test.go @@ -99,14 +99,14 @@ func registerLocalTests() { LiveTests: LiveTests{ cred: cred, LiveTests: jujutest.LiveTests{ - TestConfig: jujutest.TestConfig{config}, + TestConfig: config, }, }, }) gc.Suite(&localServerSuite{ cred: cred, Tests: jujutest.Tests{ - TestConfig: jujutest.TestConfig{config}, + TestConfig: config, }, }) gc.Suite(&publicBucketSuite{ @@ -202,7 +202,7 @@ func (s *localServerSuite) TearDownSuite(c *gc.C) { func (s *localServerSuite) SetUpTest(c *gc.C) { s.LoggingSuite.SetUpTest(c) s.srv.start(c, s.cred) - s.TestConfig = s.TestConfig.Merge(testing.Attrs{ + s.TestConfig = s.TestConfig.Merge(coretesting.Attrs{ "auth-url": s.cred.URL, }) s.Tests.SetUpTest(c)
provider/openstack: tests pass
juju_juju
train
8bd9595c50498a301a3e605bef4737773a70b725
diff --git a/modules/optimaticBidAdapter.js b/modules/optimaticBidAdapter.js index <HASH>..<HASH> 100644 --- a/modules/optimaticBidAdapter.js +++ b/modules/optimaticBidAdapter.js @@ -3,6 +3,9 @@ import { registerBidder } from 'src/adapters/bidderFactory'; export const ENDPOINT = '//mg-bid.optimatic.com/adrequest/'; export const spec = { + + version: '1.0.4', + code: 'optimatic', supportedMediaTypes: ['video'], @@ -33,7 +36,7 @@ export const spec = { } catch (e) { response = null; } - if (!response || !bid || !bid.adm || !bid.price) { + if (!response || !bid || (!bid.adm && !bid.nurl) || !bid.price) { utils.logWarn(`No valid bids from ${spec.code} bidder`); return []; } @@ -43,7 +46,6 @@ export const spec = { bidderCode: spec.code, cpm: bid.price, creativeId: bid.id, - vastXml: bid.adm, width: size.width, height: size.height, mediaType: 'video', @@ -51,6 +53,11 @@ export const spec = { ttl: 300, netRevenue: true }; + if (bid.nurl) { + bidResponse.vastUrl = bid.nurl; + } else if (bid.adm) { + bidResponse.vastXml = bid.adm; + } return bidResponse; } }; diff --git a/test/spec/modules/optimaticBidAdapter_spec.js b/test/spec/modules/optimaticBidAdapter_spec.js index <HASH>..<HASH> 100644 --- a/test/spec/modules/optimaticBidAdapter_spec.js +++ b/test/spec/modules/optimaticBidAdapter_spec.js @@ -106,7 +106,7 @@ describe('OptimaticBidAdapter', () => { expect(bidResponse.length).to.equal(0); }); - it('should return no bids if the response "adm" is missing', () => { + it('should return no bids if the response "nurl" and "adm" are missing', () => { const serverResponse = {seatbid: [{bid: [{price: 5.01}]}]}; const bidResponse = spec.interpretResponse({ body: serverResponse }, { bidRequest }); expect(bidResponse.length).to.equal(0); @@ -118,7 +118,7 @@ describe('OptimaticBidAdapter', () => { expect(bidResponse.length).to.equal(0); }); - it('should return a valid bid response', () => { + it('should return a valid bid response with just "adm"', () => { const serverResponse = {seatbid: [{bid: [{id: 1, price: 5.01, adm: '<VAST></VAST>'}]}], cur: 'USD'}; const bidResponse = spec.interpretResponse({ body: serverResponse }, { bidRequest }); let o = { @@ -136,5 +136,43 @@ describe('OptimaticBidAdapter', () => { }; expect(bidResponse).to.deep.equal(o); }); + + it('should return a valid bid response with just "nurl"', () => { + const serverResponse = {seatbid: [{bid: [{id: 1, price: 5.01, nurl: 'https://mg-bid-win.optimatic.com/win/134eb262-948a-463e-ad93-bc8b622d399c?wp=${AUCTION_PRICE}'}]}], cur: 'USD'}; + const bidResponse = spec.interpretResponse({ body: serverResponse }, { bidRequest }); + let o = { + requestId: bidRequest.bidId, + bidderCode: spec.code, + cpm: serverResponse.seatbid[0].bid[0].price, + creativeId: serverResponse.seatbid[0].bid[0].id, + vastUrl: serverResponse.seatbid[0].bid[0].nurl, + width: 640, + height: 480, + mediaType: 'video', + currency: 'USD', + ttl: 300, + netRevenue: true + }; + expect(bidResponse).to.deep.equal(o); + }); + + it('should return a valid bid response with "nurl" when both nurl and adm exist', () => { + const serverResponse = {seatbid: [{bid: [{id: 1, price: 5.01, adm: '<VAST></VAST>', nurl: 'https://mg-bid-win.optimatic.com/win/134eb262-948a-463e-ad93-bc8b622d399c?wp=${AUCTION_PRICE}'}]}], cur: 'USD'}; + const bidResponse = spec.interpretResponse({ body: serverResponse }, { bidRequest }); + let o = { + requestId: bidRequest.bidId, + bidderCode: spec.code, + cpm: serverResponse.seatbid[0].bid[0].price, + creativeId: serverResponse.seatbid[0].bid[0].id, + vastUrl: serverResponse.seatbid[0].bid[0].nurl, + width: 640, + height: 480, + mediaType: 'video', + currency: 'USD', + ttl: 300, + netRevenue: true + }; + expect(bidResponse).to.deep.equal(o); + }); }); });
Added support for NURL and ADM as backup (#<I>) + Updated unit tests to test code updates + Added version number (<I>) for optimatic records
prebid_Prebid.js
train
7dbaf9f100d9c2f5df450a12f56b60de30962d2d
diff --git a/tests/dummy/snippets/transition-arguments.js b/tests/dummy/snippets/transition-arguments.js index <HASH>..<HASH> 100644 --- a/tests/dummy/snippets/transition-arguments.js +++ b/tests/dummy/snippets/transition-arguments.js @@ -1,7 +1,7 @@ /* app/transitions/my-animation.js */ export default function(color, opts) { //... -}); +} /* within app/transitions.js */ this.transition(
Update transition-arguments.js nothing to close with the right paren. export default function doesn't need semicolon afterwards either
ember-animation_liquid-fire
train
0c34a01a60f8283908d52dae2deeb99bb3a4d27e
diff --git a/master/buildbot/test/unit/test_changes_hgpoller.py b/master/buildbot/test/unit/test_changes_hgpoller.py index <HASH>..<HASH> 100644 --- a/master/buildbot/test/unit/test_changes_hgpoller.py +++ b/master/buildbot/test/unit/test_changes_hgpoller.py @@ -178,13 +178,13 @@ class TestHgPoller(gpo.GetProcessOutputMixin, self.expectCommands( gpo.Expect('hg', 'pull', '-b', 'one', '-b', 'two', 'ssh://example.com/foo/baz') - .path('/some/dir'), + .path('/some/dir'), gpo.Expect( 'hg', 'heads', '-r', 'one', '--template={rev}' + os.linesep) - .path('/some/dir').stdout(b"73591"), + .path('/some/dir').stdout(b"73591"), gpo.Expect( 'hg', 'heads', '-r', 'two', '--template={rev}' + os.linesep) - .path('/some/dir').stdout(b"22341"), + .path('/some/dir').stdout(b"22341"), ) # do the poll @@ -196,6 +196,7 @@ class TestHgPoller(gpo.GetProcessOutputMixin, yield self.check_current_rev(73591, 'one') yield self.check_current_rev(22341, 'two') + class HgPollerNoTimestamp(TestHgPoller): """ Test HgPoller() without parsing revision commit timestamp """
Make flake8 happy with hgpoller.
buildbot_buildbot
train
1d64386b3de266b0155221b60ba8f7b5cfd2e2c8
diff --git a/pylutron/__init__.py b/pylutron/__init__.py index <HASH>..<HASH> 100644 --- a/pylutron/__init__.py +++ b/pylutron/__init__.py @@ -405,6 +405,10 @@ class Lutron(object): def guid(self): return self._guid + @property + def name(self): + return self._name + def subscribe(self, obj, handler): """Subscribes to status updates of the requested object.
Add getter for the project name. (#<I>)
thecynic_pylutron
train
853d2df7c2e2dd7a6ee31d514e50bcc3002cbe4c
diff --git a/src/main/java/org/dynjs/parser/ast/RegexpLiteralExpression.java b/src/main/java/org/dynjs/parser/ast/RegexpLiteralExpression.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/dynjs/parser/ast/RegexpLiteralExpression.java +++ b/src/main/java/org/dynjs/parser/ast/RegexpLiteralExpression.java @@ -11,7 +11,8 @@ import org.dynjs.runtime.ExecutionContext; public class RegexpLiteralExpression extends BaseExpression { static class RegexpLiteralExpressionParser { - private static final String REG_EXP_PATTERN = "^\\/(.*)\\/([igm]{0,})$"; + // \u0085 is not a line terminator in JS but is in Java regexes + private static final String REG_EXP_PATTERN = "^\\/((?:.|\u0085)*)\\/([igm]{0,})$"; static RegexpLiteralExpressionParser parse(String text) { Pattern pattern = Pattern.compile(REG_EXP_PATTERN);
Javascript has different line terminators than Java
dynjs_dynjs
train
ca8be3f6bd40ca3353ba3fc7d2e634eb853e2941
diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java index <HASH>..<HASH> 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java @@ -231,10 +231,11 @@ public final class Health { } /** - * Add details from the given {@code details} map into existing details. Keys from - * the given map will replace any existing keys if there are duplicates. + * Record details from the given {@code details} map. Keys from the given map + * replace any existing keys if there are duplicates. * @param details map of details * @return this {@link Builder} instance + * @since 2.1.0 */ public Builder withDetails(Map<String, ?> details) { Assert.notNull(details, "Details must not be null"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index <HASH>..<HASH> 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -25,6 +25,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; /** * Tests for {@link Health}. @@ -97,59 +98,30 @@ public class HealthTests { Map<String, Object> details = new LinkedHashMap<>(); details.put("a", "b"); details.put("c", "d"); - - Health.Builder builder = Health.up(); - builder.withDetails(details); - - Health health = builder.build(); - assertThat(health.getDetails().get("a")).isEqualTo("b"); - assertThat(health.getDetails().get("c")).isEqualTo("d"); + Health health = Health.up().withDetails(details).build(); + assertThat(health.getDetails()).containsOnly(entry("a", "b"), entry("c", "d")); } @Test public void withDetailsMapDuplicateKeys() { Map<String, Object> details = new LinkedHashMap<>(); - details.put("a", "b"); details.put("c", "d"); details.put("a", "e"); - - Health.Builder builder = Health.up(); - builder.withDetails(details); - - Health health = builder.build(); - assertThat(health.getDetails().get("a")).isEqualTo("e"); - assertThat(health.getDetails().get("c")).isEqualTo("d"); + Health health = Health.up().withDetail("a", "b").withDetails(details).build(); + assertThat(health.getDetails()).containsOnly(entry("a", "e"), entry("c", "d")); } @Test - public void withMultipleDetailsMaps() { + public void withDetailsMultipleMaps() { Map<String, Object> details1 = new LinkedHashMap<>(); details1.put("a", "b"); details1.put("c", "d"); - Map<String, Object> details2 = new LinkedHashMap<>(); - details2.put("1", "2"); - - Health.Builder builder = Health.up(); - builder.withDetails(details1); - builder.withDetails(details2); - - Health health = builder.build(); - assertThat(health.getDetails().get("a")).isEqualTo("b"); - assertThat(health.getDetails().get("c")).isEqualTo("d"); - assertThat(health.getDetails().get("1")).isEqualTo("2"); - } - - @Test - public void mixWithDetailsUsage() { - Map<String, Object> details = new LinkedHashMap<>(); - details.put("a", "b"); - - Health.Builder builder = Health.up().withDetails(details).withDetail("c", "d"); - - Health health = builder.build(); - assertThat(health.getDetails().get("a")).isEqualTo("b"); - assertThat(health.getDetails().get("c")).isEqualTo("d"); + details1.put("a", "e"); + details1.put("1", "2"); + Health health = Health.up().withDetails(details1).withDetails(details2).build(); + assertThat(health.getDetails()).containsOnly(entry("a", "e"), entry("c", "d"), + entry("1", "2")); } @Test
Polish "Add Health details using maps" Closes gh-<I>
spring-projects_spring-boot
train
e88067ac9196bf43365e7d4aa7f0950312492bd1
diff --git a/lib/execjs/external_runtime.rb b/lib/execjs/external_runtime.rb index <HASH>..<HASH> 100644 --- a/lib/execjs/external_runtime.rb +++ b/lib/execjs/external_runtime.rb @@ -183,7 +183,10 @@ module ExecJS if ExecJS.windows? def shell_escape(*args) # see http://technet.microsoft.com/en-us/library/cc723564.aspx#XSLTsection123121120120 - args.map { |arg| arg.gsub(/([&|()<>^ "])/,'^\1') }.join(" ") + args.map { |arg| + arg = %Q("#{arg.gsub('"','""')}") if arg.match(/[&|()<>^ "]/) + arg + }.join(" ") end else def shell_escape(*args)
Ensure that commands and args are properly quoted if they contain spaces or reserved shell characters (on Windows). <URL>
rails_execjs
train
0cd41f78d25b97eeb049276884dd01726beb8217
diff --git a/packages/mail/src/classes/mail-service.js b/packages/mail/src/classes/mail-service.js index <HASH>..<HASH> 100644 --- a/packages/mail/src/classes/mail-service.js +++ b/packages/mail/src/classes/mail-service.js @@ -27,6 +27,8 @@ class MailService { */ setClient(client) { this.client = client; + + return this; } /** @@ -34,6 +36,8 @@ class MailService { */ setApiKey(apiKey) { this.client.setApiKey(apiKey); + + return this; } /** @@ -66,6 +70,8 @@ class MailService { } this.substitutionWrappers[0] = left; this.substitutionWrappers[1] = right; + + return this; } /**
feat: Add method chaining in mail-service.js (#<I>)
sendgrid_sendgrid-nodejs
train
7950f8bb9bf8226a7a1b915f8d8ef3d824c8c5a6
diff --git a/test/unit/fixtures/fixture.js b/test/unit/fixtures/fixture.js index <HASH>..<HASH> 100644 --- a/test/unit/fixtures/fixture.js +++ b/test/unit/fixtures/fixture.js @@ -3,5 +3,8 @@ define(function (require) { return d3.select("body") .append("div") - .attr("class", "chart"); + .attr("class", "chart") + .append("svg") + .attr("width", 500) + .attr("height", 500); }); diff --git a/test/unit/specs/modules/element/circle.js b/test/unit/specs/modules/element/circle.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/modules/element/circle.js +++ b/test/unit/specs/modules/element/circle.js @@ -9,18 +9,13 @@ define(function (require) { beforeEach(function () { fixture = d3fixture; - // Add SVG - fixture.append("svg") - .attr("width", 500) - .attr("height", 500); - fixture .datum(data) .call(element); }); afterEach(function () { - fixture.remove(); + fixture.selectAll("*").remove(); fixture = null; }); diff --git a/test/unit/specs/modules/element/clipPath.js b/test/unit/specs/modules/element/clipPath.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/modules/element/clipPath.js +++ b/test/unit/specs/modules/element/clipPath.js @@ -8,17 +8,13 @@ define(function (require) { beforeEach(function () { fixture = d3fixture; - fixture.append("svg") - .attr("width", 500) - .attr("height", 500); - fixture .datum([{}]) // Only render 1 clippath .call(element); }); afterEach(function () { - fixture.remove(); + fixture.selectAll("*").remove(); fixture = null; }); diff --git a/test/unit/specs/modules/element/ellipse.js b/test/unit/specs/modules/element/ellipse.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/modules/element/ellipse.js +++ b/test/unit/specs/modules/element/ellipse.js @@ -9,17 +9,13 @@ define(function (require) { beforeEach(function () { fixture = d3fixture; - fixture.append("svg") - .attr("width", 500) - .attr("height", 500); - fixture .datum(data) .call(element); }); afterEach(function () { - fixture.remove(); + fixture.selectAll("*").remove(); fixture = null; }); diff --git a/test/unit/specs/modules/element/image.js b/test/unit/specs/modules/element/image.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/modules/element/image.js +++ b/test/unit/specs/modules/element/image.js @@ -9,17 +9,13 @@ define(function (require) { beforeEach(function () { fixture = d3fixture; - fixture.append("svg") - .attr("width", 500) - .attr("height", 500); - fixture .datum(data) .call(element); }); afterEach(function () { - fixture.remove(); + fixture.selectAll("*").remove(); fixture = null; }); diff --git a/test/unit/specs/modules/element/line.js b/test/unit/specs/modules/element/line.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/modules/element/line.js +++ b/test/unit/specs/modules/element/line.js @@ -9,17 +9,13 @@ define(function (require) { beforeEach(function () { fixture = d3fixture; - fixture.append("svg") - .attr("width", 500) - .attr("height", 500); - fixture .datum(data) .call(element); }); afterEach(function () { - fixture.remove(); + fixture.selectAll("*").remove(); fixture = null; }); diff --git a/test/unit/specs/modules/element/rect.js b/test/unit/specs/modules/element/rect.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/modules/element/rect.js +++ b/test/unit/specs/modules/element/rect.js @@ -9,17 +9,13 @@ define(function (require) { beforeEach(function () { fixture = d3fixture; - fixture.append("svg") - .attr("width", 500) - .attr("height", 500); - fixture .datum(data) .call(element); }); afterEach(function () { - fixture.remove(); + fixture.selectAll("*").remove(); fixture = null; });
cleaning up tests, troubleshooting test failures
stormpython_jubilee
train
d19a3e2f8d3f8433526da5d0ba74154648909493
diff --git a/pycm/pycm_param.py b/pycm/pycm_param.py index <HASH>..<HASH> 100644 --- a/pycm/pycm_param.py +++ b/pycm/pycm_param.py @@ -23,7 +23,6 @@ MATRIX_CLASS_TYPE_ERROR = "Type of the input matrix classes is assumed be the s MATRIX_FORMAT_ERROR = "Input confusion matrix format error" MAPPING_FORMAT_ERROR = "Mapping format error" MAPPING_CLASS_NAME_ERROR = "Mapping class names error" -INVALID_PLOT_LIBRARY_ERROR = "{} is not a valid plotting library" SEABORN_PLOT_LIBRARY_ERROR = "Importing seaborn module error" MATPLOTLIB_PLOT_LIBRARY_ERROR = "Importing matplotlib module error" VECTOR_TYPE_ERROR = "The type of input vectors is assumed to be a list or a NumPy array"
del : unused ERROR deleted.
sepandhaghighi_pycm
train
fffba33cd3db052bb6c84d497da049c8b436397c
diff --git a/IPython/html/static/notebook/js/widgetmanager.js b/IPython/html/static/notebook/js/widgetmanager.js index <HASH>..<HASH> 100644 --- a/IPython/html/static/notebook/js/widgetmanager.js +++ b/IPython/html/static/notebook/js/widgetmanager.js @@ -209,7 +209,7 @@ clear_output : handle_clear_output, status : function (msg) { - view.model._handle_status(msg, that.callbacks()); + view.model._handle_status(msg, that.callbacks(view)); }, // Special function only registered by widget messages.
Missing view argument when recursively calling widgetmanager.callbacks(view)
jupyter-widgets_ipywidgets
train
bdade0fe08199904785f87f808a22d1941a4f54b
diff --git a/cake/libs/view/media.php b/cake/libs/view/media.php index <HASH>..<HASH> 100644 --- a/cake/libs/view/media.php +++ b/cake/libs/view/media.php @@ -20,6 +20,12 @@ App::import('View', 'View', false); class MediaView extends View { +/** + * Indicates whether response gzip compression was enabled for this class + * + * @var boolean + */ + private $compressionEnabled = false; /** * Constructor @@ -42,7 +48,7 @@ class MediaView extends View { * @return unknown */ function render() { - $name = $download = $extension = $id = $modified = $path = $size = $cache = $mimeType = null; + $name = $download = $extension = $id = $modified = $path = $size = $cache = $mimeType = $compress = null; extract($this->viewVars, EXTR_OVERWRITE); if ($size) { @@ -135,7 +141,9 @@ class MediaView extends View { )); } $this->_clearBuffer(); - $this->_sendFile($handle); + if ($compress) { + $this->compressionEnabled = $this->response->compress(); + } $this->response->send(); return $this->_sendFile($handle); @@ -155,7 +163,9 @@ class MediaView extends View { set_time_limit(0); $buffer = fread($handle, $chunkSize); echo $buffer; - $this->_flushBuffer(); + if (!$this->compressionEnabled) { + $this->_flushBuffer(); + } } fclose($handle); }
Adding the ability to compress the response sent from the MeviaView class
cakephp_cakephp
train
5bbd1bf6f1dff0f01dd1614794086ad2151e9eea
diff --git a/src/schema.js b/src/schema.js index <HASH>..<HASH> 100644 --- a/src/schema.js +++ b/src/schema.js @@ -26,6 +26,7 @@ Schema.prototype.parse = function (config) { assertRequired(this.required, Object.keys(config)); return this.properties.reduce(function (parsed, property) { var value = types.cast(config[property.key], property.type); + value = (property.transform || identity)(value); parsed.set(property.path, value); return parsed; }, traverse({})).value; @@ -47,4 +48,8 @@ function assertRequired (required, provided) { } } +function identity (value) { + return value; +} + module.exports = Schema; diff --git a/test/index.js b/test/index.js index <HASH>..<HASH> 100644 --- a/test/index.js +++ b/test/index.js @@ -71,3 +71,25 @@ test('using types', function (t) { }); t.end(); }); + +test('transforms', function (t) { + var schema = new Schema({ + foo: { + bar: { + key: 'ENV_KEY', + transform: function (value) { + return 'https://' + value; + } + } + } + }); + var parsed = schema.parse({ + ENV_KEY: 'apple.com' + }); + t.deepEqual(parsed, { + foo: { + bar: 'https://apple.com' + } + }); + t.end(); +});
Add support for transforming parsed config after casting
bendrucker_confidential
train
e3645d517b58007804cb8a08c73b59daf983951f
diff --git a/webgl4j/src/main/java/com/shc/webgl4j/client/WebGL20.java b/webgl4j/src/main/java/com/shc/webgl4j/client/WebGL20.java index <HASH>..<HASH> 100644 --- a/webgl4j/src/main/java/com/shc/webgl4j/client/WebGL20.java +++ b/webgl4j/src/main/java/com/shc/webgl4j/client/WebGL20.java @@ -28,6 +28,7 @@ import com.google.gwt.canvas.client.Canvas; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.CanvasElement; import com.google.gwt.typedarrays.shared.ArrayBufferView; +import com.google.gwt.typedarrays.shared.Int32Array; /** * @author Sri Harsha Chilakapati @@ -427,6 +428,26 @@ public final class WebGL20 nglReadBuffer(src); } + public static Int32Array glGetInternalformatParameter(int target, int internalFormat, int pName) + { + checkContextCompatibility(); + return nglGetInternalformatParameter(target, internalFormat, pName); + } + + public static void glRenderbufferStorageMultisample(int target, int samples, int internalFormat, int width, int height) + { + checkContextCompatibility(); + nglRenderbufferStorageMultisample(target, samples, internalFormat, width, height); + } + + private static native void nglRenderbufferStorageMultisample(int target, int samples, int internalFormat, int width, int height) /*-{ + $wnd.gl.renderbufferStorageMultisample(target, samples, internalFormat, width, height); + }-*/; + + private static native Int32Array nglGetInternalformatParameter(int target, int internalFormat, int pName); /*-{ + return $wnd.gl.getInternalformatParameter(target, internalFormat, pName); + }-*/; + private static native void nglReadBuffer(int src) /*-{ $wnd.gl.readBuffer(src); }-*/;
Added renderbuffer object functions to WebGL<I>
sriharshachilakapati_WebGL4J
train
402880a29d8e312e316584043316836ebab66e81
diff --git a/tests/Storage/SessionStorageTest.php b/tests/Storage/SessionStorageTest.php index <HASH>..<HASH> 100644 --- a/tests/Storage/SessionStorageTest.php +++ b/tests/Storage/SessionStorageTest.php @@ -12,6 +12,7 @@ namespace chillerlan\OAuthTest\Storage; +use chillerlan\OAuth\OAuthOptions; use chillerlan\OAuth\Storage\{OAuthStorageException, SessionStorage}; /** @@ -72,4 +73,16 @@ class SessionStorageTest extends StorageTestAbstract{ public function testStoreWithExistingToken(){ parent::testStoreWithExistingToken(); } + + /** + * @runInSeparateProcess + */ + public function testStoreStateWithNonExistentArray(){ + $options = new OAuthOptions; + unset($_SESSION[$options->sessionStateVar]); + + $this->assertFalse($this->storage->hasCSRFState($this->tsn)); + $this->storage->storeCSRFState($this->tsn, 'foobar'); + $this->assertTrue($this->storage->hasCSRFState($this->tsn)); + } }
:octocat: SessionStorage: coverage
chillerlan_php-oauth-core
train
cd5c67f6fa2c4263449e7a8515155711b2bc4e71
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project will be documented in this file. This projec ### Added - Can now assert that a resource object is one of multiple types using `assertTypeIs()`. - Can now assert that the `data` member of a document is `null`. +- Can now assert that a resource object matches an expected structure. ### Fixed - Resource object type assertion caused a PHP error. diff --git a/src/ResourceObjectTester.php b/src/ResourceObjectTester.php index <HASH>..<HASH> 100644 --- a/src/ResourceObjectTester.php +++ b/src/ResourceObjectTester.php @@ -56,7 +56,7 @@ class ResourceObjectTester { $this->resource = $resource; $this->index = $index; - $this->isComplete(); + $this->assertComplete(); } /** @@ -86,6 +86,41 @@ class ResourceObjectTester } /** + * Assert that the resource matches the expected structure. + * + * @param array $expected + * the expected array representation of the resource. + * @return $this + */ + public function assertMatches(array $expected) + { + if (!isset($expected[self::KEYWORD_TYPE])) { + PHPUnit::fail('Expected resource data must contain a type key.'); + } + + $attributes = isset($expected[self::KEYWORD_ATTRIBUTES]) ? + $expected[self::KEYWORD_ATTRIBUTES] : []; + + $relationships = isset($expected[self::KEYWORD_RELATIONSHIPS]) ? + $this->normalizeRelationships($expected[self::KEYWORD_RELATIONSHIPS]) : []; + + /** Have we got the correct resource id? */ + if (isset($expected[self::KEYWORD_ID])) { + $this->assertIs($expected[self::KEYWORD_TYPE], $expected[self::KEYWORD_ID]); + } else { + $this->assertTypeIs($expected[self::KEYWORD_TYPE]); + } + + /** Have we got the correct attributes? */ + $this->assertAttributesSubset($attributes); + + /** Have we got the correct relationships? */ + $this->assertRelationshipsSubset($relationships); + + return $this; + } + + /** * Assert that the resource matches the expected type and id. * * @param $type @@ -277,7 +312,7 @@ class ResourceObjectTester /** * @return void */ - private function isComplete() + private function assertComplete() { $type = $this->getType(); @@ -293,4 +328,25 @@ class ResourceObjectTester PHPUnit::fail($this->withIndex('Resource has an empty string id member')); } } + + /** + * @param array $relationships + * @return array + */ + private function normalizeRelationships(array $relationships) + { + $normalized = []; + + foreach ($relationships as $key => $value) { + + if (is_numeric($key)) { + $key = $value; + $value = []; + } + + $normalized[$key] = $value; + } + + return $normalized; + } } diff --git a/tests/ResourceObjectTesterTest.php b/tests/ResourceObjectTesterTest.php index <HASH>..<HASH> 100644 --- a/tests/ResourceObjectTesterTest.php +++ b/tests/ResourceObjectTesterTest.php @@ -172,7 +172,19 @@ JSON_API; $resource = DocumentTester::create($content)->assertResource(); - $resource->assertAttribute('title', 'My First Post') + $expected = [ + 'type' => 'posts', + 'id' => '123', + 'attributes' => [ + 'title' => 'My First Post', + 'tags' => ['news', 'misc'], + 'content' => 'This is my first post', + 'rank' => 1, + ], + ]; + + $resource->assertMatches($expected) + ->assertAttribute('title', 'My First Post') ->assertAttribute('rank', '1') ->assertAttributeIs('rank', 1); @@ -184,6 +196,11 @@ JSON_API; $resource->assertAttributeIs('rank', '1'); }); + $this->willFail(function () use ($resource, $expected) { + $expected['attributes']['tags'][] = 'another'; + $resource->assertMatches($expected); + }); + return $resource; }
[Feature] Assert that a resource object matches expected structure
cloudcreativity_json-api-testing
train
0de3dd1826becbfdfbe80e2c82baccac304a0270
diff --git a/lib/SimpleSAML/Error/Exception.php b/lib/SimpleSAML/Error/Exception.php index <HASH>..<HASH> 100644 --- a/lib/SimpleSAML/Error/Exception.php +++ b/lib/SimpleSAML/Error/Exception.php @@ -23,17 +23,37 @@ class SimpleSAML_Error_Exception extends Exception { /** + * The cause of this exception. + * + * @var SimpleSAML_Error_Exception + */ + private $cause; + + + /** * Constructor for this error. * + * Note that the cause will be converted to a SimpleSAML_Error_UnserializableException + * unless it is a subclass of SimpleSAML_Error_Exception. + * * @param string $message Exception message * @param int $code Error code + * @param Exception|NULL $cause The cause of this exception. */ - public function __construct($message, $code = 0) { - assert('is_string($message) || is_int($code)'); + public function __construct($message, $code = 0, Exception $cause = NULL) { + assert('is_string($message)'); + assert('is_int($code)'); parent::__construct($message, $code); $this->backtrace = SimpleSAML_Utilities::buildBacktrace($this); + + if ($cause !== NULL) { + if (!($cause instanceof SimpleSAML_Error_Exception)) { + $cause = new SimpleSAML_Error_UnserializableException($cause); + } + $this->cause = $cause; + } } @@ -63,6 +83,16 @@ class SimpleSAML_Error_Exception extends Exception { /** + * Retrieve the cause of this exception. + * + * @return SimpleSAML_Error_Exception|NULL The cause of this exception. + */ + public function getCause() { + return $this->cause; + } + + + /** * Function for serialization. * * This function builds a list of all variables which should be serialized.
Error_Exception: Include the cause of the exception as an parameter. Including the cause of the exception will make it simpler to trace exceptions through the program.
simplesamlphp_saml2
train
bbddb2c99553e2cf041d15b5972f67602602378e
diff --git a/catalog/src/main/java/org/killbill/billing/catalog/CatalogUpdater.java b/catalog/src/main/java/org/killbill/billing/catalog/CatalogUpdater.java index <HASH>..<HASH> 100644 --- a/catalog/src/main/java/org/killbill/billing/catalog/CatalogUpdater.java +++ b/catalog/src/main/java/org/killbill/billing/catalog/CatalogUpdater.java @@ -266,7 +266,7 @@ public class CatalogUpdater { private void validateNewPlanDescriptor(final SimplePlanDescriptor desc) throws CatalogApiException { if (desc.getProductCategory() == null || desc.getBillingPeriod() == null || - (desc.getAmount() == null || desc.getAmount().compareTo(BigDecimal.ZERO) <= 0) || + (desc.getAmount() == null || desc.getAmount().compareTo(BigDecimal.ZERO) < 0) || desc.getCurrency() == null) { throw new CatalogApiException(ErrorCode.CAT_INVALID_SIMPLE_PLAN_DESCRIPTOR, desc); }
catalog: Allow to create plans with -bash recurring items
killbill_killbill
train
744978fa0c55ed0743a022ba89847648845a1c76
diff --git a/plugin/src/main/java/com/stratio/cassandra/lucene/query/BiTemporalCondition.java b/plugin/src/main/java/com/stratio/cassandra/lucene/query/BiTemporalCondition.java index <HASH>..<HASH> 100644 --- a/plugin/src/main/java/com/stratio/cassandra/lucene/query/BiTemporalCondition.java +++ b/plugin/src/main/java/com/stratio/cassandra/lucene/query/BiTemporalCondition.java @@ -100,6 +100,8 @@ public class BiTemporalCondition extends Condition { return SpatialOperation.Contains; } else if (operation.equalsIgnoreCase("intersects")) { return SpatialOperation.Intersects; + } else if (operation.equalsIgnoreCase("iswithin")) { + return SpatialOperation.IsWithin; } else { throw new IllegalArgumentException("Operation is invalid: " + operation); }
Added spatialOperation isWithin to BitemporalCondition
Stratio_cassandra-lucene-index
train
b8d091c9df79d29930ae7829b5dbac9709b11873
diff --git a/andes/models/line.py b/andes/models/line.py index <HASH>..<HASH> 100644 --- a/andes/models/line.py +++ b/andes/models/line.py @@ -73,6 +73,9 @@ class Line(LineData, Model): self.ghk = ConstService(tex_name='g_{hk}') self.bhk = ConstService(tex_name='b_{hk}') + self.itap = ConstService(tex_name='1/t_{ap}') + self.itap2 = ConstService(tex_name='1/t_{ap}^2') + self.gh.v_str = 'g1 + 0.5 * g' self.bh.v_str = 'b1 + 0.5 * b' self.gk.v_str = 'g2 + 0.5 * g' @@ -85,18 +88,21 @@ class Line(LineData, Model): self.ghk.v_str = 're(yhk)' self.bhk.v_str = 'im(yhk)' - self.a1.e_str = 'u * (v1 ** 2 * (gh + ghk) / tap ** 2 - \ + self.itap.v_str = '1/tap' + self.itap2.v_str = '1/tap/tap' + + self.a1.e_str = 'u * (v1 ** 2 * (gh + ghk) * itap2 - \ v1 * v2 * (ghk * cos(a1 - a2 - phi) + \ - bhk * sin(a1 - a2 - phi)) / tap)' + bhk * sin(a1 - a2 - phi)) * itap)' - self.v1.e_str = 'u * (-v1 ** 2 * (bh + bhk) / tap ** 2 - \ + self.v1.e_str = 'u * (-v1 ** 2 * (bh + bhk) * itap2 - \ v1 * v2 * (ghk * sin(a1 - a2 - phi) - \ - bhk * cos(a1 - a2 - phi)) / tap)' + bhk * cos(a1 - a2 - phi)) * itap)' self.a2.e_str = 'u * (v2 ** 2 * (gh + ghk) - \ v1 * v2 * (ghk * cos(a1 - a2 - phi) - \ - bhk * sin(a1 - a2 - phi)) / tap)' + bhk * sin(a1 - a2 - phi)) * itap)' self.v2.e_str = 'u * (-v2 ** 2 * (bh + bhk) + \ v1 * v2 * (ghk * sin(a1 - a2 - phi) + \ - bhk * cos(a1 - a2 - phi)) / tap)' + bhk * cos(a1 - a2 - phi)) * itap)' diff --git a/tests/test_paths.py b/tests/test_paths.py index <HASH>..<HASH> 100644 --- a/tests/test_paths.py +++ b/tests/test_paths.py @@ -17,3 +17,6 @@ class TestPaths(unittest.TestCase): ieee14 = andes.get_case("ieee14/ieee14.raw") path, case = os.path.split(ieee14) andes.load('ieee14.raw', addfile='ieee14.dyr', input_path=path) + + andes.run('ieee14.raw', addfile='ieee14.dyr', input_path=path, + no_output=True)
Added itap and itap2 for line to reduce division
cuihantao_andes
train
f30f7269112578ef9337de155ea0b50f73510210
diff --git a/uportal-war/src/main/java/org/jasig/portal/events/aggr/LoggingPortalEventAggregator.java b/uportal-war/src/main/java/org/jasig/portal/events/aggr/LoggingPortalEventAggregator.java index <HASH>..<HASH> 100644 --- a/uportal-war/src/main/java/org/jasig/portal/events/aggr/LoggingPortalEventAggregator.java +++ b/uportal-war/src/main/java/org/jasig/portal/events/aggr/LoggingPortalEventAggregator.java @@ -34,6 +34,6 @@ public class LoggingPortalEventAggregator implements IPortalEventAggregator<Port @Override public void aggregateEvent(PortalEvent e) { - logger.warn(e.toString()); + logger.debug(e.toString()); } } diff --git a/uportal-war/src/main/java/org/jasig/portal/events/aggr/PortalEventAggregationManagerImpl.java b/uportal-war/src/main/java/org/jasig/portal/events/aggr/PortalEventAggregationManagerImpl.java index <HASH>..<HASH> 100644 --- a/uportal-war/src/main/java/org/jasig/portal/events/aggr/PortalEventAggregationManagerImpl.java +++ b/uportal-war/src/main/java/org/jasig/portal/events/aggr/PortalEventAggregationManagerImpl.java @@ -175,7 +175,7 @@ public class PortalEventAggregationManagerImpl implements IPortalEventAggregatio }); eventAggregatorStatus.setLastEnd(new Date()); - logger.info("Aggregated {} events between {} and {}", new Object[] { events, lastAggregated, newestEventTime }); + logger.debug("Aggregated {} events between {} and {}", new Object[] { events, lastAggregated, newestEventTime }); //Store the results of the aggregation eventAggregationManagementDao.updateEventAggregatorStatus(eventAggregatorStatus); @@ -212,7 +212,7 @@ public class PortalEventAggregationManagerImpl implements IPortalEventAggregatio //Purge events logger.debug("Starting purge of events before {}", purgeEnd); final int events = portalEventDao.deletePortalEventsBefore(purgeEnd); - logger.info("Purged {} events before {}", events, purgeEnd); + logger.debug("Purged {} events before {}", events, purgeEnd); //Update the status object and store it eventPurgerStatus.setLastEnd(new Date());
Turn down logging in aggregation code
Jasig_uPortal
train
06793a87e087e627d5a6b0f6339a061e56268bee
diff --git a/debian/changelog b/debian/changelog index <HASH>..<HASH> 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,4 +1,5 @@ [Michele Simionato] + * Fixed a tricky segfault on macOS caused by a call to requests.get * Fixed the risk exporters for tags containing non-ASCII characters [Valerio Poggi] diff --git a/openquake/baselib/python3compat.py b/openquake/baselib/python3compat.py index <HASH>..<HASH> 100644 --- a/openquake/baselib/python3compat.py +++ b/openquake/baselib/python3compat.py @@ -27,6 +27,13 @@ import sys import math import importlib import subprocess +try: + # Python 3 + from urllib.request import urlopen, Request +except ImportError: + # Python 2 + from urllib2 import urlopen, Request + PY3 = sys.version_info[0] >= 3 PY2 = sys.version_info[0] == 2 diff --git a/openquake/engine/engine.py b/openquake/engine/engine.py index <HASH>..<HASH> 100644 --- a/openquake/engine/engine.py +++ b/openquake/engine/engine.py @@ -22,13 +22,13 @@ calculations.""" import os import re import sys +import json import signal -import logging import traceback -import requests import platform from openquake.baselib.performance import Monitor +from openquake.baselib.python3compat import urlopen, Request, decode from openquake.baselib import ( parallel, general, config, datastore, __version__, zeromq as z) from openquake.commonlib.oqvalidation import OqParam @@ -300,19 +300,14 @@ def check_obsolete_version(calculation_mode='WebUI'): headers = {'User-Agent': 'OpenQuake Engine %s;%s;%s' % (__version__, calculation_mode, platform.platform())} try: - logger = logging.getLogger() # root logger - level = logger.level - # requests.get logs at level INFO: raising the level so that - # the log is hidden - logger.setLevel(logging.WARN) - try: - json = requests.get(OQ_API + '/engine/latest', timeout=0.5, - headers=headers).json() - finally: - logger.setLevel(level) # back as it was - tag_name = json['tag_name'] + # we are not using requests.get here because it causes a segfault + # on macOS: https://github.com/gem/oq-engine/issues/3161 + req = Request(OQ_API + '/engine/latest', headers=headers) + # NB: a timeout < 1 does not work + data = urlopen(req, timeout=1).read() # bytes + tag_name = json.loads(decode(data))['tag_name'] current = version_triple(__version__) - latest = version_triple(json['tag_name']) + latest = version_triple(tag_name) except: # page not available or wrong version tag return if current < latest:
Fixed a tricky segfault on macOS caused by a call to requests.get Former-commit-id: <I>ac<I>a<I>dcc<I>eccfeec<I>c<I>caccf<I>
gem_oq-engine
train
5bf4bac5369d415e919b745c45e08b0fb7df1838
diff --git a/revel/bugsnagrevel.go b/revel/bugsnagrevel.go index <HASH>..<HASH> 100644 --- a/revel/bugsnagrevel.go +++ b/revel/bugsnagrevel.go @@ -22,7 +22,7 @@ func Filter(c *revel.Controller, fc []revel.Filter) { } // Add support to bugsnag for reading data out of *revel.Controllers -func middleware(event *bugsnag.Event, config *bugsnag.Configuration) bool { +func middleware(event *bugsnag.Event, config *bugsnag.Configuration) error { for _, datum := range event.RawData { if controller, ok := datum.(*revel.Controller); ok { // make the request visible to the builtin HttpMIddleware @@ -32,7 +32,7 @@ func middleware(event *bugsnag.Event, config *bugsnag.Configuration) bool { } } - return true + return nil } func init() {
Fix revel with new middleware api
bugsnag_bugsnag-go
train
d9ba44ef89519e2eb4f7184a146118d839a95014
diff --git a/spring-cloud-aws-core/src/main/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProvider.java b/spring-cloud-aws-core/src/main/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProvider.java index <HASH>..<HASH> 100644 --- a/spring-cloud-aws-core/src/main/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProvider.java +++ b/spring-cloud-aws-core/src/main/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProvider.java @@ -19,27 +19,19 @@ package org.springframework.cloud.aws.core.region; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.util.EC2MetadataUtils; +import org.springframework.util.Assert; public class Ec2MetadataRegionProvider implements RegionProvider { @Override public Region getRegion() { - String availabilityZone = getAvailabilityZone(); - if (availabilityZone == null) { - throw new IllegalStateException("There is not EC2 meta data available, because the application is not running " + - "in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance"); - } - - for (Regions candidate : Regions.values()) { - if (availabilityZone.startsWith(candidate.getName())) { - return Region.getRegion(candidate); - } - } - - throw new IllegalStateException("There could be no region detected for the availability zone '" + availabilityZone + "'"); + Region currentRegion = getCurrentRegion(); + Assert.state(currentRegion != null, "There is not EC2 meta data available, because the application is not running " + + "in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance"); + return currentRegion; } - protected String getAvailabilityZone() { - return EC2MetadataUtils.getAvailabilityZone(); + protected Region getCurrentRegion() { + return Regions.getCurrentRegion(); } } \ No newline at end of file diff --git a/spring-cloud-aws-core/src/test/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProviderTest.java b/spring-cloud-aws-core/src/test/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProviderTest.java index <HASH>..<HASH> 100644 --- a/spring-cloud-aws-core/src/test/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProviderTest.java +++ b/spring-cloud-aws-core/src/test/java/org/springframework/cloud/aws/core/region/Ec2MetadataRegionProviderTest.java @@ -38,8 +38,8 @@ public class Ec2MetadataRegionProviderTest { Ec2MetadataRegionProvider regionProvider = new Ec2MetadataRegionProvider() { @Override - protected String getAvailabilityZone() { - return "eu-west-1a"; + protected Region getCurrentRegion() { + return Region.getRegion(Regions.EU_WEST_1); } }; @@ -51,26 +51,6 @@ public class Ec2MetadataRegionProviderTest { } @Test - public void getRegion_availabilityZoneWithNonMatchingRegion_throwsIllegalStateException() throws Exception { - //Arrange - this.expectedException.expect(IllegalStateException.class); - this.expectedException.expectMessage("There could be no region detected for the availability zone 'eu-east-1a'"); - - Ec2MetadataRegionProvider regionProvider = new Ec2MetadataRegionProvider() { - - @Override - protected String getAvailabilityZone() { - return "eu-east-1a"; - } - }; - - //Act - regionProvider.getRegion(); - - //Assert - } - - @Test public void getRegion_noMetadataAvailable_throwsIllegalStateException() throws Exception { //Arrange this.expectedException.expect(IllegalStateException.class); @@ -79,7 +59,7 @@ public class Ec2MetadataRegionProviderTest { Ec2MetadataRegionProvider regionProvider = new Ec2MetadataRegionProvider() { @Override - protected String getAvailabilityZone() { + protected Region getCurrentRegion() { return null; } };
User sdk support to fetch current region
spring-cloud_spring-cloud-aws
train
b62f46899f25eec797f2ce49aebd018ee660a2bc
diff --git a/src/main/java/nl/hsac/fitnesse/fixture/util/HttpClient.java b/src/main/java/nl/hsac/fitnesse/fixture/util/HttpClient.java index <HASH>..<HASH> 100755 --- a/src/main/java/nl/hsac/fitnesse/fixture/util/HttpClient.java +++ b/src/main/java/nl/hsac/fitnesse/fixture/util/HttpClient.java @@ -175,6 +175,29 @@ public class HttpClient { } } + protected HttpContext createContext(HttpResponse response) { + HttpContext localContext = new BasicHttpContext(); + CookieStore store = response.getCookieStore(); + if (store != null) { + localContext.setAttribute(HttpClientContext.COOKIE_STORE, store); + } + return localContext; + } + + protected org.apache.http.HttpResponse executeMethod(HttpContext context, HttpRequestBase method) + throws IOException { + return httpClient.execute(method, context); + } + + protected void storeResponse(HttpResponse response, org.apache.http.HttpResponse resp) throws IOException { + int returnCode = resp.getStatusLine().getStatusCode(); + response.setStatusCode(returnCode); + + addHeadersFromResponse(response.getResponseHeaders(), resp.getAllHeaders()); + + copyResponseContent(response, resp); + } + protected void addHeadersFromResponse(Map<String, Object> responseHeaders, Header[] respHeaders) { for (Header h : respHeaders) { String headerName = h.getName(); @@ -200,15 +223,6 @@ public class HttpClient { } } - protected void storeResponse(HttpResponse response, org.apache.http.HttpResponse resp) throws IOException { - int returnCode = resp.getStatusLine().getStatusCode(); - response.setStatusCode(returnCode); - - addHeadersFromResponse(response.getResponseHeaders(), resp.getAllHeaders()); - - copyResponseContent(response, resp); - } - protected void copyResponseContent(HttpResponse response, org.apache.http.HttpResponse resp) throws IOException { HttpEntity entity = resp.getEntity(); if (entity == null) { @@ -249,20 +263,6 @@ public class HttpClient { return fileName; } - protected HttpContext createContext(HttpResponse response) { - HttpContext localContext = new BasicHttpContext(); - CookieStore store = response.getCookieStore(); - if (store != null) { - localContext.setAttribute(HttpClientContext.COOKIE_STORE, store); - } - return localContext; - } - - protected org.apache.http.HttpResponse executeMethod(HttpContext context, HttpRequestBase method) - throws IOException { - return httpClient.execute(method, context); - } - protected void cleanupAfterRequest(org.apache.http.HttpResponse response, HttpRequestBase method) { method.reset(); if (response instanceof CloseableHttpResponse) {
Order methods in same sequence as called [ci skip]
fhoeben_hsac-fitnesse-fixtures
train
83d36e24d260acd13f0071db9b0bef071ecb5684
diff --git a/ext/mysql2/extconf.rb b/ext/mysql2/extconf.rb index <HASH>..<HASH> 100644 --- a/ext/mysql2/extconf.rb +++ b/ext/mysql2/extconf.rb @@ -94,14 +94,7 @@ end # This is our wishlist. We use whichever flags work on the host. # -Wall and -Wextra are included by default. -usable_flags = [ - '-fsanitize=address', - '-fsanitize=cfi', - '-fsanitize=integer', - '-fsanitize=memory', - '-fsanitize=thread', - '-fsanitize=undefined', - '-Werror', +wishlist = [ '-Weverything', '-Wno-bad-function-cast', # rb_thread_call_without_gvl returns void * that we cast to VALUE '-Wno-conditional-uninitialized', # false positive in client.c @@ -117,7 +110,21 @@ usable_flags = [ '-Wno-switch-enum', # result.c -- enum_field_types (when not fully covered, e.g. mysql 5.6+) '-Wno-undef', # rubinius :( '-Wno-used-but-marked-unused', # rubby :( -].select do |flag| +] + +if ENV['CI'] + wishlist += [ + '-Werror', + '-fsanitize=address', + '-fsanitize=cfi', + '-fsanitize=integer', + '-fsanitize=memory', + '-fsanitize=thread', + '-fsanitize=undefined', + ] +end + +usable_flags = wishlist.select do |flag| try_link('int main() {return 0;}', flag) end
move some CFLAGS to CI only
brianmario_mysql2
train
02f8709258369dc3f3dc84b6f2ce5b12fa939007
diff --git a/src/Error/Debug/ConsoleFormatter.php b/src/Error/Debug/ConsoleFormatter.php index <HASH>..<HASH> 100644 --- a/src/Error/Debug/ConsoleFormatter.php +++ b/src/Error/Debug/ConsoleFormatter.php @@ -40,9 +40,9 @@ class ConsoleFormatter implements FormatterInterface // cyan 'class' => '0;36', // grey - 'punct' => '0;8', - // black - 'property' => '0;30', + 'punct' => '0;90', + // default foreground + 'property' => '0;39', // magenta 'visibility' => '0;35', // red
Fix colours in dark terminals Don't use the black ansi code as it is hard to see in dark terminals. Instead use the foreground color which *should* be visible.
cakephp_cakephp
train
160c044908efa059cf43f4324f63fe073c2b3166
diff --git a/transport.go b/transport.go index <HASH>..<HASH> 100644 --- a/transport.go +++ b/transport.go @@ -112,8 +112,8 @@ func Activate() { if Disabled() { return } - originalTransport = http.DefaultClient.Transport - http.DefaultClient.Transport = DefaultTransport + originalTransport = http.DefaultTransport + http.DefaultTransport = DefaultTransport } // Deactivate shuts down the mock environment. Any HTTP calls made after this will use a live @@ -130,7 +130,7 @@ func Deactivate() { if Disabled() { return } - http.DefaultClient.Transport = originalTransport + http.DefaultTransport = originalTransport } // Reset will remove any registered mocks and return the mock environment to it's initial state.
Activate/Deactivate operate on http.DefaultTransport rather than http.DefaultClient.Transport
jarcoal_httpmock
train
c53067abc8658f42719eb3511ac324c52bc1235f
diff --git a/icons.js b/icons.js index <HASH>..<HASH> 100644 --- a/icons.js +++ b/icons.js @@ -16,8 +16,8 @@ export function getIcon(name, data) { let use = svg.appendChild(document.createElementNS(SVG, "use")) use.setAttributeNS(XLINK, "href", "#pm-icon-" + name) } else { - node.textContent = data.text - if (data.css) node.style.cssText = data.css + node.appendChild(document.createElement("span")).textContent = data.text + if (data.css) node.firstChild.style.cssText = data.css } return node } @@ -41,7 +41,7 @@ insertCSS(` .ProseMirror-icon { display: inline-block; line-height: .8; - vertical-align: middle; + vertical-align: -2px; /* Compensate for padding */ padding: 2px 8px; cursor: pointer; } @@ -55,4 +55,7 @@ insertCSS(` fill: currentColor; height: 1em; } + +.ProseMirror-icon span { + vertical-align: text-top; `) diff --git a/menu.js b/menu.js index <HASH>..<HASH> 100644 --- a/menu.js +++ b/menu.js @@ -341,7 +341,6 @@ insertCSS(` content: "︙"; opacity: 0.5; padding: 0 4px; - vertical-align: baseline; } .ProseMirror-select, .ProseMirror-select-menu { @@ -353,7 +352,7 @@ insertCSS(` .ProseMirror-select { padding: 1px 12px 1px 4px; display: inline-block; - vertical-align: middle; + vertical-align: 1px; position: relative; cursor: pointer; margin: 0 8px;
Slightly improve alignment of menu items
ProseMirror_prosemirror-menu
train
cd82bd3c320e21ecb258d5da90c03ad956a3e4db
diff --git a/lib/patterns.rb b/lib/patterns.rb index <HASH>..<HASH> 100644 --- a/lib/patterns.rb +++ b/lib/patterns.rb @@ -17,6 +17,7 @@ module Patterns continuation coverage delegate + digest drb e2mmap english
digest library was still standard library on Ruby <I>
rubygems_rubygems.org
train
c4be839667095948bb0aed125085dd8daf0aa3fc
diff --git a/lib/copter.js b/lib/copter.js index <HASH>..<HASH> 100644 --- a/lib/copter.js +++ b/lib/copter.js @@ -37,7 +37,6 @@ var Copter = module.exports = function Copter(driver) }; util.inherits(Copter, events.EventEmitter); - //------------------------------ // This is the public API. @@ -60,8 +59,6 @@ Copter.prototype.connect = function(uri) .done(); }; -// state transitions - Copter.prototype.takeoff = function() { // take off & hover. @@ -243,9 +240,9 @@ Copter.prototype.enterLanding = function() this.setpoint(0, 0, 0, 0); }; +// ------------------------------ // Lower-level control functions. - Copter.prototype.pulse = function() { return this.setpoint( @@ -275,7 +272,6 @@ Copter.prototype.setpoint = function(roll, pitch, yaw, thrust) return this.driver.setpoint(roll, pitch, yaw, thrust); }; - var EPSILON = 0.01; Copter.prototype.handleStabilizerTelemetry = function(data) diff --git a/lib/crazyradio.js b/lib/crazyradio.js index <HASH>..<HASH> 100644 --- a/lib/crazyradio.js +++ b/lib/crazyradio.js @@ -1,6 +1,7 @@ var _ = require('lodash'), assert = require('assert'), + domain = require('domain'), events = require('events'), usb = require('usb'), util = require('util'), @@ -264,9 +265,7 @@ Crazyradio.prototype.usbSendVendor = function(request, value, index, data) console.log(TYPE_VENDOR, request, value, index, data); return deferred.reject(err); } - // console.log('successful usbSendVendor', request); - deferred.resolve('OK'); }); @@ -318,6 +317,12 @@ Crazyradio.prototype.onReadable = function() if (ack.packet.data.length === 0) return; + /* + We inspect the packet to determinewhich channel it's addressed + to. We then handed off to be parsed further & sent along to any subscribers + to that kind of event. + */ + // console.log('got packet for port ' + ack.packet.port, 'length:', ack.packet.data.length); switch (ack.packet.port) @@ -345,18 +350,6 @@ Crazyradio.prototype.onReadable = function() default: console.log('unknown port', ack.packet.port); } - - - /* - TODO - The packet gets parsed enough that we know which channel it's addressed - to. It then gets handed off to be parsed further & sent along to any subscribers - to that kind of event. - Handler types to write: - radio acks for communication link quality reporting - telemetry handlers (toc, logging data) - parameter handlers (changing flie settings) - */ }; Crazyradio.prototype.onInputEnd = function() @@ -374,12 +367,22 @@ Crazyradio.prototype.write = function(data, timeout) var self = this, deferred = P.defer(); - this.outputStream().write(data, function(err) + var d = domain.create(); + + d.on('error', function(err) { - if (err) - deferred.reject(err); - else - deferred.resolve('OK'); + deferred.reject(err); + }); + + d.run(function() + { + self.outputStream().write(data, function(err) + { + if (err) + deferred.reject(err); + else + deferred.resolve('OK'); + }); }); return deferred.promise;
Domains in action, maybe, catching errors with the USB radio dongle going away mid-use. I'll need to reproduce this error, perhaps with a test.
ceejbot_aerogel
train
ec884235131f51c4cacdaaa86d1c7f1cdcb5bb49
diff --git a/pupa/importers/base.py b/pupa/importers/base.py index <HASH>..<HASH> 100644 --- a/pupa/importers/base.py +++ b/pupa/importers/base.py @@ -150,10 +150,23 @@ class BaseImporter(object): data_by_id = {} # hash(json): id seen_hashes = {} + # all psuedo parent ids we've seen + psuedo_ids = set() + # psuedo matches + psuedo_matches = {} + # all data items with a psuedo_id parent + psuedo_children = [] # load all json, mapped by json_id for data in dicts: json_id = data.pop('_id') + + # collect parent psuedo_ids + parent_id = data.get('parent_id', None) or '' + if parent_id.startswith('~'): + psuedo_ids.add(parent_id) + + # map duplicates (using omnihash to tell if json dicts are identical-ish) objhash = omnihash(data) if objhash not in seen_hashes: seen_hashes[objhash] = json_id @@ -161,6 +174,23 @@ class BaseImporter(object): else: self.duplicates[json_id] = seen_hashes[objhash] + # turn psuedo_ids into a tuple of dictionaries + psuedo_ids = [(ppid, get_psuedo_id(ppid)) for ppid in psuedo_ids] + + # loop over all data again, finding the psuedo ids true json id + for json_id, data in data_by_id.items(): + # check if this matches one of our ppids + for ppid, spec in psuedo_ids: + match = True + for k, v in spec.items(): + if data[k] != v: + match = False + break + if match: + if ppid in psuedo_matches: + raise Exception("multiple matches for psuedo-id " + ppid) + psuedo_matches[ppid] = json_id + # toposort the nodes so parents are imported first network = Network() in_network = set() @@ -168,6 +198,11 @@ class BaseImporter(object): for json_id, data in data_by_id.items(): parent_id = data.get('parent_id', None) + + # resolve psuedo_ids to their json id before building the network + if parent_id in psuedo_matches: + parent_id = psuedo_matches[parent_id] + network.add_node(json_id) if parent_id: # Right. There's an import dep. We need to add the edge from
pre-resolve psuedo-ids for organizations
opencivicdata_pupa
train
e0a1a42370f4f2b189e3ba8550739f7202213e8f
diff --git a/test/moment/getters_setters.js b/test/moment/getters_setters.js index <HASH>..<HASH> 100644 --- a/test/moment/getters_setters.js +++ b/test/moment/getters_setters.js @@ -217,6 +217,28 @@ exports.gettersSetters = { test.done(); }, + 'setter with multiple unit values' : function (test) { + var a = moment(); + a.set({ + year: 2011, + month: 9, + date: 12, + hours: 6, + minutes: 7, + seconds: 8, + milliseconds: 9 + }); + test.equal(a.year(), 2011, 'year'); + test.equal(a.month(), 9, 'month'); + test.equal(a.date(), 12, 'date'); + test.equal(a.day(), 3, 'day'); + test.equal(a.hours(), 6, 'hour'); + test.equal(a.minutes(), 7, 'minute'); + test.equal(a.seconds(), 8, 'second'); + test.equal(a.milliseconds(), 9, 'milliseconds'); + test.done(); + }, + 'day setter' : function (test) { test.expect(18);
Adding tests for <I>c<I>
moment_moment
train
9775e6bf23bc669018fdf2c8d28ac94e5ad6e242
diff --git a/go/cmd/vtgate/plugin_zkocctopo.go b/go/cmd/vtgate/plugin_zkocctopo.go index <HASH>..<HASH> 100644 --- a/go/cmd/vtgate/plugin_zkocctopo.go +++ b/go/cmd/vtgate/plugin_zkocctopo.go @@ -7,7 +7,6 @@ package main // Imports and register the Zookeeper TopologyServer with Zkocc Connection import ( - "github.com/youtube/vitess/go/stats" "github.com/youtube/vitess/go/vt/topo" "github.com/youtube/vitess/go/vt/zktopo" "github.com/youtube/vitess/go/zk" @@ -15,6 +14,5 @@ import ( func init() { zkoccconn := zk.NewMetaConn(true) - stats.Publish("ZkOccConn", zkoccconn) topo.RegisterServer("zkocc", zktopo.NewServer(zkoccconn)) }
Removing useless stats registration.
vitessio_vitess
train
9e9a9fd2d1d08da4c02b7ffb7b8362573ae70157
diff --git a/test/seahorse/client_plugin_methods_test.rb b/test/seahorse/client_plugin_methods_test.rb index <HASH>..<HASH> 100644 --- a/test/seahorse/client_plugin_methods_test.rb +++ b/test/seahorse/client_plugin_methods_test.rb @@ -19,6 +19,12 @@ module Seahorse Plugin1 = Class.new Plugin2 = Class.new + SingletonPlugin = Class.new(Client::Plugin) do + def self.new + @instance ||= super + end + end + def api @api ||= { 'endpoint' => 'http://endpoint:123' } end @@ -30,19 +36,9 @@ module Seahorse describe 'adding configuration' do def plugin_class - @plugin_class ||= begin - Class.new(Client::Plugin) do - - def add_configuration(config) - @config = config - end - - attr_reader :config - - def self.new - @instance ||= super - end - + @plugin_class ||= Class.new(SingletonPlugin) do + def add_configuration(config) + config.add_option(:plugin_option) end end end @@ -53,12 +49,11 @@ module Seahorse it 'tells the plugin to add configuration' do client_class.add_plugin(plugin_class) - client = client_class.new - plugin.config.must_be_same_as(client.config) + client_class.new.config.must_respond_to(:plugin_option) end - it 'calls #add_configuration only if the plugin responds' do - plugin = Object.new # does not respond to #add_configuration + it 'calls plugin#add_configuration only if the plugin responds' do + plugin = Object.new client_class.add_plugin(plugin) client_class.new end
Cleaned up Plugin#add_configuration tests.
aws_aws-sdk-ruby
train
92ca3c0e4ee0e45a2705899ba76f19b053fe2de0
diff --git a/lib/heroku/plugin.rb b/lib/heroku/plugin.rb index <HASH>..<HASH> 100644 --- a/lib/heroku/plugin.rb +++ b/lib/heroku/plugin.rb @@ -10,6 +10,7 @@ module Heroku DEPRECATED_PLUGINS = %w( heroku-cedar heroku-certs + heroku-credentials heroku-kill heroku-labs heroku-logging
add heroku-credentials to deprecated plugins was previously used by vulcan for auth:token like capabilities see also #<I>
heroku_legacy-cli
train
ce14726f2fceb86b65f064c59ff5110407b66924
diff --git a/isso/db/comments.py b/isso/db/comments.py index <HASH>..<HASH> 100644 --- a/isso/db/comments.py +++ b/isso/db/comments.py @@ -37,6 +37,12 @@ class Comments: Add new comment to DB and return a mapping of :attribute:`fields` and database values. """ + + if "parent" in c: + rv = self.db.execute("SELECT parent FROM comments WHERE id=?", (c.get('parent'), )).fetchone() + if rv and rv[0] is not None: + c["parent"] = None + self.db.execute([ 'INSERT INTO comments (', ' tid, parent,'
set parent to null if parent is not top-level comment
posativ_isso
train
295a5c571bc1482bb5b0107f535956beb8a6ab42
diff --git a/mini.py b/mini.py index <HASH>..<HASH> 100644 --- a/mini.py +++ b/mini.py @@ -2,7 +2,8 @@ import urllib2 import json from conf import Google_API_KEY -def google(url): +# This will minify url using google url minifier and return minified url +def google_mini(url): post_url = 'https://www.googleapis.com/urlshortener/v1/url?key='+Google_API_KEY postdata = {'longUrl':url} headers = {'Content-Type':'application/json'} @@ -13,3 +14,13 @@ def google(url): ) ret = urllib2.urlopen(req).read() return json.loads(ret)['id'] + + +# This will stats of the minified url using google url shortner +def google_stat(min_url) + pass + + +# This will minify url using bily +def bitly_mini(url) + pass
change of names and planned bitly usage
MicroPyramid_microurl
train
fa7565d295f2abd3fd5b9ecd32e5484392d62f83
diff --git a/docs/source/conf.py b/docs/source/conf.py index <HASH>..<HASH> 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -27,7 +27,7 @@ author = "The Font Bakery Authors" # The short X.Y version version = "0.7" # The full version, including alpha/beta/rc tags -release = "0.7.2" +release = "0.7.3" # -- General configuration ---------------------------------------------------
update version on docs/source/conf.py
googlefonts_fontbakery
train
51c176576ead100139d8abfdbfa9da4f04b8f9f0
diff --git a/bfg9000/iterutils.py b/bfg9000/iterutils.py index <HASH>..<HASH> 100644 --- a/bfg9000/iterutils.py +++ b/bfg9000/iterutils.py @@ -6,7 +6,7 @@ __all__ = ['default_sentinel', 'first', 'isiterable', 'iterate', 'listify', 'merge_dicts', 'merge_into_dict', 'reverse_enumerate', 'tween', 'uniques', 'unlistify'] -# XXX: This could go in a funcutils module if we ever create one... +# This could go in a funcutils module if we ever create one... default_sentinel = object() diff --git a/bfg9000/tools/cc.py b/bfg9000/tools/cc.py index <HASH>..<HASH> 100644 --- a/bfg9000/tools/cc.py +++ b/bfg9000/tools/cc.py @@ -443,7 +443,6 @@ class CcLinker(BuildCommand): return [] def _entry_point(self, entry_point): - # This only applies to GCJ. XXX: Move GCJ-stuff to a separate class? if self.lang == 'java' and entry_point: return ['--main={}'.format(entry_point)] return []
Update some more XXX comments
jimporter_bfg9000
train
b74ab93b4b31f4115d1c9112b13b91ed23bbae79
diff --git a/autopep8.py b/autopep8.py index <HASH>..<HASH> 100755 --- a/autopep8.py +++ b/autopep8.py @@ -462,17 +462,14 @@ class FixPEP8(object): original = self.source[line_index] fixed = original - for symbol in ['(', '[', '{']: - if symbol in logical_lines[0]: - fixed = logical_lines[0].find(symbol) * ' ' + original.lstrip() - - if fixed != original: - pass - elif logical_lines[0].rstrip().endswith('\\'): + if logical_lines[0].rstrip().endswith('\\'): fixed = (_get_indentation(logical_lines[0]) + self.indent_word + original.lstrip()) else: - return [] + for symbol in ['(', '[', '{']: + if symbol in logical_lines[0]: + fixed = logical_lines[0].find(symbol) * ' ' + original.lstrip() + break if fixed == original: return [] diff --git a/test/test_autopep8.py b/test/test_autopep8.py index <HASH>..<HASH> 100644 --- a/test/test_autopep8.py +++ b/test/test_autopep8.py @@ -771,6 +771,24 @@ def draw(self): self._inner_setup(line) self.assertEqual(self.result, fixed) + def test_e127_with_backslash(self): + line = r""" +if True: + if True: + self.date = meta.session.query(schedule.Appointment)\ + .filter(schedule.Appointment.id == + appointment_id).one().agenda.endtime +""".lstrip() + fixed = r""" +if True: + if True: + self.date = meta.session.query(schedule.Appointment)\ + .filter(schedule.Appointment.id == + appointment_id).one().agenda.endtime +""".lstrip() + self._inner_setup(line) + self.assertEqual(self.result, fixed) + def test_e12_with_backslash(self): line = r""" if True:
Handle backslash case first for E<I>
hhatto_autopep8
train
ec6e99f7f16a3cc6d2923f1f3e2057b197cba9ab
diff --git a/framework/src/play-test/src/main/java/play/test/Helpers.java b/framework/src/play-test/src/main/java/play/test/Helpers.java index <HASH>..<HASH> 100644 --- a/framework/src/play-test/src/main/java/play/test/Helpers.java +++ b/framework/src/play-test/src/main/java/play/test/Helpers.java @@ -108,7 +108,14 @@ public class Helpers implements play.mvc.Http.Status, play.mvc.Http.HeaderNames * Constructs a in-memory (h2) database configuration to add to a FakeApplication. */ public static Map<String,String> inMemoryDatabase() { - return inMemoryDatabase("default", Collections.<String, String>emptyMap()); + return inMemoryDatabase("default"); + } + + /** + * Constructs a in-memory (h2) database configuration to add to a FakeApplication. + */ + public static Map<String,String> inMemoryDatabase(String name) { + return inMemoryDatabase(name, Collections.<String, String>emptyMap()); } /**
Don't delete play.test.Helpers.inMemoryDatabase(String name) for backwards compatibility.
playframework_playframework
train
e9e67a402bb680b15b9d6c20188c74c66a2db82e
diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java index <HASH>..<HASH> 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java @@ -381,7 +381,7 @@ public class WatchConnectionManager<T extends HasMetadata, L extends KubernetesR if (exponentOfTwo > maxIntervalExponent) exponentOfTwo = maxIntervalExponent; long ret = reconnectInterval * (1 << exponentOfTwo); - logger.info("Current reconnect backoff is " + ret + " milliseconds (T" + exponentOfTwo + ")"); + logger.debug("Current reconnect backoff is " + ret + " milliseconds (T" + exponentOfTwo + ")"); return ret; } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java index <HASH>..<HASH> 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java @@ -311,7 +311,7 @@ public class WatchHTTPManager<T extends HasMetadata, L extends KubernetesResourc if (exponentOfTwo > maxIntervalExponent) exponentOfTwo = maxIntervalExponent; long ret = reconnectInterval * (1 << exponentOfTwo); - logger.info("Current reconnect backoff is " + ret + " milliseconds (T" + exponentOfTwo + ")"); + logger.debug("Current reconnect backoff is " + ret + " milliseconds (T" + exponentOfTwo + ")"); return ret; }
chore: Switch reconnect backoff message in wach manager to debug level info level seems to be inappropriate for this internal processing message as this regularly happens and does not really add much information, looks more like random noise. Its valuable for debugging though, so I suggest to move this from "info" to "debug" level.
fabric8io_kubernetes-client
train
3fec0f8abd5329425eaf232523b85c3b65ac5ac0
diff --git a/djfrontend/templatetags/djfrontend.py b/djfrontend/templatetags/djfrontend.py index <HASH>..<HASH> 100644 --- a/djfrontend/templatetags/djfrontend.py +++ b/djfrontend/templatetags/djfrontend.py @@ -261,8 +261,10 @@ def djfrontend_twbs_css(version=None): Returns Twitter Bootstrap CSS file. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ - if version is None: - version = getattr(settings, 'DJFRONTEND_TWBS_CSS', '3.0.3') + if version is None and getattr(settings, 'DJFRONTEND_TWBS_CSS', False) is False: + version = getattr(settings, 'DJFRONTEND_TWBS', '3.0.3') + else: + version = getattr(settings, 'DJFRONTEND_TWBS_CSS', '3.0.3') if getattr(settings, 'TEMPLATE_DEBUG', False): return '<link rel="stylesheet" href="%sdjfrontend/css/twbs/%s/bootstrap.css">' % (settings.STATIC_URL, version) @@ -278,8 +280,10 @@ def djfrontend_twbs_theme_css(version=None): """ Returns Twitter Bootstrap Theme CSS file. """ - if version is None: - version = getattr(settings, 'DJFRONTEND_TWBS_THEME_CSS', '3.0.3') + if version is None and getattr(settings, 'DJFRONTEND_TWBS_THEME_CSS', False) is False: + version = getattr(settings, 'DJFRONTEND_TWBS', '3.0.3') + else: + version = getattr(settings, 'DJFRONTEND_TWBS_THEME_CSS', '3.0.3') if getattr(settings, 'TEMPLATE_DEBUG', False): return '<link rel="stylesheet" href="%sdjfrontend/css/twbs/%s/bootstrap-theme.css">' % (settings.STATIC_URL, version) @@ -312,8 +316,10 @@ def djfrontend_twbs_js(version=None, files='all'): Individual files are not minified. """ - if version is None: - version = getattr(settings, 'DJFRONTEND_TWBS_JS', '3.0.3') + if version is None and getattr(settings, 'DJFRONTEND_TWBS_JS', False) is False: + version = getattr(settings, 'DJFRONTEND_TWBS', '3.0.3') + else: + version = getattr(settings, 'DJFRONTEND_TWBS_JS', '3.0.3') if files is 'all': files = getattr(settings, 'DJFRONTEND_TWBS_JS', 'all')
DJFRONTEND_TWBS setting.
jonfaustman_django-frontend
train
ea53420924198686847228b84d709cb481529a3a
diff --git a/ryu/ofproto/ofproto_v1_2.py b/ryu/ofproto/ofproto_v1_2.py index <HASH>..<HASH> 100644 --- a/ryu/ofproto/ofproto_v1_2.py +++ b/ryu/ofproto/ofproto_v1_2.py @@ -406,6 +406,11 @@ OFPGT_INDIRECT = 2 # Indirect group. OFPGT_FF = 3 # Fast failover group. # struct ofp_bucket +OFP_BUCKET_PACK_STR = '!HHII4x' +OFP_BUCKET_SIZE = 16 +assert calcsize(OFP_BUCKET_PACK_STR) == OFP_BUCKET_SIZE + +# struct ofp_port_mod OFP_PORT_MOD_PACK_STR = '!I4x' + OFP_ETH_ALEN_STR + 's' + '2xIII4x' OFP_PORT_MOD_SIZE = 40 assert calcsize(OFP_PORT_MOD_PACK_STR) + OFP_HEADER_SIZE == OFP_PORT_MOD_SIZE
of<I>: add missing struct ofp_bucket definition
osrg_ryu
train
723f884aef2e17b6544062c728e5a7cac68b06f7
diff --git a/src/Message/AbstractRequest.php b/src/Message/AbstractRequest.php index <HASH>..<HASH> 100644 --- a/src/Message/AbstractRequest.php +++ b/src/Message/AbstractRequest.php @@ -269,14 +269,24 @@ abstract class AbstractRequest extends BaseAbstractRequest return $this->setParameter('taxExempt', (bool) $value); } - public function getUsePaymentMethodToken() + public function getPaymentMethodToken() { - return $this->getParameter('usePaymentMethodToken'); + return $this->getParameter('paymentMethodToken'); } - public function setUsePaymentMethodToken($value) + public function setPaymentMethodToken($value) { - return $this->setParameter('usePaymentMethodToken', (bool)$value); + return $this->setParameter('paymentMethodToken', $value); + } + + public function getPaymentMethodNonce() + { + return $this->getToken(); + } + + public function setPaymentMethodNonce($value) + { + return $this->setToken($value); } /** diff --git a/src/Message/AuthorizeRequest.php b/src/Message/AuthorizeRequest.php index <HASH>..<HASH> 100644 --- a/src/Message/AuthorizeRequest.php +++ b/src/Message/AuthorizeRequest.php @@ -1,6 +1,7 @@ <?php namespace Omnipay\Braintree\Message; +use Omnipay\Common\Exception\InvalidRequestException; use Omnipay\Common\Message\ResponseInterface; /** @@ -12,7 +13,7 @@ class AuthorizeRequest extends AbstractRequest { public function getData() { - $this->validate('amount', 'token'); + $this->validate('amount'); $data = [ 'amount' => $this->getAmount(), @@ -40,10 +41,13 @@ class AuthorizeRequest extends AbstractRequest 'taxExempt' => $this->getTaxExempt(), ]; - if ($this->getUsePaymentMethodToken() === true) { - $data['paymentMethodToken'] = $this->getToken(); - } else { + // special validation + if ($this->getPaymentMethodToken()) { + $data['paymentMethodToken'] = $this->getPaymentMethodToken(); + } elseif($this->getToken()) { $data['paymentMethodNonce'] = $this->getToken(); + } else { + throw new InvalidRequestException("The token (payment nonce) or paymentMethodToken field should be set."); } // Remove null values diff --git a/tests/Message/AuthorizeRequestTest.php b/tests/Message/AuthorizeRequestTest.php index <HASH>..<HASH> 100644 --- a/tests/Message/AuthorizeRequestTest.php +++ b/tests/Message/AuthorizeRequestTest.php @@ -51,12 +51,11 @@ class AuthorizeRequestTest extends TestCase $this->assertSame('production', \Braintree_Configuration::environment()); } - public function testPaymentToken() + public function testPaymentMethodToken() { $this->request->initialize( array( 'amount' => '10.00', - 'token' => 'abc123', 'transactionId' => '684', 'testMode' => false, 'taxExempt' => false, @@ -64,15 +63,36 @@ class AuthorizeRequestTest extends TestCase 'firstName' => 'Kayla', 'shippingCompany' => 'League', ], - 'usePaymentMethodToken' => true + 'paymentMethodToken' => 'fake-token-123' ) ); $data = $this->request->getData(); - $this->assertSame('abc123', $data['paymentMethodToken']); + $this->assertSame('fake-token-123', $data['paymentMethodToken']); $this->assertArrayNotHasKey('paymentMethodNonce', $data); } + public function testPaymentMethodNonce() + { + $this->request->initialize( + array( + 'amount' => '10.00', + 'transactionId' => '684', + 'testMode' => false, + 'taxExempt' => false, + 'card' => [ + 'firstName' => 'Kayla', + 'shippingCompany' => 'League', + ], + 'paymentMethodNonce' => 'abc123' + ) + ); + + $data = $this->request->getData(); + $this->assertSame('abc123', $data['paymentMethodNonce']); + $this->assertArrayNotHasKey('paymentMethodToken', $data); + } + public function testSandboxEnvironment() { $this->request->setTestMode(true);
expose another method paymentMethodToken instead of using `usePaymentMethodToken`
thephpleague_omnipay-braintree
train
62286781446a0252eb3c35ae63019d12c6de4a3f
diff --git a/external/elasticsearch/src/main/java/com/digitalpebble/storm/crawler/elasticsearch/persistence/StatusUpdaterBolt.java b/external/elasticsearch/src/main/java/com/digitalpebble/storm/crawler/elasticsearch/persistence/StatusUpdaterBolt.java index <HASH>..<HASH> 100644 --- a/external/elasticsearch/src/main/java/com/digitalpebble/storm/crawler/elasticsearch/persistence/StatusUpdaterBolt.java +++ b/external/elasticsearch/src/main/java/com/digitalpebble/storm/crawler/elasticsearch/persistence/StatusUpdaterBolt.java @@ -43,6 +43,7 @@ import com.digitalpebble.storm.crawler.persistence.Status; import com.digitalpebble.storm.crawler.util.ConfUtils; import com.digitalpebble.storm.crawler.util.URLPartitioner; +import backtype.storm.metric.api.IMetric; import backtype.storm.metric.api.MultiCountMetric; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; @@ -107,6 +108,14 @@ public class StatusUpdaterBolt extends AbstractStatusUpdaterBolt { StatusUpdaterBolt.ESStatusRoutingFieldParamName); } + // create gauge for waitAck + context.registerMetric("waitAck", new IMetric() { + @Override + public Object getValueAndReset() { + return waitAck.size(); + } + }, 30); + /** Custom listener so that we can control the bulk responses **/ BulkProcessor.Listener listener = new BulkProcessor.Listener() { @Override
ES Status updater reports metric for size of waitAck buffer
DigitalPebble_storm-crawler
train
b500f183c8c22eb15f0a7a81a3d6b49f39984524
diff --git a/pyensembl/__init__.py b/pyensembl/__init__.py index <HASH>..<HASH> 100644 --- a/pyensembl/__init__.py +++ b/pyensembl/__init__.py @@ -41,7 +41,7 @@ from .species import ( ) from .transcript import Transcript -__version__ = '1.4.1' +__version__ = '1.4.2' __all__ = [ "MemoryCache", diff --git a/pyensembl/shell.py b/pyensembl/shell.py index <HASH>..<HASH> 100755 --- a/pyensembl/shell.py +++ b/pyensembl/shell.py @@ -48,6 +48,7 @@ import argparse import logging import logging.config import pkg_resources +import os from .ensembl_release import EnsemblRelease from .genome import Genome @@ -177,7 +178,11 @@ def run(): if args.action == "list": genomes = collect_all_install_ensembl_releases() for genome in genomes: - print("-- %s" % genome) + # print every directory in which downloaded files are located + # in most case this will be only one directory + filepaths = genome.required_local_files() + directories = {os.path.split(path)[0] for path in filepaths} + print("-- %s: %s" % (genome, ", ".join(directories))) else: genomes = collect_selected_genomes(args)
List dirs in cli (#<I>) * add directories to pyensembl list * version bump
openvax_pyensembl
train