hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
3d30b4be1d0d86d07bb9854f90c13756e895a55b
diff --git a/test/extended/prometheus/prometheus.go b/test/extended/prometheus/prometheus.go index <HASH>..<HASH> 100644 --- a/test/extended/prometheus/prometheus.go +++ b/test/extended/prometheus/prometheus.go @@ -217,17 +217,6 @@ var _ = g.Describe("[Feature:Prometheus][Conformance] Prometheus", func() { } runQueries(tests, oc, ns, execPodName, url, bearerToken) }) - g.It("should have machine api operator metrics", func() { - oc.SetupProject() - ns := oc.Namespace() - execPodName := e2e.CreateExecPodOrFail(oc.AdminKubeClient(), ns, "execpod", func(pod *v1.Pod) { pod.Spec.Containers[0].Image = "centos:7" }) - defer func() { oc.AdminKubeClient().CoreV1().Pods(ns).Delete(execPodName, metav1.NewDeleteOptions(1)) }() - - tests := map[string][]metricTest{ - `mapi_machine_set_status_replicas`: {metricTest{greaterThanEqual: true, value: 1}}, - } - runQueries(tests, oc, ns, execPodName, url, bearerToken) - }) g.It("should provide ingress metrics", func() { oc.SetupProject() ns := oc.Namespace()
test/extended/prometheus: Remove machine api operator metrics test This test was failing because machine-api-operator component is not installed everywhere, so we often see this test failing. We will remove it for now, and rethink the test in a future PR.
openshift_origin
train
7c8a893ea2dd6771da13428ce8bd3bd80bb8453d
diff --git a/ths.go b/ths.go index <HASH>..<HASH> 100644 --- a/ths.go +++ b/ths.go @@ -11,8 +11,8 @@ const ( ManualTHS = "M" // SimulatorTHS simulated THS heading SimulatorTHS = "S" - // NotValidTHS not valid THS heading (or standby) - NotValidTHS = "V" + // InvalidTHS not valid THS heading (or standby) + InvalidTHS = "V" ) // THS is the Actual vessel heading in degrees True with status. @@ -30,7 +30,7 @@ func newTHS(s BaseSentence) (THS, error) { m := THS{ BaseSentence: s, Heading: p.Float64(0, "heading"), - Status: p.EnumString(1, "status", AutonomousTHS, EstimatedTHS, ManualTHS, SimulatorTHS, NotValidTHS), + Status: p.EnumString(1, "status", AutonomousTHS, EstimatedTHS, ManualTHS, SimulatorTHS, InvalidTHS), } return m, p.Err() } diff --git a/ths_test.go b/ths_test.go index <HASH>..<HASH> 100644 --- a/ths_test.go +++ b/ths_test.go @@ -45,11 +45,11 @@ var thstests = []struct { }, }, { - name: "good sentence NotValidTHS", + name: "good sentence InvalidTHS", raw: "$INTHS,,V*1E", msg: THS{ Heading: 0.0, - Status: NotValidTHS, + Status: InvalidTHS, }, }, {
Renamed NotValidTHS to InvalidTHS
adrianmo_go-nmea
train
d712ee2163bd98105a83be81350863b9dfc49337
diff --git a/lib/cube_solver/cube.rb b/lib/cube_solver/cube.rb index <HASH>..<HASH> 100644 --- a/lib/cube_solver/cube.rb +++ b/lib/cube_solver/cube.rb @@ -48,6 +48,14 @@ module CubeSolver state == SOLVED_STATE.join(' ') end + def edge_solved?(edge) + cubie_solved? :edges, edge + end + + def corner_solved?(corner) + cubie_solved? :corners, corner + end + def has_edges_solved? unsolved_edge_locations.empty? end @@ -112,6 +120,10 @@ module CubeSolver state.split.map { |state| CubeSolver::Cubie.new state } end + def cubie_solved?(type, cubie) + send(type).index(cubie) == location_for(cubie) + end + def unsolved_locations_for(type) send(type).each_with_index.map do |cubie, location| location == location_for(cubie) ? nil : location diff --git a/spec/cube_solver/cube_spec.rb b/spec/cube_solver/cube_spec.rb index <HASH>..<HASH> 100644 --- a/spec/cube_solver/cube_spec.rb +++ b/spec/cube_solver/cube_spec.rb @@ -107,6 +107,30 @@ describe CubeSolver::Cube do end end + describe '#edge_solved?' do + it 'returns true when the cubie is solved' do + subject.u + + solved_edge = subject.edges[4] + unsolved_edge = subject.edges[0] + + expect(subject.edge_solved? unsolved_edge).to be_false + expect(subject.edge_solved? solved_edge).to be_true + end + end + + describe '#corner_solved?' do + it 'returns true when the cubie is solved' do + subject.f + + solved_corner = subject.corners[2] + unsolved_corner = subject.corners[1] + + expect(subject.corner_solved? unsolved_corner).to be_false + expect(subject.corner_solved? solved_corner).to be_true + end + end + describe '#has_edges_solved?' do context 'when the edges are solved, but corners are not' do let(:state) {
Add Cube{edge,corner}_solved? for checking cubies
chrishunt_rubiks-cube
train
8f5f6f3d0c2744252629fd006a3dbe54209feb63
diff --git a/src/ElasticSearch/Client.php b/src/ElasticSearch/Client.php index <HASH>..<HASH> 100644 --- a/src/ElasticSearch/Client.php +++ b/src/ElasticSearch/Client.php @@ -191,9 +191,9 @@ class Client { * @param array $document */ public function search($query) { - $start = $this->getMicroTime(); + $start = microtime(true); $result = $this->transport->search($query); - $result['time'] = $this->getMicroTime() - $start; + $result['time'] = microtime(true) - $start; return $result; } @@ -229,11 +229,6 @@ class Client { return $this->request('_refresh', "POST"); } - private function getMicroTime() { - list($usec, $sec) = explode(" ", microtime()); - return ((float)$usec + (float)$sec); - } - protected static function parseDsn($dsn) { $parts = parse_url($dsn); $protocol = $parts['scheme'];
Client::getMicroTime() replaced with microtime() In php <I> microtime() function started support returnig float value.
nervetattoo_elasticsearch
train
b6dd66d8f1d91ed532c35f4696801746fcd0b764
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleService.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleService.java index <HASH>..<HASH> 100644 --- a/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleService.java +++ b/sonar-server/src/main/java/org/sonar/server/qualityprofile/ActiveRuleService.java @@ -87,13 +87,11 @@ public class ActiveRuleService implements ServerComponent { verifyParam(ruleParamDto, value); change.setParameter(ruleParamDto.getName(), StringUtils.defaultIfEmpty(value, ruleParamDto.getDefaultValue())); } - changes.add(change); + // TODO filter changes without any differences + persist(changes, context, dbSession); - dbSession.commit(); - previewCache.reportGlobalModification(); - // TODO filter changes without any differences return changes; } finally { @@ -141,6 +139,10 @@ public class ActiveRuleService implements ServerComponent { } } } + if (!changes.isEmpty()) { + dbSession.commit(); + previewCache.reportGlobalModification(); + } } /** @@ -161,8 +163,6 @@ public class ActiveRuleService implements ServerComponent { change = new ActiveRuleChange(ActiveRuleChange.Type.DEACTIVATED, key); changes.add(change); persist(changes, context, dbSession); - dbSession.commit(); - previewCache.reportGlobalModification(); return changes; } finally {
SONAR-<I> flush previewDb cache when a rule is deactivated
SonarSource_sonarqube
train
e1ec5e7ae8f19ad2db2a4e4b3aa2727b789eeeec
diff --git a/client/my-sites/domains/domain-management/list/test/index.js b/client/my-sites/domains/domain-management/list/test/index.js index <HASH>..<HASH> 100644 --- a/client/my-sites/domains/domain-management/list/test/index.js +++ b/client/my-sites/domains/domain-management/list/test/index.js @@ -7,8 +7,8 @@ import { getEmptyResponseCart, createShoppingCartManagerClient, } from '@automattic/shopping-cart'; +import { render, screen } from '@testing-library/react'; import deepFreeze from 'deep-freeze'; -import { shallow, mount } from 'enzyme'; import { Provider as ReduxProvider } from 'react-redux'; import { createReduxStore } from 'calypso/state'; import { SiteDomains } from '../site-domains'; @@ -21,6 +21,10 @@ jest.mock( 'calypso/lib/wp', () => ( { }, } ) ); +jest.mock( 'calypso/my-sites/domains/domain-management/list/domain-row', () => () => ( + <div data-testid="domain-row" /> +) ); + const emptyResponseCart = getEmptyResponseCart(); function getCart() { @@ -45,8 +49,6 @@ function TestProvider( { store, cartManagerClient, children } ) { } describe( 'index', () => { - let component; - const selectedSite = deepFreeze( { slug: 'example.com', ID: 1, @@ -77,44 +79,42 @@ describe( 'index', () => { translate: ( string ) => string, } ); - function renderWithProps( props = defaultProps ) { - const store = createReduxStore( - { - purchases: {}, - ui: { - selectedSiteId: 1, - section: 'section', - }, - documentHead: {}, - sites: { - plans: [], - domains: { - items: [], + describe( 'regular cases', () => { + test( 'should list two domains', () => { + const store = createReduxStore( + { + purchases: {}, + ui: { + selectedSiteId: 1, + section: 'section', }, + documentHead: {}, + sites: { + plans: [], + domains: { + items: [], + }, + }, + currentUser: { + capabilities: {}, + }, + productsList: {}, }, - currentUser: { - capabilities: {}, - }, - productsList: {}, - }, - ( state ) => { - return state; - } - ); - const cartManagerClient = createShoppingCartManagerClient( { getCart, setCart } ); - return mount( <SiteDomains { ...props } />, { - wrappingComponent: TestProvider, - wrappingComponentProps: { store, cartManagerClient }, - } ); - } - - describe( 'regular cases', () => { - beforeEach( () => { - component = renderWithProps(); - } ); + ( state ) => { + return state; + } + ); + const cartManagerClient = createShoppingCartManagerClient( { getCart, setCart } ); + + render( <SiteDomains { ...defaultProps } />, { + wrapper: ( { children } ) => ( + <TestProvider store={ store } cartManagerClient={ cartManagerClient }> + { children } + </TestProvider> + ), + } ); - test( 'should list two domains', () => { - expect( component.find( 'DomainRow' ) ).toHaveLength( 2 ); + expect( screen.getAllByTestId( 'domain-row' ) ).toHaveLength( 2 ); } ); } ); @@ -125,9 +125,9 @@ describe( 'index', () => { userCanManageOptions: false, } ); - const wrapper = shallow( <SiteDomains { ...props } /> ); + render( <SiteDomains { ...props } /> ); - expect( wrapper.find( 'EmptyContent' ) ).toHaveLength( 1 ); + expect( screen.queryByText( /not authorized to view this page/i ) ).toBeInTheDocument(); } ); } ); } );
`SiteDomains`: refactor tests to `@testing-library/react` (#<I>) * `SiteDomains`: refactor tests to `@testing-library/react` * inline test-specific setup
Automattic_wp-calypso
train
77c304c0e96330e69206816c3902d489e64b3239
diff --git a/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/AppClassLoader.java b/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/AppClassLoader.java index <HASH>..<HASH> 100644 --- a/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/AppClassLoader.java +++ b/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/AppClassLoader.java @@ -685,12 +685,24 @@ public class AppClassLoader extends ContainerClassLoader implements SpringLoader sb.append(type).append(" "); } sb.append(LS); - + + sb.append(" ClassPath: ").append(LS); + for (Collection<URL> containerURLs : getClassPath()) { + sb.append(" * "); + for (URL url : containerURLs) { + sb.append(url.toString()).append(" | "); + } + sb.append(LS); + } + sb.append(LS); + sb.append(" CodeSources: "); for (Map.Entry<String, ProtectionDomain> entry : protectionDomains.entrySet()) { sb.append(LS).append(" ").append(entry.getKey()).append(" = ") .append(entry.getValue().getCodeSource().getLocation()); } + sb.append(LS); + return sb.toString(); } } \ No newline at end of file diff --git a/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/ContainerClassLoader.java b/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/ContainerClassLoader.java index <HASH>..<HASH> 100644 --- a/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/ContainerClassLoader.java +++ b/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/ContainerClassLoader.java @@ -198,6 +198,15 @@ abstract class ContainerClassLoader extends IdentifiedLoader { * Map is keyed by the hashcode of the package string. */ void updatePackageMap(Map<Integer, List<UniversalContainer>> map); + + /** + * Returns a collection of URLs represented by the underlying + * Container or ArtifactContainer. Depending on the instance of + * this UniversalContainer, this will return either + * <code>Container.getURLs()</code> or + * <code>ArtifactContainer.getURLs()</code>. + */ + Collection<URL> getContainerURLs(); } /** @@ -455,6 +464,11 @@ abstract class ContainerClassLoader extends IdentifiedLoader { } @Override + public Collection<URL> getContainerURLs() { + return container == null ? null : container.getURLs(); + } + + @Override public String toString() { if (debugString == null) { String physicalPath = this.container.getPhysicalPath(); @@ -616,6 +630,11 @@ abstract class ContainerClassLoader extends IdentifiedLoader { } processContainer(container, map, chop); } + + @Override + public Collection<URL> getContainerURLs() { + return container == null ? null : container.getURLs(); + } } private static class ArtifactContainerUniversalResource implements UniversalContainer.UniversalResource { @@ -668,6 +687,8 @@ abstract class ContainerClassLoader extends IdentifiedLoader { Collection<URL> getResourceURLs(String path, String jarProtocol); boolean containsContainer(Container container); + + Collection<Collection<URL>> getClassPath(); } /** @@ -1065,6 +1086,15 @@ abstract class ContainerClassLoader extends IdentifiedLoader { public boolean containsContainer(Container container) { return containers.contains(container); } + + @Override + public Collection<Collection<URL>> getClassPath() { + List<Collection<URL>> containerURLs = new ArrayList<>(); + for (UniversalContainer uc : classPath) { + containerURLs.add(uc.getContainerURLs()); + } + return containerURLs; + } } /** @@ -1141,6 +1171,11 @@ abstract class ContainerClassLoader extends IdentifiedLoader { public boolean containsContainer(Container container) { return delegate.containsContainer(container); } + + @Override + public Collection<Collection<URL>> getClassPath() { + return delegate.getClassPath(); + } } /** @@ -1796,4 +1831,8 @@ abstract class ContainerClassLoader extends IdentifiedLoader { } } } + + Collection<Collection<URL>> getClassPath() { + return smartClassPath.getClassPath(); + } }
Include classpath URLs in ClassLoadingService dump introspector
OpenLiberty_open-liberty
train
55445cd456822bf4941ed93e31e5aa3e522e5b86
diff --git a/src/Everon/Config/ExpressionMatcher.php b/src/Everon/Config/ExpressionMatcher.php index <HASH>..<HASH> 100644 --- a/src/Everon/Config/ExpressionMatcher.php +++ b/src/Everon/Config/ExpressionMatcher.php @@ -68,9 +68,9 @@ class ExpressionMatcher implements Interfaces\ExpressionMatcher $this->values[$item] = $data[$config_section][$config_section_variable]; } - if (empty($this->values)) { //todo fix this madness - foreach ($configs_data as $name => $items) { //remove inheritance info from section names in order to prepare values, eg. 'myitem < default' - foreach ($items as $section_name => $section_items) { + foreach ($configs_data as $name => $items) { //remove inheritance info from section names in order to prepare values, eg. 'myitem < default' + foreach ($items as $section_name => $section_items) { + if (strpos($section_name, '<') !== false) { $tokens = explode('<', $section_name); if (count($tokens) === 2) { $new_section_name = trim($tokens[0]); @@ -79,12 +79,12 @@ class ExpressionMatcher implements Interfaces\ExpressionMatcher } } } - - $this->values = $this->arrayDotKeysFlattern($configs_data); - $this->values = $this->arrayDotKeysFlattern($this->values); - $this->values = $this->arrayDotKeysFlattern($this->values); - $this->values = $this->arrayPrefixKey('%', $this->values, '%'); } + + $this->values = $this->arrayDotKeysFlattern($configs_data); + $this->values = $this->arrayDotKeysFlattern($this->values); + $this->values = $this->arrayDotKeysFlattern($this->values); + $this->values = $this->arrayPrefixKey('%', $this->values, '%'); //compile to update self references, eg. //'%application.assets.themes%' => string (34) "%application.env.url_statc%themes/" @@ -110,7 +110,6 @@ class ExpressionMatcher implements Interfaces\ExpressionMatcher array_walk_recursive($config_data, $SetExpressions); } - $this->expressions = array_keys($this->expressions); $this->expressions = array_merge($this->expressions, $custom_expressions); } } \ No newline at end of file diff --git a/src/Everon/View/Manager.php b/src/Everon/View/Manager.php index <HASH>..<HASH> 100644 --- a/src/Everon/View/Manager.php +++ b/src/Everon/View/Manager.php @@ -112,10 +112,14 @@ class Manager implements Interfaces\Manager $TemplateDirectory = new \SplFileInfo($template_directory); $Layout = $this->createView($name, $TemplateDirectory->getPathname().DIRECTORY_SEPARATOR, $namespace); - $view_data = $this->getConfigManager()->getConfigValue('view.'.$Layout->getName(), []); + $view_data = $this->getConfigManager()->getConfigValue('view.'.$Layout->getName(), null); + if ($view_data === null) { + throw new Exception\ConfigItem('Undefined view data for: "%s"', $name); + } + $IndexTemplate = $Layout->getTemplate('index', $view_data); if ($IndexTemplate === null) { - throw new Exception\Factory('Invalid index template for layout: "%s"', $name); + throw new Exception\ViewManager('Invalid index template for layout: "%s"', $name); } $Layout->setContainer($IndexTemplate); @@ -125,7 +129,7 @@ class Manager implements Interfaces\Manager try { $Layout = $makeLayout($name); } - catch (Exception\Factory $e) { + catch (Exception $e) { $Layout = $makeLayout($default_view); } @@ -298,7 +302,6 @@ class Manager implements Interfaces\Manager public function renderWidget($name) { - sd('render', $name); return $this->getWidgetManager()->includeWidget($name); }
config items values are inheritable again
oliwierptak_Everon1
train
8c281541a0e7f025f28a2b805f90107292b85c20
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -31,7 +31,8 @@ module.exports = function nuxtApollo(moduleOptions) { config.resolve.extensions = config.resolve.extensions.concat('.graphql', '.gql') config.module.rules.push({ test: /\.(graphql|gql)$/, - use: 'graphql-tag/loader' + use: 'graphql-tag/loader', + exclude: /(node_modules)/ }) }) }
Exclude graphql-tag rule from node_modules
nuxt-community_apollo-module
train
fc7ee9368c15e996d2d06ba94675c650a7f50435
diff --git a/devtools/debug.py b/devtools/debug.py index <HASH>..<HASH> 100644 --- a/devtools/debug.py +++ b/devtools/debug.py @@ -317,23 +317,19 @@ class Debug: first_line = None last_line = None - for instr in instructions: + for instr in instructions: # pragma: no branch if instr.starts_line: if instr.opname in {'LOAD_GLOBAL', 'LOAD_NAME'} and instr.argval == func_name: first_line = instr.starts_line - break elif instr.opname == 'LOAD_GLOBAL' and instr.argval == 'debug': if next(instructions).argval == func_name: first_line = instr.starts_line - break + if instr.offset == call_frame.f_lasti: + break if first_line is None: raise IntrospectionError('error parsing code, unable to find "{}" function statement'.format(func_name)) - for instr in instructions: # pragma: no branch - if instr.offset == call_frame.f_lasti: - break - for instr in instructions: if instr.starts_line: last_line = instr.starts_line - 1 diff --git a/tests/test_main.py b/tests/test_main.py index <HASH>..<HASH> 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -258,3 +258,28 @@ def test_pretty_error(): " b: <tests.test_main.test_pretty_error.<locals>.BadPretty object at 0x000> (BadPretty)\n" " !!! error pretty printing value: RuntimeError('this is an error')" ) + + [email protected](sys.version_info >= (3, 8), reason='different between 3.7 and 3.8') +def test_multiple_debugs_37(): + debug.format([i * 2 for i in range(2)]) + debug.format([i * 2 for i in range(2)]) + v = debug.format([i * 2 for i in range(2)]) + s = re.sub(r':\d{2,}', ':<line no>', str(v)) + assert s == ( + 'tests/test_main.py:<line no> test_multiple_debugs_37\n' + ' [i * 2 for i in range(2)]: [0, 2] (list) len=2' + ) + + [email protected](sys.version_info < (3, 8), reason='different between 3.7 and 3.8') +def test_multiple_debugs_38(): + debug.format([i * 2 for i in range(2)]) + debug.format([i * 2 for i in range(2)]) + v = debug.format([i * 2 for i in range(2)]) + s = re.sub(r':\d{2,}', ':<line no>', str(v)) + # FIXME there's an extraneous bracket here, due to some error building code from the ast + assert s == ( + 'tests/test_main.py:<line no> test_multiple_debugs_38\n' + ' ([i * 2 for i in range(2)]: [0, 2] (list) len=2' + )
fix statements finding for multiple debug calls in the same block (#<I>) * fix sttatement finding for multiple debug calls in the same block * different for <I> and <I> * coverage
samuelcolvin_python-devtools
train
fc187f121b0ebcb04844420f5e975ffea1cc4538
diff --git a/glances/glances.py b/glances/glances.py index <HASH>..<HASH> 100644 --- a/glances/glances.py +++ b/glances/glances.py @@ -3914,7 +3914,20 @@ class GlancesInstance(): # Update and return current date/hour self.__update__() return json.dumps(stats.getNow().strftime(_("%Y-%m-%d %H:%M:%S"))) - + + def __getTimeSinceLastUpdate(self, IOType): + assert(IOType in ['net', 'disk', 'process_disk']) + return getTimeSinceLastUpdate(IOType) + + def getNetTimeSinceLastUpdate(self): + return getTimeSinceLastUpdate('net') + + def getDiskTimeSinceLastUpdate(self): + return getTimeSinceLastUpdate('net') + + def getProcessDiskTimeSinceLastUpdate(self): + return getTimeSinceLastUpdate('process_disk') + class GlancesServer(): """
Cherry pick ef<I> to bffeb<I>
nicolargo_glances
train
759682810a6d87651810ea52420aae8bcedfa67f
diff --git a/nonblock/common.py b/nonblock/common.py index <HASH>..<HASH> 100644 --- a/nonblock/common.py +++ b/nonblock/common.py @@ -7,28 +7,28 @@ def detect_stream_mode(stream): @param stream <object> - A stream object - If "mode" is present, that will be used. + If "mode" is present, that will be used. - @return <str> - 'b' for bytes, 't' for text. + @return <type> - "Bytes" type or "str" type ''' # If "Mode" is present, pull from that if hasattr(stream, 'mode'): if 'b' in stream.mode: - return 'b' + return bytes elif 't' in stream.mode: - return 't' + return str # Read a zero-length string off the device if hasattr(stream, 'read'): zeroStr = stream.read(0) if type(zeroStr) is str: - return 't' - return 'b' + return str + return bytes elif hasattr(stream, 'recv'): zeroStr = stream.recv(0) if type(zeroStr) is str: - return 't' - return 'b' + return str + return bytes # Cannot figure it out, assume bytes. - return 'b' + return bytes diff --git a/nonblock/read.py b/nonblock/read.py index <HASH>..<HASH> 100644 --- a/nonblock/read.py +++ b/nonblock/read.py @@ -29,18 +29,15 @@ def nonblock_read(stream, limit=None, forceMode=None): if forceMode: if 'b' in forceMode: - streamMode = 'b' + streamMode = bytes elif 't' in forceMode: - streamMode = 't' + streamMode = str else: streamMode = detect_stream_mode(stream) else: streamMode = detect_stream_mode(stream) - if streamMode == 'b': - emptyStr = b'' - else: - emptyStr = '' + emptyStr = streamMode() # Determine if our function is "read" (file-like objects) or "recv" (socket-like objects) if hasattr(stream, 'read'):
Change detect_stream_mode to return the type itself (bytes/str) instead of 'b'/'t'
kata198_python-nonblock
train
12639bc0018afcf7d00d2e15c3d191fbffc1b8b0
diff --git a/src/geometry/Marker.js b/src/geometry/Marker.js index <HASH>..<HASH> 100644 --- a/src/geometry/Marker.js +++ b/src/geometry/Marker.js @@ -73,8 +73,11 @@ class Marker extends CenterMixin(Geometry) { Symbolizers.ImageMarkerSymbolizer.test(symbol); } - _containsPoint(point) { - const extent = this._getPainter().getContainerExtent(); + _containsPoint(point, t) { + let extent = this._getPainter().getContainerExtent(); + if (t) { + extent = extent.expand(t); + } return extent.contains(this.getMap()._pointToContainerPoint(point)); } diff --git a/src/layer/OverlayLayer.js b/src/layer/OverlayLayer.js index <HASH>..<HASH> 100644 --- a/src/layer/OverlayLayer.js +++ b/src/layer/OverlayLayer.js @@ -386,7 +386,8 @@ class OverlayLayer extends Layer { * Identify the geometries on the given coordinate * @param {maptalks.Coordinate} coordinate - coordinate to identify * @param {Object} [options=null] - options - * @param {Object} [options.count=null] - result count + * @param {Object} [options.tolerance=0] - identify tolerance in pixel + * @param {Object} [options.count=null] - result count * @return {Geometry[]} geometries identified */ identify(coordinate, options = {}) { @@ -394,7 +395,8 @@ class OverlayLayer extends Layer { } _hitGeos(geometries, coordinate, options = {}) { - const filter = options.filter, + const filter = options['filter'], + tolerance = options['tolerance'], hits = []; const map = this.getMap(); const point = map.coordinateToPoint(coordinate); @@ -406,12 +408,15 @@ class OverlayLayer extends Layer { } if (!(geo instanceof LineString) || !geo._getArrowStyle()) { // Except for LineString with arrows - const extent = geo._getPainter().getContainerExtent(); + let extent = geo._getPainter().getContainerExtent(); + if (tolerance) { + extent = extent.expand(tolerance); + } if (!extent || !extent.contains(cp)) { continue; } } - if (geo._containsPoint(point) && (!filter || filter(geo))) { + if (geo._containsPoint(point, tolerance) && (!filter || filter(geo))) { hits.push(geo); if (options['count']) { if (hits.length >= options['count']) { diff --git a/src/map/Map.Topo.js b/src/map/Map.Topo.js index <HASH>..<HASH> 100644 --- a/src/map/Map.Topo.js +++ b/src/map/Map.Topo.js @@ -52,6 +52,7 @@ Map.include(/** @lends Map.prototype */ { * @param {Object} opts.layers - the layers to perform identify on. * @param {Function} [opts.filter=null] - filter function of the result geometries, return false to exclude. * @param {Number} [opts.count=null] - limit of the result count. + * @param {Number} [opts.tolerance=0] - identify tolerance in pixel. * @param {Boolean} [opts.includeInternals=false] - whether to identify internal layers. * @param {Boolean} [opts.includeInvisible=false] - whether to identify invisible layers. * @param {Function} callback - the callback function using the result geometries as the parameter. diff --git a/test/map/MapSpec.js b/test/map/MapSpec.js index <HASH>..<HASH> 100644 --- a/test/map/MapSpec.js +++ b/test/map/MapSpec.js @@ -655,6 +655,35 @@ describe('Map.Spec', function () { }); }); + it('identify with tolerace', function (done) { + var layer = new maptalks.VectorLayer('id'); + var marker = new maptalks.Marker(map.getCenter(), { + symbol : { + markerType : 'ellipse', + markerWidth : 4, + markerHeight : 4, + markerDx : 4 + } + }); + layer.addGeometry(marker); + map.addLayer(layer); + + map.identify({ + coordinate: center, + layers: [layer] + }, function (geos) { + expect(geos.length).to.be.eql(0); + map.identify({ + coordinate: center, + layers: [layer], + tolerance : 5 + }, function (geos) { + expect(geos.length).to.be.eql(1); + done(); + }); + }); + }); + it('identify on empty line', function (done) { var layer = new maptalks.VectorLayer('id'); var line = new maptalks.LineString([]);
Add tolerance in identify, close #<I> (#<I>)
maptalks_maptalks.js
train
b8066ceb23daa57ac722ed69a6f7f61dedd402a4
diff --git a/lib/love.rb b/lib/love.rb index <HASH>..<HASH> 100644 --- a/lib/love.rb +++ b/lib/love.rb @@ -187,6 +187,14 @@ module Love def get_queue(id_or_href) get(singleton_uri(id_or_href, 'queues'), options) end + + # Returns a single Tender FAQ. + # @param [URI, String, Integer] id_or_href The faq ID or HREF. Can be either a URI + # instance, a string containing a URI, or a queue ID as a numeric string or integer. + # @return [Hash] The faq attributes in a Hash. + def get_faq(id_or_href) + get(singleton_uri(id_or_href, 'faqs')) + end # Iterates over all Tender categories. # @yield [Hash] The attributes of each category will be yielded as (nested) Hash. @@ -268,7 +276,7 @@ module Love when Net::HTTPSuccess; Yajl::Parser.new.parse(safely_convert_to_utf8(response.body)) when Net::HTTPUnauthorized; raise Love::Unauthorized, "Invalid credentials used!" when Net::HTTPForbidden; raise Love::Unauthorized, "You don't have permission to access this resource!" - when Net::NotFound; raise Love::NotFound, "The resource #{uri} was not found!" + when Net::HTTPNotFound; raise Love::NotFound, "The resource #{uri} was not found!" else raise Love::Exception, "#{response.code}: #{response.body}" end ensure
Added support for retrieving a FAQ. Fixed NotFound constant.
wvanbergen_love
train
e7d60e6b29d658fd5c96e2e56671696b2f8aef0e
diff --git a/alpine-server/src/main/java/alpine/server/auth/LdapConnectionWrapper.java b/alpine-server/src/main/java/alpine/server/auth/LdapConnectionWrapper.java index <HASH>..<HASH> 100644 --- a/alpine-server/src/main/java/alpine/server/auth/LdapConnectionWrapper.java +++ b/alpine-server/src/main/java/alpine/server/auth/LdapConnectionWrapper.java @@ -97,7 +97,7 @@ public class LdapConnectionWrapper { env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); if (IS_LDAP_SSLTLS) { - env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory"); + env.put("java.naming.ldap.factory.socket", "alpine.security.crypto.RelaxedSSLSocketFactory"); } try { return new InitialLdapContext(env, null); @@ -123,7 +123,7 @@ public class LdapConnectionWrapper { env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); if (IS_LDAP_SSLTLS) { - env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory"); + env.put("java.naming.ldap.factory.socket", "alpine.security.crypto.RelaxedSSLSocketFactory"); } return new InitialDirContext(env); }
correct the package name for Relaxed Factory
stevespringett_Alpine
train
bab8f32acc5e50f13986f38a5d071fd66eaf72af
diff --git a/src/org/opencms/search/solr/CmsSolrDocument.java b/src/org/opencms/search/solr/CmsSolrDocument.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/search/solr/CmsSolrDocument.java +++ b/src/org/opencms/search/solr/CmsSolrDocument.java @@ -175,7 +175,10 @@ public class CmsSolrDocument implements I_CmsSearchDocument { */ public void addFileSizeField(int length) { - m_doc.addField(CmsSearchField.FIELD_SIZE, new Integer(length)); + if (OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema().hasExplicitField( + CmsSearchField.FIELD_SIZE)) { + m_doc.addField(CmsSearchField.FIELD_SIZE, new Integer(length)); + } } /**
Check if the field "size" exists before adding it.
alkacon_opencms-core
train
1e3fa3c197c2ee3bee677965557d1394434469c3
diff --git a/examples/largeimages/main.rb b/examples/largeimages/main.rb index <HASH>..<HASH> 100644 --- a/examples/largeimages/main.rb +++ b/examples/largeimages/main.rb @@ -86,8 +86,8 @@ loop do " [#{all_direct_urls.size} images]" if all_direct_urls.size > 1 } #{ title.sub(/\s*\[?#{width}\s*[*x×]\s*#{height}\]?\s*/i, " "). - gsub(/\s+/, " ").strip. - sub(/(.{#{100 - subreddit.size}}).+/, '\1...') + sub("[OC]", " ").gsub(/\s+/, " ").strip. + gsub(/(?<=.{190 - subreddit.size}).+/, "...") } /r/#{subreddit}". gsub(/\s+\(\s+\)\s+/, " ") logger.warn "new post #{source}: #{url} #{title.inspect}"
removing '[OC]' from title
Nakilon_reddit_bot
train
74eb4dd4b923dafc95d85bdd7c782d6ab42409e1
diff --git a/test.js b/test.js index <HASH>..<HASH> 100644 --- a/test.js +++ b/test.js @@ -69,7 +69,7 @@ it('considering filter option to stringify an object', function () { assert.equal(actual, '{\n\tbar: {\n\t\tval: 10\n\t}\n}'); }); -it('should not crash with circular recursion in arrays', function () { +it.skip('should not crash with circular references in arrays', function () { var array = []; array.push(array); assert.doesNotThrow( @@ -85,7 +85,18 @@ it('should not crash with circular recursion in arrays', function () { }, RangeError); }); -it('should stringify complex circular arrays', function () { +it.skip('should handle circular references in arrays', function () { + var array2 = []; + var array = [array2]; + array2[0] = array2; + + assert.doesNotThrow( + function () { + stringifyObject(array); + }, RangeError); +}); + +it.skip('should stringify complex circular arrays', function () { var array = [[[]]]; array[0].push(array); array[0][0].push(array);
add another testcase for handling of circular references in arrays
yeoman_stringify-object
train
228e8b47a538d74433ac7a6dab30b8689dedd5a5
diff --git a/agent/engine/docker_container_engine.go b/agent/engine/docker_container_engine.go index <HASH>..<HASH> 100644 --- a/agent/engine/docker_container_engine.go +++ b/agent/engine/docker_container_engine.go @@ -193,9 +193,14 @@ func (dg *DockerGoClient) pullImage(image string) DockerContainerMetadata { defer pullWriter.Close() repository, tag := parsers.ParseRepositoryTag(image) - tag = utils.DefaultIfBlank(tag, dockerDefaultTag) + if tag == "" { + repository = repository + ":" + dockerDefaultTag + } else { + repository = image + } + opts := docker.PullImageOptions{ - Repository: repository + ":" + tag, + Repository: repository, OutputStream: pullWriter, } timeout := ttime.After(dockerPullBeginTimeout) diff --git a/agent/engine/docker_container_engine_test.go b/agent/engine/docker_container_engine_test.go index <HASH>..<HASH> 100644 --- a/agent/engine/docker_container_engine_test.go +++ b/agent/engine/docker_container_engine_test.go @@ -127,6 +127,33 @@ func TestPullImage(t *testing.T) { } } +func TestPullImageTag(t *testing.T) { + mockDocker, client, _, done := dockerclientSetup(t) + defer done() + + mockDocker.EXPECT().PullImage(&pullImageOptsMatcher{"image:mytag"}, gomock.Any()).Return(nil) + + metadata := client.PullImage("image:mytag") + if metadata.Error != nil { + t.Error("Expected pull to succeed") + } +} + +func TestPullImageDigest(t *testing.T) { + mockDocker, client, _, done := dockerclientSetup(t) + defer done() + + mockDocker.EXPECT().PullImage( + &pullImageOptsMatcher{"image@sha256:bc8813ea7b3603864987522f02a76101c17ad122e1c46d790efc0fca78ca7bfb"}, + gomock.Any(), + ).Return(nil) + + metadata := client.PullImage("image@sha256:bc8813ea7b3603864987522f02a76101c17ad122e1c46d790efc0fca78ca7bfb") + if metadata.Error != nil { + t.Error("Expected pull to succeed") + } +} + func TestPullEmptyvolumeImage(t *testing.T) { mockDocker, client, _, done := dockerclientSetup(t) defer done() diff --git a/agent/engine/engine_integ_test.go b/agent/engine/engine_integ_test.go index <HASH>..<HASH> 100644 --- a/agent/engine/engine_integ_test.go +++ b/agent/engine/engine_integ_test.go @@ -208,6 +208,40 @@ func TestStartStopUnpulledImage(t *testing.T) { } } +// TestStartStopUnpulledImageDigest ensures that an unpulled image with +// specified digest is successfully pulled, run, and stopped via docker. +func TestStartStopUnpulledImageDigest(t *testing.T) { + imageDigest := "tianon/true@sha256:30ed58eecb0a44d8df936ce2efce107c9ac20410c915866da4c6a33a3795d057" + taskEngine := setup(t) + // Ensure this image isn't pulled by deleting it + removeImage(imageDigest) + + testTask := createTestTask("testStartUnpulledDigest") + testTask.Containers[0].Image = imageDigest + + taskEvents, contEvents := taskEngine.TaskEvents() + + defer discardEvents(contEvents)() + + go taskEngine.AddTask(testTask) + + expected_events := []api.TaskStatus{api.TaskRunning, api.TaskStopped} + + for taskEvent := range taskEvents { + if taskEvent.TaskArn != testTask.Arn { + continue + } + expected_event := expected_events[0] + expected_events = expected_events[1:] + if taskEvent.Status != expected_event { + t.Error("Got event " + taskEvent.Status.String() + " but expected " + expected_event.String()) + } + if len(expected_events) == 0 { + break + } + } +} + // TestPortForward runs a container serving data on the randomly chosen port // 24751 and verifies that when you do forward the port you can access it and if // you don't forward the port you can't
Make pullImage less tightly-coupled to tag format
aws_amazon-ecs-agent
train
4106a711508c02395227043885f8abe655e28918
diff --git a/src/recipe/lumen-deployer.php b/src/recipe/lumen-deployer.php index <HASH>..<HASH> 100644 --- a/src/recipe/lumen-deployer.php +++ b/src/recipe/lumen-deployer.php @@ -13,15 +13,18 @@ task('deploy', [ 'deploy:lock', 'deploy:release', 'deploy:update_code', + 'hook:build', 'deploy:shared', 'firstdeploy:shared', 'deploy:vendors', 'deploy:writable', 'artisan:cache:clear', 'artisan:optimize', + 'hook:ready', 'deploy:symlink', 'deploy:unlock', 'cleanup', + 'hook:done', ]); after('deploy:failed', 'deploy:unlock');
:pencil: Add shallow hooks to lumen deployer
lorisleiva_laravel-deployer
train
634275b551e7aa52a55c470bfaa4fcf0770cd246
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog All Notable changes to `Csv` will be documented in this file + ## Next - TBD ### Added diff --git a/src/CharsetConverter.php b/src/CharsetConverter.php index <HASH>..<HASH> 100644 --- a/src/CharsetConverter.php +++ b/src/CharsetConverter.php @@ -47,10 +47,7 @@ class CharsetConverter extends php_user_filter public $filtername; /** - * Contents of the params parameter passed to stream_filter_append - * or stream_filter_prepend functions. - * - * @var mixed + * @var mixed value passed to passed to stream_filter_append or stream_filter_prepend functions. */ public $params; @@ -194,8 +191,8 @@ class CharsetConverter extends php_user_filter /** * Walker method to convert the offset and the value of a CSV record field. * - * @param mixed $value - * @param mixed $offset + * @param mixed $value can be a scalar type or null + * @param mixed $offset can be a string or an int */ protected function encodeField(&$value, &$offset): void { diff --git a/src/EncloseField.php b/src/EncloseField.php index <HASH>..<HASH> 100644 --- a/src/EncloseField.php +++ b/src/EncloseField.php @@ -42,10 +42,7 @@ class EncloseField extends php_user_filter public $filtername; /** - * Contents of the params parameter passed to stream_filter_append - * or stream_filter_prepend functions. - * - * @var mixed + * @var mixed value passed to passed to stream_filter_append or stream_filter_prepend functions. */ public $params; diff --git a/src/RFC4180Field.php b/src/RFC4180Field.php index <HASH>..<HASH> 100644 --- a/src/RFC4180Field.php +++ b/src/RFC4180Field.php @@ -50,10 +50,7 @@ class RFC4180Field extends php_user_filter public $filtername; /** - * Contents of the params parameter passed to stream_filter_append - * or stream_filter_prepend functions. - * - * @var mixed + * @var mixed value passed to passed to stream_filter_append or stream_filter_prepend functions. */ public $params; diff --git a/src/Stream.php b/src/Stream.php index <HASH>..<HASH> 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -72,7 +72,7 @@ class Stream implements SeekableIterator /** * Current iterator value. * - * @var mixed + * @var mixed can be a null false or a scalar type value */ protected $value; diff --git a/tests/WriterTest.php b/tests/WriterTest.php index <HASH>..<HASH> 100644 --- a/tests/WriterTest.php +++ b/tests/WriterTest.php @@ -122,7 +122,7 @@ class WriterTest extends TestCase self::expectExceptionMessage('Unable to write record to the CSV document'); } else { self::expectException(Notice::class); - self::expectExceptionMessageRegExp('/write of \d+ bytes failed with errno=9 Bad file descriptor/'); + self::expectExceptionMessageMatches('/write of \d+ bytes failed with errno=9 Bad file descriptor/'); } Writer::createFromPath(__DIR__.'/data/foo.csv', 'r')->insertOne($record);
Update docblock and test suite for development
thephpleague_csv
train
11cc12126f1f6df912e21f9a5f1e6af5f8e72848
diff --git a/eZ/Publish/Core/REST/Server/Controller/Trash.php b/eZ/Publish/Core/REST/Server/Controller/Trash.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/REST/Server/Controller/Trash.php +++ b/eZ/Publish/Core/REST/Server/Controller/Trash.php @@ -16,6 +16,8 @@ use eZ\Publish\API\Repository\TrashService; use eZ\Publish\API\Repository\LocationService; use eZ\Publish\API\Repository\Values\Content\Query; +use eZ\Publish\API\Repository\Exceptions\NotFoundException; +use eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException; use Qafoo\RMF; @@ -153,7 +155,14 @@ class Trash $locationPath = $destinationValues['location']; $locationPathParts = explode( '/', $locationPath ); - $parentLocation = $this->locationService->loadLocation( array_pop( $locationPathParts ) ); + try + { + $parentLocation = $this->locationService->loadLocation( array_pop( $locationPathParts ) ); + } + catch ( NotFoundException $e ) + { + throw new ForbiddenException( $e->getMessage() ); + } } $values = $this->urlHandler->parse( 'trash', $request->path );
REST: Fix MOVE /content/trash/<ID> not returning <I> if parent location does not exist
ezsystems_ezpublish-kernel
train
a1934421b5ef90b5c9b944b72ab444703ae80518
diff --git a/driver/src/main/java/org/neo4j/driver/internal/ExplicitTransaction.java b/driver/src/main/java/org/neo4j/driver/internal/ExplicitTransaction.java index <HASH>..<HASH> 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/ExplicitTransaction.java +++ b/driver/src/main/java/org/neo4j/driver/internal/ExplicitTransaction.java @@ -67,16 +67,16 @@ public class ExplicitTransaction extends AbstractStatementRunner implements Tran private final Connection connection; private final BoltProtocol protocol; - private final NetworkSession session; + private final BookmarksHolder bookmarksHolder; private final ResultCursorsHolder resultCursors; private volatile State state = State.ACTIVE; - public ExplicitTransaction( Connection connection, NetworkSession session ) + public ExplicitTransaction( Connection connection, BookmarksHolder bookmarksHolder ) { this.connection = connection; this.protocol = connection.protocol(); - this.session = session; + this.bookmarksHolder = bookmarksHolder; this.resultCursors = new ResultCursorsHolder(); } @@ -247,12 +247,7 @@ public class ExplicitTransaction extends AbstractStatementRunner implements Tran return failedFuture( new ClientException( "Transaction can't be committed. " + "It has been rolled back either because of an error or explicit termination" ) ); } - return protocol.commitTransaction( connection ) - .thenApply( newBookmarks -> - { - session.setBookmarks( newBookmarks ); - return null; - } ); + return protocol.commitTransaction( connection ).thenAccept( bookmarksHolder::setBookmarks ); } private CompletionStage<Void> doRollbackAsync()
Use only BookmarksHolder contract instead of concrete NetworkSession.
neo4j_neo4j-java-driver
train
3c57af62241ce6e5b2643f831e5f44288f97986f
diff --git a/dociter.go b/dociter.go index <HASH>..<HASH> 100644 --- a/dociter.go +++ b/dociter.go @@ -59,7 +59,7 @@ func (m *candidateMatch) caseMatches(fileCaseBits []byte) bool { start := m.offset - startExtend end := m.offset + uint32(patLen) + endExtend - fileBits := append([]byte{}, fileCaseBits[start/8:end/8]...) + fileBits := fileCaseBits[start/8 : end/8] mask := m.caseMask[startExtend] bits := m.caseBits[startExtend]
Optimization: avoid allocation in case comparison.
google_zoekt
train
15b068dd5619b1dd04f97777f14eb8f25b55dd76
diff --git a/drop_down_menus.py b/drop_down_menus.py index <HASH>..<HASH> 100644 --- a/drop_down_menus.py +++ b/drop_down_menus.py @@ -25,7 +25,9 @@ class Menus(): if self.data_type == 'specimen': choices = {2: (belongs_to, False)} if self.data_type == 'sample' or self.data_type == 'site': - choices = {2: (belongs_to, False), 3: (vocab.site_class, False), 4: (vocab.site_lithology, True), 5: (vocab.site_type, False), 6: (vocab.site_definition, False)} + choices = {2: (belongs_to, False), 3: (vocab.site_class, False), 4: (vocab.site_lithology, True), 5: (vocab.site_type, False)} + if self.data_type == 'site': + choices[6] = (vocab.site_definition, False) if self.data_type == 'location': choices = {1: (vocab.location_type, False)} if self.data_type == 'age': @@ -61,7 +63,7 @@ class Menus(): for row in range(self.grid.GetNumberRows()): self.grid.SetCellBackgroundColour(row, col, 'light blue') self.grid.ForceRefresh() - has_dropdown = ((col == 2 and self.data_type is 'specimen') or (col in range(2, 7) and self.data_type in ['site', 'sample']) or (col in (3, 5) and self.data_type == 'age') or (col == 1 and self.data_type == 'location')) + has_dropdown = ((col == 2 and self.data_type is 'specimen') or (col in range(2, 6) and self.data_type in ['site', 'sample']) or (col in (3, 5) and self.data_type == 'age') or (col == 6 and self.data_type == 'site') or (col == 1 and self.data_type == 'location')) # if the column has no drop-down list, allow user to edit all cells in the column through text entry if not has_dropdown and col not in (0, 1): diff --git a/pmag_basic_dialogs.py b/pmag_basic_dialogs.py index <HASH>..<HASH> 100755 --- a/pmag_basic_dialogs.py +++ b/pmag_basic_dialogs.py @@ -2658,7 +2658,7 @@ class check(wx.Frame): self.locations = self.Data_hierarchy['locations'] # key1 = self.ErMagic.data_er_locations.keys()[0] - col_labels = self.ErMagic.data_er_locations[key1].keys() + col_labels = sorted(self.ErMagic.data_er_locations[key1].keys()) try: col_labels.remove('er_location_name') col_labels.remove('location_type') @@ -2726,7 +2726,7 @@ class check(wx.Frame): self.sites = self.Data_hierarchy['sites'] # key1 = self.ErMagic.data_er_ages.keys()[0] - col_labels = self.ErMagic.data_er_ages[key1].keys() + col_labels = sorted(self.ErMagic.data_er_ages[key1].keys()) try: for col_label in ['er_site_name', 'er_location_name', 'er_citation_names', 'magic_method_codes', 'age_description', 'age_unit', 'age']: col_labels.remove(col_label)
QuickMagic Step 3: fix a few minor bugs
PmagPy_PmagPy
train
8791d5c4a698cec06ace79fdc7d70c9c3f453370
diff --git a/library/src/main/java/com/mikepenz/materialdrawer/Drawer.java b/library/src/main/java/com/mikepenz/materialdrawer/Drawer.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/mikepenz/materialdrawer/Drawer.java +++ b/library/src/main/java/com/mikepenz/materialdrawer/Drawer.java @@ -793,7 +793,7 @@ public class Drawer { //get the drawer root mDrawerContentRoot = (ScrimInsetsFrameLayout) mDrawerLayout.getChildAt(0); - if (!alreadyInflated && mTranslucentStatusBar && !mTranslucentActionBarCompatibility) { + if (!alreadyInflated && (mTranslucentStatusBar || mTranslucentActionBarCompatibility)) { if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) { setTranslucentStatusFlag(true); } @@ -1019,7 +1019,7 @@ public class Drawer { mSliderLayout.addView(mListView, params); //some extra stuff to beautify the whole thing ;) - if (!mTranslucentStatusBar) { + if (!mTranslucentStatusBar || mTranslucentActionBarCompatibility) { //disable the shadow if we don't use a translucent activity mSliderLayout.getChildAt(0).setVisibility(View.GONE); } else {
* fix wrong margin and wrong alignment with mTranslucentActionBarCompatiblity = true
mikepenz_MaterialDrawer
train
1d6cdb65b32f918fc497953adf02b60e26ea3fec
diff --git a/js/src/scrollspy.js b/js/src/scrollspy.js index <HASH>..<HASH> 100644 --- a/js/src/scrollspy.js +++ b/js/src/scrollspy.js @@ -258,7 +258,7 @@ const ScrollSpy = (($) => { } else { // todo (fat) this is kinda sus... // recursively add actives to tested nav-links - $link.parents(Selector.LI).find(Selector.NAV_LINKS).addClass(ClassName.ACTIVE) + $link.parents(Selector.LI).find(`> ${Selector.NAV_LINKS}`).addClass(ClassName.ACTIVE) } $(this._scrollElement).trigger(Event.ACTIVATE, {
scrollspy: fix wrong activation of all nested links (#<I>) * fix wrong activation of all nested links; just first level item should be activated * use template instead of string concatenation
twbs_bootstrap
train
ae2398de51e51a85f213e3538b3c10250fed7b94
diff --git a/tests/big-ass-files.test.js b/tests/big-ass-files.test.js index <HASH>..<HASH> 100644 --- a/tests/big-ass-files.test.js +++ b/tests/big-ass-files.test.js @@ -1,4 +1,4 @@ -describe.skip('when some big files start coming in, this adapter', function() { +describe('when some big files start coming in, this adapter', function() { before(function () { // Set up a route which listens to uploads diff --git a/tests/file-metadata.test.js b/tests/file-metadata.test.js index <HASH>..<HASH> 100644 --- a/tests/file-metadata.test.js +++ b/tests/file-metadata.test.js @@ -189,7 +189,6 @@ function bindTestRoute() { app.post('/upload_metadata_test', function (req, res, next) { assert(_.isFunction(req.file)); - require('async').auto({ // defaults (uuid for the fd) avatar: function (cb) { diff --git a/tests/tons-o-requests.test.js b/tests/tons-o-requests.test.js index <HASH>..<HASH> 100644 --- a/tests/tons-o-requests.test.js +++ b/tests/tons-o-requests.test.js @@ -1,4 +1,4 @@ -describe.skip('under a bit of load, this adapter', function() { +describe('under a bit of load, this adapter', function() { before(function () { // Set up a route which listens to uploads
Revert the .skips.
balderdashy_skipper-adapter-tests
train
62ef2c36cf3b0d3ba4b9fc78a5c85b74e5fa9a4d
diff --git a/vyked/__init__.py b/vyked/__init__.py index <HASH>..<HASH> 100644 --- a/vyked/__init__.py +++ b/vyked/__init__.py @@ -1,7 +1,7 @@ __all__ = ['TCPServiceClient', 'TCPApplicationService', 'TCPDomainService', 'TCPInfraService', 'HTTPServiceClient', 'HTTPApplicationService', 'HTTPDomainService', 'HTTPInfraService', 'api', 'request', 'subscribe', 'publish', 'message_pub', 'get', 'post', 'head', 'put', 'patch', 'delete', 'options', 'trace', 'Entity', 'Value', - 'Aggregate', 'Factory', 'Repository', 'Bus', 'Registry', 'SQLStore' 'log', 'cursor'] + 'Aggregate', 'Factory', 'Repository', 'Bus', 'Registry', 'PostgresStore' 'log', 'cursor'] from .services import (TCPServiceClient, TCPApplicationService, TCPDomainService, TCPInfraService, HTTPServiceClient, HTTPApplicationService, HTTPDomainService, HTTPInfraService, api, request, subscribe, publish, @@ -10,6 +10,6 @@ from .model import (Entity, Value, Aggregate, Factory, Repository) from .bus import Bus from .registry import Registry from .utils import log -from .sql import SQLStore, cursor +from .sql import PostgresStore, cursor log.setup() \ No newline at end of file diff --git a/vyked/sql.py b/vyked/sql.py index <HASH>..<HASH> 100644 --- a/vyked/sql.py +++ b/vyked/sql.py @@ -3,12 +3,18 @@ from functools import wraps from aiopg import create_pool, Pool, Cursor -class SQLStore: + +class PostgresStore: _pool = None _connection_params = {} + _insert_string = "insert into {} {} values ({});" + _update_string = "update {} set {} = ({}) where {} = %s;" @classmethod - def connect(cls, database, user, password, host, port): + def connect(cls, database:str, user:str, password:str, host:str, port:int): + """ + Sets connection parameters + """ cls._connection_params['database'] = database cls._connection_params['user'] = user cls._connection_params['password'] = password @@ -16,12 +22,19 @@ class SQLStore: cls._connection_params['port'] = port @classmethod - def use_pool(cls, pool): + def use_pool(cls, pool:Pool): + """ + Sets an existing connection pool instead of using connect() to make one + """ cls._pool = pool @classmethod @coroutine def get_pool(cls) -> Pool: + """ + Yields: + existing db connection pool + """ if len(cls._connection_params) < 5: raise ConnectionError('Please call SQLStore.connect before calling this method') if not cls._pool: @@ -31,14 +44,67 @@ class SQLStore: @classmethod @coroutine def get_cursor(cls) -> Cursor: + """ + Yields: + new client-side cursor from existing db connection pool + """ pool = yield from cls.get_pool() cursor = yield from pool.cursor() return cursor + @classmethod + def make_insert_query(cls, table_name:str, values:dict): + """ + Creates an insert statement with only chosen fields + + Args: + table_name: a string indicating the name of the table + values: a dict of fields and values to be inserted + + Returns: + query: a SQL string with + values: a tuple of values to replace placeholder(%s) tokens in query + + """ + keys = str(tuple(values.keys())).replace("'", "") + value_place_holder = ' %s,' * len(values) + query = cls._insert_string.format(table_name, keys, value_place_holder[:-1]) + return query, tuple(values.values()) + + @classmethod + def make_update_query(cls, table_name:str, values:dict, where_key): + """ + Creates an update query with only chosen fields + Supports only a single field where clause + + Args: + table_name: a string indicating the name of the table + values: a dict of fields and values to be inserted + where_key: the 'where' clause field + + Returns: + query: a SQL string with + values: a tuple of values to replace placeholder(%s) tokens in query - except the where clause value + + """ + keys = str(tuple(values.keys())).replace("'", "") + value_place_holder = ' %s,' * len(values) + query = cls._update_string.format(table_name, keys, value_place_holder[:-1], where_key) + return query, tuple(values.values()) + def cursor(func): """ - decorator that provides a cursor from a pool and executes the function within its context manager + Decorator that provides a cursor to the calling function + + Adds the cursor as the second argument to the calling functions + + Requires that the function being decorated is an instance of a class or object + that yields a cursor from a get_cursor() coroutine or provides such an object + as the first argument in its signature + + Yields: + A client-side cursor """ @wraps(func)
add convenience methods for insert and update queries to PostgresStore
kashifrazzaqui_vyked
train
dcfb45f56993bec983827ad7e26e61de89d0f2f9
diff --git a/spec/emarsys_test_suite_spec.rb b/spec/emarsys_test_suite_spec.rb index <HASH>..<HASH> 100644 --- a/spec/emarsys_test_suite_spec.rb +++ b/spec/emarsys_test_suite_spec.rb @@ -41,10 +41,7 @@ module Escher request[:url] = request.delete :uri request.each { |_, v| v.sort! if v.class.method_defined? :sort! } - expected_request = test_case[:expected][:request] - expected_request.each { |_, v| v.sort! if v.class.method_defined? :sort! } - - expect(request).to eq(expected_request) + expect(request).to eq(test_case.expected_request) end end diff --git a/spec/helpers/emarsys_test_suite_helpers.rb b/spec/helpers/emarsys_test_suite_helpers.rb index <HASH>..<HASH> 100644 --- a/spec/helpers/emarsys_test_suite_helpers.rb +++ b/spec/helpers/emarsys_test_suite_helpers.rb @@ -37,13 +37,6 @@ module EmarsysTestSuiteHelpers - def convert_naming - @test_data[:request][:uri] = @test_data[:request].delete :url - @test_data[:config][:api_key_id] = @test_data[:config].delete :access_key_id - end - - - def [](arg) @test_data[arg] end @@ -61,6 +54,20 @@ module EmarsysTestSuiteHelpers @escher ||= ::Escher::Auth.new(@test_data[:config][:credential_scope], @test_data[:config]) end + + + def expected_request + @test_data[:expected][:request].each { |_, v| v.sort! if v.class.method_defined? :sort! } + end + + + + private + def convert_naming + @test_data[:request][:uri] = @test_data[:request].delete :url + @test_data[:config][:api_key_id] = @test_data[:config].delete :access_key_id + end + end end
move expected_request into TestCase class for emarsys test suite
emartech_escher-ruby
train
b4790afdafaf243ca7a1ec250917f30ed00a2d2d
diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py index <HASH>..<HASH> 100755 --- a/tools/mpy-tool.py +++ b/tools/mpy-tool.py @@ -444,10 +444,7 @@ def dump_mpy(raw_codes): for rc in raw_codes: rc.dump() -def freeze_mpy(qcfgs, base_qstrs, raw_codes): - cfg_bytes_len = int(qcfgs['BYTES_IN_LEN']) - cfg_bytes_hash = int(qcfgs['BYTES_IN_HASH']) - +def freeze_mpy(base_qstrs, raw_codes): # add to qstrs new = {} for q in global_qstrs: @@ -505,7 +502,8 @@ def freeze_mpy(qcfgs, base_qstrs, raw_codes): print(' %u, // used entries' % len(new)) print(' {') for _, _, qstr in new: - print(' %s,' % qstrutil.make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr)) + print(' %s,' + % qstrutil.make_bytes(config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr)) print(' },') print('};') @@ -549,10 +547,15 @@ def main(): }[args.mlongint_impl] config.MPZ_DIG_SIZE = args.mmpz_dig_size + # set config values for qstrs, and get the existing base set of qstrs if args.qstr_header: qcfgs, base_qstrs = qstrutil.parse_input_headers([args.qstr_header]) + config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs['BYTES_IN_LEN']) + config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs['BYTES_IN_HASH']) else: - qcfgs, base_qstrs = {'BYTES_IN_LEN':1, 'BYTES_IN_HASH':1}, {} + config.MICROPY_QSTR_BYTES_IN_LEN = 1 + config.MICROPY_QSTR_BYTES_IN_HASH = 1 + base_qstrs = {} raw_codes = [read_mpy(file) for file in args.files] @@ -560,7 +563,7 @@ def main(): dump_mpy(raw_codes) elif args.freeze: try: - freeze_mpy(qcfgs, base_qstrs, raw_codes) + freeze_mpy(base_qstrs, raw_codes) except FreezeError as er: print(er, file=sys.stderr) sys.exit(1)
tools/mpy-tool.py: Store qstr config values in global config object. Makes it easier to access them without passing around another dict of the config values.
micropython_micropython
train
5684665883a718b59b9ce55878e96f374693325c
diff --git a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementSuggestor2.java b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementSuggestor2.java index <HASH>..<HASH> 100644 --- a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementSuggestor2.java +++ b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/AgreementSuggestor2.java @@ -37,7 +37,8 @@ import static java.util.Collections.*; class AgreementSuggestor2 { private final static String detTemplate = "ART:IND/DEF:NOM/AKK/DAT/GEN:SIN/PLU:MAS/FEM/NEU"; - private final static String proPosTemplate = "PRO:POS:NOM/AKK/DAT/GEN:SIN/PLU:MAS/FEM/NEU:BEG"; + private final static List<String> proPosTemplate = Arrays.asList("PRO:POS:NOM/AKK/DAT/GEN:SIN/PLU:MAS/FEM/NEU:BEG", + "PRO:POS:NOM/AKK/DAT/GEN:SIN/PLU:MAS/FEM/NEU:B/S"); private final static List<String> proDemTemplates = Arrays.asList( "PRO:DEM:NOM/AKK/DAT/GEN:SIN/PLU:MAS/FEM/NEU:BEG", "PRO:DEM:NOM/AKK/DAT/GEN:SIN/PLU:MAS/FEM/NEU:B/S"); @@ -229,7 +230,7 @@ class AgreementSuggestor2 { } else if (detPos.contains("ART:")) { templates = singletonList(detTemplate); } else if (detPos.contains("PRO:POS:")) { - templates = singletonList(proPosTemplate); + templates = proPosTemplate; } else if (detPos.contains("PRO:DEM:")) { templates = proDemTemplates; } else if (detPos.contains("PRO:IND:")) { diff --git a/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementSuggestor2Test.java b/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementSuggestor2Test.java index <HASH>..<HASH> 100644 --- a/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementSuggestor2Test.java +++ b/languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/AgreementSuggestor2Test.java @@ -84,6 +84,7 @@ public class AgreementSuggestor2Test { assertSuggestion1("demselben Frau", "[derselben Frau, dieselbe Frau]"); assertSuggestion1("desselben Mann", "[denselben Mann, demselben Mann, desselben Manns, derselbe Mann, desselben Mannes]"); assertSuggestion1("meinem Eltern", "[meine Eltern, meinen Eltern, meiner Eltern]"); + assertSuggestion1("eure Auge", "[eurem Auge, eure Augen, euer Auge, euerem Auge, euerm Auge, eures Auges, euren Augen, eueres Auges, euerer Augen]"); } @Test
[de] offer suggestions for a few more cases ("eure Auge" -> "eure Augen" etc.)
languagetool-org_languagetool
train
fabb6fd782caf8f0124fad4dc5e710b01a1dba13
diff --git a/ontrack-model/src/main/java/net/nemerosa/ontrack/model/extension/ExtensionFeatureOptions.java b/ontrack-model/src/main/java/net/nemerosa/ontrack/model/extension/ExtensionFeatureOptions.java index <HASH>..<HASH> 100644 --- a/ontrack-model/src/main/java/net/nemerosa/ontrack/model/extension/ExtensionFeatureOptions.java +++ b/ontrack-model/src/main/java/net/nemerosa/ontrack/model/extension/ExtensionFeatureOptions.java @@ -20,7 +20,7 @@ public class ExtensionFeatureOptions { */ public static final ExtensionFeatureOptions DEFAULT = builder() .gui(false) - .dependencies(Collections.<ExtensionFeatureDescription>emptySet()) + .dependencies(Collections.<String>emptySet()) .build(); /** @@ -30,23 +30,23 @@ public class ExtensionFeatureOptions { private final boolean gui; /** - * List of extensions this feature depends on. + * List of extensions IDs this feature depends on. */ @Wither - private final Set<ExtensionFeatureDescription> dependencies; + private final Set<String> dependencies; /** * Adds a dependency */ public ExtensionFeatureOptions withDependency(ExtensionFeature feature) { - Set<ExtensionFeatureDescription> existing = this.dependencies; - Set<ExtensionFeatureDescription> newDependencies; + Set<String> existing = this.dependencies; + Set<String> newDependencies; if (existing == null) { newDependencies = new HashSet<>(); } else { newDependencies = new HashSet<>(existing); } - newDependencies.add(feature.getFeatureDescription()); + newDependencies.add(feature.getId()); return withDependencies(newDependencies); } diff --git a/ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/ExtensionManagerImpl.java b/ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/ExtensionManagerImpl.java index <HASH>..<HASH> 100644 --- a/ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/ExtensionManagerImpl.java +++ b/ontrack-service/src/main/java/net/nemerosa/ontrack/service/security/ExtensionManagerImpl.java @@ -96,7 +96,7 @@ public class ExtensionManagerImpl implements ExtensionManager, StartupService { // Adds the dependencies as edges extensionFeatures.forEach(source -> source.getOptions().getDependencies().forEach(target -> - g.addEdge(target.getId(), source.getId()) + g.addEdge(target, source.getId()) )); // Cycle detection
#<I> Extension dependency model - only strings as dependencies
nemerosa_ontrack
train
34d9e584ac074f765ab99df64e94179f01a19a2e
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/UtilSerializers.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/UtilSerializers.java index <HASH>..<HASH> 100644 --- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/UtilSerializers.java +++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/UtilSerializers.java @@ -84,7 +84,7 @@ final class UtilSerializers { public final static class ClassSerializer implements SerializerShim<Class> { @Override public <O extends OutputShim> void write(final KryoShim<?, O> kryo, final O output, final Class object) { - output.writeString(object.getCanonicalName()); + output.writeString(object.getName()); } @Override
Don't use the canonical name when serializing to gryo. The canonical name won't recognize the inner classes when deserializing with Class.forName() CTR
apache_tinkerpop
train
1e25e12537203438d3fffe94a847fe3355c412c4
diff --git a/NEWS b/NEWS index <HASH>..<HASH> 100644 --- a/NEWS +++ b/NEWS @@ -6,6 +6,16 @@ Changes and improvements to pybars, grouped by release. NEXT ---- +0.0.2 +----- + +* Add support for '{{else}}'. (Mjumbe Wawatu Ukweli, lp:997180) + +* Bump dependency on PyMeta to 0.5.0. (Robert Collins) + +0.0.1 +----- + * Initial release, passes acceptance tests from handlebars.js, except for deliberately skipped features (.data hashes and stringParams). (Robert Collins) diff --git a/pybars/_compiler.py b/pybars/_compiler.py index <HASH>..<HASH> 100644 --- a/pybars/_compiler.py +++ b/pybars/_compiler.py @@ -60,6 +60,7 @@ expression ::= <start> '{' <expression_inner>:e '}' => ('expand', ) + e escapedexpression ::= <start> <expression_inner>:e => ('escapedexpand', ) + e block_inner ::= <spaces> <symbol>:s <arguments>:args <spaces> <finish> => (u''.join(s), args) +alt_inner ::= <spaces> ('^' | 'e' 'l' 's' 'e') <spaces> <finish> partial ::= <start> '>' <block_inner>:i => ('partial',) + i path ::= ~('/') <pathseg>+:segments => ('path', segments) kwliteral ::= <symbol>:s '=' (<literal>|<path>):v => ('kwparam', s, v) @@ -71,7 +72,7 @@ false ::= 'f' 'a' 'l' 's' 'e' => False true ::= 't' 'r' 'u' 'e' => True notquote ::= <escapedquote> | (~('"') <anything>) escapedquote ::= '\\' '"' => '\\"' -symbol ::= '['? (<letterOrDigit>|'-'|'@')+:symbol ']'? => u''.join(symbol) +symbol ::= ~<alt_inner> '['? (<letterOrDigit>|'-'|'@')+:symbol ']'? => u''.join(symbol) pathseg ::= <symbol> | '/' => u'' | ('.' '.' '/') => u'__parent' @@ -82,7 +83,7 @@ blockrule ::= <start> '#' <block_inner>:i <template>:t <alttemplate>:alt_t <symbolfinish i[0]> => ('block',) + i + (t, alt_t) | <start> '^' <block_inner>:i <template>:t <symbolfinish i[0]> => ('invertedblock',) + i + (t,) -alttemplate ::= (<start>'^'<finish> <template>)?:alt_t => alt_t or [] +alttemplate ::= (<start> <alt_inner> <template>)?:alt_t => alt_t or [] """ # this grammar compiles the template to python diff --git a/pybars/tests/test_acceptance.py b/pybars/tests/test_acceptance.py index <HASH>..<HASH> 100644 --- a/pybars/tests/test_acceptance.py +++ b/pybars/tests/test_acceptance.py @@ -343,6 +343,7 @@ class TestAcceptance(TestCase): rootMessage = {'people': [], 'message': "Nobody's here"} src1 = u"{{#list people}}{{name}}{{^}}<em>Nobody's here</em>{{/list}}" src2 = u"{{#list people}}Hello{{^}}{{message}}{{/list}}" + src3 = u"{{#list people}}{{name}}{{else}}<em>Nobody's here</em>{{/list}}" helpers = {'list': list} # inverse not executed by helper: self.assertEqual("<ul><li>Alan</li><li>Yehuda</li></ul>", @@ -354,6 +355,11 @@ class TestAcceptance(TestCase): # helpers. self.assertEqual("<p>Nobody&#x27;s here</p>", render(src2, rootMessage, helpers=helpers)) + # inverse can also be denoted by 'else': + self.assertEqual("<ul><li>Alan</li><li>Yehuda</li></ul>", + render(src3, context, helpers)) + self.assertEqual("<p><em>Nobody's here</em></p>", + render(src3, empty, helpers)) def test_providing_a_helpers_hash(self): self.assertEqual("Goodbye cruel world!", diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ description = file( os.path.join(os.path.dirname(__file__), 'README'), 'rb').read() setup(name="pybars", - version="0.0.1", + version="0.0.2", description=\ "handlebars.js templating for Python.", long_description=description, diff --git a/versions.cfg b/versions.cfg index <HASH>..<HASH> 100644 --- a/versions.cfg +++ b/versions.cfg @@ -4,7 +4,7 @@ versions = versions [versions] fixtures = 0.3.6 iso8601 = 0.1.4 -PyMeta = 0.4.0 +PyMeta = 0.5.0 pytz = 2010o setuptools = 0.6c11 testtools = 0.9.11
<I> ----- * Add support for '{{else}}'. (Mjumbe Wawatu Ukweli, lp:<I>) * Bump dependency on PyMeta to <I>. (Robert Collins)
wbond_pybars3
train
edde29d7dbebd9fa697829d4c4c57be9e199afde
diff --git a/jbpm-flow/src/main/java/org/jbpm/process/instance/ProcessRuntimeImpl.java b/jbpm-flow/src/main/java/org/jbpm/process/instance/ProcessRuntimeImpl.java index <HASH>..<HASH> 100644 --- a/jbpm-flow/src/main/java/org/jbpm/process/instance/ProcessRuntimeImpl.java +++ b/jbpm-flow/src/main/java/org/jbpm/process/instance/ProcessRuntimeImpl.java @@ -53,6 +53,7 @@ import org.jbpm.workflow.core.node.EventTrigger; import org.jbpm.workflow.core.node.StartNode; import org.jbpm.workflow.core.node.Trigger; import org.kie.api.KieBase; +import org.kie.api.cluster.ClusterAwareService; import org.kie.api.command.ExecutableCommand; import org.kie.api.definition.process.Node; import org.kie.api.definition.process.Process; @@ -60,6 +61,7 @@ import org.kie.api.event.process.ProcessEventListener; import org.kie.api.event.rule.DefaultAgendaEventListener; import org.kie.api.event.rule.MatchCreatedEvent; import org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent; +import org.kie.api.internal.utils.ServiceRegistry; import org.kie.api.runtime.Context; import org.kie.api.runtime.EnvironmentName; import org.kie.api.runtime.KieSession; @@ -108,7 +110,12 @@ public class ProcessRuntimeImpl implements InternalProcessRuntime { } public void initStartTimers() { - KieBase kbase = kruntime.getKieBase(); + // if there is no service implementation registered or is cluster coordinator we should start timers + if(ServiceRegistry.ifSupported(ClusterAwareService.class, cluster -> !cluster.isCoordinator()).orElse(Boolean.FALSE)) { + return; + } + + KieBase kbase = kruntime.getKieBase(); Collection<Process> processes = kbase.getProcesses(); for (Process process : processes) { RuleFlowProcess p = (RuleFlowProcess) process; diff --git a/jbpm-services/jbpm-executor/src/main/java/org/jbpm/executor/impl/AbstractAvailableJobsExecutor.java b/jbpm-services/jbpm-executor/src/main/java/org/jbpm/executor/impl/AbstractAvailableJobsExecutor.java index <HASH>..<HASH> 100644 --- a/jbpm-services/jbpm-executor/src/main/java/org/jbpm/executor/impl/AbstractAvailableJobsExecutor.java +++ b/jbpm-services/jbpm-executor/src/main/java/org/jbpm/executor/impl/AbstractAvailableJobsExecutor.java @@ -312,8 +312,9 @@ public abstract class AbstractAvailableJobsExecutor { requestInfo.setRequestData(null); } } - + eventSupport.fireBeforeJobScheduled(requestInfo, null); executorStoreService.persistRequest(requestInfo, ((ExecutorImpl) executor).scheduleExecution(requestInfo, requestInfo.getTime())); + eventSupport.fireAfterJobScheduled(requestInfo, null); } } }
[JBPM-<I>] Add support to jBPM and runtime/cluster environments detection
kiegroup_jbpm
train
559e93c305b1a37d8ae7bfd3a4c98e7b3992d4f7
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -69,6 +69,7 @@ function run (options) { function receive(options, results) { if (options.dump) { + // TODO: Move this into fetch? return dump(options, results).then(map.bind(null, options)); } @@ -87,7 +88,7 @@ function dump (options, results) { fs.writeFile( target, - JSON.stringify(results, null, ' '), + JSON.stringify(results), { encoding: 'utf8', mode: 420 }, function (error) { if (error) {
Disable pretty-printing of intermediate results.
springernature_webpagetest-mapper
train
36dc3761dc1009c0af52366b17765501be7d0a39
diff --git a/i18n.class.php b/i18n.class.php index <HASH>..<HASH> 100644 --- a/i18n.class.php +++ b/i18n.class.php @@ -313,7 +313,7 @@ class i18n { $userLangs2 = array(); foreach ($userLangs as $key => $value) { // only allow a-z, A-Z and 0-9 and _ and - - if (preg_match('/^[a-zA-Z0-9_-]*$/', $value) === 1) + if (preg_match('/^[a-zA-Z0-9_-]+$/', $value) === 1) $userLangs2[$key] = $value; }
discard empty language codes at regex level
Philipp15b_php-i18n
train
1b1d483e5a84a60641a9924adc2f7db775c85368
diff --git a/quandl/message.py b/quandl/message.py index <HASH>..<HASH> 100644 --- a/quandl/message.py +++ b/quandl/message.py @@ -24,10 +24,10 @@ class Message: WARN_DATA_LIMIT_EXCEEDED = 'This call exceeds the amount of data that quandl.get_table() allows. \ Please use the following link in your browser, which will download the full results as \ - a CSV file: https://www.quandl.com/api/v3/datatables/%s?qopts.export=true&api_key=%s. See \ + a CSV file: https://www.quandl.com/api/v3/datatables/%s?qopts.export=true&api_key=%s . See \ our API documentation for more info: \ https://docs.quandl.com/docs/in-depth-usage-1#section-download-an-entire-table' - WARN_PAGE_LIMIT_EXCEEDED = 'To request more pages, please set paginate=true in your \ + WARN_PAGE_LIMIT_EXCEEDED = 'To request more pages, please set paginate=True in your \ quandl.get_table() call. For more information see our documentation: \ https://github.com/quandl/quandl-python/blob/master/FOR_ANALYSTS.md#things-to-note' WARN_PARAMS_NOT_SUPPORTED = '%s will no longer supported. Please use %s instead'
Fix two small typos. (#<I>)
quandl_quandl-python
train
1307bf30da77a1b945df2e52facb16bb85192689
diff --git a/django_xworkflows/models.py b/django_xworkflows/models.py index <HASH>..<HASH> 100644 --- a/django_xworkflows/models.py +++ b/django_xworkflows/models.py @@ -55,16 +55,23 @@ class StateFieldProperty(object): Similar to django.db.models.fields.subclassing.Creator, but doesn't raise AttributeError. """ - def __init__(self, field): + def __init__(self, field, parent_property): self.field = field + self.parent_property = parent_property def __get__(self, instance, owner): """Retrieve the related attributed from a class / an instance. If retrieving from an instance, return the actual value; if retrieving from a class, return the workflow. + + When working on instances with a .only() queryset, the instance value + could be hidden behind a DeferredAttribute. """ if instance: + if self.parent_property and hasattr(self.parent_property, '__get__'): + # We override a property. + return self.parent_property.__get__(instance, owner) return instance.__dict__.get(self.field.name, self.field.workflow.initial_state) else: return self.field.workflow @@ -110,7 +117,9 @@ class StateField(models.Field): Attaches a StateFieldProperty to wrap the attribute. """ super(StateField, self).contribute_to_class(cls, name) - setattr(cls, self.name, StateFieldProperty(self)) + + parent_property = getattr(cls, self.name, None) + setattr(cls, self.name, StateFieldProperty(self, parent_property)) def to_python(self, value): """Converts the DB-stored value into a Python value.""" diff --git a/docs/changelog.rst b/docs/changelog.rst index <HASH>..<HASH> 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,7 @@ ChangeLog - Fix compatibility issue with Django>=1.11 migration framework when adding both a ``WorkflowEnabled`` model a ``ForeignKey`` to it. + - Properly interact with Django's .only() querysets. 0.12.1 (2017-09-03) diff --git a/tests/djworkflows/tests.py b/tests/djworkflows/tests.py index <HASH>..<HASH> 100644 --- a/tests/djworkflows/tests.py +++ b/tests/djworkflows/tests.py @@ -148,7 +148,7 @@ class ModelTestCase(test.TestCase): self.assertEqual(1, len(models.MyWorkflowEnabled.objects.filter(state=bar))) self.assertEqual(0, len(models.MyWorkflowEnabled.objects.filter(state=baz))) - # Also test with only + # Also test with only() qs_only = models.MyWorkflowEnabled.objects.only('other') self.assertEqual([val.state.name for val in qs_only.filter(state=foo)], ['foo']) self.assertEqual([val.state.name for val in qs_only.filter(state=bar)], ['bar'])
Fix issue with Django qs.only() When fetching an object from a queryset with only() (<URL>) the StateField was not retrieved correctly and the default value was used instead. Closes #<I>.
rbarrois_django_xworkflows
train
bcc1d9d9f2dd341aa5b180bde226d8f8e9f68100
diff --git a/lib/tower_cli/resources/credential.py b/lib/tower_cli/resources/credential.py index <HASH>..<HASH> 100644 --- a/lib/tower_cli/resources/credential.py +++ b/lib/tower_cli/resources/credential.py @@ -43,8 +43,21 @@ class Resource(models.Resource): # What type of credential is this (machine, SCM, etc.)? kind = models.Field( help_text='The type of credential being added. ' - 'Valid options are: ssh, scm, aws, rax, gce, azure.', - type=click.Choice(['ssh', 'scm', 'aws', 'rax', 'gce', 'azure']), + 'Valid options are: ssh, scm, aws, rax, vmware,' + ' gce, azure, openstack.', + type=click.Choice(['ssh', 'scm', 'aws', 'rax', 'vmware', + 'gce', 'azure', 'openstack']), + ) + + # need host in order to use VMware + host = models.Field( + help_text = 'The hostname or IP address to use.', + required = False, + ) + # need project to use openstack + project = models.Field( + help_text = 'The identifier for the project.', + required = False ) # SSH and SCM fields. diff --git a/lib/tower_cli/resources/group.py b/lib/tower_cli/resources/group.py index <HASH>..<HASH> 100644 --- a/lib/tower_cli/resources/group.py +++ b/lib/tower_cli/resources/group.py @@ -19,7 +19,8 @@ from tower_cli import get_resource, models, resources from tower_cli.api import client from tower_cli.utils import exceptions as exc, types -INVENTORY_SOURCES = ['manual', 'ec2', 'rax', 'gce', 'azure'] +INVENTORY_SOURCES = ['manual', 'ec2', 'rax', 'vmware', + 'gce', 'azure', 'openstack'] class Resource(models.Resource): diff --git a/lib/tower_cli/resources/inventory_source.py b/lib/tower_cli/resources/inventory_source.py index <HASH>..<HASH> 100644 --- a/lib/tower_cli/resources/inventory_source.py +++ b/lib/tower_cli/resources/inventory_source.py @@ -32,7 +32,8 @@ class Resource(models.MonitorableResource): source = models.Field( default='manual', help_text='The type of inventory source in use.', - type=click.Choice(['manual', 'ec2', 'rax', 'gce', 'azure']), + type=click.Choice(['manual', 'ec2', 'rax', 'vmware', + 'gce', 'azure', 'openstack']), ) @click.argument('inventory_source', type=types.Related('inventory_source'))
upgrade to resolve #<I>, more types of credentials
ansible_tower-cli
train
bace223f1010475ff68347a88b2d7c59aea05606
diff --git a/h11/tests/test_events.py b/h11/tests/test_events.py index <HASH>..<HASH> 100644 --- a/h11/tests/test_events.py +++ b/h11/tests/test_events.py @@ -40,8 +40,10 @@ def test_event_bundle(): T(a=1, b=0, c=10) # missing required field - with pytest.raises(TypeError): + with pytest.raises(TypeError) as exc: T(b=0) + # make sure we error on the right missing kwarg + assert 'kwarg a' in str(exc) # _validate is called with pytest.raises(ValueError):
Fix EventBundle tests to make sure we're erroring on the right missing kwarg.
python-hyper_h11
train
3b6d98da8677b93f47cc526f91727d5cfbd140b8
diff --git a/audit/components/AuditFieldBehavior.php b/audit/components/AuditFieldBehavior.php index <HASH>..<HASH> 100644 --- a/audit/components/AuditFieldBehavior.php +++ b/audit/components/AuditFieldBehavior.php @@ -26,11 +26,9 @@ class AuditFieldBehavior extends CActiveRecordBehavior /** * Set to false if you just want to use getDbAttribute and other methods in this class. * If left unset the value will come from AuditModule::enableAuditField - * @see getEnableAuditField() - * @see setEnableAuditField() * @var bool */ - private $_enableAuditField; + public $enableAuditField; /** * Any additional models you want to use to write model and model_id audits to. If this array is not empty then @@ -328,23 +326,16 @@ class AuditFieldBehavior extends CActiveRecordBehavior } /** - * + * @param CComponent $owner */ - public function getEnableAuditField() + public function attach($owner) { - if ($this->_enableAuditField === null) { + parent::attach($owner); + if ($this->enableAuditField === null) { /** @var AuditModule $audit */ $audit = Yii::app()->getModule('audit'); - $this->_enableAuditField = $audit->enableAuditField; + $this->enableAuditField = $audit->enableAuditField; } } - /** - * @param $enableAuditField - */ - public function setEnableAuditField($enableAuditField) - { - $this->_enableAuditField = $enableAuditField; - } - }
better fix when enableAuditField is set to in behavior options, for #7
cornernote_yii-audit-module
train
416f80d82eabc2c65ece41a0d781f101625582f2
diff --git a/src/java/org/apache/cassandra/config/DatabaseDescriptor.java b/src/java/org/apache/cassandra/config/DatabaseDescriptor.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/config/DatabaseDescriptor.java +++ b/src/java/org/apache/cassandra/config/DatabaseDescriptor.java @@ -146,8 +146,8 @@ public class DatabaseDescriptor Yaml yaml = new Yaml(new Loader(constructor)); conf = (Config)yaml.load(input); - if (!System.getProperty("os.arch").contains("64")) - logger.info("32bit JVM detected. It is recommended to run Cassandra on a 64bit JVM for better performance."); + logger.info("Data files directories: " + Arrays.toString(conf.data_file_directories)); + logger.info("Commit log directory: " + conf.commitlog_directory); if (conf.commitlog_sync == null) { @@ -393,7 +393,9 @@ public class DatabaseDescriptor logger.debug("setting auto_bootstrap to " + conf.auto_bootstrap); } - if (conf.in_memory_compaction_limit_in_mb != null && conf.in_memory_compaction_limit_in_mb <= 0) + logger.info((conf.multithreaded_compaction ? "" : "Not ") + "using multi-threaded compaction"); + + if (conf.in_memory_compaction_limit_in_mb != null && conf.in_memory_compaction_limit_in_mb <= 0) { throw new ConfigurationException("in_memory_compaction_limit_in_mb must be a positive integer"); } diff --git a/src/java/org/apache/cassandra/service/CassandraDaemon.java b/src/java/org/apache/cassandra/service/CassandraDaemon.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/service/CassandraDaemon.java +++ b/src/java/org/apache/cassandra/service/CassandraDaemon.java @@ -119,6 +119,9 @@ public class CassandraDaemon */ protected void setup() { + // log warnings for different kinds of sub-optimal JVMs. tldr use 64-bit Oracle >= 1.6u32 + if (!System.getProperty("os.arch").contains("64")) + logger.info("32bit JVM detected. It is recommended to run Cassandra on a 64bit JVM for better performance."); String javaVersion = System.getProperty("java.version"); String javaVmName = System.getProperty("java.vm.name"); logger.info("JVM vendor/version: {}/{}", javaVmName, javaVersion);
add logging of data directories and multithreaded_compaction patch by Joaquin Casares; reviewed by jbellis for CASSANDRA-<I>
Stratio_stratio-cassandra
train
70da8343a93f9abaa2af329be634ba6a35a403ed
diff --git a/catsql/main.py b/catsql/main.py index <HASH>..<HASH> 100755 --- a/catsql/main.py +++ b/catsql/main.py @@ -78,7 +78,7 @@ class Viewer(object): nargs = json.loads(fin.read()) self.url = nargs['url'] self.tables = set(nargs['table']) - self.selected_columns = narg.get('column', []) + self.selected_columns = nargs.get('column', []) self.context_filters = nargs['context'] self.context_columns = set(nargs['hidden_columns']) if args.value is None: @@ -321,7 +321,7 @@ class Viewer(object): from subprocess import call EDITOR = os.environ.get('EDITOR', 'nano') call([EDITOR, edit_filename]) - call(['patchsql', self.args.catsql_database_url] + + call(['patchsql', self.url] + ['--table'] + self.tables_so_far + ['--follow', output_filename, edit_filename] + ['--safe-null'])
use correct url when patching from bookmark
paulfitz_catsql
train
6c814a00b9e814e056ee237b5ed4f1947eec1a48
diff --git a/rsrc.go b/rsrc.go index <HASH>..<HASH> 100644 --- a/rsrc.go +++ b/rsrc.go @@ -269,7 +269,7 @@ func run(fnamein, fnameico, fnameout string) error { N := `\[(\d+)\]` dir_n := regexp.MustCompile("^/Dir/Dirs" + N + "$") - //dir_n_n := regexp.MustCompile("^/Dir/Dirs" + N + "/Dirs" + N + "$") + dir_n_n := regexp.MustCompile("^/Dir/Dirs" + N + "/Dirs" + N + "$") //dataentry_n := regexp.MustCompile("^/DataEntries" + N + "$") //dataentry_n_off := regexp.MustCompile("^/DataEntries" + N + "/OffsetToData$") //data_n := regexp.MustCompile("^/Data" + N + "$") @@ -283,8 +283,8 @@ func run(fnamein, fnameico, fnameout string) error { diroff = offset //case "/Dir/Dirs[0]": // coff.Dir.DirEntries[0].OffsetToData = MASK_SUBDIRECTORY | (offset - diroff) - case "/Dir/Dirs[0]/Dirs[0]": - coff.Dir.Dirs[0].DirEntries[0].OffsetToData = MASK_SUBDIRECTORY | (offset - diroff) + //case "/Dir/Dirs[0]/Dirs[0]": + // coff.Dir.Dirs[0].DirEntries[0].OffsetToData = MASK_SUBDIRECTORY | (offset - diroff) case "/DataEntries[0]": direntry := <-leafwalker direntry.OffsetToData = offset - diroff @@ -302,6 +302,8 @@ func run(fnamein, fnameico, fnameout string) error { switch { case m.Find(path, dir_n): coff.Dir.DirEntries[m[0]].OffsetToData = MASK_SUBDIRECTORY | (offset - diroff) + case m.Find(path, dir_n_n): + coff.Dir.Dirs[m[0]].DirEntries[m[1]].OffsetToData = MASK_SUBDIRECTORY | (offset - diroff) } if Plain(v.Kind()) {
enabling new approach for dir_n_n
akavel_rsrc
train
df338c439939e5f9165d01e6b8e46fe6fbb75ec5
diff --git a/tests/config.py b/tests/config.py index <HASH>..<HASH> 100644 --- a/tests/config.py +++ b/tests/config.py @@ -9,24 +9,15 @@ from trezorlib.transport_hid import HidTransport devices = HidTransport.enumerate() if len(devices) > 0: - if devices[0][1] != None: - print('Using TREZOR') - TRANSPORT = HidTransport - TRANSPORT_ARGS = (devices[0],) - TRANSPORT_KWARGS = {'debug_link': False} - DEBUG_TRANSPORT = HidTransport - DEBUG_TRANSPORT_ARGS = (devices[0],) - DEBUG_TRANSPORT_KWARGS = {'debug_link': True} - else: - print('Using Raspberry Pi') - TRANSPORT = HidTransport - TRANSPORT_ARGS = (devices[0],) - TRANSPORT_KWARGS = {'debug_link': False} - DEBUG_TRANSPORT = SocketTransportClient - DEBUG_TRANSPORT_ARGS = ('trezor.bo:2000',) - DEBUG_TRANSPORT_KWARGS = {} + print('Using TREZOR') + TRANSPORT = HidTransport + TRANSPORT_ARGS = (devices[0],) + TRANSPORT_KWARGS = {'debug_link': False} + DEBUG_TRANSPORT = HidTransport + DEBUG_TRANSPORT_ARGS = (devices[0],) + DEBUG_TRANSPORT_KWARGS = {'debug_link': True} else: - print('Using Emulator') + print('Using Emulator(v1)') TRANSPORT = PipeTransport TRANSPORT_ARGS = ('/tmp/pipe.trezor', False) TRANSPORT_KWARGS = {}
tests: remove obsoleted raspi code
trezor_python-trezor
train
4b2170a5e33de86b2cd459bc2d0fe118b66af3b5
diff --git a/query/src/main/java/org/infinispan/query/dsl/impl/JPAQueryGeneratorVisitor.java b/query/src/main/java/org/infinispan/query/dsl/impl/JPAQueryGeneratorVisitor.java index <HASH>..<HASH> 100644 --- a/query/src/main/java/org/infinispan/query/dsl/impl/JPAQueryGeneratorVisitor.java +++ b/query/src/main/java/org/infinispan/query/dsl/impl/JPAQueryGeneratorVisitor.java @@ -17,13 +17,9 @@ class JPAQueryGeneratorVisitor implements Visitor<String> { private static final TimeZone GMT_TZ = TimeZone.getTimeZone("GMT"); - private final DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); - private static final String alias = "_gen0"; - public JPAQueryGeneratorVisitor() { - dateFormat.setTimeZone(GMT_TZ); - } + private DateFormat dateFormat; @Override public String visit(LuceneQueryBuilder luceneQueryBuilder) { @@ -292,10 +288,18 @@ class JPAQueryGeneratorVisitor implements Visitor<String> { } if (argument instanceof Date) { - sb.append('\'').append(dateFormat.format(argument)).append('\''); + sb.append('\'').append(getDateFormatter().format(argument)).append('\''); return; } sb.append(argument); } + + private DateFormat getDateFormatter() { + if (dateFormat == null) { + dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + dateFormat.setTimeZone(GMT_TZ); + } + return dateFormat; + } }
ISPN-<I> DateFormatter could be initialized lazily
infinispan_infinispan
train
9626360ec0fee59b1888f1ad369e58ca9daa0b35
diff --git a/lib/reek/smell_warning.rb b/lib/reek/smell_warning.rb index <HASH>..<HASH> 100644 --- a/lib/reek/smell_warning.rb +++ b/lib/reek/smell_warning.rb @@ -1,4 +1,5 @@ require 'forwardable' +require 'psych' module Reek # diff --git a/reek.gemspec b/reek.gemspec index <HASH>..<HASH> 100644 --- a/reek.gemspec +++ b/reek.gemspec @@ -33,6 +33,7 @@ Gem::Specification.new do |s| s.add_runtime_dependency('parser', ['~> 2.2.0.pre.7']) s.add_runtime_dependency('unparser', ['~> 0.2.2']) s.add_runtime_dependency('rainbow', ['>= 1.99', '< 3.0']) + s.add_runtime_dependency('psych', ['~> 2.0']) s.add_development_dependency('bundler', ['~> 1.1']) s.add_development_dependency('rake', ['~> 10.0']) diff --git a/spec/reek/smell_warning_spec.rb b/spec/reek/smell_warning_spec.rb index <HASH>..<HASH> 100644 --- a/spec/reek/smell_warning_spec.rb +++ b/spec/reek/smell_warning_spec.rb @@ -93,7 +93,6 @@ describe SmellWarning do before :each do @message = 'test message' @lines = [24, 513] - @class = 'FeatureEnvy' @context_name = 'Module::Class#method/block' # Use a random string and a random bool end
Force use of Psych for YAML serialization This ensures the #encode_with method is used and YAML output is the same on all platforms.
troessner_reek
train
0eee3bb0e3212bb9b6a81bc236479ed2e28d7ebe
diff --git a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/ScaleBarOverlay.java b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/ScaleBarOverlay.java index <HASH>..<HASH> 100644 --- a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/ScaleBarOverlay.java +++ b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/ScaleBarOverlay.java @@ -45,13 +45,14 @@ import org.osmdroid.util.constants.GeoConstants; import org.osmdroid.views.MapView; import org.osmdroid.views.MapView.Projection; -import android.app.Activity; +import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Picture; import android.graphics.Rect; +import android.view.WindowManager; public class ScaleBarOverlay extends Overlay implements GeoConstants { @@ -75,7 +76,7 @@ public class ScaleBarOverlay extends Overlay implements GeoConstants { // Internal - private final Activity activity; + private final Context context; protected final Picture scaleBarPicture = new Picture(); @@ -98,14 +99,14 @@ public class ScaleBarOverlay extends Overlay implements GeoConstants { // Constructors // =========================================================== - public ScaleBarOverlay(final Activity activity) { - this(activity, new DefaultResourceProxyImpl(activity)); + public ScaleBarOverlay(final Context context) { + this(context, new DefaultResourceProxyImpl(context)); } - public ScaleBarOverlay(final Activity activity, final ResourceProxy pResourceProxy) { + public ScaleBarOverlay(final Context context, final ResourceProxy pResourceProxy) { super(pResourceProxy); this.resourceProxy = pResourceProxy; - this.activity = activity; + this.context = context; this.barPaint = new Paint(); this.barPaint.setColor(Color.BLACK); @@ -120,11 +121,11 @@ public class ScaleBarOverlay extends Overlay implements GeoConstants { this.textPaint.setAlpha(255); this.textPaint.setTextSize(textSize); - this.xdpi = this.activity.getResources().getDisplayMetrics().xdpi; - this.ydpi = this.activity.getResources().getDisplayMetrics().ydpi; + this.xdpi = this.context.getResources().getDisplayMetrics().xdpi; + this.ydpi = this.context.getResources().getDisplayMetrics().ydpi; - this.screenWidth = this.activity.getResources().getDisplayMetrics().widthPixels; - this.screenHeight = this.activity.getResources().getDisplayMetrics().heightPixels; + this.screenWidth = this.context.getResources().getDisplayMetrics().widthPixels; + this.screenHeight = this.context.getResources().getDisplayMetrics().heightPixels; // DPI corrections for specific models String manufacturer = null; @@ -137,7 +138,9 @@ public class ScaleBarOverlay extends Overlay implements GeoConstants { if ("motorola".equals(manufacturer) && "DROIDX".equals(android.os.Build.MODEL)) { // If the screen is rotated, flip the x and y dpi values - if (activity.getWindowManager().getDefaultDisplay().getOrientation() > 0) { + WindowManager windowManager = (WindowManager) this.context + .getSystemService(Context.WINDOW_SERVICE); + if (windowManager.getDefaultDisplay().getOrientation() > 0) { this.xdpi = (float) (this.screenWidth / 3.75); this.ydpi = (float) (this.screenHeight / 2.1); } else {
Changing ScaleBarOverlay to take a Context rather than an activity in its constructor.
osmdroid_osmdroid
train
67f674d0387b49bdf06c38388381bedd96807cd4
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -198,7 +198,7 @@ function processCopy(result, urlMeta, opts, decl, oldValue) { urlMeta.value.indexOf('#') === 0 || /^[a-z]+:\/\//.test(urlMeta.value) ) { - updateUrl(decl, oldValue, urlMeta); + return updateUrl(decl, oldValue, urlMeta); } /**
return early when processing data/absolute/hash urls Currently the `updateUrl` gets called but goes on to try and process these urls just like any other, usually failing.
geut_postcss-copy
train
7e8288a8640c459e0dd6fbbc02f23e95f8c0dc7d
diff --git a/graph/functions/planarity/kocay_algorithm.py b/graph/functions/planarity/kocay_algorithm.py index <HASH>..<HASH> 100644 --- a/graph/functions/planarity/kocay_algorithm.py +++ b/graph/functions/planarity/kocay_algorithm.py @@ -44,7 +44,7 @@ def kocay_planarity_test(graph): def __setup_dfs_data(graph, adj): """Sets up the dfs_data object, for consistency.""" - dfs_data = __get_dfs_data(graph) + dfs_data = __get_dfs_data(graph, adj) dfs_data['graph'] = graph dfs_data['adj'] = adj @@ -113,7 +113,7 @@ def __branch_point_dfs(dfs_data): stem = {} stem[u] = u b = {} - b[u] = 0 + b[u] = 1 __branch_point_dfs_recursive(u, large_n, b, stem, dfs_data) dfs_data['N_u_lookup'] = large_n dfs_data['b_u_lookup'] = b @@ -122,28 +122,30 @@ def __branch_point_dfs(dfs_data): def __branch_point_dfs_recursive(u, large_n, b, stem, dfs_data): """A recursive implementation of the BranchPtDFS function, as defined on page 14 of the paper.""" - t = dfs_data['adj'][u][0] - large_w = wt(u, t, dfs_data) + first_vertex = dfs_data['adj'][u][0] + large_w = wt(u, first_vertex, dfs_data) if large_w % 2 == 0: large_w += 1 v_I = 0 v_II = 0 for v in [v for v in dfs_data['adj'][u] if wt(u, v, dfs_data) <= large_w]: - if a(v, dfs_data) == u: + stem[u] = v # not in the original paper, but a logical extension based on page 13 + if a(v, dfs_data) == u: # uv is a tree edge large_n[v] = 0 if wt(u, v, dfs_data) % 2 == 0: v_I = v else: b_u = b[u] l2_v = L2(v, dfs_data) - if l2_v > b_u: + #if l2_v > b_u: # If this is true, then we're not on a branch at all - continue + # continue if l2_v < b_u: large_n[v] = 1 elif b_u != 1: print stem print dfs_data['lowpoint_2_lookup'] + print b xnode = stem[l2_v] if large_n[xnode] != 0: large_n[v] = large_n[xnode] + 1
Code tweaks to fix misunderstandings in algorithm implementation
jciskey_pygraph
train
150de100f4b9cc55525c5a1ede8241be853439a9
diff --git a/guide/gatsby-node.js b/guide/gatsby-node.js index <HASH>..<HASH> 100644 --- a/guide/gatsby-node.js +++ b/guide/gatsby-node.js @@ -10,8 +10,8 @@ function modifyWebpackConfig(_ref, options) { if (stage === 'build-javascript' || stage === 'develop') { addElmLoader(config); } - addRawLoader(config); addMarkdownLoader(config); + addStyleGuideBabelLoader(config); return config; } @@ -116,13 +116,6 @@ function addSvgLoaders(config) { }); } -function addRawLoader(config) { - config.loader('raw-loader', { - test: /\.md$/, - loaders: ['raw-loader'], - }); -} - function addMarkdownLoader(config) { const babelConfig = { presets: ['env', 'stage-0', 'react'], @@ -139,7 +132,7 @@ function addMarkdownLoader(config) { ], }; config.loader('markdown-component-loader', { - test: /\.mdx$/i, + test: /\.mdx?$/i, loaders: [ 'babel-loader?' + JSON.stringify(babelConfig), require.resolve('./src/webpack-util/markdownWrapper.js'), @@ -148,6 +141,21 @@ function addMarkdownLoader(config) { }); } +function addStyleGuideBabelLoader(config) { + const babelConfig = { + presets: ['env', 'stage-0', 'react'], + }; + config.loader('style-guide-babel', { + test: /\.jsx?$/i, + include: path.resolve( + 'node_modules', + 'cultureamp-style-guide', + 'components' + ), + loaders: ['babel-loader?' + JSON.stringify(babelConfig)], + }); +} + function addSrcResolveRoot(config) { config.merge({ resolve: { diff --git a/util/error.js b/util/error.js index <HASH>..<HASH> 100644 --- a/util/error.js +++ b/util/error.js @@ -1,19 +1,26 @@ -const chalk = require('chalk'); +const red = '\u001b[31m '; +const yellow = '\u001b[33m '; +const reset = '\u001b[0m '; function error(message) { throw new Error( - chalk.red(`\nCULTUREAMP STYLE GUIDE ERROR:\n${singleLine(message)}\n`) + `${red}\nCULTUREAMP STYLE GUIDE ERROR:\n${singleLine(message)}${reset}\n` ); } function warn(message) { console.warn( - chalk.yellow(`\nCULTUREAMP STYLE GUIDE WARNING:\n${singleLine(message)}\n`) + `${yellow}\nCULTUREAMP STYLE GUIDE WARNING:\n${singleLine( + message + )}${reset}\n` ); } function singleLine(string) { - return string.replace(/^ +/gm, ' ').replace(/\n|\r/gm, '').trim(); + return string + .replace(/^ +/gm, ' ') + .replace(/\n|\r/gm, '') + .trim(); } module.exports = {
Fix the build after gatsby upgrade - Babel seems to no longer process node_modules with Babel by default - Get cultureamp-style-guide repo to be processed with babel - No longer include chalk in runtime code as it uses ES6 features - BONUS: get rid of "raw-loader" for md files, and treat them the same as mdx files
cultureamp_cultureamp-style-guide
train
6726b1d45347e8c5691c4b902b346ff0a06f3f67
diff --git a/concrete/controllers/frontend/assets_localization.php b/concrete/controllers/frontend/assets_localization.php index <HASH>..<HASH> 100644 --- a/concrete/controllers/frontend/assets_localization.php +++ b/concrete/controllers/frontend/assets_localization.php @@ -29,6 +29,7 @@ var ccmi18n = ' . json_encode([ 'deleteBlockMsg' => t('The block has been removed successfully.'), 'addBlock' => t('Add Block'), 'addBlockNew' => t('Add Block'), + 'addBlockContainer' => t('Add Container'), 'addBlockStack' => t('Add Stack'), 'addBlockStackMsg' => t('The stack has been added successfully'), 'addBlockPaste' => t('Paste from Clipboard'), @@ -46,6 +47,7 @@ var ccmi18n = ' . json_encode([ 'confirmLayoutPresetDelete' => t('Are you sure you want to delete this layout preset?'), 'setAreaPermissions' => t('Set Permissions'), 'addBlockMsg' => t('The block has been added successfully.'), + 'addBlockContainerMsg' => t('The container has been added successfully.'), 'updateBlock' => t('Update Block'), 'updateBlockMsg' => t('The block has been saved successfully.'), 'copyBlockToScrapbookMsg' => t('The block has been added to your clipboard.'),
Added success message and title when adding containers to the page
concrete5_concrete5
train
51c86d2552bae431f867d45aee0dd2d2962230b8
diff --git a/pushbullet_cli/app.py b/pushbullet_cli/app.py index <HASH>..<HASH> 100755 --- a/pushbullet_cli/app.py +++ b/pushbullet_cli/app.py @@ -83,7 +83,7 @@ def purge(): pb.delete_pushes() [email protected]("dismiss", help="Mark all your pushes as read") [email protected]("dismiss", help="Mark all your pushes as read.") def dismiss(): pb = _get_pb() @@ -92,7 +92,7 @@ def dismiss(): pb.dismiss_push(current_push['iden']) [email protected]("list-devices", help="List your devices") [email protected]("list-devices", help="List your devices.") def list_devices(): pb = _get_pb() for i, device in enumerate(pb.devices): @@ -105,12 +105,12 @@ def set_key(): keyring.set_password("pushbullet", "cli", key) [email protected]("delete-key", help="Remove your API key from the system keyring") [email protected]("delete-key", help="Remove your API key from the system keyring.") def delete_key(): keyring.delete_password("pushbullet", "cli") [email protected]("sms", help="Send an SMS") [email protected]("sms", help="Send an SMS.") @click.option("-d", "--device", type=int, default=None, required=True, help="Device index to send SMS from. Use pb list-devices to get the indices") @click.option("-n", "--number", type=str, default=None, required=True, help="The phone number to send the SMS to") @click.argument('message', default=None, required=False)
Add trailing dots to command help strings
GustavoKatel_pushbullet-cli
train
b1b4cf0cefdf04bbde77eb04843aee08f014d05e
diff --git a/modules/social_features/social_mentions/js/jquery.mentions.ckeditor.js b/modules/social_features/social_mentions/js/jquery.mentions.ckeditor.js index <HASH>..<HASH> 100644 --- a/modules/social_features/social_mentions/js/jquery.mentions.ckeditor.js +++ b/modules/social_features/social_mentions/js/jquery.mentions.ckeditor.js @@ -525,4 +525,3 @@ }).call(this); -//# sourceMappingURL=jquery.mentions.js.map \ No newline at end of file
Merge pull request #<I> from goalgorilla/feature/<I> Issue #<I>: Failed to load resource: jquery.mentions.js.map
goalgorilla_open_social
train
f114c40846eab7cd62df1fdd424d83ffa7f510b3
diff --git a/test/transport.test.js b/test/transport.test.js index <HASH>..<HASH> 100644 --- a/test/transport.test.js +++ b/test/transport.test.js @@ -430,6 +430,45 @@ describe('transport', function () { }) }) + it('transport-star-pin-object', function (done) { + var tt = make_test_transport() + + Seneca({timeout: 5555, log: 'silent', debug: {short_logs: true}}) + .use(tt) + .add('foo:1', testact) + .add('foo:2', testact) + .listen({type: 'test', pin: {'foo':'*'}}) + .ready(function () { + var si = Seneca({timeout: 5555, log: 'silent', debug: {short_logs: true}}) + .use(tt) + + .client({type: 'test', pin: {'foo': '*'}}) + + .start(done) + + .wait('foo:1') + .step(function (out) { + expect(out.foo).to.equal(1) + return true + }) + + .wait('foo:2') + .step(function (out) { + expect(out.foo).to.equal(2) + return true + }) + + .wait(function (data, done) { + si.act('bar:1', function (err, out) { + expect(err.code).to.equal('act_not_found') + done() + }) + }) + + .end() + }) + }) + it('transport-single-notdef', function (done) { var tt = make_test_transport()
added test that fails with pin as object
senecajs_seneca
train
ec7aa793741d2393b1eec7324c9f6b1552086315
diff --git a/lib/ruote/exp/fe_set.rb b/lib/ruote/exp/fe_set.rb index <HASH>..<HASH> 100644 --- a/lib/ruote/exp/fe_set.rb +++ b/lib/ruote/exp/fe_set.rb @@ -114,6 +114,29 @@ module Ruote::Exp # set 'f_${v:v}' => 'val2' # end # + # === shorter form and non-string values + # + # Dollar substitutions like '${a}' will always squash the field or the + # variable into a string. It's useful, especially when one is doing + # 'user-${name}', but when the field (or variable) is an array or an hash + # + # set 'f' => '${array}' + # + # will put the string representation of array into the field 'f', not + # a copy of the array itself. + # + # This will copy the array into the field 'f': + # + # set 'f' => '$f:array' + # + # Note the mandatory 'f:'. There is a thing to be aware of: if the field + # array is missing, it will resolve into "$f:array" (no substitution at all). + # + # There is always the old-style fallback: + # + # set :field => 'f', :field_value => 'array' + # + # # == set and rset # # Some gems (Sinatra) for example may provide a set method that hides calls
precisions about dollar substitution in reply to: <URL>
jmettraux_ruote
train
4022b04acb98420db1ca74497279457b0976528c
diff --git a/zhaquirks/xiaomi/__init__.py b/zhaquirks/xiaomi/__init__.py index <HASH>..<HASH> 100644 --- a/zhaquirks/xiaomi/__init__.py +++ b/zhaquirks/xiaomi/__init__.py @@ -393,9 +393,9 @@ class PressureMeasurementCluster(CustomCluster, PressureMeasurement): self.endpoint.device.pressure_bus.add_listener(self) def _update_attribute(self, attrid, value): - # drop values above and below documented range for this sensor + # drop unreasonable values # value is in hectopascals - if attrid == self.ATTR_ID and (300 <= value <= 1100): + if attrid == self.ATTR_ID and (0 <= value <= 1100): super()._update_attribute(attrid, value) def pressure_reported(self, value):
Expand usable pressure range of Aquara weather sensor (#<I>) While the device specs list the pressure sensor going down to <I>kPa, the device still generates usable data below that. fixes #<I>
dmulcahey_zha-device-handlers
train
47960cc9a6c617ee51b449ab02d1b86fbd541d5a
diff --git a/Command/AbstractCommand.php b/Command/AbstractCommand.php index <HASH>..<HASH> 100644 --- a/Command/AbstractCommand.php +++ b/Command/AbstractCommand.php @@ -61,6 +61,10 @@ abstract class AbstractCommand extends ContainerAwareCommand false ); - return end($bundles); + foreach ($bundles as $bundle) { + if ($bundle->getName() == $bundleName) { + return $bundle; + } + } } }
Commands updated to allow any bundle with any inheritance.
claroline_MigrationBundle
train
5a8902365f5b76eccf6514069a2f86b88720e432
diff --git a/BaragonService/src/main/java/com/hubspot/baragon/service/elb/ApplicationLoadBalancer.java b/BaragonService/src/main/java/com/hubspot/baragon/service/elb/ApplicationLoadBalancer.java index <HASH>..<HASH> 100644 --- a/BaragonService/src/main/java/com/hubspot/baragon/service/elb/ApplicationLoadBalancer.java +++ b/BaragonService/src/main/java/com/hubspot/baragon/service/elb/ApplicationLoadBalancer.java @@ -129,19 +129,13 @@ public class ApplicationLoadBalancer extends ElasticLoadBalancer { return Optional.absent(); } - public Collection<TargetDescription> getTargetsOn(TargetGroup targetGroup) { + public Collection<TargetHealthDescription> getTargetsOn(TargetGroup targetGroup) { DescribeTargetHealthRequest targetHealthRequest = new DescribeTargetHealthRequest() .withTargetGroupArn(targetGroup.getTargetGroupArn()); - Collection<TargetHealthDescription> targetHealth = elbClient + + return elbClient .describeTargetHealth(targetHealthRequest) .getTargetHealthDescriptions(); - - Collection<TargetDescription> targets = new HashSet<>(); - for (TargetHealthDescription targetHealthDescription : targetHealth) { - targets.add(targetHealthDescription.getTarget()); - } - - return targets; } @Override diff --git a/BaragonService/src/main/java/com/hubspot/baragon/service/resources/AlbResource.java b/BaragonService/src/main/java/com/hubspot/baragon/service/resources/AlbResource.java index <HASH>..<HASH> 100644 --- a/BaragonService/src/main/java/com/hubspot/baragon/service/resources/AlbResource.java +++ b/BaragonService/src/main/java/com/hubspot/baragon/service/resources/AlbResource.java @@ -28,9 +28,9 @@ import com.amazonaws.services.elasticloadbalancingv2.model.ModifyRuleRequest; import com.amazonaws.services.elasticloadbalancingv2.model.ModifyTargetGroupRequest; import com.amazonaws.services.elasticloadbalancingv2.model.Rule; import com.amazonaws.services.elasticloadbalancingv2.model.RuleNotFoundException; -import com.amazonaws.services.elasticloadbalancingv2.model.TargetDescription; import com.amazonaws.services.elasticloadbalancingv2.model.TargetGroup; import com.amazonaws.services.elasticloadbalancingv2.model.TargetGroupNotFoundException; +import com.amazonaws.services.elasticloadbalancingv2.model.TargetHealthDescription; import com.google.common.base.Optional; import com.google.inject.Inject; import com.hubspot.baragon.auth.NoAuth; @@ -297,7 +297,7 @@ public class AlbResource { @GET @NoAuth @Path("/target-groups/{targetGroup}/targets") - public Collection<TargetDescription> getTargets(@PathParam("targetGroup") String targetGroup) { + public Collection<TargetHealthDescription> getTargets(@PathParam("targetGroup") String targetGroup) { if (config.isPresent()) { try { Optional<TargetGroup> maybeTargetGroup = applicationLoadBalancer.getTargetGroup(targetGroup); diff --git a/BaragonUI/app/components/targetGroupDetail/TargetGroupDetail.jsx b/BaragonUI/app/components/targetGroupDetail/TargetGroupDetail.jsx index <HASH>..<HASH> 100644 --- a/BaragonUI/app/components/targetGroupDetail/TargetGroupDetail.jsx +++ b/BaragonUI/app/components/targetGroupDetail/TargetGroupDetail.jsx @@ -60,8 +60,10 @@ const TargetGroupDetail = ({targets, targetGroup, loadBalancerArnsToNames, edita <DetailGroup name="Instances" items={targets} keyGetter={(instance) => instance.id} field={ (instance) => ( <ul className="list-unstyled"> - <li><strong>ID:</strong> {instance.id}</li> - <li><strong>Port</strong>: {instance.port}</li> + <li><strong>ID:</strong> {instance.target.id}</li> + <li><strong>Port</strong>: {instance.target.port}</li> + <li><strong>Status</strong>: {instance.targetHealth.state}</li> + { instance.targetHealth.reason && <li><strong>Reason</strong>: {instance.targetHealth.reason}</li>} </ul> ) } @@ -79,8 +81,14 @@ const TargetGroupDetail = ({targets, targetGroup, loadBalancerArnsToNames, edita TargetGroupDetail.propTypes = { targets: PropTypes.arrayOf(PropTypes.shape({ - id: PropTypes.string, - port: PropTypes.number + target: PropTypes.shape({ + id: PropTypes.string, + port: PropTypes.string, + }), + targetHealth: PropTypes.shape({ + state: PropTypes.oneOf(['healthy', 'initial', 'unhealthy', 'unused', 'draining']), + reason: PropTypes.string, + }) })), targetGroup: PropTypes.object, loadBalancerArnsToNames: PropTypes.object,
Show health information for instance on ALBs Show health details (eg, healthy, unhealthy, initial, ...) for instances that are attached to an application load balancer. This was relatively low-hanging fruit because I already had the information available but was throwing it away on the backend. This includes both the change to the resource to make this happen and the change to the front-end to visualize it. Ideally.
HubSpot_Baragon
train
3d9a5a3164ee1c340df2c07e0f6b388cb942faeb
diff --git a/internal/cmd/gentokens/main.go b/internal/cmd/gentokens/main.go index <HASH>..<HASH> 100644 --- a/internal/cmd/gentokens/main.go +++ b/internal/cmd/gentokens/main.go @@ -182,6 +182,8 @@ func _main() error { {Ident: "VARCHAR"}, {Ident: "YEAR"}, {Ident: "ZEROFILL"}, + {Ident: "ASC"}, + {Ident: "DESC"}, } for _, tok := range tokens { diff --git a/tokens_gen.go b/tokens_gen.go index <HASH>..<HASH> 100644 --- a/tokens_gen.go +++ b/tokens_gen.go @@ -152,6 +152,8 @@ const ( VARCHAR YEAR ZEROFILL + ASC + DESC ) var keywordIdentMap = map[string]TokenType{ @@ -264,6 +266,8 @@ var keywordIdentMap = map[string]TokenType{ "VARCHAR": VARCHAR, "YEAR": YEAR, "ZEROFILL": ZEROFILL, + "ASC": ASC, + "DESC": DESC, } func (t TokenType) String() string { @@ -528,6 +532,10 @@ func (t TokenType) String() string { return "YEAR" case ZEROFILL: return "ZEROFILL" + case ASC: + return "ASC" + case DESC: + return "DESC" } return "(invalid)" }
include ASC/DESC tokens
schemalex_schemalex
train
898f6155cabbbe43a4cd50d01ec90754ff139929
diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ws/IndexAction.java b/server/sonar-server/src/main/java/org/sonar/server/platform/ws/IndexAction.java index <HASH>..<HASH> 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ws/IndexAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/ws/IndexAction.java @@ -80,7 +80,7 @@ public class IndexAction implements WsAction { json.beginObject(); i18n.getPropertyKeys().forEach(messageKey -> json.prop(messageKey, i18n.message(locale, messageKey, messageKey))); json.endObject(); - json.endObject().close(); + json.endObject(); } } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/ws/CacheWriter.java b/server/sonar-server/src/main/java/org/sonar/server/ws/CacheWriter.java index <HASH>..<HASH> 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/ws/CacheWriter.java +++ b/server/sonar-server/src/main/java/org/sonar/server/ws/CacheWriter.java @@ -30,10 +30,12 @@ import org.apache.commons.io.IOUtils; class CacheWriter extends Writer { private final StringWriter bufferWriter; private final Writer outputWriter; + private boolean isClosed; CacheWriter(Writer outputWriter) { this.bufferWriter = new StringWriter(); this.outputWriter = outputWriter; + this.isClosed = false; } @Override @@ -48,7 +50,12 @@ class CacheWriter extends Writer { @Override public void close() throws IOException { + if (isClosed) { + return; + } + IOUtils.write(bufferWriter.toString(), outputWriter); outputWriter.close(); + this.isClosed = true; } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/ws/CacheWriterTest.java b/server/sonar-server/src/test/java/org/sonar/server/ws/CacheWriterTest.java index <HASH>..<HASH> 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/ws/CacheWriterTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/ws/CacheWriterTest.java @@ -21,12 +21,16 @@ package org.sonar.server.ws; import java.io.IOException; import java.io.StringWriter; +import java.io.Writer; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; public class CacheWriterTest { - private StringWriter writer = new StringWriter(); + private Writer writer = new StringWriter(); private CacheWriter underTest = new CacheWriter(writer); @Test @@ -38,4 +42,15 @@ public class CacheWriterTest { assertThat(writer.toString()).isEqualTo("content"); } + + @Test + public void close_encapsulated_writer_once() throws IOException { + writer = mock(Writer.class); + underTest = new CacheWriter(writer); + + underTest.close(); + underTest.close(); + + verify(writer, times(1)).close(); + } }
SONAR-<I> CacheWriter closes encapsulated writer once
SonarSource_sonarqube
train
bee7e6551a0b70a841be229458f38183fc3d34db
diff --git a/lib/serif/admin_server.rb b/lib/serif/admin_server.rb index <HASH>..<HASH> 100755 --- a/lib/serif/admin_server.rb +++ b/lib/serif/admin_server.rb @@ -184,6 +184,7 @@ class AdminServer relative_path = "/images/#{uid}#{File.extname(filename)}" FileUtils.mkdir_p(File.join(site.directory, "images")) + FileUtils.mkdir_p(File.join(site_path("images"))) # move to the source directory FileUtils.mv(tempfile.path, File.join(site.directory, relative_path))
mkdir_p the source directory.
aprescott_serif
train
4203bcd96bd48cc3b3a3b16d39eabc824de1d6ac
diff --git a/tests/test_np.py b/tests/test_np.py index <HASH>..<HASH> 100755 --- a/tests/test_np.py +++ b/tests/test_np.py @@ -6,6 +6,7 @@ Created on Wed Feb 24 19:49:23 2016 """ import unittest +import unittest.mock import np import sys @@ -37,6 +38,24 @@ class QuickSubscriptArray(NPTestCase): self.assertIdenticalArray(np[[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]]], np.array(a3d)) + +class QuickSubscriptMatrix(NPTestCase): + def test_row(self): + self.assertIdenticalArray(np.m[1,2,3], np.array([[1,2,3]])) + + def test_matrix_singlecolon(self): + self.assertIdenticalArray(np.m[1,2 : 3,4 : 5,6], np.array([[1,2],[3,4],[5,6]])) + + def test_matrix_doublecolon(self): + self.assertIdenticalArray(np.m[1,2: + :3,4: + :5,6], np.array([[1,2],[3,4],[5,6]])) + + def test_mixed_values(self): + self.assertIdenticalArray(np.m[1,2.3:4,5.6], np.array([[1,2.3],[4,5.6]])) + + def test_float_values(self): + self.assertIdenticalArray(np.m[1.0, 2.0: 3.0, 4.0], np.array([[1.0, 2.0],[3.0,4.0]])) class QuickArray(NPTestCase): def test_0D(self): @@ -64,7 +83,14 @@ def for_dtype_shortcuts(test_method): for shortcut, dtype in np.np_quick_types.items(): test_method(self, getattr(np, shortcut), dtype) return test_for_all_shortcuts - + + +def for_dtype_matrix_shortcuts(test_method): + def test_for_all_shortcuts(self): + for shortcut, dtype in np.np_quick_types.items(): + test_method(self, getattr(np.m, shortcut), dtype) + return test_for_all_shortcuts + class QuickTypeSubscriptArray(NPTestCase): @for_dtype_shortcuts @@ -92,7 +118,30 @@ class QuickTypeSubscriptArray(NPTestCase): [[ 6, 7], [ 8, 9], [10, 11]]], np.array(a3d, dtype=dtype)) [email protected]("Skipping dtyped subscript matrices (not yet implemented)") +class QuickTypeSubscriptMatrix(NPTestCase): + @for_dtype_matrix_shortcuts + def test_row(self, sc, dtype): + self.assertIdenticalArray(sc[1,2,3], np.array([[1,2,3]], dtype=dtype)) + @for_dtype_matrix_shortcuts + def test_matrix_singlecolon(self, sc, dtype): + self.assertIdenticalArray(sc[1,2 : 3,4 : 5,6], np.array([[1,2],[3,4],[5,6]], dtype=dtype)) + + @for_dtype_matrix_shortcuts + def test_matrix_doublecolon(self, sc, dtype): + self.assertIdenticalArray(sc[1,2: + :3,4: + :5,6], np.array([[1,2],[3,4],[5,6]], dtype=dtype)) + + @for_dtype_matrix_shortcuts + def test_mixed_values(self, sc, dtype): + self.assertIdenticalArray(sc[1,2.3:4,5.6], np.array([[1,2.3],[4,5.6]], dtype=dtype)) + + @for_dtype_matrix_shortcuts + def test_float_values(self, sc, dtype): + self.assertIdenticalArray(sc[1.0, 2.0: 3.0, 4.0], np.array([[1.0, 2.0],[3.0,4.0]], dtype=dtype)) + class QuickTypeArray(NPTestCase): @for_dtype_shortcuts def test_0D(self, sc, dtype): @@ -121,4 +170,4 @@ class QuickTypeArray(NPTestCase): self.assertIdenticalArray(sc(a3d), np.array(a3d, dtype=dtype)) if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main()
Tests for new 2-D matrix syntax
k7hoven_np
train
f9914f3edd83c947bb29579e1775a205709b4455
diff --git a/arquillian/container-managed/src/main/java/org/jboss/as/arquillian/container/managed/JBossAsManagedContainer.java b/arquillian/container-managed/src/main/java/org/jboss/as/arquillian/container/managed/JBossAsManagedContainer.java index <HASH>..<HASH> 100644 --- a/arquillian/container-managed/src/main/java/org/jboss/as/arquillian/container/managed/JBossAsManagedContainer.java +++ b/arquillian/container-managed/src/main/java/org/jboss/as/arquillian/container/managed/JBossAsManagedContainer.java @@ -16,21 +16,9 @@ */ package org.jboss.as.arquillian.container.managed; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Logger; - -import javax.management.MBeanServerConnection; - import org.jboss.arquillian.protocol.jmx.JMXMethodExecutor; -import org.jboss.arquillian.protocol.jmx.JMXTestRunnerMBean; import org.jboss.arquillian.protocol.jmx.JMXMethodExecutor.ExecutionType; +import org.jboss.arquillian.protocol.jmx.JMXTestRunnerMBean; import org.jboss.arquillian.spi.Configuration; import org.jboss.arquillian.spi.ContainerMethodExecutor; import org.jboss.arquillian.spi.Context; @@ -39,6 +27,17 @@ import org.jboss.as.arquillian.container.AbstractDeployableContainer; import org.jboss.as.arquillian.container.JBossAsContainerConfiguration; import org.jboss.as.arquillian.container.MBeanServerConnectionProvider; +import javax.management.MBeanServerConnection; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + /** * JBossASEmbeddedContainer * @@ -50,6 +49,7 @@ public class JBossAsManagedContainer extends AbstractDeployableContainer { private final Logger log = Logger.getLogger(JBossAsManagedContainer.class.getName()); private MBeanServerConnectionProvider provider; private Process process; + private Thread shutdownThread; @Override public void setup(Context context, Configuration configuration) { @@ -114,6 +114,22 @@ public class JBossAsManagedContainer extends AbstractDeployableContainer { Thread.sleep(100); timeout -= 100; } + final Process proc = process; + shutdownThread = new Thread(new Runnable() { + @Override + public void run() { + if (proc != null) { + proc.destroy(); + try { + proc.waitFor(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } + }); + Runtime.getRuntime().addShutdownHook(shutdownThread); + } catch (Exception e) { throw new LifecycleException("Could not start container", e); } @@ -121,6 +137,10 @@ public class JBossAsManagedContainer extends AbstractDeployableContainer { @Override public void stop(Context context) throws LifecycleException { + if(shutdownThread != null) { + Runtime.getRuntime().removeShutdownHook(shutdownThread); + shutdownThread = null; + } try { if (process != null) { process.destroy();
Register a shutdown hook so the container is always stopped
wildfly_wildfly
train
e0a90f0c0e16ab81e31712c18cc05b1ca98bd388
diff --git a/nxviz/__init__.py b/nxviz/__init__.py index <HASH>..<HASH> 100644 --- a/nxviz/__init__.py +++ b/nxviz/__init__.py @@ -1,3 +1,3 @@ from nxviz.plots import ArcPlot, CircosPlot, MatrixPlot # NOQA -__version__ = 0.3.3 +__version__ = "0.3.3"
version is now encoded in a string...
ericmjl_nxviz
train
e017829685e756cadd95b79807f914fb1cd6f594
diff --git a/entity/templates/src/main/java/package/domain/_Entity.java b/entity/templates/src/main/java/package/domain/_Entity.java index <HASH>..<HASH> 100644 --- a/entity/templates/src/main/java/package/domain/_Entity.java +++ b/entity/templates/src/main/java/package/domain/_Entity.java @@ -1,6 +1,17 @@ package <%=packageName%>.domain; <% if (databaseType == 'cassandra') { %> -import com.datastax.driver.mapping.annotations.*;<% } %><% if (relationships.length > 0 && (fieldsContainOwnerManyToMany == false || fieldsContainOwnerOneToOne == false || fieldsContainOneToMany == true)) { %> +import com.datastax.driver.mapping.annotations.*;<% } %><% +var importJsonignore = false; +for (relationshipId in relationships) { + if (relationships[relationshipId].relationshipType == 'one-to-many') { + importJsonignore = true; + } else if (relationships[relationshipId].relationshipType == 'one-to-one' && relationships[relationshipId].ownerSide == false) { + importJsonignore = true; + } else if (relationships[relationshipId].relationshipType == 'many-to-many' && relationships[relationshipId].ownerSide == false) { + importJsonignore = true; + } +} +if (importJsonignore) { %> import com.fasterxml.jackson.annotation.JsonIgnore;<% } %><% if (fieldsContainCustomTime == true) { %> import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;<% } %><% if (fieldsContainLocalDate == true) { %>
Corrected missing import when the user had two many-to-many relationships, one owner and one non-owner
jhipster_generator-jhipster
train
bd1d1f062a951e7e77f0c5dd9c0b5e7ad6995ce5
diff --git a/cmd/clicheck/check_cli_conventions.go b/cmd/clicheck/check_cli_conventions.go index <HASH>..<HASH> 100644 --- a/cmd/clicheck/check_cli_conventions.go +++ b/cmd/clicheck/check_cli_conventions.go @@ -25,10 +25,6 @@ import ( cmdsanity "k8s.io/kubernetes/pkg/kubectl/cmd/util/sanity" ) -var ( - skip = []string{} -) - func main() { var errorCount int
Remove unused var. The variable is unused as verified with: <URL>
kubernetes_kubernetes
train
4969f63bdf061acf8bda989484ef9994a2d1121d
diff --git a/lib/client.js b/lib/client.js index <HASH>..<HASH> 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1,4 +1,4 @@ -/**! +/** * Copyright(c) ali-sdk and other contributors. * MIT Licensed * @@ -131,7 +131,7 @@ proto.authorization = function (method, resource, headers) { var params = [ method.toUpperCase(), headers['Content-Md5'] || '', - headers['Content-Type'], + getHeader(headers, 'Content-Type'), headers.Date || new Date().toString() ]; @@ -189,7 +189,7 @@ proto.createRequest = function (params) { copy(params.headers).to(headers); - if ((params.content || params.stream) && !headers['Content-Type']) { + if ((params.content || params.stream) && !getHeader(headers, 'Content-Type')) { if (params.mime && params.mime.indexOf('/') > 0) { headers['Content-Type'] = params.mime; } else { @@ -364,3 +364,7 @@ proto.requestError = function* (result) { debug('generate error %j', err); return err; }; + +function getHeader(headers, name) { + return headers[name] || headers[name.toLowerCase()]; +} diff --git a/lib/image.js b/lib/image.js index <HASH>..<HASH> 100644 --- a/lib/image.js +++ b/lib/image.js @@ -1,4 +1,4 @@ -/**! +/** * Copyright(c) ali-sdk and other contributors. * MIT Licensed * diff --git a/test/object.test.js b/test/object.test.js index <HASH>..<HASH> 100644 --- a/test/object.test.js +++ b/test/object.test.js @@ -214,6 +214,18 @@ describe('test/object.test.js', function () { var info = yield this.store.head(name); assert.equal(info.res.headers['content-type'], 'text/plain; charset=gbk'); }); + + it('should set custom content-type lower case', function* () { + var name = prefix + 'ali-sdk/oss/put-Content-Type.js'; + var object = yield this.store.put(name, __filename, { + headers: { + 'content-type': 'application/javascript; charset=utf8' + } + }); + assert(object.name, name); + var info = yield this.store.head(name); + assert.equal(info.res.headers['content-type'], 'application/javascript; charset=utf8'); + }); }); describe('head()', function () {
fix(object): custom content-type support lower case
ali-sdk_ali-oss
train
33f26e3862613db02bb6efa3e93c5cc08eefbe8d
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -13,11 +13,13 @@ The Scientific PYthon Development EnviRonment from distutils.core import setup from distutils.command.build import build -from sphinx import setup_command +from distutils.command.install_data import install_data import os import os.path as osp +import subprocess import sys +from sphinx import setup_command def get_package_data(name, extlist): """Return data files for package *name* with extensions in *extlist*""" @@ -65,7 +67,18 @@ class MyBuildDoc(setup_command.BuildDoc): sys.path.pop(0) -cmdclass = {'build': MyBuild, 'build_doc': MyBuildDoc} +class MyInstallData(install_data): + def run(self): + install_data.run(self) + if sys.platform.startswith('linux'): + try: + subprocess.call(['update-desktop-database']) + except: + print >>sys.stderr, "ERROR: unable to update desktop database" + + +cmdclass = {'build': MyBuild, 'build_doc': MyBuildDoc, + 'install_data': MyInstallData} NAME = 'spyder'
setup.py: Run update-desktop-database after installing our desktop file on Linux - This will inform the OS that Spyder can open python files right away after installation.
spyder-ide_spyder
train
93ad5a9e1f4d79a072cf8c5333f704490c417b02
diff --git a/collatex/src/main/java/eu/interedition/collatex/dekker/matrix/MatchTable.java b/collatex/src/main/java/eu/interedition/collatex/dekker/matrix/MatchTable.java index <HASH>..<HASH> 100644 --- a/collatex/src/main/java/eu/interedition/collatex/dekker/matrix/MatchTable.java +++ b/collatex/src/main/java/eu/interedition/collatex/dekker/matrix/MatchTable.java @@ -49,7 +49,7 @@ public class MatchTable { // step 1: build the MatchTable MatchTable table = createEmptyTable(graph, witness); // step 2: do the matching and fill the table - fillTableWithMatches(graph, witness, table, comparator); + table.fillTableWithMatches(graph, witness, comparator); return table; } @@ -73,21 +73,16 @@ public class MatchTable { return new MatchTable(witness, set); } - // remove static; move parameters into fields - private static void fillTableWithMatches(VariantGraph graph, Iterable<Token> witness, MatchTable table, Comparator<Token> comparator) { + // move parameters into fields? + private void fillTableWithMatches(VariantGraph graph, Iterable<Token> witness, Comparator<Token> comparator) { Matches matches = Matches.between(graph.vertices(), witness, comparator); Set<Token> unique = matches.getUnique(); Set<Token> ambiguous = matches.getAmbiguous(); for (Token t : witness) { - List<VariantGraphVertex> matchingVertices = matches.getAll().get(t); - //TODO: dit kan simpeler! zie de duplicatie - if (unique.contains(t)) { - table.set(t, matchingVertices.get(0).getRank() - 1, matchingVertices.get(0)); - } else { - if (ambiguous.contains(t)) { - for (VariantGraphVertex vgv : matchingVertices) { - table.set(t, vgv.getRank() - 1, vgv); - } + if (unique.contains(t) || ambiguous.contains(t)) { + List<VariantGraphVertex> matchingVertices = matches.getAll().get(t); + for (VariantGraphVertex vgv : matchingVertices) { + set(t, vgv.getRank() - 1, vgv); } } } @@ -155,5 +150,4 @@ public class MatchTable { } return pairs; } - }
[RHD] Cleaned up MatchTable.fillTable method
interedition_collatex
train
4d62c2dbfa2d5ef3bedd0ab622b5c9d4ec1a2d19
diff --git a/src/sap.m/src/sap/m/TextArea.js b/src/sap.m/src/sap/m/TextArea.js index <HASH>..<HASH> 100644 --- a/src/sap.m/src/sap/m/TextArea.js +++ b/src/sap.m/src/sap/m/TextArea.js @@ -416,14 +416,12 @@ function( var oTextAreaRef = this.getFocusDomRef(), sValue = oTextAreaRef.value, + bShowExceededText = this.getShowExceededText(), iMaxLength = this.getMaxLength(); - if (this.getShowExceededText() === false && this._getInputValue().length < this.getMaxLength()) { - // some browsers do not respect to maxlength property of textarea - if (iMaxLength > 0 && sValue.length > iMaxLength) { - sValue = sValue.substring(0, iMaxLength); - oTextAreaRef.value = sValue; - } + if (!bShowExceededText && iMaxLength && sValue.length > iMaxLength) { + sValue = sValue.substring(0, iMaxLength); + oTextAreaRef.value = sValue; } // update value property if needed diff --git a/src/sap.m/test/sap/m/qunit/TextArea.qunit.js b/src/sap.m/test/sap/m/qunit/TextArea.qunit.js index <HASH>..<HASH> 100755 --- a/src/sap.m/test/sap/m/qunit/TextArea.qunit.js +++ b/src/sap.m/test/sap/m/qunit/TextArea.qunit.js @@ -822,4 +822,39 @@ sap.ui.define([ oTA.destroy(); }); + QUnit.test("showExceededText = false on phone", function (assert) { + // system under test + var oDeviceStub = this.stub(Device, "system", { + desktop: false, + phone: true, + tablet: false + }); + + // Arrange + var iMaxLength = 6, + sInitValue = "This is test text.", + oTextArea = new TextArea({ + showExceededText: false, + maxLength: 6, + width: "100%" + }); + + oTextArea.placeAt("content"); + sap.ui.getCore().applyChanges(); + + var $textarea = $("textarea"); + + //Act + $textarea.val(sInitValue).trigger("input"); + sap.ui.getCore().applyChanges(); + + // Assert + assert.strictEqual(oTextArea.getValue(), sInitValue.substring(0, iMaxLength), "The TextArea value is correct"); + assert.strictEqual(oTextArea.getMaxLength(), iMaxLength, "The TextArea maxLength property is correctly set to 6"); + + // cleanup + oTextArea.destroy(); + oDeviceStub.restore(); + }); + }); \ No newline at end of file
[FIX] sap.m.TextArea: maxLength is now working on phone - When showExceededText was set to false and maxLength was specified, on android phones, the maxLength property was not taken into account. - Now it works correctly. BCP: <I> Change-Id: I<I>af0c2b<I>f4b<I>db<I>c8a<I>c<I>
SAP_openui5
train
24599b406a32127d436cabefb31a9553d52601fc
diff --git a/src/Handler.php b/src/Handler.php index <HASH>..<HASH> 100644 --- a/src/Handler.php +++ b/src/Handler.php @@ -36,7 +36,7 @@ class Handler * * @return void */ - protected function __construct(Client $client) + public function __construct(Client $client) { $this->client = $client; }
Make constructor public instead of protected (#<I>) This is needed when you want to call handler methods explicitly without registering default php error/exception/shutdown handlers. An example use case would be if you utilized your own error/exception/shutdown handlers and within that handler called these handler methods. You may also call other handler methods unrelated to bugsnag.
bugsnag_bugsnag-php
train
9a5794d5ac434ccb1b6160831467943a29bce59b
diff --git a/karma.conf.js b/karma.conf.js index <HASH>..<HASH> 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -6,7 +6,7 @@ module.exports = function (config) { browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ], - singleRun: false, + singleRun: true, frameworks: [ 'mocha' ],
should enable single run to pass the build on travis-ci
bdefore_universal-redux
train
f12a890c662acd639e7c81b747e54b0feb01e183
diff --git a/src/Manipulator/Kernel.php b/src/Manipulator/Kernel.php index <HASH>..<HASH> 100644 --- a/src/Manipulator/Kernel.php +++ b/src/Manipulator/Kernel.php @@ -58,12 +58,9 @@ class Kernel extends FileContent */ public function addBundle($bundle) { - if ($bundle[0] == '\\') { - $bundle = substr($bundle, 1); - } + $bundle = $this->getBundleTemplate($bundle); // not root bundle if (strpos($this->getKernal(), $bundle) === false) { - $bundle = 'new '.$bundle.'()'; $bundles = $this->getBundles(); if (!in_array($bundle, $bundles)) { $bundles[] = $bundle; @@ -79,10 +76,7 @@ class Kernel extends FileContent */ public function removeBundle($bundle) { - if ($bundle[0] == '\\') { - $bundle = substr($bundle, 1); - } - $bundle = 'new '.$bundle.'()'; + $bundle = $this->getBundleTemplate($bundle); $bundles = $this->getBundles(); if (($key = array_search($bundle, $bundles)) !== false) { unset($bundles[$key]); @@ -91,6 +85,21 @@ class Kernel extends FileContent } /** + * Get bundle template + * + * @param string $bundle + * + * @return string + */ + protected function getBundleTemplate($bundle) + { + if ($bundle[0] == '\\') { + $bundle = substr($bundle, 1); + } + return 'new '.$bundle.'()'; + } + + /** * Get AppKernal content * * @return string
move out method for build bundle tpl
anime-db_anime-db
train
177a36389e6e122d4dda0530453fe5b6862599fe
diff --git a/networkdb/cluster.go b/networkdb/cluster.go index <HASH>..<HASH> 100644 --- a/networkdb/cluster.go +++ b/networkdb/cluster.go @@ -360,6 +360,10 @@ func (nDB *NetworkDB) bulkSync(nid string, nodes []string, all bool) ([]string, nodes = nDB.mRandomNodes(1, nodes) } + if len(nodes) == 0 { + return nil, nil + } + logrus.Debugf("%s: Initiating bulk sync with nodes %v", nDB.config.NodeName, nodes) var err error var networks []string
networkdb: do nothing in bulkSync if nodes is empty This patch allows getting rid of annoying debug message.
docker_libnetwork
train
d35210d88071f1e5fda31535fa7c71187e746fa3
diff --git a/maven-dx-plugin/src/main/java/org/jvending/masa/plugin/dx/DxMojo.java b/maven-dx-plugin/src/main/java/org/jvending/masa/plugin/dx/DxMojo.java index <HASH>..<HASH> 100644 --- a/maven-dx-plugin/src/main/java/org/jvending/masa/plugin/dx/DxMojo.java +++ b/maven-dx-plugin/src/main/java/org/jvending/masa/plugin/dx/DxMojo.java @@ -55,6 +55,14 @@ public class DxMojo extends AbstractMojo { */ private MavenProjectHelper mavenProjectHelper; + /** + * Extra JVM Arguments + * + * @parameter + * @optional + */ + private String[] jvmArguments; + public void execute() throws MojoExecutionException, MojoFailureException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); @@ -89,6 +97,16 @@ public class DxMojo extends AbstractMojo { } List<String> commands = new ArrayList<String>(); + if (jvmArguments != null){ + for (String jvmArgument : jvmArguments) { + if (jvmArgument != null){ + if (jvmArgument.startsWith("-")){ + jvmArgument = jvmArgument.substring(1); + } + commands.add("-J" + jvmArgument); + } + } + } commands.add("--dex"); commands.add("--output=" + outputFile.getAbsolutePath()); commands.add(outputDirectory.getAbsolutePath());
Merged from lp:~hugojosefson/masa/fix-jvmarguments
simpligility_android-maven-plugin
train
ee9626cfbb52eb99de465969874f8996b253456f
diff --git a/devices.js b/devices.js index <HASH>..<HASH> 100644 --- a/devices.js +++ b/devices.js @@ -1761,7 +1761,7 @@ const devices = [ ]), }, { - zigbeeModel: ['LIGHTIFY A19 RGBW'], + zigbeeModel: ['LIGHTIFY A19 RGBW', 'A19 RGBW'], model: '73693', vendor: 'Sylvania', description: 'LIGHTIFY LED RGBW A19',
Add additional model identifier used by Sylvania <I> bulbs (#<I>)
Koenkk_zigbee-shepherd-converters
train
44b4fe329492e7aae99edb65aced5951a62dd31a
diff --git a/lib/components/Img/index.js b/lib/components/Img/index.js index <HASH>..<HASH> 100644 --- a/lib/components/Img/index.js +++ b/lib/components/Img/index.js @@ -27,6 +27,7 @@ import bsTheme from 'theme'; import { imgFluid } from '../../styled/mixins/image'; import { boxShadow } from '../../styled/mixins/box-shadow'; import { borderRadius } from '../../styled/mixins/border-radius'; +import { transition } from '../../styled/mixins/transition'; var defaultProps = { theme: bsTheme }; @@ -71,7 +72,7 @@ var Img = function (_React$Component) { Img = styled(Img)(_templateObject, function (props) { - return '\n \n /* \n Responsive images (ensure images don\'t scale beyond their parents)\n This is purposefully opt-in via an explicit class rather than being the default for all \'img\'s.\n We previously tried the "images are responsive by default" approach in Bootstrap v2,\n and abandoned it in Bootstrap v3 because it breaks lots of third-party widgets (including Google Maps)\n which weren\'t expecting the images within themselves to be involuntarily resized.\n See also https://github.com/twbs/bootstrap/issues/18178\n */\n \n &.img-fluid {\n ' + imgFluid() + '\n }\n \n \n /* Image thumbnails */ \n &.img-thumbnail {\n padding: ' + props.theme['$thumbnail-padding'] + ';\n background-color: ' + props.theme['$thumbnail-bg'] + ';\n border: ' + props.theme['$thumbnail-border-width'] + ' solid ' + props.theme['$thumbnail-border-color'] + ';\n ' + borderRadius(props.theme['$enable-rounded'], props.theme['$thumbnail-border-radius']) + '\n transition: all .2s ease-in-out;\n ' + boxShadow(props.theme['$enable-shadows'], props.theme['$thumbnail-box-shadow']) + '\n /* Keep them at most 100% wide */\n ' + imgFluid() + '\n }\n \n /* Reboot Scss */\n \n /*\n By default, \'img\'s are \'inline-block\'. This assumes that, and vertically\n centers them. This won\'t apply should you reset them to \'block\' level.\n */\n vertical-align: middle;\n /*\n Note: \'img\'s are deliberately not made responsive by default.\n For the rationale behind this, see the comments on the \'.img-fluid\' class.\n */\n '; + return '\n \n /* \n Responsive images (ensure images don\'t scale beyond their parents)\n This is purposefully opt-in via an explicit class rather than being the default for all \'img\'s.\n We previously tried the "images are responsive by default" approach in Bootstrap v2,\n and abandoned it in Bootstrap v3 because it breaks lots of third-party widgets (including Google Maps)\n which weren\'t expecting the images within themselves to be involuntarily resized.\n See also https://github.com/twbs/bootstrap/issues/18178\n */\n \n &.img-fluid {\n ' + imgFluid() + '\n }\n \n \n /* Image thumbnails */ \n &.img-thumbnail {\n padding: ' + props.theme['$thumbnail-padding'] + ';\n background-color: ' + props.theme['$thumbnail-bg'] + ';\n border: ' + props.theme['$thumbnail-border-width'] + ' solid ' + props.theme['$thumbnail-border-color'] + ';\n ' + borderRadius(props.theme['$enable-rounded'], props.theme['$thumbnail-border-radius']) + '\n ' + transition(props.theme['$enable-transitions'], 'all .2s ease-in-out') + '\n ' + boxShadow(props.theme['$enable-shadows'], props.theme['$thumbnail-box-shadow']) + '\n /* Keep them at most 100% wide */\n ' + imgFluid() + '\n }\n \n /* Reboot Scss */\n \n /*\n By default, \'img\'s are \'inline-block\'. This assumes that, and vertically\n centers them. This won\'t apply should you reset them to \'block\' level.\n */\n vertical-align: middle;\n /*\n Note: \'img\'s are deliberately not made responsive by default.\n For the rationale behind this, see the comments on the \'.img-fluid\' class.\n */\n '; }); Img.defaultProps = defaultProps; diff --git a/src/components/Img/index.js b/src/components/Img/index.js index <HASH>..<HASH> 100644 --- a/src/components/Img/index.js +++ b/src/components/Img/index.js @@ -11,6 +11,7 @@ import bsTheme from 'theme'; import { imgFluid } from '../../styled/mixins/image'; import { boxShadow } from '../../styled/mixins/box-shadow'; import { borderRadius } from '../../styled/mixins/border-radius'; +import { transition } from '../../styled/mixins/transition'; const defaultProps = { theme: bsTheme }; @@ -73,7 +74,10 @@ Img = styled(Img)` props.theme['$enable-rounded'], props.theme['$thumbnail-border-radius'] )} - transition: all .2s ease-in-out; + ${transition( + props.theme['$enable-transitions'], + 'all .2s ease-in-out' + )} ${boxShadow( props.theme['$enable-shadows'], props.theme['$thumbnail-box-shadow']
added enable-tranistion for Image transition
bootstrap-styled_bootstrap-styled
train
ee7fe8ebaebe25ccbb8d9f7bb1bf9b3245a9da08
diff --git a/src/Repositories/ProductDatetimeRepository.php b/src/Repositories/ProductDatetimeRepository.php index <HASH>..<HASH> 100644 --- a/src/Repositories/ProductDatetimeRepository.php +++ b/src/Repositories/ProductDatetimeRepository.php @@ -69,7 +69,7 @@ class ProductDatetimeRepository extends AbstractRepository implements ProductDat // prepare the params $params = array( - ParamNames::PK => $pk, + ParamNames::PK => $pk, ParamNames::STORE_ID => $storeId ); diff --git a/src/Services/ProductBunchProcessorInterface.php b/src/Services/ProductBunchProcessorInterface.php index <HASH>..<HASH> 100644 --- a/src/Services/ProductBunchProcessorInterface.php +++ b/src/Services/ProductBunchProcessorInterface.php @@ -132,6 +132,27 @@ interface ProductBunchProcessorInterface extends ProductProcessorInterface, EavA public function getCategoryProductRepository(); /** + * Return's the repository to load the stock status with. + * + * @return \TechDivision\Import\Product\Repositories\StockStatusRepository The repository instance + */ + public function getStockStatusRepository(); + + /** + * Return's the repository to load the stock items with. + * + * @return \TechDivision\Import\Product\Repositories\StockItemRepository The repository instance + */ + public function getStockItemRepository(); + + /** + * Return's the assembler to load the product attributes with. + * + * @return \TechDivision\Import\Product\Assemblers\ProductAttributeAssemblerInterface The assembler instance + */ + public function getProductAttributeAssembler(); + + /** * Return's an array with the available EAV attributes for the passed is user defined flag. * * @param integer $isUserDefined The flag itself
Add missing methods to ProductBunchProcessorInterface + fixed type
techdivision_import-product
train
beafd597ddbd30671ebfe4ff554cd701e0d44e43
diff --git a/src/store/indexeddb-local-backend.js b/src/store/indexeddb-local-backend.js index <HASH>..<HASH> 100644 --- a/src/store/indexeddb-local-backend.js +++ b/src/store/indexeddb-local-backend.js @@ -101,6 +101,7 @@ const LocalIndexedDBStoreBackend = function LocalIndexedDBStoreBackend( this.indexedDB = indexedDBInterface; this._dbName = "matrix-js-sdk:" + (dbName || "default"); this.db = null; + this._disconnected = true; this._syncAccumulator = new SyncAccumulator(); }; @@ -112,13 +113,15 @@ LocalIndexedDBStoreBackend.prototype = { * @return {Promise} Resolves if successfully connected. */ connect: function() { - if (this.db) { + if (!this._disconnected) { console.log( - `LocalIndexedDBStoreBackend.connect: already connected`, + `LocalIndexedDBStoreBackend.connect: already connected or connecting`, ); return Promise.resolve(); } + this._disconnected = false; + console.log( `LocalIndexedDBStoreBackend.connect: connecting`, );
ensure indexeddb workers are never double-connected
matrix-org_matrix-js-sdk
train
846b2025f29e48e4165b8373be0d19a3ddc561de
diff --git a/lib/sup/modes/label-list-mode.rb b/lib/sup/modes/label-list-mode.rb index <HASH>..<HASH> 100644 --- a/lib/sup/modes/label-list-mode.rb +++ b/lib/sup/modes/label-list-mode.rb @@ -29,6 +29,11 @@ class LabelListMode < LineCursorMode BufferManager.flash "No labels messages with unread messages." end end + + def focus + reload # make sure unread message counts are up-to-date + end + protected def toggle_show_unread_only
reload label list on focus This ensures the unread count for each label is correct. I often read my list mail from the label list. When I close the thread index and go back to the label list the unread message count is wrong. This bugs me. I'm sure a less brutal way of doing this is possible with the UpdateManager but that seems complicated and therefore prone to errors.
sup-heliotrope_sup
train
11b8e91a544357f1b33e1523a5bcf12df5a6cc4e
diff --git a/axe/queue.go b/axe/queue.go index <HASH>..<HASH> 100644 --- a/axe/queue.go +++ b/axe/queue.go @@ -78,15 +78,17 @@ func (q *Queue) Enqueue(name, label string, model Model, delay time.Duration) (* // Callback is a factory to create callbacks that can be used to enqueue jobs // during request processing. -func (q *Queue) Callback(name, label string, delay time.Duration, matcher fire.Matcher, cb func(ctx *fire.Context) Model) *fire.Callback { +func (q *Queue) Callback(name string, matcher fire.Matcher, cb func(ctx *fire.Context) (string, time.Duration, Model)) *fire.Callback { return fire.C("axe/Queue.Callback", matcher, func(ctx *fire.Context) error { // set task tag ctx.Tracer.Tag("task", name) - // get model + // get label, delay and model var model Model + var delay time.Duration + var label string if cb != nil { - model = cb(ctx) + label, delay, model = cb(ctx) } // check if controller uses same store diff --git a/example/main.go b/example/main.go index <HASH>..<HASH> 100644 --- a/example/main.go +++ b/example/main.go @@ -6,6 +6,7 @@ import ( "net/http" "os" "strconv" + "time" "github.com/goware/cors" "github.com/opentracing/opentracing-go" @@ -164,8 +165,8 @@ func itemController(store *coal.Store, queue *axe.Queue) *fire.Controller { ResourceActions: fire.M{ "add": &fire.Action{ Methods: []string{"POST"}, - Callback: queue.Callback("increment", "", 0, fire.All(), func(ctx *fire.Context) axe.Model { - return &count{ + Callback: queue.Callback("increment", fire.All(), func(ctx *fire.Context) (string, time.Duration, axe.Model) { + return "", 0, &count{ Item: ctx.Model.ID(), } }),
return label and delay also from callback
256dpi_fire
train
6730f99160a4ac8c6f786fb1d78caf4a76c53d21
diff --git a/game.py b/game.py index <HASH>..<HASH> 100644 --- a/game.py +++ b/game.py @@ -14,7 +14,7 @@ game_fps = 60 game_size = Vec2d(1024, 600) -block_size = Vec2d(24, 24) +atom_size = Vec2d(24, 24) class Control: MoveLeft = 0 @@ -42,8 +42,13 @@ class Atom: class Tank: def __init__(self, dims): self.dims = dims + self.size = dims * atom_size self.atoms = [] + def hit_atom(self, pos): + + return False + class Game(object): def __init__(self, window): self.batch = pyglet.graphics.Batch() @@ -75,7 +80,7 @@ class Game(object): self.tank_dims = Vec2d(16, 22) self.tank_pos = Vec2d(108, 18) self.man_dims = Vec2d(1, 2) - self.man_size = Vec2d(self.man_dims.x*block_size.x, self.man_dims.y*block_size.y) + self.man_size = Vec2d(self.man_dims * atom_size) self.time_between_drops = 1 self.time_until_next_drop = 0 @@ -89,18 +94,39 @@ class Game(object): # drop a random atom flavor_index = random.randint(0, len(Atom.flavors)-1) pos = Vec2d( - block_size.x*random.randint(0, self.tank.dims.x-1), - block_size.y*(self.tank.dims.y-1), + atom_size.x*random.randint(0, self.tank.dims.x-1), + atom_size.y*(self.tank.dims.y-1), ) atom = Atom(pos, flavor_index, pyglet.sprite.Sprite(self.atom_imgs[flavor_index], batch=self.batch, group=self.group_main)) self.tank.atoms.append(atom) # velocity for atom in self.tank.atoms: - atom.pos.y += atom.vel.y * dt + atom.new_pos = atom.pos + atom.vel * dt + # hit walls of tank x + if atom.new_pos.x < 0: + atom.new_pos.x = 0 + atom.vel.x = 0 + elif atom.new_pos.x + atom_size.x > self.tank.size.x: + atom.new_pos.x = self.tank.size.x - atom_size.x + atom.vel.x = 0 + # hit walls of tank y + if atom.new_pos.y < 0: + atom.new_pos.y = 0 + atom.vel.y = 0 + elif atom.new_pos.y + atom_size.y > self.tank.size.y: + atom.new_pos.y = self.tank.size.y - atom_size.y + atom.vel.y = 0 + # stick to other atoms + if self.tank.hit_atom(atom.new_pos): + atom.new_pos = (atom.pos / atom_size).do(int) * atom_size + atom.vel = Vec2d(0, 0) + + for atom in self.tank.atoms: + atom.pos = atom.new_pos # gravity - gravity_accel = 400 + gravity_accel = 200 for atom in self.tank.atoms: atom.vel.y -= gravity_accel * dt @@ -108,7 +134,7 @@ class Game(object): self.window.clear() for atom in self.tank.atoms: - atom.sprite.set_position(atom.pos.x + self.tank_pos.x, atom.pos.y + self.tank_pos.y) + atom.sprite.set_position(*(atom.pos + self.tank_pos)) self.batch.draw() self.fps_display.draw()
atoms get stuck on the bottom
andrewrk_chem
train
a18d7386bfd8c8c7c8f65e69938aad32d4028bdb
diff --git a/lib/Internal/Operation.php b/lib/Internal/Operation.php index <HASH>..<HASH> 100644 --- a/lib/Internal/Operation.php +++ b/lib/Internal/Operation.php @@ -2,6 +2,8 @@ namespace Amp\Postgres\Internal; +use Amp\Loop; + trait Operation { /** @var bool */ private $complete = false; @@ -9,10 +11,6 @@ trait Operation { /** @var callable[] */ private $onComplete = []; - public function __destruct() { - $this->complete(); - } - public function onComplete(callable $onComplete) { if ($this->complete) { $onComplete(); @@ -29,7 +27,13 @@ trait Operation { $this->complete = true; foreach ($this->onComplete as $callback) { - $callback(); + try { + $callback(); + } catch (\Throwable $exception) { + Loop::defer(function () use ($exception) { + throw $exception; // Rethrow to event loop error handler. + }); + } } $this->onComplete = null; } diff --git a/lib/Listener.php b/lib/Listener.php index <HASH>..<HASH> 100644 --- a/lib/Listener.php +++ b/lib/Listener.php @@ -29,6 +29,12 @@ class Listener implements Iterator, Operation { $this->unlisten = $unlisten; } + public function __destruct() { + if ($this->unlisten) { + $this->unlisten(); // Invokes $this->complete(). + } + } + /** * {@inheritdoc} */ @@ -56,10 +62,17 @@ class Listener implements Iterator, Operation { * Unlistens from the channel. No more values will be emitted from this listener. * * @return \Amp\Promise<\Amp\Postgres\CommandResult> + * + * @throws \Error If this method was previously invoked. */ public function unlisten(): Promise { + if (!$this->unlisten) { + throw new \Error("Already unlistened on this channel"); + } + /** @var \Amp\Promise $promise */ $promise = ($this->unlisten)($this->channel); + $this->unlisten = null; $promise->onResolve($this->callableFromInstanceMethod("complete")); return $promise; } diff --git a/lib/Transaction.php b/lib/Transaction.php index <HASH>..<HASH> 100644 --- a/lib/Transaction.php +++ b/lib/Transaction.php @@ -19,9 +19,6 @@ class Transaction implements Executor, Operation { /** @var int */ private $isolation; - /** @var callable */ - private $onResolve; - /** * @param \Amp\Postgres\Executor $executor * @param int $isolation @@ -42,7 +39,12 @@ class Transaction implements Executor, Operation { } $this->executor = $executor; - $this->onResolve = $this->callableFromInstanceMethod("complete"); + } + + public function __destruct() { + if ($this->executor) { + $this->rollback(); // Invokes $this->complete(). + } } /** @@ -126,7 +128,7 @@ class Transaction implements Executor, Operation { $promise = $this->executor->query("COMMIT"); $this->executor = null; - $promise->onResolve($this->onResolve); + $promise->onResolve($this->callableFromInstanceMethod("complete")); return $promise; } @@ -145,7 +147,7 @@ class Transaction implements Executor, Operation { $promise = $this->executor->query("ROLLBACK"); $this->executor = null; - $promise->onResolve($this->onResolve); + $promise->onResolve($this->callableFromInstanceMethod("complete")); return $promise; }
Remove __destruct() from Internal\Operation Users now define their own destruct methods invoking complete().
amphp_postgres
train
0dec08f8c88874019a1ad37584fb1675e6c69234
diff --git a/spec/index_spec.js b/spec/index_spec.js index <HASH>..<HASH> 100644 --- a/spec/index_spec.js +++ b/spec/index_spec.js @@ -11,6 +11,12 @@ describe('node-promise-es6', () => { expect(dirContents.sort()) .toEqual(jasmine.arrayContaining(['index.js', 'fs.js'])); }); + + it('re-exports the non-async fs functions', () => { + expect(fs.watch).toBeDefined(); + expect(fs.createReadStream).toBeDefined(); + expect(fs.renameSync).toBeDefined(); + }); }); describe('child_process', () => { diff --git a/src/fs.js b/src/fs.js index <HASH>..<HASH> 100644 --- a/src/fs.js +++ b/src/fs.js @@ -1,6 +1,8 @@ import fs from 'fs'; import promisify from 'node-promise-es6/promisify'; +export * from 'fs'; + export const rename = promisify(fs.rename); export const ftruncate = promisify(fs.ftruncate); export const truncate = promisify(fs.truncate); @@ -32,8 +34,3 @@ export const appendFile = promisify(fs.appendFile); export const access = promisify(fs.access); export const write = promisify(fs.write, ['written', 'data']); export const read = promisify(fs.read, ['bytesRead', 'buffer']); -export const watchFile = fs.watchFile; -export const unwatchFile = fs.unwatchFile; -export const watch = fs.watch; -export const createReadStream = fs.createReadStream; -export const createWriteStream = fs.createWriteStream;
Make sure to export all functions from fs
vinsonchuong_node-promise-es6
train
1cbf1686c865c8f79d89715d545bec29d9bb6cc9
diff --git a/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java b/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java index <HASH>..<HASH> 100644 --- a/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java +++ b/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java @@ -10,6 +10,7 @@ import com.google.inject.Singleton; import io.mangoo.exceptions.MangooSchedulerException; import io.mangoo.interfaces.MangooLifecycle; +import io.mangoo.managers.ExecutionManager; import io.mangoo.scheduler.Scheduler; /** @@ -32,12 +33,17 @@ public class Shutdown extends Thread { invokeLifecycle(); stopScheduler(); stopUndertow(); + stopExecutionManager(); } private void invokeLifecycle() { Application.getInstance(MangooLifecycle.class).applicationStopped(); } + private void stopExecutionManager() { + Application.getInstance(ExecutionManager.class).shutdown(); + } + private void stopScheduler() { try { this.scheduler.shutdown();
#<I> Added shutdown of execution manager
svenkubiak_mangooio
train
9528d6f081e5b35c7ca8124e922145ffd11866a3
diff --git a/resource_openstack_networking_router_v2.go b/resource_openstack_networking_router_v2.go index <HASH>..<HASH> 100644 --- a/resource_openstack_networking_router_v2.go +++ b/resource_openstack_networking_router_v2.go @@ -63,50 +63,6 @@ func resourceNetworkingRouterV2() *schema.Resource { } } -// routerCreateOpts contains all the values needed to create a new router. There are -// no required values. -type RouterCreateOpts struct { - Name string - AdminStateUp *bool - Distributed *bool - TenantID string - GatewayInfo *routers.GatewayInfo - ValueSpecs map[string]string -} - -// ToRouterCreateMap casts a routerCreateOpts struct to a map. -func (opts RouterCreateOpts) ToRouterCreateMap() (map[string]interface{}, error) { - r := make(map[string]interface{}) - - if gophercloud.MaybeString(opts.Name) != nil { - r["name"] = opts.Name - } - - if opts.AdminStateUp != nil { - r["admin_state_up"] = opts.AdminStateUp - } - - if opts.Distributed != nil { - r["distributed"] = opts.Distributed - } - - if gophercloud.MaybeString(opts.TenantID) != nil { - r["tenant_id"] = opts.TenantID - } - - if opts.GatewayInfo != nil { - r["external_gateway_info"] = opts.GatewayInfo - } - - if opts.ValueSpecs != nil { - for k, v := range opts.ValueSpecs { - r[k] = v - } - } - - return map[string]interface{}{"router": r}, nil -} - func resourceNetworkingRouterV2Create(d *schema.ResourceData, meta interface{}) error { config := meta.(*Config) networkingClient, err := config.networkingV2Client(d.Get("region").(string)) @@ -115,9 +71,11 @@ func resourceNetworkingRouterV2Create(d *schema.ResourceData, meta interface{}) } createOpts := RouterCreateOpts{ - Name: d.Get("name").(string), - TenantID: d.Get("tenant_id").(string), - ValueSpecs: MapValueSpecs(d), + routers.CreateOpts{ + Name: d.Get("name").(string), + TenantID: d.Get("tenant_id").(string), + }, + MapValueSpecs(d), } if asuRaw, ok := d.GetOk("admin_state_up"); ok { diff --git a/types.go b/types.go index <HASH>..<HASH> 100644 --- a/types.go +++ b/types.go @@ -2,6 +2,7 @@ package openstack import ( "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/routers" "github.com/gophercloud/gophercloud/openstack/networking/v2/subnets" ) @@ -16,3 +17,15 @@ type SubnetCreateOpts struct { func (opts SubnetCreateOpts) ToSubnetCreateMap() (map[string]interface{}, error) { return BuildRequest(opts, "subnet") } + +// RouterCreateOpts represents the attributes used when creating a new router. +type RouterCreateOpts struct { + routers.CreateOpts + ValueSpecs map[string]string `json:"value_specs,omitempty"` +} + +// ToRouterCreateMap casts a CreateOpts struct to a map. +// It overrides routers.ToRouterCreateMap to add the ValueSpecs field. +func (opts RouterCreateOpts) ToRouterCreateMap() (map[string]interface{}, error) { + return BuildRequest(opts, "router") +}
provider/openstack: gophercloud migration: Migrate RouterCreateOpts to types.go
terraform-providers_terraform-provider-openstack
train
d97077841883624ad99e080c2cba1da5376d1257
diff --git a/lib/domainr.rb b/lib/domainr.rb index <HASH>..<HASH> 100644 --- a/lib/domainr.rb +++ b/lib/domainr.rb @@ -6,7 +6,7 @@ module Domainr include HTTParty format :json - base_uri 'domainr.com' + base_uri 'api.domainr.com' def self.client_id=(id) @client_id = id @@ -18,12 +18,12 @@ module Domainr def search(term) options = { :q => term, :client_id => client_id } - Hashie::Mash.new(get('/api/json/search', { :query => options })) + Hashie::Mash.new(get('/v1/search', { :query => options })) end def info(domain) options = { :q => domain, :client_id => client_id } - Hashie::Mash.new(get('/api/json/info', { :query => options })) + Hashie::Mash.new(get('/v1/info', { :query => options })) end end
Update to new v1 API endpoint
stve_domainr
train
ed629040b866abfa3f9aa3d03a15bc1a37ccce4b
diff --git a/pylivetrader/assets/assets.py b/pylivetrader/assets/assets.py index <HASH>..<HASH> 100644 --- a/pylivetrader/assets/assets.py +++ b/pylivetrader/assets/assets.py @@ -91,7 +91,11 @@ class Asset: ------- boolean: whether the asset's exchange is open at the given minute. """ - calendar = get_calendar(self.exchange) + + # We currently support only US Equity calendar + # (to avoid unexpected exchange name that's missing in + # the trading_calendars package) + calendar = get_calendar('NYSE') return calendar.is_open_on_minute(dt_minute) def is_alive_for_session(self, session_label):
Fix the missing key in calendar module It would be nice to support more calendars, but it is a reasonable assumption that pylivetrader runs only for US equities for now than failing with unexpected exchange name.
alpacahq_pylivetrader
train
56ac4b4c283c9a177cd1ac43bfd477368db03d1c
diff --git a/src/pps/store/in_memory_client.go b/src/pps/store/in_memory_client.go index <HASH>..<HASH> 100644 --- a/src/pps/store/in_memory_client.go +++ b/src/pps/store/in_memory_client.go @@ -16,9 +16,9 @@ type inMemoryClient struct { timer timing.Timer - runLock *sync.RWMutex - runStatusesLock *sync.RWMutex - containerIDsLock *sync.RWMutex + runLock *sync.RWMutex + runStatusesLock *sync.RWMutex + containersLock *sync.RWMutex } func newInMemoryClient() *inMemoryClient { @@ -97,8 +97,8 @@ func (c *inMemoryClient) AddPipelineRunStatus(id string, statusType pps.Pipeline } func (c *inMemoryClient) GetPipelineRunContainers(id string) ([]*PipelineContainer, error) { - c.containerIDsLock.RLock() - defer c.containerIDsLock.RUnlock() + c.containersLock.RLock() + defer c.containersLock.RUnlock() containers, ok := c.idToContainers[id] if !ok { @@ -107,16 +107,16 @@ func (c *inMemoryClient) GetPipelineRunContainers(id string) ([]*PipelineContain return containers, nil } -func (c *inMemoryClient) AddPipelineRunContainerIDs(id string, containerIDs ...string) error { - c.containerIDsLock.Lock() - defer c.containerIDsLock.Unlock() +func (c *inMemoryClient) AddPipelineRunContainers(pipelineContainers ...*PipelineContainer) error { + c.containersLock.Lock() + defer c.containersLock.Unlock() - _, ok := c.idToContainers[id] - if !ok { - return fmt.Errorf("no run for id %s", id) - } - for _, containerID := range containerIDs { - c.idToContainers[id] = append(c.idToContainers[id], &PipelineContainer{PipelineRunId: id, ContainerId: containerID}) + for _, container := range pipelineContainers { + _, ok := c.idToContainers[container.PipelineRunId] + if !ok { + return fmt.Errorf("no run for id %s", container.PipelineRunId) + } + c.idToContainers[container.PipelineRunId] = append(c.idToContainers[container.PipelineRunId], container) } return nil } diff --git a/src/pps/store/rethink_client.go b/src/pps/store/rethink_client.go index <HASH>..<HASH> 100644 --- a/src/pps/store/rethink_client.go +++ b/src/pps/store/rethink_client.go @@ -144,11 +144,10 @@ func (c *rethinkClient) GetPipelineRunStatusLatest(id string) (*pps.PipelineRunS return &pipelineRunStatus, nil } -func (c *rethinkClient) AddPipelineRunContainerIDs(id string, containerIDs ...string) error { +func (c *rethinkClient) AddPipelineRunContainers(containers ...*PipelineContainer) error { var pipelineContainers []gorethink.Term - for _, containerID := range containerIDs { - pipelineContainer := PipelineContainer{id, containerID} - data, err := marshaller.MarshalToString(&pipelineContainer) + for _, pipelineContainer := range containers { + data, err := marshaller.MarshalToString(pipelineContainer) if err != nil { return err } diff --git a/src/pps/store/store.go b/src/pps/store/store.go index <HASH>..<HASH> 100644 --- a/src/pps/store/store.go +++ b/src/pps/store/store.go @@ -8,7 +8,7 @@ type Client interface { GetPipelineRun(id string) (*pps.PipelineRun, error) AddPipelineRunStatus(id string, statusType pps.PipelineRunStatusType) error GetPipelineRunStatusLatest(id string) (*pps.PipelineRunStatus, error) - AddPipelineRunContainerIDs(id string, containerIDs ...string) error + AddPipelineRunContainers(pipelineContainers ...*PipelineContainer) error GetPipelineRunContainers(id string) ([]*PipelineContainer, error) } diff --git a/src/pps/store/store_test.go b/src/pps/store/store_test.go index <HASH>..<HASH> 100644 --- a/src/pps/store/store_test.go +++ b/src/pps/store/store_test.go @@ -46,7 +46,7 @@ func testBasic(t *testing.T, client Client) { require.NoError(t, err) require.Equal(t, pipelineRunStatusResponse.PipelineRunStatusType, pps.PipelineRunStatusType_PIPELINE_RUN_STATUS_TYPE_SUCCESS) - require.NoError(t, client.AddPipelineRunContainerIDs("id", "container")) + require.NoError(t, client.AddPipelineRunContainers(&PipelineContainer{"id", "container"})) containerIDs, err := client.GetPipelineRunContainers("id") require.NoError(t, err) require.Equal(t, []*PipelineContainer{&PipelineContainer{"id", "container"}}, containerIDs)
AddPipelineRunContainerIDs to AddPipelineRunContainers
pachyderm_pachyderm
train
02f9ba8b48cd2c915d76d22678ee92e46f62c623
diff --git a/lib/qu/job.rb b/lib/qu/job.rb index <HASH>..<HASH> 100644 --- a/lib/qu/job.rb +++ b/lib/qu/job.rb @@ -18,12 +18,7 @@ module Qu end def self.create(*args) - Qu.instrument("push.#{InstrumentationNamespace}") do |ipayload| - Payload.new(:klass => self, :args => args).tap do |payload| - ipayload[:payload] = payload - payload.job.run_hook(:push) { Qu.backend.push(payload) } - end - end + Payload.new(:klass => self, :args => args).tap { |payload| payload.push } end # Public: Feel free to override this in your class with specific arg names diff --git a/lib/qu/payload.rb b/lib/qu/payload.rb index <HASH>..<HASH> 100644 --- a/lib/qu/payload.rb +++ b/lib/qu/payload.rb @@ -61,6 +61,14 @@ module Qu } end + # Internal: Pushes payload to backend. + def push + instrument("push.#{InstrumentationNamespace}") do |payload| + payload[:payload] = self + job.run_hook(:push) { Qu.backend.push(self) } + end + end + private def constantize(class_name)
Move push to Payload and instrument it there. Gets all instrumentation for payloads in one place.
bkeepers_qu
train
6939dded904a317b19f54011b3c43fa033e684ff
diff --git a/lavalink/lavalink.py b/lavalink/lavalink.py index <HASH>..<HASH> 100644 --- a/lavalink/lavalink.py +++ b/lavalink/lavalink.py @@ -84,6 +84,7 @@ async def initialize( ) await lavalink_node.connect(timeout=timeout) + lavalink_node._retries = 0 bot.add_listener(node.on_socket_response) bot.add_listener(_on_guild_remove, name="on_guild_remove") diff --git a/lavalink/node.py b/lavalink/node.py index <HASH>..<HASH> 100644 --- a/lavalink/node.py +++ b/lavalink/node.py @@ -151,6 +151,7 @@ class Node: self.state = NodeState.CONNECTING self._state_handlers: List = [] + self._retries = 0 self.player_manager = PlayerManager(self) @@ -267,6 +268,7 @@ class Node: await self._ws.close(code=4006, message=b"Reconnecting") while self._is_shutdown is False and (self._ws is None or self._ws.closed): + self._retries += 1 try: ws = await self.session.ws_connect(url=uri, headers=self.headers, heartbeat=60) except OSError: @@ -381,6 +383,7 @@ class Node: else: ws_ll_log.info("[NODE] | Reconnect successful.") self.dispatch_reconnect() + self._retries = 0 def dispatch_reconnect(self): for guild_id in self.player_manager.guild_ids: @@ -392,6 +395,7 @@ class Node: "code": 42069, "reason": "Lavalink WS reconnected", "byRemote": True, + "retries": self._retries, }, ) diff --git a/lavalink/player_manager.py b/lavalink/player_manager.py index <HASH>..<HASH> 100644 --- a/lavalink/player_manager.py +++ b/lavalink/player_manager.py @@ -121,11 +121,13 @@ class Player(RESTClient): else: raise - async def connect(self, deafen: bool = False): + async def connect(self, deafen: bool = False, channel: Optional[discord.VoiceChannel] = None): """ Connects to the voice channel associated with this Player. """ self._last_resume = datetime.datetime.now(tz=datetime.timezone.utc) + if channel: + self.channel = channel await self.channel.guild.change_voice_state( channel=self.channel, self_mute=False, self_deaf=deafen )
This gives the tools needed for the player to handle the <I> loop properly locally.
Cog-Creators_Red-Lavalink
train
218304d72da38fdb94bcc1bf980bfcd2a068ac14
diff --git a/testsuite/tests/src/test/java/org/mobicents/slee/resources/diameter/tests/factories/CCAFactoriesTest.java b/testsuite/tests/src/test/java/org/mobicents/slee/resources/diameter/tests/factories/CCAFactoriesTest.java index <HASH>..<HASH> 100644 --- a/testsuite/tests/src/test/java/org/mobicents/slee/resources/diameter/tests/factories/CCAFactoriesTest.java +++ b/testsuite/tests/src/test/java/org/mobicents/slee/resources/diameter/tests/factories/CCAFactoriesTest.java @@ -167,6 +167,17 @@ public class CCAFactoriesTest { } @Test + public void hasTFlagSetCCA() throws Exception { + CreditControlRequest ccr = ccaMessageFactory.createCreditControlRequest(); + ((DiameterMessageImpl) ccr).getGenericData().setReTransmitted(true); + + assertTrue("The 'T' flag should be set in Credit-Control-Request", ccr.getHeader().isPotentiallyRetransmitted()); + + CreditControlAnswer cca = ccaMessageFactory.createCreditControlAnswer(ccr); + assertFalse("The 'T' flag should be set in Credit-Control-Answer", cca.getHeader().isPotentiallyRetransmitted()); + } + + @Test public void testGettersAndSettersCCA() throws Exception { CreditControlAnswer cca = ccaMessageFactory.createCreditControlAnswer(ccaMessageFactory.createCreditControlRequest("582364567346578348")); @@ -819,14 +830,14 @@ public class CCAFactoriesTest { // add(UseUriAsFqdn, true); // Set Common Applications add(ApplicationId, - // AppId 1 + // AppId 1 getInstance(). add(VendorId, 193L). add(AuthApplId, 0L). add(AcctApplId, 19302L)); // Set peer table add(PeerTable, - // Peer 1 + // Peer 1 getInstance(). add(PeerRating, 1). add(PeerName, serverURI));
Fixing + Regression Tests for "T Flag is set on Answer if Request has it set" for CCA Update Issue <I> Fixed for Diameter CCA RA. Added regression check tests. git-svn-id: <URL>
RestComm_jdiameter
train
daf2a6a247e9957f5d21fc68b25446820c30351a
diff --git a/src/ChrisKonnertz/DeepLy/ResponseBag/TranslationBag.php b/src/ChrisKonnertz/DeepLy/ResponseBag/TranslationBag.php index <HASH>..<HASH> 100644 --- a/src/ChrisKonnertz/DeepLy/ResponseBag/TranslationBag.php +++ b/src/ChrisKonnertz/DeepLy/ResponseBag/TranslationBag.php @@ -108,7 +108,10 @@ class TranslationBag extends AbstractBag $beams = $this->responseContent->translations[0]->beams; - $translationAlternatives = array_column($beams, 'postprocessed_sentence'); + $translationAlternatives = []; + foreach ($beams as $beam) { + $translationAlternatives[] = $beam->postprocessed_sentence; + } return $translationAlternatives; }
Fixed bug while accessing the properties of the beam classes
chriskonnertz_DeepLy
train
618b17e5eaa7ce15aa34e67971ad5310e519fca5
diff --git a/lib/webinterface_layout.py b/lib/webinterface_layout.py index <HASH>..<HASH> 100644 --- a/lib/webinterface_layout.py +++ b/lib/webinterface_layout.py @@ -43,7 +43,7 @@ from invenio.webmessage_webinterface import WebInterfaceYourMessagesPages from invenio.errorlib_webinterface import WebInterfaceErrorPages from invenio.oai_repository_webinterface import WebInterfaceOAIProviderPages from invenio.webstat_webinterface import WebInterfaceStatsPages -#from invenio.webjournal_webinterface import WebInterfaceJournalPages +from invenio.webjournal_webinterface import WebInterfaceJournalPages class WebInterfaceInvenio(WebInterfaceSearchInterfacePages): """ The global URL layout is composed of the search API plus all
had to take out webjournal import (module in dev, not submitted yet)
inveniosoftware_invenio-base
train
9846ebedb29997a7a1e3331f0610de6ceb03b40a
diff --git a/safe/gis/vector/tools.py b/safe/gis/vector/tools.py index <HASH>..<HASH> 100644 --- a/safe/gis/vector/tools.py +++ b/safe/gis/vector/tools.py @@ -134,8 +134,10 @@ def copy_layer(source, target): geom = feature.geometry() if aggregation_layer: # See issue https://github.com/inasafe/inasafe/issues/3713 + # and issue https://github.com/inasafe/inasafe/issues/3927 + # Also handle if feature has no geometry. geom = geometry_checker(geom) - if not geom.isGeosValid(): + if not geom or not geom.isGeosValid(): LOGGER.info( 'One geometry in the aggregation layer is still invalid ' 'after cleaning.') diff --git a/safe/gui/tools/minimum_needs/needs_calculator_dialog.py b/safe/gui/tools/minimum_needs/needs_calculator_dialog.py index <HASH>..<HASH> 100644 --- a/safe/gui/tools/minimum_needs/needs_calculator_dialog.py +++ b/safe/gui/tools/minimum_needs/needs_calculator_dialog.py @@ -200,6 +200,7 @@ class NeedsCalculatorDialog(QtGui.QDialog, FORM_CLASS): display_critical_message_box( title=self.tr('Error while calculating minimum needs'), message=message) + return # remove monkey patching keywords del self.result_layer.keywords
handle none geometry (#<I>) * return if minimum_needs function failed * handle if feature has no geometry
inasafe_inasafe
train
126f1780e0052220d5103daa3cb631e3b3c0d479
diff --git a/src/Picqer/Financials/Moneybird/Connection.php b/src/Picqer/Financials/Moneybird/Connection.php index <HASH>..<HASH> 100644 --- a/src/Picqer/Financials/Moneybird/Connection.php +++ b/src/Picqer/Financials/Moneybird/Connection.php @@ -393,7 +393,7 @@ class Connection return 'http://httpbin.org/' . $method; } - return $this->apiUrl . '/' . $this->administrationId . '/' . $url . '.json'; + return $this->apiUrl . '/' . ($this->administrationId ? $this->administrationId . '/' : '') . $url . '.json'; } /** diff --git a/src/Picqer/Financials/Moneybird/Entities/Administration.php b/src/Picqer/Financials/Moneybird/Entities/Administration.php index <HASH>..<HASH> 100644 --- a/src/Picqer/Financials/Moneybird/Entities/Administration.php +++ b/src/Picqer/Financials/Moneybird/Entities/Administration.php @@ -26,5 +26,5 @@ class Administration extends Model { /** * @var string */ - protected $url = 'administration'; + protected $url = 'administrations'; } \ No newline at end of file
Fix for wrong administrations url and correct URL format when no administration ID given
picqer_moneybird-php-client
train
443304c96dbf60a5b3441cb57b2e3a735b11c5fb
diff --git a/bigfloat_cython/setup.py b/bigfloat_cython/setup.py index <HASH>..<HASH> 100644 --- a/bigfloat_cython/setup.py +++ b/bigfloat_cython/setup.py @@ -148,7 +148,10 @@ Links """ setup( - name='BigFloat', + # Name should really be capitalized as 'BigFloat'. We keep 'bigfloat' to avoid + # upload problems on PyPI. (Previous versions of the package were also + # called bigfloat.) + name='bigfloat', version='0.3.0a1', description=DESCRIPTION, long_description=LONG_DESCRIPTION,
Make package name 'bigfloat' rather than 'BigFloat' for PyPI purposes.
mdickinson_bigfloat
train