hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
797ecfc613573ffee616caf60cefd520a6fd9c22
diff --git a/mzgtfs/export.py b/mzgtfs/export.py index <HASH>..<HASH> 100644 --- a/mzgtfs/export.py +++ b/mzgtfs/export.py @@ -13,7 +13,7 @@ if __name__ == "__main__": args = parser.parse_args() g = feed.Feed(args.filename) - f.preload() + g.preload() print "===== GTFS: %s ====="%g.filename for agency in g.agencies(): print "Agency:", agency['agency_name']
Fix f is not defined in export.py
transitland_mapzen-gtfs
train
762787a4fe4ebf90af7647cf2fdddcc17829faaa
diff --git a/zipline/pipeline/pipeline.py b/zipline/pipeline/pipeline.py index <HASH>..<HASH> 100644 --- a/zipline/pipeline/pipeline.py +++ b/zipline/pipeline/pipeline.py @@ -14,11 +14,11 @@ class Pipeline(object): `Term` instances, and 'screen', a Filter representing criteria for including an asset in the results of a Pipeline. - To compute a pipeline in the context of a TradingAlgorithm, users should - call `attach_pipeline` in their `initialize` function to register that the - pipeline computed for each trading day. The outputs of the pipeline on a - given day can be accessed by calling `pipeline_outputs` in `handle_data` or - `before_trading_start`. + To compute a pipeline in the context of a TradingAlgorithm, users must call + `attach_pipeline` in their `initialize` function to register that the + pipeline should be computed each trading day. The outputs of a pipeline on + a given day can be accessed by calling `pipeline_outputs` in `handle_data` + or `before_trading_start`. Parameters ----------
DOC: Tweaks to pipeline language.
quantopian_zipline
train
d8984d57c4c68ba5642fd1a03965f9b1eaf68446
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer-table.js b/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer-table.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer-table.js +++ b/bundles/org.eclipse.orion.client.ui/web/orion/explorers/explorer-table.js @@ -345,7 +345,8 @@ define(['i18n!orion/navigate/nls/messages', 'require', 'orion/Deferred', 'orion/ }); } else { progress.progress(fileClient.createFolder(target.Location, entry.name), "Creating folder " + entry.name).then(function(subFolder) { - explorer.changedItem(target, true); + var dispatcher = explorer.modelEventDispatcher; + dispatcher.dispatchEvent({ type: "create", parent: item, newValue: subFolder }); //$NON-NLS-0$ traverseChildren(subFolder); }); }
Bug <I> - DND of file in nav does not update folder nav on the RHS (directory case)
eclipse_orion.client
train
87b8e5d05687b02b86559b27823607f7b7486d10
diff --git a/server/container_create_linux.go b/server/container_create_linux.go index <HASH>..<HASH> 100644 --- a/server/container_create_linux.go +++ b/server/container_create_linux.go @@ -136,6 +136,14 @@ func (s *Server) createSandboxContainer(ctx context.Context, ctr ctrIface.Contai // eventually, we'd like to access all of these variables through the interface themselves, and do most // of the translation between CRI config -> oci/storage container in the container package + + // TODO: eventually, this should be in the container package, but it's going through a lot of churn + // and SpecAddAnnotations is already being passed too many arguments + // Filter early so any use of the annotations don't use the wrong values + if err := s.Runtime().FilterDisallowedAnnotations(sb.RuntimeHandler(), ctr.Config().Annotations); err != nil { + return nil, err + } + containerID := ctr.ID() containerName := ctr.Name() containerConfig := ctr.Config() @@ -598,12 +606,6 @@ func (s *Server) createSandboxContainer(ctx context.Context, ctr ctrIface.Contai } }() - // TODO: eventually, this should be in the container package, but it's going through a lot of churn - // and SpecAddAnnotations is already passed too many arguments - if err := s.Runtime().FilterDisallowedAnnotations(sb.RuntimeHandler(), ctr.Config().Annotations); err != nil { - return nil, err - } - // Get RDT class rdtClass, err := s.Config().Rdt().ContainerClassFromAnnotations(metadata.Name, containerConfig.Annotations, sb.Annotations()) if err != nil {
server: FilterDisallowedAnnotations of containers earlier
cri-o_cri-o
train
bbb90ea5f4fe3156106a564e8d4ed00a020fad24
diff --git a/example.js b/example.js index <HASH>..<HASH> 100644 --- a/example.js +++ b/example.js @@ -1,9 +1,9 @@ var Pokeio = require('./poke.io') -var location = 'Stockflethsvej 39'; - -var username = 'Arm4x'; -var password = 'OHSHITWADDUP'; +//Set environment variables or replace placeholder text +var location = process.env.PGO_LOCATION || 'times squere'; +var username = process.env.PGO_USERNAME || 'USERNAME'; +var password = process.env.PGO_PASSWORD || 'PASSWORD'; Pokeio.SetLocation(location, function(err, loc) { if (err) throw err;
Add optional env vars to prevent additional leakage of personal info
Armax_Pokemon-GO-node-api
train
f436c842daf5330c188141a6f092d6b604f96f18
diff --git a/recommonmark/parser.py b/recommonmark/parser.py index <HASH>..<HASH> 100644 --- a/recommonmark/parser.py +++ b/recommonmark/parser.py @@ -36,6 +36,9 @@ class _SectionHandler(object): class CommonMarkParser(object, parsers.Parser): supported = ('md', 'markdown') + def __init__(self, env=None): + self.env = env + def convert_blocks(self, blocks): for block in blocks: self.convert_block(block) @@ -66,8 +69,10 @@ class CommonMarkParser(object, parsers.Parser): self.horizontal_rule() elif (block.t == "HtmlBlock"): self.html_block(block) + elif (block.t == "ExtensionBlock"): + self.extension_block(block) else: - warn("Unsupported block type" + block.t) + warn("Unsupported block type: " + block.t) def parse(self, inputstring, document): self.setup_parse(inputstring, document) @@ -155,6 +160,30 @@ class CommonMarkParser(object, parsers.Parser): raw_node.line = block.start_line self.current_node.append(raw_node) + def extension_block(self, block): + rst_template = '.. {name}:: {arguments}' + rst_options_template = ' :{arg}: {value}' + + to_parse = rst_template.format( + name=block.title, + arguments=block.attributes.pop('arguments', ''), + ) + to_parse += "\n" + for arg, value in block.attributes.items(): + to_parse += rst_options_template.format( + arg=arg, + value=value, + ) + to_parse += "\n\n" + for line in block.strings: + to_parse += " {}\n".format(line) + + print "Sphinx Directive:\n[\n%s\n]\n" % to_parse + document = self.env.node_from_directive(to_parse) + for node in document.children: + self.current_node.append(node) + + def horizontal_rule(self): transition_node = nodes.transition() self.current_node.append(transition_node)
Add extension block parsing that renders RST blocks inline.
rtfd_recommonmark
train
f70b3b01522394e918c764b33d8f56b6803da552
diff --git a/src/Composer/Command/SelfUpdateCommand.php b/src/Composer/Command/SelfUpdateCommand.php index <HASH>..<HASH> 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -84,8 +84,10 @@ EOT $versionsUtil = new Versions($config, $remoteFilesystem); // switch channel if requested + $requestedChannel = null; foreach (Versions::CHANNELS as $channel) { if ($input->getOption($channel)) { + $requestedChannel = $channel; $versionsUtil->setChannel($channel); break; } @@ -130,8 +132,8 @@ EOT $latestVersion = $latest['version']; $updateVersion = $input->getArgument('version') ?: $latestVersion; - if (is_numeric($channel) && substr($latestStable['version'], 0, 1) !== $channel) { - $io->writeError('<warning>Warning: You forced the install of '.$latestVersion.' via --'.$channel.', but '.$latestStable['version'].' is the latest stable version. Updating to it via composer self-update --stable is recommended.</warning>'); + if ($requestedChannel && is_numeric($requestedChannel) && substr($latestStable['version'], 0, 1) !== $requestedChannel) { + $io->writeError('<warning>Warning: You forced the install of '.$latestVersion.' via --'.$requestedChannel.', but '.$latestStable['version'].' is the latest stable version. Updating to it via composer self-update --stable is recommended.</warning>'); } if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) {
Avoid warning about --2 usage when no channel is requested
composer_composer
train
467c2646a8bab51f21abd21172a57322b32aa679
diff --git a/exa/container.py b/exa/container.py index <HASH>..<HASH> 100644 --- a/exa/container.py +++ b/exa/container.py @@ -216,7 +216,7 @@ class Container: edges[(n0, n1)] = edge_color_map['index-index'] edges[(n1, n0)] = edge_color_map['index-index'] for col in v1.columns: - if name in col: + if name in col and '_' not in col: # Catches things like index name == 'index', column name == 'index0' edges[(n0, n1)] = edge_color_map['index-column'] edges[(n1, n0)] = edge_color_map['index-column'] g = nx.Graph() @@ -520,8 +520,8 @@ class TypedMeta(type): if not isinstance(obj, ptype): try: obj = ptype(obj) - except: - raise TypeError('Object {0} must instance of {1}'.format(name, ptype)) + except Exception: + raise TypeError('Must be able to convert object {0} to {1} (or must be of type {1})'.format(name, ptype)) setattr(self, pname, obj) def deleter(self): diff --git a/exa/relational/isotope.py b/exa/relational/isotope.py index <HASH>..<HASH> 100644 --- a/exa/relational/isotope.py +++ b/exa/relational/isotope.py @@ -142,7 +142,7 @@ def symbol_to_element_mass(): df['fmass'] = df['mass'].mul(df['af']) s = df.groupby('name').sum() mapper = df.drop_duplicates('name').set_index('name')['symbol'] - s.index = data.index.map(lambda x: mapper[x]) + s.index = df.index.map(lambda x: mapper[x]) s = s['fmass'] return s
Fixed a typo in relational.isotope
exa-analytics_exa
train
6f182a799364a6ad31675e0fad974c6d47ea47e4
diff --git a/codegen/src/main/java/io/sundr/codegen/model/JavaProperty.java b/codegen/src/main/java/io/sundr/codegen/model/JavaProperty.java index <HASH>..<HASH> 100644 --- a/codegen/src/main/java/io/sundr/codegen/model/JavaProperty.java +++ b/codegen/src/main/java/io/sundr/codegen/model/JavaProperty.java @@ -79,4 +79,25 @@ public class JavaProperty extends AttributeSupport implements Property<JavaType> public boolean isArray() { return array; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + JavaProperty that = (JavaProperty) o; + + if (array != that.array) return false; + if (type != null ? !type.equals(that.type) : that.type != null) return false; + return !(name != null ? !name.equals(that.name) : that.name != null); + + } + + @Override + public int hashCode() { + int result = type != null ? type.hashCode() : 0; + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + (array ? 1 : 0); + return result; + } }
Add equals and hashCode to JavaProperty.
sundrio_sundrio
train
5549491cbbcbd5fe578c37964fc5378ee7a7af05
diff --git a/library/ZExt/Di/InitializerAbstract.php b/library/ZExt/Di/InitializerAbstract.php index <HASH>..<HASH> 100755 --- a/library/ZExt/Di/InitializerAbstract.php +++ b/library/ZExt/Di/InitializerAbstract.php @@ -152,7 +152,7 @@ abstract class InitializerAbstract implements InitializerInterface, LocatorAware $this->_services[$id] = $service; } else { if (count($arguments) > 1) { - $service = call_user_method_array($method, $this, $arguments); + $service = call_user_func_array([$this, $method], $arguments); } else { $service = $this->$method($arguments[0]); }
ZExt\Di\InitializerAbstract::initialize() initialize with args bugfix
mikemirten_ZExt
train
89dbe2df8930f5bd2a61d34d5099f161ab892324
diff --git a/struct.js b/struct.js index <HASH>..<HASH> 100644 --- a/struct.js +++ b/struct.js @@ -108,7 +108,7 @@ StructRW.prototype.readFrom = function readFrom(buffer, offset) { obj[field.name] = res.value; } } - return ReadResult(null, offset, obj); + return ReadResult.just(offset, obj); }; function makeObject() {
StructRW: trivial change for clarity
uber_bufrw
train
7a643ca28cb40aa6559015e99f85b2d873b6f4d3
diff --git a/integration-tests/src/test/java/org/torquebox/integration/MessagingTest.java b/integration-tests/src/test/java/org/torquebox/integration/MessagingTest.java index <HASH>..<HASH> 100644 --- a/integration-tests/src/test/java/org/torquebox/integration/MessagingTest.java +++ b/integration-tests/src/test/java/org/torquebox/integration/MessagingTest.java @@ -20,9 +20,11 @@ public class MessagingTest extends AbstractIntegrationTest { @Test public void testQueueMessageProcessor() throws Exception { + Ruby runtime = IntegrationTestRubyFactory.createRuby(); + runtime.evalScriptlet(" require 'org.torquebox.torquebox-messaging-client'\n" ); + driver.get( "http://localhost:8080/messaging-rails/message/queue?text=ham%20biscuit" ); - Ruby runtime = IntegrationTestRubyFactory.createRuby(); Object result = runtime.evalScriptlet( slurpResource( "org/torquebox/integration/messaging_test.rb" ) ); System.err.println(" result=" + result ); diff --git a/integration-tests/src/test/java/org/torquebox/integration/messaging_test.rb b/integration-tests/src/test/java/org/torquebox/integration/messaging_test.rb index <HASH>..<HASH> 100644 --- a/integration-tests/src/test/java/org/torquebox/integration/messaging_test.rb +++ b/integration-tests/src/test/java/org/torquebox/integration/messaging_test.rb @@ -1,8 +1,3 @@ -require 'rubygems' -require 'org.torquebox.torquebox-messaging-client' -result = TorqueBox::Messaging::Queue.new('/queues/results').receive(:timeout => 2000) +TorqueBox::Messaging::Queue.new('/queues/results').receive(:timeout => 10000) -puts "result from receive is #{result.inspect}" - -result
Break up the loading of gem and execution. Increase timeout. More cowbell.
torquebox_torquebox
train
1ea85d84b3bab5e468c87eb5c4d63fd9eac780b7
diff --git a/parsl/dataflow/dflow.py b/parsl/dataflow/dflow.py index <HASH>..<HASH> 100644 --- a/parsl/dataflow/dflow.py +++ b/parsl/dataflow/dflow.py @@ -9,7 +9,6 @@ import typeguard import inspect import threading import sys -# import multiprocessing import datetime from getpass import getuser diff --git a/parsl/executors/extreme_scale/executor.py b/parsl/executors/extreme_scale/executor.py index <HASH>..<HASH> 100644 --- a/parsl/executors/extreme_scale/executor.py +++ b/parsl/executors/extreme_scale/executor.py @@ -78,7 +78,7 @@ class ExtremeScaleExecutor(HighThroughputExecutor, RepresentationMixin): launch_cmd : str Command line string to launch the mpi_worker_pool from the provider. The command line string will be formatted with appropriate values for the following values (debug, task_url, result_url, - ranks_per_node, nodes_per_block, heartbeat_period ,heartbeat_threshold, logdir). For eg: + ranks_per_node, nodes_per_block, heartbeat_period ,heartbeat_threshold, logdir). For example: launch_cmd="mpiexec -np {ranks_per_node} mpi_worker_pool.py {debug} --task_url={task_url} --result_url={result_url}" address : string @@ -86,7 +86,7 @@ class ExtremeScaleExecutor(HighThroughputExecutor, RepresentationMixin): workers will be running. This can be either a hostname as returned by `hostname` or an IP address. Most login nodes on clusters have several network interfaces available, only some of which can be reached from the compute nodes. Some trial and error might be - necessary to indentify what addresses are reachable from compute nodes. + necessary to identify what addresses are reachable from compute nodes. worker_ports : (int, int) Specify the ports to be used by workers to connect to Parsl. If this option is specified, diff --git a/parsl/executors/high_throughput/executor.py b/parsl/executors/high_throughput/executor.py index <HASH>..<HASH> 100644 --- a/parsl/executors/high_throughput/executor.py +++ b/parsl/executors/high_throughput/executor.py @@ -81,7 +81,7 @@ class HighThroughputExecutor(ParslExecutor, RepresentationMixin): launch_cmd : str Command line string to launch the process_worker_pool from the provider. The command line string will be formatted with appropriate values for the following values (debug, task_url, result_url, - cores_per_worker, nodes_per_block, heartbeat_period ,heartbeat_threshold, logdir). For eg: + cores_per_worker, nodes_per_block, heartbeat_period ,heartbeat_threshold, logdir). For example: launch_cmd="process_worker_pool.py {debug} -c {cores_per_worker} --task_url={task_url} --result_url={result_url}" address : string @@ -89,7 +89,7 @@ class HighThroughputExecutor(ParslExecutor, RepresentationMixin): workers will be running. This can be either a hostname as returned by `hostname` or an IP address. Most login nodes on clusters have several network interfaces available, only some of which can be reached from the compute nodes. Some trial and error might be - necessary to indentify what addresses are reachable from compute nodes. + necessary to identify what addresses are reachable from compute nodes. worker_ports : (int, int) Specify the ports to be used by workers to connect to Parsl. If this option is specified, diff --git a/parsl/executors/low_latency/executor.py b/parsl/executors/low_latency/executor.py index <HASH>..<HASH> 100644 --- a/parsl/executors/low_latency/executor.py +++ b/parsl/executors/low_latency/executor.py @@ -5,7 +5,6 @@ from concurrent.futures import Future import logging import threading import queue -# import pickle from multiprocessing import Process, Queue from ipyparallel.serialize import pack_apply_message # ,unpack_apply_message @@ -15,7 +14,6 @@ from parsl.executors.low_latency import zmq_pipes from parsl.executors.low_latency import interchange from parsl.executors.errors import ScalingFailed, DeserializationError, BadMessage from parsl.executors.base import ParslExecutor -# from parsl.dataflow.error import ConfigurationError from parsl.utils import RepresentationMixin from parsl.providers import LocalProvider diff --git a/parsl/providers/cluster_provider.py b/parsl/providers/cluster_provider.py index <HASH>..<HASH> 100644 --- a/parsl/providers/cluster_provider.py +++ b/parsl/providers/cluster_provider.py @@ -72,7 +72,7 @@ class ClusterProvider(ExecutionProvider): self.cmd_timeout = cmd_timeout if not callable(self.launcher): raise(BadLauncher(self.launcher, - "Launcher for executor:{} is of type:{}. Expects a parsl.launcher.launcher.Launcher or callable".format( + "Launcher for executor: {} is of type: {}. Expects a parsl.launcher.launcher.Launcher or callable".format( label, type(self.launcher)))) self.script_dir = None
Make assorted changes to human readable text/comments (#<I>) * Fix docstring typo * Remove commented out imports * Rearrange exception human text spaces * Expand "for eg" to "for example"
Parsl_parsl
train
73027752fcd12e3a352a26958a064edfc8ba717c
diff --git a/src/aws_encryption_sdk/materials_managers/__init__.py b/src/aws_encryption_sdk/materials_managers/__init__.py index <HASH>..<HASH> 100644 --- a/src/aws_encryption_sdk/materials_managers/__init__.py +++ b/src/aws_encryption_sdk/materials_managers/__init__.py @@ -223,6 +223,9 @@ class EncryptionMaterials(CryptographicMaterials): if data_encryption_key is None and encrypted_data_keys is not None: raise TypeError("encrypted_data_keys cannot be provided without data_encryption_key") + if encrypted_data_keys is None: + encrypted_data_keys = [] + super(EncryptionMaterials, self).__init__( algorithm=algorithm, encryption_context=encryption_context, @@ -242,6 +245,24 @@ class EncryptionMaterials(CryptographicMaterials): """ return frozenset(self._encrypted_data_keys) + @property + def is_complete(self): + # type: () -> bool + """Determine whether these materials are sufficiently complete for use as decryption materials. + + :rtype: bool + """ + if self.data_encryption_key is None: + return False + + if not self.encrypted_data_keys: + return False + + if self.algorithm.signing_algorithm_info is not None and self.signing_key is None: + return False + + return True + def add_data_encryption_key(self, data_encryption_key, keyring_trace): # type: (Union[DataKey, RawDataKey], KeyringTrace) -> None """Add a plaintext data encryption key. @@ -381,6 +402,24 @@ class DecryptionMaterials(CryptographicMaterials): attr.validate(self) @property + def is_complete(self): + # type: () -> bool + """Determine whether these materials are sufficiently complete for use as decryption materials. + + :rtype: bool + """ + if None in (self.algorithm, self.encryption_context): + return False + + if self.data_encryption_key is None: + return False + + if self.algorithm.signing_algorithm_info is not None and self.verification_key is None: + return False + + return True + + @property def data_key(self): # type: () -> RawDataKey """Backwards-compatible shim for access to data key.""" diff --git a/test/unit/test_material_managers.py b/test/unit/test_material_managers.py index <HASH>..<HASH> 100644 --- a/test/unit/test_material_managers.py +++ b/test/unit/test_material_managers.py @@ -215,6 +215,16 @@ def test_immutable_keyring_trace(material_class): materials.keyring_trace.append(42) +@pytest.mark.parametrize("material_class", (CryptographicMaterials, EncryptionMaterials, DecryptionMaterials)) +def test_empty_keyring_trace(material_class): + materials = material_class(**_copy_and_update_kwargs(material_class.__name__, dict(keyring_trace=_REMOVE))) + + trace = materials.keyring_trace + + assert isinstance(trace, tuple) + assert not trace + + def test_immutable_encrypted_data_keys(): materials = EncryptionMaterials(**_VALID_KWARGS["EncryptionMaterials"]) @@ -222,6 +232,15 @@ def test_immutable_encrypted_data_keys(): materials.encrypted_data_keys.add(42) +def test_empty_encrypted_data_keys(): + materials = EncryptionMaterials(**_copy_and_update_kwargs("EncryptionMaterials", dict(encrypted_data_keys=_REMOVE))) + + edks = materials.encrypted_data_keys + + assert isinstance(edks, frozenset) + assert not edks + + @pytest.mark.parametrize( "material_class, flag", ( @@ -415,3 +434,46 @@ def test_add_verification_key_fail(mod_kwargs, verification_key, exception_type, materials.add_verification_key(verification_key=verification_key) excinfo.match(exception_message) + + +def test_decryption_materials_is_complete(): + materials = DecryptionMaterials(**_copy_and_update_kwargs("DecryptionMaterials", {})) + + assert materials.is_complete + + +@pytest.mark.parametrize( + "mod_kwargs", + ( + dict(algorithm=_REMOVE), + dict(encryption_context=_REMOVE), + dict(data_encryption_key=_REMOVE, data_key=_REMOVE), + dict(verification_key=_REMOVE), + ), +) +def test_decryption_materials_is_not_complete(mod_kwargs): + kwargs = _copy_and_update_kwargs("DecryptionMaterials", mod_kwargs) + materials = DecryptionMaterials(**kwargs) + + assert not materials.is_complete + + +def test_encryption_materials_is_complete(): + materials = EncryptionMaterials(**_copy_and_update_kwargs("EncryptionMaterials", {})) + + assert materials.is_complete + + +@pytest.mark.parametrize( + "mod_kwargs", + ( + dict(data_encryption_key=_REMOVE, encrypted_data_keys=_REMOVE), + dict(encrypted_data_keys=_REMOVE), + dict(signing_key=_REMOVE), + ), +) +def test_encryption_materials_is_not_complete(mod_kwargs): + kwargs = _copy_and_update_kwargs("EncryptionMaterials", mod_kwargs) + materials = EncryptionMaterials(**kwargs) + + assert not materials.is_complete
add is_complete properties to EncryptionMaterials and DecryptionMaterials
aws_aws-encryption-sdk-python
train
79ed6206e88f6d8bb79558afdf30809d7681339c
diff --git a/openxc/sources/usb.py b/openxc/sources/usb.py index <HASH>..<HASH> 100644 --- a/openxc/sources/usb.py +++ b/openxc/sources/usb.py @@ -60,7 +60,7 @@ class UsbDataSource(DataSource): def read(self, num_bytes=None, timeout=None): num_bytes = num_bytes or self.DEFAULT_READ_REQUEST_SIZE timeout = timeout or self.DEFAULT_READ_TIMEOUT - if self.out_endpoint is None: + if self.in_endpoint is None: LOG.warn("Can't read from USB, IN endpoint is %s", self.in_endpoint) return "" else:
Check the correct endpoint when doing error checking before reading.
openxc_openxc-python
train
d8714e55ced58c7291dbd550c549e99ade068d38
diff --git a/lib/paper-house/version.rb b/lib/paper-house/version.rb index <HASH>..<HASH> 100644 --- a/lib/paper-house/version.rb +++ b/lib/paper-house/version.rb @@ -17,7 +17,7 @@ module PaperHouse - VERSION = "0.1.15" + VERSION = "0.1.16" end
Version bump to <I>.
trema_paper-house
train
03d3e166f1f9389a31fa7b78e4cadd6e96452038
diff --git a/stagpy/_helpers.py b/stagpy/_helpers.py index <HASH>..<HASH> 100644 --- a/stagpy/_helpers.py +++ b/stagpy/_helpers.py @@ -2,13 +2,13 @@ from __future__ import annotations from inspect import getdoc -import typing +from typing import TYPE_CHECKING, Generic, TypeVar import matplotlib.pyplot as plt from . import conf -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from typing import Optional, Any, List, Callable from matplotlib.figure import Figure from numpy import ndarray @@ -125,7 +125,11 @@ def find_in_sorted_arr(value: Any, array: ndarray, after=False) -> int: return ielt -class CachedReadOnlyProperty: +T = TypeVar('T') +V = TypeVar('V') + + +class CachedReadOnlyProperty(Generic[T, V]): """Descriptor implementation of read-only cached properties. Properties are cached as ``_cropped_{name}`` instance attribute. @@ -140,13 +144,13 @@ class CachedReadOnlyProperty: property is read-only instead of being writeable. """ - def __init__(self, thunk: Callable[[Any], Any]): + def __init__(self, thunk: Callable[[T], V]): self._thunk = thunk self._name = thunk.__name__ self._cache_name = f'_cropped_{self._name}' self.__doc__ = thunk.__doc__ - def __get__(self, instance: Any, _) -> Any: + def __get__(self, instance: T, _) -> V: try: return getattr(instance, self._cache_name) except AttributeError: @@ -155,6 +159,6 @@ class CachedReadOnlyProperty: setattr(instance, self._cache_name, cached_value) return cached_value - def __set__(self, instance: Any, _): + def __set__(self, instance: T, _): raise AttributeError( f'Cannot set {self._name} property of {instance!r}')
Declare CachedReadOnlyProperty as generic It allows type checking of instances and property values.
StagPython_StagPy
train
f7af10a0e1b6d952654c82f434c6a52381e79ceb
diff --git a/bin/webpack.js b/bin/webpack.js index <HASH>..<HASH> 100755 --- a/bin/webpack.js +++ b/bin/webpack.js @@ -1,17 +1,19 @@ #!/usr/bin/env node +const { exec, execSync } = require("child_process"); +const inquirer = require("inquirer"); + function runCommand(command, options) { - const cp = require("child_process"); return new Promise((resolve, reject) => { const executedCommand = cp.spawn(command, options, { stdio: "inherit" }); - executedCommand.on("error", error => { + executedCommand.on("error", (error) => { reject(error); }); - executedCommand.on("exit", code => { - if (code === 0) { + executedCommand.on("exit", (code) => { + if(code === 0) { resolve(true); } else { reject(); @@ -21,24 +23,38 @@ function runCommand(command, options) { } let webpackCliInstalled = false; +// try { +// const blah = require("webpack-cli"); // eslint-disable-line node/no-missing-require, node/no-extraneous-require, node/no-unpublished-require +// webpackCliInstalled = true; +// } catch(e) { +// console.log("error", e); +// webpackCliInstalled = false; +// } + try { - require.resolve("webpack-cli"); + execSync("node -e require.resolve('webpack-cli')", { stdio: "ignore" }); webpackCliInstalled = true; } catch (err) { webpackCliInstalled = false; } -if (!webpackCliInstalled) { + +if(webpackCliInstalled) { + require("webpack-cli"); // eslint-disable-line node/no-missing-require, node/no-extraneous-require, node/no-unpublished-require +} else { const path = require("path"); const fs = require("fs"); - const inquirer = require("inquirer"); const isYarn = fs.existsSync(path.resolve(process.cwd(), "yarn.lock")); + let command; - const packageManager = isYarn ? "yarn" : "npm"; - const options = ["install", "-D", "webpack-cli"]; - - if (isYarn) { - options[0] = "add"; + let packageManager; + let options = []; + if(isYarn) { + packageManager = "yarn"; + options = ["add", "-D", "webpack-cli"]; + } else { + packageManager = "npm"; + options = ["install", "--save-dev", "webpack-cli"]; } const commandToBeRun = `${packageManager} ${options.join(" ")}`; @@ -46,19 +62,25 @@ if (!webpackCliInstalled) { const question = { type: "confirm", name: "shouldInstall", - message: `Would you like to install webpack-cli? (That will run ${ - commandToBeRun - })`, + message: `Would you like to install webpack-cli? (That will run ${commandToBeRun})`, default: true }; - console.error("The CLI moved into a separate package: webpack-cli"); - inquirer.prompt(question).then(answer => { - if (answer) { + if(isYarn) { + command = "yarn add webpack-cli -D"; + } else { + command = "npm install --save-dev webpack-cli"; + } + + console.error("The CLI moved into a separate package: webpack-cli.\n"); + inquirer.prompt(question).then((answer) => { + if(answer) { console.error("Installing webpack-cli"); - runCommand(packageManager, options) - .then(result => require("webpack-cli")) // eslint-disable-line - .catch(error => console.error(error)); + runCommand(packageManager, options).then((result) => { + require("webpack-cli"); // eslint-disable-line + }).catch((error) => { + console.error(error); + }); } else { process.exitCode(1); } @@ -66,3 +88,4 @@ if (!webpackCliInstalled) { } else { require("webpack-cli"); // eslint-disable-line } +
* Pipe stdout and stderr from child_process to main process * code refactoring and using promises
webpack_webpack
train
7bb71195a0d99287f42913be0324b96e12817852
diff --git a/lib/conf/cli.js b/lib/conf/cli.js index <HASH>..<HASH> 100755 --- a/lib/conf/cli.js +++ b/lib/conf/cli.js @@ -8,6 +8,7 @@ var fs = require('fs'), util = require('util'), path = require('path'), + os = require('os'), dialog = require('dialog'), common = require('./../common'), pidfile = require('./../utils/pidfile'), @@ -250,9 +251,14 @@ var show_gui_and_exit = function () { gui_path = gui_path + '.exe'; else if (os_name == 'linux') gui_path = gui_path + '.py'; - else { - args = [gui_path.replace('prey-config', 'PreyConfig.app/Contents/MacOS/prey-config.rb')] - gui_path = '/usr/bin/ruby'; + else { + args = [gui_path.replace('prey-config', 'PreyConfig.app/Contents/MacOS/prey-config.rb')]; + var mavericks_or_older = parseFloat(os.release()) >= 13; + if (mavericks_or_older) { + gui_path = '/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby'; + } else { + gui_path = '/usr/bin/ruby'; + } } helpers.run_detached(gui_path, args);
Fixed osx/cocoa require in prey-config for Mavericks or newer Macs.
prey_prey-node-client
train
d044cdd02f554a0517c5173e3e412efd91c28c27
diff --git a/cake/tests/cases/libs/view/helpers/paginator.test.php b/cake/tests/cases/libs/view/helpers/paginator.test.php index <HASH>..<HASH> 100644 --- a/cake/tests/cases/libs/view/helpers/paginator.test.php +++ b/cake/tests/cases/libs/view/helpers/paginator.test.php @@ -1574,7 +1574,7 @@ class PaginatorHelperTest extends CakeTestCase { ); $this->assertTags($result, $expected); - $this->Paginator->params['paging']['Client']['page'] = 3; + $this->Paginator->request->params['paging']['Client']['page'] = 3; $result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2, 'separator' => ' - ', 'ellipsis' => ' ~~~ ')); $expected = array( array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span', @@ -1591,7 +1591,7 @@ class PaginatorHelperTest extends CakeTestCase { ); $this->assertTags($result, $expected); - $this->Paginator->params['paging']['Client']['page'] = 3; + $this->Paginator->request->params['paging']['Client']['page'] = 3; $result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2, 'separator' => ' - ', 'ellipsis' => '<span class="ellipsis">...</span>')); $expected = array( array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
Fixing test case that was missing request access.
cakephp_cakephp
train
80f7568bd448f4d63811d48b79d1fe0ce73073d3
diff --git a/go/vt/mysqlctl/mysqld.go b/go/vt/mysqlctl/mysqld.go index <HASH>..<HASH> 100644 --- a/go/vt/mysqlctl/mysqld.go +++ b/go/vt/mysqlctl/mysqld.go @@ -148,6 +148,7 @@ func (mysqld *Mysqld) RunMysqlUpgrade() error { "--defaults-file=" + mysqld.config.path, "--socket", mysqld.config.SocketFile, "--user", mysqld.dba.Uname, + "--force", // Don't complain if it's already been upgraded. } if mysqld.dba.Pass != "" { // --password must be omitted entirely if empty, or else it will prompt.
Add --force to mysql_upgrade. Without it, mysql_upgrade dies with exit code 1 if the database doesn't need to be upgraded.
vitessio_vitess
train
5ff2ec563de9743c6113f0e8491d23ef66fc7715
diff --git a/lib/netsuite/records/assembly_item.rb b/lib/netsuite/records/assembly_item.rb index <HASH>..<HASH> 100644 --- a/lib/netsuite/records/assembly_item.rb +++ b/lib/netsuite/records/assembly_item.rb @@ -50,6 +50,7 @@ module NetSuite attr_reader :internal_id attr_accessor :external_id + attr_accessor :search_joins def initialize(attributes = {}) @internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id)
Update assembly_item.rb Added attr_accessor for :search_joins
NetSweet_netsuite
train
344f378096d93d7bcb34fd4aea46138c388159b9
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -161,6 +161,9 @@ gulp.task("mocha", [ "istanbul:hook" ], function() { "test/**/*.test.js" ]) .pipe(mocha({ui: "bdd"})) + .on("error", function (err) { + process.exit(1); + }) .pipe(istanbul.writeReports()); });
Prevents green builds with failing tests (#<I>) e.g. <URL>
inversify_InversifyJS
train
c30d78b2c763e8872d88b72363d65fff0fade188
diff --git a/detox/test/e2e/l-permissions.js b/detox/test/e2e/l-permissions.js index <HASH>..<HASH> 100644 --- a/detox/test/e2e/l-permissions.js +++ b/detox/test/e2e/l-permissions.js @@ -1,13 +1,13 @@ describe('Permissions', () => { it('Permissions is granted', async () => { - await device.relaunchApp({permissions: {calendar: 'YES'}}); + await device.launchApp({permissions: {calendar: 'YES'}}); await element(by.label('Permissions')).tap(); await expect(element(by.text('granted'))).toBeVisible(); }); it('Permissions denied', async () => { - await device.relaunchApp({permissions: {calendar: 'NO'}}); + await device.launchApp({permissions: {calendar: 'NO'}}); await element(by.label('Permissions')).tap(); await expect(element(by.text('denied'))).toBeVisible(); });
test permissions with new `launchApp` API
wix_Detox
train
e5a1c8b4982dc5c4dd4224e5ec0f8530e25efa99
diff --git a/lib/queue_classic/setup.rb b/lib/queue_classic/setup.rb index <HASH>..<HASH> 100644 --- a/lib/queue_classic/setup.rb +++ b/lib/queue_classic/setup.rb @@ -5,7 +5,7 @@ module QC CreateTable = File.join(Root, "/sql/create_table.sql") DropSqlFunctions = File.join(Root, "/sql/drop_ddl.sql") UpgradeTo_3_0_0 = File.join(Root, "/sql/update_to_3_0_0.sql") - DowngradeTo_3_0_0 = File.join(Root, "/sql/downgrade_from_3_0_0.sql") + DowngradeFrom_3_0_0 = File.join(Root, "/sql/downgrade_from_3_0_0.sql") def self.create(c = QC::default_conn_adapter.connection) conn = QC::ConnAdapter.new(c) @@ -37,7 +37,7 @@ module QC def self.downgrade_from_3_0_0(c = QC::default_conn_adapter.connection) conn = QC::ConnAdapter.new(c) - conn.execute(File.read(DowngradeTo_3_0_0)) + conn.execute(File.read(DowngradeFrom_3_0_0)) end end end
rename variable in QC Setup
QueueClassic_queue_classic
train
c1874cfac0238b2b0078ee9c97da8d6664a700f7
diff --git a/lib/epp-client/client.rb b/lib/epp-client/client.rb index <HASH>..<HASH> 100644 --- a/lib/epp-client/client.rb +++ b/lib/epp-client/client.rb @@ -147,28 +147,6 @@ module EPP command(ack) end - # Calls an EPP command after connecting to the EPP Server and logging in. - # - # @overload method_missing(command, payload, extension) - # @param [String, #to_s] command EPP Command to call - # @param [XML::Node, XML::Document, String] payload EPP XML Payload - # @param [XML::Node, XML::Document, String] extension EPP XML Extension - # @overload method_missing(command) { |cmd, ext| payload } - # @param [String, #to_s] command EPP Command to call - # @yield [cmd, ext] block to construct payload - # @yieldparam [XML::Node] cmd XML Node of the command - # for the payload to be added into - # @yieldparam [XML::Node] ext XML Node of the extension block - # for the extension payload to be added into - # @return [Response] EPP Response object - # def method_missing(command, payload = nil, extension = nil, &block) - # @conn.connection do - # @conn.with_login do - # @conn.request(command, payload, extension, &block) - # end - # end - # end - protected def command(cmd, extension = nil) @conn.connection do
Remove method_missing from EPP::Client
m247_epp-client
train
44a56b2139e9629342bcc32fc55b31c8a3242cca
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ setup( include_package_data=True, author='Roman Miroshnychenko (fork author)', author_email='romanvm@yandex.ua', - description='A Django application that provides' + description='A Django application that provides ' 'a fully functional TinyMCE 4 editor widget for models and forms.', long_description=long_description, license='MIT License',
Fixes description in setup.py
romanvm_django-tinymce4-lite
train
baf4579e63facdbcad4ada09077004e28b7f6e3b
diff --git a/salt/cloud/clouds/msazure.py b/salt/cloud/clouds/msazure.py index <HASH>..<HASH> 100644 --- a/salt/cloud/clouds/msazure.py +++ b/salt/cloud/clouds/msazure.py @@ -1591,7 +1591,7 @@ def cleanup_unattached_disks(kwargs=None, conn=None, call=None): for disk in disks: if disks[disk]['attached_to'] is None: del_kwargs = { - 'name': disks[disk]['name'][0], + 'name': disks[disk]['name'], 'delete_vhd': kwargs.get('delete_vhd', False) } log.info('Deleting disk {name}, deleting VHD: {delete_vhd}'.format(**del_kwargs))
Update cleanup function for azure
saltstack_salt
train
2c4e591e3ae9d84c8f6150f8c15235d45f53ae7a
diff --git a/src/cf/terminal/color.go b/src/cf/terminal/color.go index <HASH>..<HASH> 100644 --- a/src/cf/terminal/color.go +++ b/src/cf/terminal/color.go @@ -61,7 +61,7 @@ func ColorizeBold(message string, color Color) string { var decolorizerRegex = regexp.MustCompile(`\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]`) -func decolorize(message string) string { +func Decolorize(message string) string { return string(decolorizerRegex.ReplaceAll([]byte(message), []byte(""))) } diff --git a/src/cf/terminal/table.go b/src/cf/terminal/table.go index <HASH>..<HASH> 100644 --- a/src/cf/terminal/table.go +++ b/src/cf/terminal/table.go @@ -49,7 +49,7 @@ func (t *PrintableTable) Print() { func (t *PrintableTable) calculateMaxSize(row []string) { for index, value := range row { - cellLength := len(decolorize(value)) + cellLength := len(Decolorize(value)) if t.maxSizes[index] < cellLength { t.maxSizes[index] = cellLength } @@ -79,7 +79,7 @@ func (t *PrintableTable) printRow(row []string) { func (t *PrintableTable) cellValue(col int, value string) string { padding := "" if col < len(t.header)-1 { - padding = strings.Repeat(" ", t.maxSizes[col]-len(decolorize(value))) + padding = strings.Repeat(" ", t.maxSizes[col]-len(Decolorize(value))) } return fmt.Sprintf("%s%s ", value, padding) } diff --git a/src/testhelpers/matchers/contain_substring.go b/src/testhelpers/matchers/contain_substring.go index <HASH>..<HASH> 100644 --- a/src/testhelpers/matchers/contain_substring.go +++ b/src/testhelpers/matchers/contain_substring.go @@ -1,6 +1,7 @@ package matchers import ( + "cf/terminal" "fmt" "github.com/onsi/gomega" "strings" @@ -25,7 +26,7 @@ func (matcher SliceMatcher) Match(actual interface{}) (success bool, err error) for _, actualValue := range actualStrings { allStringsFound := true for _, expectedValue := range matcher.expected[matcher.failedAtIndex] { - allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue)) + allStringsFound = allStringsFound && strings.Contains(terminal.Decolorize(strings.ToLower(actualValue)), strings.ToLower(expectedValue)) } if allStringsFound {
Decolorize strings in ContainsSubstrings matcher [Finishes #<I>] Closes #<I>
cloudfoundry_cli
train
75e3335a30d9c0fb7de0d52a4739fa05f025c46d
diff --git a/lib/yard-tomdoc.rb b/lib/yard-tomdoc.rb index <HASH>..<HASH> 100644 --- a/lib/yard-tomdoc.rb +++ b/lib/yard-tomdoc.rb @@ -60,7 +60,8 @@ module YARD yard.create_tag(:deprecated, 'Do not use this in new code, and replace it when updating old code.') if tomdoc.deprecated? - yard.create_tag(:private, 'Intended for internal use only.') if tomdoc.internal? + yard.create_tag(:api, 'public') if tomdoc.public? + yard.create_tag(:api, 'private') if tomdoc.internal? tomdoc end
Use @api private tag instead of @private for Internal status.
rubyworks_yard-tomdoc
train
0985a76566ab18537d4e459c7513adb6c53ade99
diff --git a/mode/javascript/javascript.js b/mode/javascript/javascript.js index <HASH>..<HASH> 100644 --- a/mode/javascript/javascript.js +++ b/mode/javascript/javascript.js @@ -322,7 +322,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { register(value); return isTS ? cont(maybetype, vardef2) : cont(vardef2); } - return cont(); + return pass(); } function vardef2(type, value) { if (value == "=") return cont(expression, vardef2); @@ -388,7 +388,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; - if (type == "vardef") return lexical.indented + 4; + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat")
[javascript mode] Also count on semicolon omittance in var lists Issue #<I>
codemirror_CodeMirror
train
ec1721dd74b70ae9353e48daad97b5f1a6299d50
diff --git a/bankwire.php b/bankwire.php index <HASH>..<HASH> 100644 --- a/bankwire.php +++ b/bankwire.php @@ -163,7 +163,7 @@ class BankWire extends PaymentModule $payment_options = array( 'cta_text' => $this->l('Pay by Bank Wire'), - 'logo' => Media::getMediaPath(dirname(__FILE__).'/bankwire.jpg'), + 'logo' => Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/bankwire.jpg'), 'action' => $this->context->link->getModuleLink($this->name, 'validation', array(), true) );
[-] MO: Fix issue on bankwire logo path from displayPayment hook
PrestaShop_ps_wirepayment
train
6af4386f368e110da231434f7d0ce3ded9f677a1
diff --git a/dpr/main.go b/dpr/main.go index <HASH>..<HASH> 100644 --- a/dpr/main.go +++ b/dpr/main.go @@ -11,6 +11,7 @@ import ( var ( dataDir = flag.String("D", os.Getenv("HOME")+"/.dpr", "Location of data dir") addr = flag.String("H", ":80", "Address to bind to") + bucket = flag.String("B", "", "S3 bucket to use for push") ) func main() { @@ -18,6 +19,7 @@ func main() { server := &Server{ DataRoot: *dataDir, Address: *addr, + Bucket: *bucket, AwsAccessKeyId: os.Getenv("AWS_ACCESS_KEY_ID"), AwsSecretAccessKey: os.Getenv("AWS_SECRET_ACCESS_KEY"), } diff --git a/dpr/server.go b/dpr/server.go index <HASH>..<HASH> 100644 --- a/dpr/server.go +++ b/dpr/server.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "github.com/dynport/gocloud/aws/s3" "io" "log" "net/http" @@ -10,6 +9,8 @@ import ( "strconv" "strings" "sync" + + "github.com/dynport/gocloud/aws/s3" ) type Server struct { @@ -17,6 +18,7 @@ type Server struct { Address string AwsAccessKeyId string AwsSecretAccessKey string + Bucket string } func (s *Server) Run() error { @@ -28,14 +30,14 @@ func (server *Server) newResource(r *http.Request) Resource { client := s3.NewFromEnv() client.UseSsl = true client.CustomEndpointHost = "s3-eu-west-1.amazonaws.com" - return &S3Resource{Request: r, Bucket: "de.1414.registry", Client: client} + return &S3Resource{Request: r, Bucket: server.Bucket, Client: client} } else { return NewFileResource(server.DataRoot, r) } } func (server *Server) awsConfigured() bool { - return server.AwsAccessKeyId != "" && server.AwsSecretAccessKey != "" + return server.AwsAccessKeyId != "" && server.AwsSecretAccessKey != "" && server.Bucket != "" } var ancestryCache = map[string]string{}
move bucket name into cli flags
dynport_dgtk
train
d9ef89b6bc76ecc89f5aed4668d78d2feb63ddbc
diff --git a/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBaseElementBuilder.java b/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBaseElementBuilder.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBaseElementBuilder.java +++ b/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBaseElementBuilder.java @@ -329,6 +329,10 @@ public abstract class AbstractBaseElementBuilder<B extends AbstractBaseElementBu shapeBounds.setY(y); } + public BpmnEdge createBpmnEdge(SequenceFlow sequenceFlow) { + return createBpmnEdge((BaseElement) sequenceFlow); + } + public BpmnEdge createBpmnEdge(BaseElement baseElement) { BpmnPlane bpmnPlane = findBpmnPlane(); if (bpmnPlane != null) { @@ -366,10 +370,10 @@ public abstract class AbstractBaseElementBuilder<B extends AbstractBaseElementBu throw new RuntimeException("Bpmn element type not supported"); } - setWaypoints(edge, edgeSource, edgeTarget); + setWaypointsWithSourceAndTarget(edge, edgeSource, edgeTarget); } - protected void setWaypoints(BpmnEdge edge, FlowNode edgeSource, FlowNode edgeTarget) { + protected void setWaypointsWithSourceAndTarget(BpmnEdge edge, FlowNode edgeSource, FlowNode edgeTarget) { BpmnShape source = findBpmnShape(edgeSource); BpmnShape target = findBpmnShape(edgeTarget); diff --git a/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBoundaryEventBuilder.java b/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBoundaryEventBuilder.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBoundaryEventBuilder.java +++ b/src/main/java/org/camunda/bpm/model/bpmn/builder/AbstractBoundaryEventBuilder.java @@ -148,7 +148,7 @@ public abstract class AbstractBoundaryEventBuilder<B extends AbstractBoundaryEve } @Override - protected void setWaypoints(BpmnEdge edge, FlowNode edgeSource, FlowNode edgeTarget) { + protected void setWaypointsWithSourceAndTarget(BpmnEdge edge, FlowNode edgeSource, FlowNode edgeTarget) { BpmnShape source = findBpmnShape(edgeSource); BpmnShape target = findBpmnShape(edgeTarget);
fix(fluent-builder): adjust code to be backward compatible
camunda_camunda-bpmn-model
train
57af8637f022e8bf7f313f6156d9873b7f5ebaba
diff --git a/proto/extensions_test.go b/proto/extensions_test.go index <HASH>..<HASH> 100644 --- a/proto/extensions_test.go +++ b/proto/extensions_test.go @@ -97,7 +97,7 @@ func TestGetExtensionForIncompleteDesc(t *testing.T) { Name: "a.c", Tag: "bytes,123456790,opt", } - ext2 := []byte{0,1,2,3,4,5,6,7} + ext2 := []byte{0, 1, 2, 3, 4, 5, 6, 7} if err := proto.SetExtension(msg, extdesc2, ext2); err != nil { t.Fatalf("Could not set ext2: %s", err) } @@ -479,7 +479,7 @@ func TestNilExtension(t *testing.T) { } if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { t.Error("expected SetExtension to fail due to a nil extension") - } else if want := "proto: SetExtension called with nil value of type *test_proto.Ext"; err.Error() != want { + } else if want := fmt.Sprintf("proto: SetExtension called with nil value of type %T", new(pb.Ext)); err.Error() != want { t.Errorf("expected error %v, got %v", want, err) } // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update diff --git a/proto/text_parser_test.go b/proto/text_parser_test.go index <HASH>..<HASH> 100644 --- a/proto/text_parser_test.go +++ b/proto/text_parser_test.go @@ -32,6 +32,7 @@ package proto_test import ( + "fmt" "math" "testing" @@ -362,7 +363,7 @@ var unMarshalTextTests = []UnmarshalTextTest{ // Missing required field { in: `name: "Pawel"`, - err: `proto: required field "test_proto.MyMessage.count" not set`, + err: fmt.Sprintf(`proto: required field "%T.count" not set`, MyMessage{}), out: &MyMessage{ Name: String("Pawel"), }, @@ -371,7 +372,7 @@ var unMarshalTextTests = []UnmarshalTextTest{ // Missing required field in a required submessage { in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: `proto: required field "test_proto.InnerMessage.host" not set`, + err: fmt.Sprintf(`proto: required field "%T.host" not set`, InnerMessage{}), out: &MyMessage{ Count: Int32(42), WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}},
proto: robustify tests that compare error messages (#<I>) For now, use fmt.Sprintf to get the proper type name that is agnostic to the package that the type is defined in. However, in the future, we should avoid such brittle testing and have more distinguishable errors.
golang_protobuf
train
19e7e6b4b831da6f17052e8e588d29894e28d599
diff --git a/lib/lwm2m-common.js b/lib/lwm2m-common.js index <HASH>..<HASH> 100644 --- a/lib/lwm2m-common.js +++ b/lib/lwm2m-common.js @@ -614,7 +614,7 @@ export class LwM2MClientProxy extends EventEmitter { let procs = lines.map((line) => { let body = line.split(':'); let command = body[0]; - if (!command || !body[1]) { + if (!command || typeof(body[1]) === 'undefined') { return Promise.resolve(); } command = command.substring(1);
Skip entire request handling process only when body[1] is undefined
CANDY-LINE_node-red-contrib-lwm2m
train
443a70e334586992f01be63d14b5bee50596e639
diff --git a/.codeclimate.yml b/.codeclimate.yml index <HASH>..<HASH> 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -1,14 +1,3 @@ -languages: - Ruby: true - JavaScript: false - PHP: false - Python: false -exclude_paths: - - "lib/active_model/jobs/engine.rb" - - "lib/active_model/jobs/version.rb" -engines: +plugins: rubocop: enabled: true -ratings: - paths: - - "**.rb" diff --git a/.rubocop.yml b/.rubocop.yml index <HASH>..<HASH> 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -13,3 +13,7 @@ Style/Documentation: # Allow any kind of string literal Style/StringLiterals: Enabled: false + +Metrics/BlockLength: + Exclude: + - spec/**/* diff --git a/active_model_jobs.gemspec b/active_model_jobs.gemspec index <HASH>..<HASH> 100644 --- a/active_model_jobs.gemspec +++ b/active_model_jobs.gemspec @@ -1,5 +1,4 @@ -# coding: utf-8 -lib = File.expand_path('../lib', __FILE__) +lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'active_model/jobs/version' @@ -22,13 +21,13 @@ Gem::Specification.new do |spec| spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] - spec.add_development_dependency "bundler", "~> 1.9" - spec.add_development_dependency "rake", "~> 10" - spec.add_development_dependency "rspec", "~> 3" - spec.add_development_dependency "rubocop", "~> 0" - spec.add_development_dependency "yard", "~> 0" - spec.add_development_dependency "codeclimate-test-reporter", "~> 0" + spec.add_development_dependency "bundler" + spec.add_development_dependency "rake" + spec.add_development_dependency "rspec" + spec.add_development_dependency "rubocop" + spec.add_development_dependency "simplecov" + spec.add_development_dependency "yard" - spec.add_dependency "activemodel", "~> 5.0.0.pre" - spec.add_dependency "activejob", "~> 5.0.0.pre" + spec.add_dependency "activejob", ">= 5.0.0" + spec.add_dependency "activemodel", ">= 5.0.0" end diff --git a/lib/active_model/jobs.rb b/lib/active_model/jobs.rb index <HASH>..<HASH> 100644 --- a/lib/active_model/jobs.rb +++ b/lib/active_model/jobs.rb @@ -18,7 +18,7 @@ module ActiveModel # end module Jobs # Method suffix for actions. - ACTION_SUFFIX = '!' + ACTION_SUFFIX = '!'.freeze # Call +perform_later+ on an ActiveJob class corresponding to an # undefined action method name. Most of the work here is done in the @@ -33,6 +33,7 @@ module ActiveModel def method_missing(method, *arguments) performer = Performer.new method, model_name return super unless respond_to?(method) && performer.job? + performer.call self end diff --git a/lib/active_model/jobs/engine.rb b/lib/active_model/jobs/engine.rb index <HASH>..<HASH> 100644 --- a/lib/active_model/jobs/engine.rb +++ b/lib/active_model/jobs/engine.rb @@ -1,5 +1,6 @@ module ActiveModel module Jobs + # Automatically includes ActiveModel::Jobs into a Rails app class Engine < Rails::Engine ActiveSupport.on_load :active_record do include ActiveModel::Jobs diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,4 @@ -$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) +$LOAD_PATH.unshift File.expand_path('../lib', __dir__) if ENV['CI'] require "codeclimate-test-reporter" diff --git a/spec/support/mocks.rb b/spec/support/mocks.rb index <HASH>..<HASH> 100644 --- a/spec/support/mocks.rb +++ b/spec/support/mocks.rb @@ -29,6 +29,7 @@ class Mocker run_callbacks :save do return false unless valid? return create unless persisted? + update end end @@ -49,6 +50,7 @@ class Mocker def create return true if persisted? + run_callbacks :create do self.id = 1 true @@ -57,6 +59,7 @@ class Mocker def update return false unless persisted? + run_callbacks :update do self.id = 2 true
Update linting and autocorrect to latest style guide
tubbo_active_model_jobs
train
d48872de0aecf516b26dabbc7702757a6aa9cfbf
diff --git a/pyuavcan/transport/can/_can.py b/pyuavcan/transport/can/_can.py index <HASH>..<HASH> 100644 --- a/pyuavcan/transport/can/_can.py +++ b/pyuavcan/transport/can/_can.py @@ -228,19 +228,20 @@ class CANTransport(pyuavcan.transport.Transport): assert not frame.loopback ss = can_id.to_input_session_specifier() accepted = False - - session = self._input_dispatch_table.get(ss) - if session is not None: - session.push_frame(can_id, frame) - accepted = True - - if ss.remote_node_id is not None: - ss = pyuavcan.transport.SessionSpecifier(ss.data_specifier, None) + dest_nid = can_id.get_destination_node_id() + if dest_nid is None or dest_nid == self._local_node_id: session = self._input_dispatch_table.get(ss) if session is not None: session.push_frame(can_id, frame) accepted = True + if ss.remote_node_id is not None: + ss = pyuavcan.transport.SessionSpecifier(ss.data_specifier, None) + session = self._input_dispatch_table.get(ss) + if session is not None: + session.push_frame(can_id, frame) + accepted = True + return accepted def _handle_loopback_frame(self, can_id: CANID, frame: TimestampedUAVCANFrame) -> None: @@ -261,7 +262,7 @@ class CANTransport(pyuavcan.transport.Transport): if isinstance(ds, pyuavcan.transport.MessageDataSpecifier) ) - fcs = generate_filter_configurations(subject_ids, self.local_node_id) + fcs = generate_filter_configurations(subject_ids, self._local_node_id) assert len(fcs) > len(subject_ids) del subject_ids diff --git a/pyuavcan/transport/can/_identifier.py b/pyuavcan/transport/can/_identifier.py index <HASH>..<HASH> 100644 --- a/pyuavcan/transport/can/_identifier.py +++ b/pyuavcan/transport/can/_identifier.py @@ -35,6 +35,10 @@ class CANID: def to_output_session_specifier(self) -> pyuavcan.transport.SessionSpecifier: raise NotImplementedError + def get_destination_node_id(self) -> typing.Optional[int]: + """Hides the destination selection logic from users of the abstract type.""" + raise NotImplementedError + @staticmethod def try_parse(identifier: int) -> typing.Optional[CANID]: _validate_unsigned_range(identifier, 2 ** 29 - 1) @@ -101,6 +105,9 @@ class MessageCANID(CANID): ds = pyuavcan.transport.MessageDataSpecifier(self.subject_id) return pyuavcan.transport.SessionSpecifier(ds, None) + def get_destination_node_id(self) -> typing.Optional[int]: + return None + @dataclasses.dataclass(frozen=True) class ServiceCANID(CANID): @@ -142,6 +149,9 @@ class ServiceCANID(CANID): ds = pyuavcan.transport.ServiceDataSpecifier(self.service_id, role) return pyuavcan.transport.SessionSpecifier(ds, self.destination_node_id) + def get_destination_node_id(self) -> typing.Optional[int]: + return self.destination_node_id + def _validate_unsigned_range(value: int, max_value: int) -> None: if not isinstance(value, int) or not (0 <= value <= max_value):
Don't forget to check the destination node ID upon reception
UAVCAN_pyuavcan
train
4c5092a504037410a5dbf5ea2f2277892846112a
diff --git a/Transferable.js b/Transferable.js index <HASH>..<HASH> 100644 --- a/Transferable.js +++ b/Transferable.js @@ -125,36 +125,28 @@ this.transferable = function(obj_or_address) { entries=[]; for(var i=0;i<logs.length;i++) { var data = logs[i].data; - if(data.length>256) { + if(data.length==386) { data=data.substr(2); _from ="0x"+ split64(data).substr(26); data=data.substr(64); _to ="0x"+split64(data).substr(26); data=data.substr(64); + _msg ="0x"+split64(data).substr(26); + data=data.substr(64); _value =(split64(data)); data=data.substr(64); _base =(split64(data)); - data=data.substr(64); - _fromSoll =(split64(data)); - data=data.substr(64); - _fromHaben =(split64(data)); - data=data.substr(64); - _toSoll =(split64(data)); - data=data.substr(64); - _toHaben =(split64(data)); - data=data.substr(64); + data=data.substr(64); if((_from.toLowerCase()==address_meterpoint.toLowerCase())||(_to.toLowerCase()==address_meterpoint.toLowerCase())) { var entry={}; entry.sender=_from; - entry.msg=_to; + entry.recipient=_to; + entry.msg=_msg; entry.base=_base; entry.value=_value; - entry.toSoll=_toSoll; - entry.toHaben=_toHaben; - entry.fromSoll=_fromSoll; - entry.fromHaben=_fromHaben; - entry.blockNumber=logs[i].blockNumber; + entry.data=data; + entry.blockNumber=logs[i].blockNumber; entries.push(entry); } } diff --git a/dist/loader.js b/dist/loader.js index <HASH>..<HASH> 100644 --- a/dist/loader.js +++ b/dist/loader.js @@ -3600,36 +3600,28 @@ this.transferable = function(obj_or_address) { entries=[]; for(var i=0;i<logs.length;i++) { var data = logs[i].data; - if(data.length>256) { + if(data.length==386) { data=data.substr(2); _from ="0x"+ split64(data).substr(26); data=data.substr(64); _to ="0x"+split64(data).substr(26); data=data.substr(64); + _msg ="0x"+split64(data).substr(26); + data=data.substr(64); _value =(split64(data)); data=data.substr(64); _base =(split64(data)); - data=data.substr(64); - _fromSoll =(split64(data)); - data=data.substr(64); - _fromHaben =(split64(data)); - data=data.substr(64); - _toSoll =(split64(data)); - data=data.substr(64); - _toHaben =(split64(data)); - data=data.substr(64); + data=data.substr(64); if((_from.toLowerCase()==address_meterpoint.toLowerCase())||(_to.toLowerCase()==address_meterpoint.toLowerCase())) { var entry={}; entry.sender=_from; - entry.msg=_to; + entry.recipient=_to; + entry.msg=_msg; entry.base=_base; entry.value=_value; - entry.toSoll=_toSoll; - entry.toHaben=_toHaben; - entry.fromSoll=_fromSoll; - entry.fromHaben=_fromHaben; - entry.blockNumber=logs[i].blockNumber; + entry.data=data; + entry.blockNumber=logs[i].blockNumber; entries.push(entry); } } diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stromdao-businessobject", - "version": "0.4.69", + "version": "0.4.71", "description": "Abstract BusinessObject for StromDAO Energy Blockchain. Abstraction layer between blockchain technology and business logic providing energy market related entities and use cases.", "main": "StromDAONode.js", "engines": {
Removed log outout from transferable class (JS)
energychain_StromDAO-BusinessObject
train
e2ab38d31f7a5ee50bb5d5e01fd6bfa4a3c5085f
diff --git a/spec/unit/provider/exec/posix_spec.rb b/spec/unit/provider/exec/posix_spec.rb index <HASH>..<HASH> 100755 --- a/spec/unit/provider/exec/posix_spec.rb +++ b/spec/unit/provider/exec/posix_spec.rb @@ -64,7 +64,7 @@ describe Puppet::Type.type(:exec).provider(:posix) do provider.resource[:path] = [File.dirname(command)] filename = File.basename(command) - Puppet::Util::Execution.expects(:execute).with { |cmdline, arguments| (cmdline == filename) && (arguments.is_a? Hash) }.returns(Puppet::Util::Execution::ProcessOutput.new('', 0)) + Puppet::Util::Execution.expects(:execute).with(filename, instance_of(Hash)).returns(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.run(filename) end @@ -95,7 +95,8 @@ describe Puppet::Type.type(:exec).provider(:posix) do provider.resource[:path] = ['/bogus/bin'] command = make_exe - Puppet::Util::Execution.expects(:execute).with { |cmdline, arguments| (cmdline == "#{command} bar --sillyarg=true --blah") && (arguments.is_a? Hash) }.returns(Puppet::Util::Execution::ProcessOutput.new('', 0)) + Puppet::Util::Execution.expects(:execute).with("#{command} bar --sillyarg=true --blah", instance_of(Hash)).returns(Puppet::Util::Execution::ProcessOutput.new('', 0)) + provider.run("#{command} bar --sillyarg=true --blah") end @@ -110,8 +111,10 @@ describe Puppet::Type.type(:exec).provider(:posix) do provider.resource[:environment] = ['WHATEVER=/something/else', 'WHATEVER=/foo'] command = make_exe - Puppet::Util::Execution.expects(:execute).with { |cmdline, arguments| (cmdline == command) && (arguments.is_a? Hash) }.returns(Puppet::Util::Execution::ProcessOutput.new('', 0)) + Puppet::Util::Execution.expects(:execute).with(command, instance_of(Hash)).returns(Puppet::Util::Execution::ProcessOutput.new('', 0)) + provider.run(command) + @logs.map {|l| "#{l.level}: #{l.message}" }.should == ["warning: Overriding environment setting 'WHATEVER' with '/foo'"] end @@ -202,10 +205,6 @@ describe Puppet::Type.type(:exec).provider(:posix) do output.strip.should == sentinel_value end end - - end - - end end
(maint) Use parameter matchers in tests This uses the mocha parameter matchers in the tests rather than a custom with() block. This is a little shorter and should provide better error messages when it fails.
puppetlabs_puppet
train
cb8b59509a23d3f48a71cc197679582abd097932
diff --git a/android/CouchbaseLite/src/androidTest/java/com/couchbase/lite/BlobTest.java b/android/CouchbaseLite/src/androidTest/java/com/couchbase/lite/BlobTest.java index <HASH>..<HASH> 100644 --- a/android/CouchbaseLite/src/androidTest/java/com/couchbase/lite/BlobTest.java +++ b/android/CouchbaseLite/src/androidTest/java/com/couchbase/lite/BlobTest.java @@ -19,10 +19,14 @@ package com.couchbase.lite; import com.couchbase.lite.utils.IOUtils; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; +import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.net.URL; import java.util.Arrays; import static org.junit.Assert.assertEquals; @@ -34,6 +38,9 @@ public class BlobTest extends BaseTest { final static String kBlobTestBlob1 = "i'm blob"; final static String kBlobTestBlob2 = "i'm blob2"; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Test public void testEquals() throws CouchbaseLiteException { @@ -186,5 +193,44 @@ public class BlobTest extends BaseTest { } + @Test + public void testBlobFromFileURL() throws Exception { + String contentType = "application/json"; + + Blob blob = null; + URL url = null; + + thrown.expect(IllegalArgumentException.class); + blob = new Blob(contentType, url); + + String assetName = "iTunesMusicLibrary.json"; + final File path = new File( + context.getFilesDir(), + "/assets/" + assetName + ); + + thrown.expect(IllegalArgumentException.class); + blob = new Blob(null, path.toURI().toURL()); + + byte[] bytes; + InputStream is = getAsset(assetName); + try { + bytes = IOUtils.toByteArray(is); + } finally { + is.close(); + } + + blob = new Blob(contentType, path.toURI().toURL()); + assertEquals(blob.getContent(), bytes); + assertEquals(blob.getContent().hashCode(), bytes.hashCode()); + assertEquals(blob.getContentStream().read(), bytes[0]); + byte[] bytesReadFromBlob = new byte[bytes.length]; + blob.getContentStream().read(bytesReadFromBlob, 0, bytes.length); + assertEquals(bytesReadFromBlob, bytes); + + InputStream iStream = blob.getContentStream(); + iStream.skip(2); + assertEquals(iStream.read(), bytes[2]); + } } \ No newline at end of file
test: add blob from file check (#<I>) * check blob from file * check blob read(), read(toDifferentByteArray), skip() methods
couchbase_couchbase-lite-android
train
e49f9ba3cedc6015c411fb78ae11838c011334ef
diff --git a/src/Enhavo/Bundle/MediaBundle/EventListener/DoctrineSubscriber.php b/src/Enhavo/Bundle/MediaBundle/EventListener/DoctrineSubscriber.php index <HASH>..<HASH> 100644 --- a/src/Enhavo/Bundle/MediaBundle/EventListener/DoctrineSubscriber.php +++ b/src/Enhavo/Bundle/MediaBundle/EventListener/DoctrineSubscriber.php @@ -77,7 +77,7 @@ class DoctrineSubscriber implements EventSubscriber $this->storage->deleteFile($object); // Delete on files doesn't use a doctrine cascade to formats, but an SQL cascade instead. This means that formats will be deleted without triggering a doctrine event. // So to clean up files associated with formats, we must delete them in the doctrine event for the file instead of the format. - $this->formatManager->deleteFormats($object); + $this->formatManager->deleteFormats($object, false); } } -} \ No newline at end of file +} diff --git a/src/Enhavo/Bundle/MediaBundle/Media/FormatManager.php b/src/Enhavo/Bundle/MediaBundle/Media/FormatManager.php index <HASH>..<HASH> 100644 --- a/src/Enhavo/Bundle/MediaBundle/Media/FormatManager.php +++ b/src/Enhavo/Bundle/MediaBundle/Media/FormatManager.php @@ -219,13 +219,13 @@ class FormatManager $this->em->flush(); } - public function deleteFormats(FileInterface $file) + public function deleteFormats(FileInterface $file, bool $flush = true) { $formats = $this->formatRepository->findBy([ 'file' => $file ]); foreach($formats as $format) { - $this->deleteFormat($format); + $this->deleteFormat($format, $flush); } } @@ -236,10 +236,12 @@ class FormatManager $this->storage->saveFile($format); } - public function deleteFormat(FormatInterface $format) + public function deleteFormat(FormatInterface $format, bool $flush = true) { $this->em->remove($format); - $this->em->flush(); + if ($flush) { + $this->em->flush(); + } $this->storage->deleteFile($format); }
fix nesting exception on delete formats (#<I>) * fix nesting exception on delete formats while listening on doctrine pre remove * rename argument
enhavo_enhavo
train
4458bfa2d9c8c879bb7d100d1cc5d3fda759389e
diff --git a/squad/api/rest.py b/squad/api/rest.py index <HASH>..<HASH> 100644 --- a/squad/api/rest.py +++ b/squad/api/rest.py @@ -1259,10 +1259,7 @@ class TestJobViewSet(ModelViewSet): @action(detail=True, methods=['post'], suffix='cancel') def cancel(self, request, **kwargs): testjob = self.get_object() - if testjob.cancel(): - # this is faking job status as real status will only be updated - # after fetch operation is complete - return Response({'job_id': testjob.job_id, 'status': 'Canceled'}, status=status.HTTP_200_OK) + testjob.cancel() return Response({'job_id': testjob.job_id, 'status': testjob.job_status}, status=status.HTTP_200_OK) diff --git a/squad/ci/models.py b/squad/ci/models.py index <HASH>..<HASH> 100644 --- a/squad/ci/models.py +++ b/squad/ci/models.py @@ -257,6 +257,12 @@ class TestJob(models.Model): def cancel(self): if self.job_id is not None: return self.backend.get_implementation().cancel(self) + else: + self.fetched = True + self.submitted = True + self.job_status = "Canceled" + self.failure = "Cancelled before submission" + self.save() return self.fetched def __str__(self): diff --git a/test/api/test_rest.py b/test/api/test_rest.py index <HASH>..<HASH> 100644 --- a/test/api/test_rest.py +++ b/test/api/test_rest.py @@ -57,7 +57,7 @@ class RestApiTest(APITestCase): target=self.project, target_build=self.build2, environment='myenv', - testrun=self.testrun2 + testrun=self.testrun2, ) self.testjob3 = ci_models.TestJob.objects.create( definition="foo: bar", @@ -593,13 +593,13 @@ class RestApiTest(APITestCase): data = self.post('/api/testjobs/%d/cancel/' % self.testjob5.id, {}) self.assertEqual(data.status_code, 200) self.assertEqual(data.json()['job_id'], self.testjob5.job_id) - self.assertEqual(data.json()['status'], 'Canceled') + self.assertEqual(data.json()['status'], self.testjob5.job_status) def test_testjob_cancel_fail(self): data = self.post('/api/testjobs/%d/cancel/' % self.testjob2.id, {}) self.assertEqual(data.status_code, 200) self.assertEqual(data.json()['job_id'], self.testjob2.job_id) - self.assertEqual(data.json()['status'], self.testjob2.job_status) + self.assertEqual(data.json()['status'], 'Canceled') def test_backends(self): data = self.hit('/api/backends/') diff --git a/test/ci/test_models.py b/test/ci/test_models.py index <HASH>..<HASH> 100644 --- a/test/ci/test_models.py +++ b/test/ci/test_models.py @@ -504,6 +504,27 @@ class TestJobTest(TestCase): impl.cancel.assert_called() + @patch('squad.ci.models.Backend.get_implementation') + def test_cancel_not_submitted(self, get_implementation): + test_job = models.TestJob.objects.create( + target=self.project, + target_build=self.build, + environment='myenv', + backend=self.backend, + submitted=False + ) + impl = MagicMock() + impl.cancel = MagicMock(return_value=True) + get_implementation.return_value = impl + + test_job.cancel() + + impl.cancel.assert_not_called() + test_job.refresh_from_db() + self.assertTrue(test_job.fetched) + self.assertTrue(test_job.submitted) + self.assertIsNotNone(test_job.failure) + @patch('squad.ci.backend.null.Backend.resubmit', return_value="1") def test_records_resubmitted_count(self, backend_resubmit): testjob = models.TestJob.objects.create(
ci: improve TestJob.cancel() When test job is not yet submitted cancel() marks it as submitted and fetched and sets failure message.
Linaro_squad
train
934090cfe460eac721a9357caf8f780dd3f801c4
diff --git a/test/helper_pagify.rb b/test/helper_pagify.rb index <HASH>..<HASH> 100644 --- a/test/helper_pagify.rb +++ b/test/helper_pagify.rb @@ -1,5 +1,8 @@ class TestPagify < TestCase + def test_silent_unit_test_in_ruby18 + end + def self.data; @data ||= (0..100).to_a; end def for_pager pager # assume data.size is 101, data is [0,1,2,3...]
[test/helper_pagify.rb] silent unit test warning in ruby <I>, which is: there's no tests in TestPagify. so i'll give you an empty one.
godfat_pagify
train
ad1ad7123d8793bc5f12d65e497e887be3438bae
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -30,6 +30,9 @@ module.exports = function (list, callback) { } if (!len && !err) return callback(null, result); }; - fn(cb); + var _cb = (function (len, result, i) { + return cb; + })(len, result, i); + fn(_cb); }); }
pass proper scopes to the callback
madhums_lll
train
947fbb2fc770f9b3d922df5ce952710eb2c407bc
diff --git a/src/G4/Mcache/Driver/Couchbase/Couchbase2x.php b/src/G4/Mcache/Driver/Couchbase/Couchbase2x.php index <HASH>..<HASH> 100644 --- a/src/G4/Mcache/Driver/Couchbase/Couchbase2x.php +++ b/src/G4/Mcache/Driver/Couchbase/Couchbase2x.php @@ -55,15 +55,21 @@ class Couchbase2x implements CouchbaseInterface } catch (\CouchbaseException $exception) { $metaDoc = false; } - return $metaDoc instanceof \CouchbaseMetaDoc - ? $metaDoc->value - : false; + $value = false; + if ($metaDoc instanceof \CouchbaseMetaDoc) { + //Drasko: "In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued." + $unserializedValue = @unserialize($metaDoc->value); + $value = is_string($metaDoc->value) && $unserializedValue !== false + ? $unserializedValue + : $metaDoc->value; + } + return $value; } public function replace($key, $value, $expiration) { try { - $metaDoc = $this->clientFactory()->replace($key, $value, ['expiry' => $expiration]); + $metaDoc = $this->clientFactory()->replace($key, serialize($value), ['expiry' => $expiration]); } catch (\CouchbaseException $exception) { $metaDoc = false; } @@ -75,7 +81,7 @@ class Couchbase2x implements CouchbaseInterface public function set($key, $value, $expiration) { try { - $metaDoc = $this->clientFactory()->upsert($key, $value, ['expiry' => $expiration]); + $metaDoc = $this->clientFactory()->upsert($key, serialize($value), ['expiry' => $expiration]); } catch (\CouchbaseException $exception) { $metaDoc = false; } diff --git a/src/G4/Mcache/Mcache.php b/src/G4/Mcache/Mcache.php index <HASH>..<HASH> 100644 --- a/src/G4/Mcache/Mcache.php +++ b/src/G4/Mcache/Mcache.php @@ -160,12 +160,11 @@ class Mcache private function getValue() { - return serialize($this->value); + return $this->value; } private function transformValue($value) { - $unserializeValue = @unserialize($value); //Drasko: "In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued." - return is_string($value) && $unserializeValue !== false ? unserialize($value) : $value; + return $value; } } \ No newline at end of file
Moved serialize and unserialize only to couchbase2x driver because of the serialize/unserialize performance issues
g4code_mcache
train
c772ff7fe5853022906b85aafa08eb2fd8f5b6ed
diff --git a/src/Chief.php b/src/Chief.php index <HASH>..<HASH> 100644 --- a/src/Chief.php +++ b/src/Chief.php @@ -26,29 +26,23 @@ class Chief implements CommandBus } /** - * Map a command to a handler by name - * - * @param $commandName - * @param $handlerName - * @return mixed - */ - public function mapHandler($commandName, $handlerName) - { - // TODO: Implement mapHandler() method. - } - - /** * Map a command to a CommandHandler * * @param $commandName * @param CommandHandler $handler * @return mixed */ - public function pushHandler($commandName, CommandHandler $handler) + public function pushHandler($commandName, $handler) { $this->handlers[$commandName] = $handler; } + /** + * Find a pushed handler + * + * @param Command $command + * @return null + */ protected function findHandler(Command $command) { foreach ($this->handlers as $handlerCommand => $handler) { diff --git a/src/CommandBus.php b/src/CommandBus.php index <HASH>..<HASH> 100644 --- a/src/CommandBus.php +++ b/src/CommandBus.php @@ -13,20 +13,11 @@ interface CommandBus public function execute(Command $command); /** - * Map a command to a handler by name - * - * @param $commandName - * @param $handlerName - * @return mixed - */ - public function mapHandler($commandName, $handlerName); - - /** * Map a command to a callable handler * * @param $commandName - * @param CommandHandler $handler + * @param CommandHandler|callable|string $handler * @return mixed */ - public function pushHandler($commandName, CommandHandler $handler); + public function pushHandler($commandName, $handler); } \ No newline at end of file diff --git a/tests/ChiefTest.php b/tests/ChiefTest.php index <HASH>..<HASH> 100644 --- a/tests/ChiefTest.php +++ b/tests/ChiefTest.php @@ -20,7 +20,7 @@ class ChiefTest extends ChiefTestCase public function testExecuteFiresHandlerAttachedByMapHandler() { - // @todo + } }
Removed CommandBus::mapHandler() method in favor of routing pushing of all handlers through pushHandler()
adamnicholson_Chief
train
2ad6419716c13e67eb48006def66f977d39f96b0
diff --git a/apiserver/watcher.go b/apiserver/watcher.go index <HASH>..<HASH> 100644 --- a/apiserver/watcher.go +++ b/apiserver/watcher.go @@ -11,6 +11,7 @@ import ( "github.com/juju/juju/apiserver/common" "github.com/juju/juju/apiserver/common/storagecommon" "github.com/juju/juju/apiserver/params" + "github.com/juju/juju/core/migration" "github.com/juju/juju/network" "github.com/juju/juju/state" ) @@ -500,7 +501,11 @@ func (w *srvMigrationStatusWatcher) Next() (params.MigrationStatus, error) { } mig, err := w.st.GetModelMigration() - if err != nil { + if errors.IsNotFound(err) { + return params.MigrationStatus{ + Phase: migration.NONE, + }, nil + } else if err != nil { return empty, errors.Annotate(err, "migration lookup") } diff --git a/apiserver/watcher_test.go b/apiserver/watcher_test.go index <HASH>..<HASH> 100644 --- a/apiserver/watcher_test.go +++ b/apiserver/watcher_test.go @@ -4,6 +4,7 @@ package apiserver_test import ( + "github.com/juju/errors" "github.com/juju/names" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" @@ -131,6 +132,22 @@ func (s *watcherSuite) TestMigrationStatusWatcher(c *gc.C) { }) } +func (s *watcherSuite) TestMigrationStatusWatcherNoMigration(c *gc.C) { + w := apiservertesting.NewFakeNotifyWatcher() + id := s.resources.Register(w) + s.authorizer.Tag = names.NewMachineTag("12") + apiserver.PatchGetMigrationBackend(s, &fakeMigrationBackend{noMigration: true}) + + w.C <- struct{}{} + facade := s.getFacade(c, "MigrationStatusWatcher", 1, id).(migrationStatusWatcher) + defer c.Check(facade.Stop(), jc.ErrorIsNil) + result, err := facade.Next() + c.Assert(err, jc.ErrorIsNil) + c.Assert(result, jc.DeepEquals, params.MigrationStatus{ + Phase: migration.NONE, + }) +} + func (s *watcherSuite) TestMigrationStatusWatcherNotAgent(c *gc.C) { id := s.resources.Register(apiservertesting.NewFakeNotifyWatcher()) s.authorizer.Tag = names.NewUserTag("frogdog") @@ -154,9 +171,14 @@ func (w *fakeStringsWatcher) Changes() <-chan []string { return w.ch } -type fakeMigrationBackend struct{} +type fakeMigrationBackend struct { + noMigration bool +} func (b *fakeMigrationBackend) GetModelMigration() (state.ModelMigration, error) { + if b.noMigration { + return nil, errors.NotFoundf("migration") + } return new(fakeModelMigration), nil }
apiserver: migration status watcher now uses NONE phase when no migration This is to handle the case of the initial watcher event when there's never been a migration attempt for the model.
juju_juju
train
32b7338bdf731e784b33a2357d2d6439cc563c98
diff --git a/modules/custom/social_magic_login/src/Controller/MagicLoginController.php b/modules/custom/social_magic_login/src/Controller/MagicLoginController.php index <HASH>..<HASH> 100644 --- a/modules/custom/social_magic_login/src/Controller/MagicLoginController.php +++ b/modules/custom/social_magic_login/src/Controller/MagicLoginController.php @@ -118,8 +118,8 @@ class MagicLoginController extends ControllerBase { // When the user hasn't set a password, redirect the user to // the set passwords page. if (NULL === $user->getPassword()) { - $message_set_password = $this->t('You need to set your passwords in order to log in.'); - if ($this->dataPolicyConsensus() === FALSE) { + $message_set_password = $this->t('You need to set your password in order to log in.'); + if ($this->dataPolicyConsensus() === TRUE) { // Set a different text when the user still needs to comply to // the data policy. $message_set_password = $this->t('Before you can log in and set your password, you need to agree to the data policy.');
#<I> - Fixed minor issues.
goalgorilla_open_social
train
978dfb9216b088d92bb8db14b6ddb409cc7c7f76
diff --git a/js/bootstrap-alerts.js b/js/bootstrap-alerts.js index <HASH>..<HASH> 100644 --- a/js/bootstrap-alerts.js +++ b/js/bootstrap-alerts.js @@ -94,9 +94,11 @@ return this.each(function () { var $this = $(this) + , data if ( typeof options == 'string' ) { - var data = $this.data('alert') + + data = $this.data('alert') if (typeof data == 'object') { return data[options].call( $this )
clean up var defintion
twbs_bootstrap
train
29584e3c5161073e25898f18f65dab1db5f8f28b
diff --git a/dbt/config.py b/dbt/config.py index <HASH>..<HASH> 100644 --- a/dbt/config.py +++ b/dbt/config.py @@ -99,7 +99,7 @@ class ConfigRenderer(object): self.context['var'] = Var(None, self.context, cli_vars) @staticmethod - def _is_hook_path(keypath): + def _is_hook_or_model_vars_path(keypath): if not keypath: return False @@ -107,10 +107,14 @@ class ConfigRenderer(object): # run hooks if first in {'on-run-start', 'on-run-end'}: return True - # model hooks + # models have two things to avoid if first in {'seeds', 'models'}: + # model-level hooks if 'pre-hook' in keypath or 'post-hook' in keypath: return True + # model-level 'vars' declarations + if 'vars' in keypath: + return True return False @@ -126,8 +130,9 @@ class ConfigRenderer(object): :param key str: The key to convert on. :return Any: The rendered entry. """ - # hooks should be treated as raw sql, they'll get rendered later - if self._is_hook_path(keypath): + # hooks should be treated as raw sql, they'll get rendered later. + # Same goes for 'vars' declarations inside 'models'/'seeds'. + if self._is_hook_or_model_vars_path(keypath): return value return self.render_value(value)
Fix a bug where vars were rendered under models/seeds in the config
fishtown-analytics_dbt
train
566b4e7b3dc6097bfcf62c7192a1584ebfe00a97
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -27,6 +27,9 @@ module.exports = function(schema, options) { options.usernameQueryFields = [options.usernameField]; } + // option to find username case insensitively + options.usernameCaseInsensitive = Boolean(options.usernameCaseInsensitive || false); + // option to convert username to lowercase when finding options.usernameLowerCase = options.usernameLowerCase || false; @@ -50,20 +53,20 @@ module.exports = function(schema, options) { options.errorMessages.NoSaltValueStoredError = options.errorMessages.NoSaltValueStoredError || 'Authentication not possible. No salt value stored'; options.errorMessages.IncorrectPasswordError = options.errorMessages.IncorrectPasswordError || 'Password or username is incorrect'; options.errorMessages.IncorrectUsernameError = options.errorMessages.IncorrectUsernameError || 'Password or username is incorrect'; - options.errorMessages.MissingUsernameError = options.errorMessages.MissingUsernameError|| 'No username was given'; - options.errorMessages.UserExistsError = options.errorMessages.UserExistsError|| 'A user with the given username is already registered'; + options.errorMessages.MissingUsernameError = options.errorMessages.MissingUsernameError || 'No username was given'; + options.errorMessages.UserExistsError = options.errorMessages.UserExistsError || 'A user with the given username is already registered'; const schemaFields = {}; if (!schema.path(options.usernameField)) { - schemaFields[options.usernameField] = {type: String, unique: options.usernameUnique}; + schemaFields[options.usernameField] = { type: String, unique: options.usernameUnique }; } - schemaFields[options.hashField] = {type: String, select: false}; - schemaFields[options.saltField] = {type: String, select: false}; + schemaFields[options.hashField] = { type: String, select: false }; + schemaFields[options.saltField] = { type: String, select: false }; if (options.limitAttempts) { - schemaFields[options.attemptsField] = {type: Number, default: 0}; - schemaFields[options.lastLoginField] = {type: Date, default: Date.now}; + schemaFields[options.attemptsField] = { type: Number, default: 0 }; + schemaFields[options.lastLoginField] = { type: Date, default: Date.now }; } schema.add(schemaFields); @@ -223,7 +226,7 @@ module.exports = function(schema, options) { const queryOrParameters = []; for (let i = 0; i < options.usernameQueryFields.length; i++) { const parameter = {}; - parameter[options.usernameQueryFields[i]] = username; + parameter[options.usernameQueryFields[i]] = options.usernameCaseInsensitive ? new RegExp(`^${username}$`, `i`) : username; queryOrParameters.push(parameter); }
add option usernameCaseInsensitive Add an option to find username case insensitively
saintedlama_passport-local-mongoose
train
08e98283d42a96f3a6cc9d9ca46e1770f66eea02
diff --git a/otree_redwood/abstract_views.py b/otree_redwood/abstract_views.py index <HASH>..<HASH> 100644 --- a/otree_redwood/abstract_views.py +++ b/otree_redwood/abstract_views.py @@ -144,6 +144,12 @@ class ContinuousDecisionPage(Page): end_decision.save() +output_functions = [] +def output_table(f): + output_functions.append(lambda: f(Event.objects.all())) + return output_functions[-1] + + _timers = {} class DiscreteEventEmitter(): diff --git a/otree_redwood/views.py b/otree_redwood/views.py index <HASH>..<HASH> 100644 --- a/otree_redwood/views.py +++ b/otree_redwood/views.py @@ -10,6 +10,7 @@ from django.core import serializers from otree_redwood import consumers, stats from otree_redwood.models import Event +from otree_redwood.abstract_views import output_functions class ExportEvents(vanilla.View): @@ -20,6 +21,11 @@ class ExportEvents(vanilla.View): def get(request, *args, **kwargs): + for f in output_functions: + f() + + return HttpResponse(content_type='text/html') + response = HttpResponse(content_type='application/json') response['Content-Disposition'] = 'attachment; filename="{}"'.format( 'Events (accessed {}).json'.format(
Added preliminary interface for data output functions.
Leeps-Lab_otree-redwood
train
7c8556e38b935e8ed18d9462ece6a842acc8e632
diff --git a/client/src/main/java/com/paypal/selion/reports/reporter/runtimereport/RuntimeReporterListener.java b/client/src/main/java/com/paypal/selion/reports/reporter/runtimereport/RuntimeReporterListener.java index <HASH>..<HASH> 100644 --- a/client/src/main/java/com/paypal/selion/reports/reporter/runtimereport/RuntimeReporterListener.java +++ b/client/src/main/java/com/paypal/selion/reports/reporter/runtimereport/RuntimeReporterListener.java @@ -44,11 +44,7 @@ public class RuntimeReporterListener implements IResultListener2, ISuiteListener */ public static final String ENABLE_RUNTIME_REPORTER_LISTENER = "enable.runtime.reporter.listener"; - private static volatile boolean bInitConfig = false; - - static void markConfigAsInitialized() { - bInitConfig = true; - } + boolean bInitConfig = false; private static SimpleLogger logger = SeLionLogger.getLogger(); @@ -261,7 +257,7 @@ public class RuntimeReporterListener implements IResultListener2, ISuiteListener } if (!bInitConfig) { - markConfigAsInitialized(); + bInitConfig = true; File outFile = new File(suite.getOutputDirectory()); outputDirectory = outFile.getParent() + File.separator + "RuntimeReporter"; logger.info("Runtime Report : " + outputDirectory + File.separator + "index.html");
Code changes to fix FileNotFoundException when reexecuting TestNG failed test cases
paypal_SeLion
train
2a97ac651b2870ba53cd76e4d2f11294f54dd71f
diff --git a/src/openaccess_epub/opf/opf.py b/src/openaccess_epub/opf/opf.py index <HASH>..<HASH> 100644 --- a/src/openaccess_epub/opf/opf.py +++ b/src/openaccess_epub/opf/opf.py @@ -80,10 +80,10 @@ class OPF(object): instance with the title argument, or calling set_title() at any time before writing will give it a title. """ - #Set internal variables to defaults - self.reset_state() #Set Collection Mode by argument self.collection_mode = collection_mode + #Set internal variables to defaults + self.reset_state() #Set location by argument self.location = location #Create the basic document
fixing error caused by reordering of resets
SavinaRoja_OpenAccess_EPUB
train
5ccc6d2727145a36c06e502758c5957d96491b3b
diff --git a/pkg/controller/deployment/deployment_controller_test.go b/pkg/controller/deployment/deployment_controller_test.go index <HASH>..<HASH> 100644 --- a/pkg/controller/deployment/deployment_controller_test.go +++ b/pkg/controller/deployment/deployment_controller_test.go @@ -497,16 +497,13 @@ func TestPodDeletionEnqueuesRecreateDeployment(t *testing.T) { f.rsLister = append(f.rsLister, rs) f.objects = append(f.objects, foo, rs) - c, informers := f.newController() + c, _ := f.newController() enqueued := false c.enqueueDeployment = func(d *extensions.Deployment) { if d.Name == "foo" { enqueued = true } } - stopCh := make(chan struct{}) - defer close(stopCh) - informers.Start(stopCh) c.deletePod(pod) @@ -532,16 +529,13 @@ func TestPodDeletionDoesntEnqueueRecreateDeployment(t *testing.T) { // return a non-empty list. f.podLister = append(f.podLister, pod) - c, informers := f.newController() + c, _ := f.newController() enqueued := false c.enqueueDeployment = func(d *extensions.Deployment) { if d.Name == "foo" { enqueued = true } } - stopCh := make(chan struct{}) - defer close(stopCh) - informers.Start(stopCh) c.deletePod(pod)
controller: don't run informers in unit tests when unnecessary
kubernetes_kubernetes
train
49ae2e39d8a4dd3fad7a08a1c5f8d0e4d4599e4b
diff --git a/cassandra/cqlengine/query.py b/cassandra/cqlengine/query.py index <HASH>..<HASH> 100644 --- a/cassandra/cqlengine/query.py +++ b/cassandra/cqlengine/query.py @@ -550,25 +550,13 @@ class AbstractQuerySet(object): clone._transaction.append(operator) for col_name, val in kwargs.items(): + if isinstance(val, Token): + raise QueryException("Token() values are not valid in conditionals") + try: column = self.model._get_column(col_name) except KeyError: - if col_name == 'pk__token': - if not isinstance(val, Token): - raise QueryException("Virtual column 'pk__token' may only be compared to Token() values") - column = columns._PartitionKeysToken(self.model) - else: - raise QueryException("Can't resolve column name: '{0}'".format(col_name)) - - if isinstance(val, Token): - if col_name != 'pk__token': - raise QueryException("Token() values may only be compared to the 'pk__token' virtual column") - partition_columns = column.partition_columns - if len(partition_columns) != len(val.value): - raise QueryException( - 'Token() received {0} arguments but model has {1} partition keys'.format( - len(val.value), len(partition_columns))) - val.set_columns(partition_columns) + raise QueryException("Can't resolve column name: '{0}'".format(col_name)) if isinstance(val, BaseQueryFunction): query_val = val
cqle: don't mess with Token values in iff conditional
datastax_python-driver
train
873c97440168eddce1f56141eacf5b04f8925f8e
diff --git a/tests/Database/QueryBuilder/LimitClauseTest.php b/tests/Database/QueryBuilder/LimitClauseTest.php index <HASH>..<HASH> 100644 --- a/tests/Database/QueryBuilder/LimitClauseTest.php +++ b/tests/Database/QueryBuilder/LimitClauseTest.php @@ -1,10 +1,6 @@ <?php namespace Zephyrus\Tests\Database\QueryBuilder; use PHPUnit\Framework\TestCase; -use Zephyrus\Database\Core\Adapters\Mysql\MysqlAdapter; -use Zephyrus\Database\Core\Adapters\Postgresql\PostgresAdapter; -use Zephyrus\Database\Core\Adapters\Sqlite\SqliteAdapter; -use Zephyrus\Database\Core\DatabaseConfiguration; use Zephyrus\Database\QueryBuilder\LimitClause; class LimitClauseTest extends TestCase @@ -12,24 +8,12 @@ class LimitClauseTest extends TestCase public function testLimit() { $limit = new LimitClause(50); - self::assertEquals("LIMIT 50", $limit->getSql(new SqliteAdapter(new DatabaseConfiguration()))); + self::assertEquals("LIMIT 50", $limit->getSql()); } - public function testLimitWithOffsetSqlite() + public function testLimitWithOffset() { $limit = new LimitClause(50, 10); - self::assertEquals("LIMIT 10, 50", $limit->getSql(new SqliteAdapter(new DatabaseConfiguration()))); - } - - public function testLimitWithOffsetMysql() - { - $limit = new LimitClause(50, 10); - self::assertEquals("LIMIT 10, 50", $limit->getSql(new MysqlAdapter(new DatabaseConfiguration()))); - } - - public function testLimitWithOffsetPostgres() - { - $limit = new LimitClause(50, 10); - self::assertEquals("LIMIT 50 OFFSET 10", $limit->getSql(new PostgresAdapter(new DatabaseConfiguration()))); + self::assertEquals("LIMIT 50 OFFSET 10", $limit->getSql()); } }
test: adapt LimitClause tests
dadajuice_zephyrus
train
ead8f6c11cea5af6eca3448a6bdacc77231b5f27
diff --git a/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/BitcoindeAdapters.java b/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/BitcoindeAdapters.java index <HASH>..<HASH> 100644 --- a/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/BitcoindeAdapters.java +++ b/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/BitcoindeAdapters.java @@ -46,7 +46,7 @@ public final class BitcoindeAdapters { List<LimitOrder> asks = createOrders(currencyPair, Order.OrderType.ASK, bitcoindeOrderBook.getAsks()); List<LimitOrder> bids = createOrders(currencyPair, Order.OrderType.BID, bitcoindeOrderBook.getBids()); - return new OrderBook(null, asks, bids); + return new OrderBook(bitcoindeOrderBook.getTimeStamp(), asks, bids); } /** diff --git a/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/dto/marketdata/BitcoindeOrderBook.java b/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/dto/marketdata/BitcoindeOrderBook.java index <HASH>..<HASH> 100644 --- a/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/dto/marketdata/BitcoindeOrderBook.java +++ b/xchange-bitcoinde/src/main/java/com/xeiam/xchange/bitcoinde/dto/marketdata/BitcoindeOrderBook.java @@ -3,6 +3,7 @@ package com.xeiam.xchange.bitcoinde.dto.marketdata; import java.math.BigDecimal; import java.util.Arrays; import java.util.Comparator; +import java.util.Date; import com.fasterxml.jackson.annotation.JsonProperty; @@ -13,6 +14,7 @@ public class BitcoindeOrderBook { private final BigDecimal[][] asks; private final BigDecimal[][] bids; + private final Date timeStamp = null; /** * Constructor. @@ -57,6 +59,10 @@ public class BitcoindeOrderBook { return bids; } + + public Date getTimeStamp() { + return this.timeStamp; + } @Override public String toString() {
fixed hardcoded null OrderBook timestamp value so that timestamp only has to be added to BitcoindeOrderBook class
knowm_XChange
train
09b10b10e76a7fba7297fa22ea496cdc9efd3dae
diff --git a/src/Provide/Transfer/CliResponder.php b/src/Provide/Transfer/CliResponder.php index <HASH>..<HASH> 100644 --- a/src/Provide/Transfer/CliResponder.php +++ b/src/Provide/Transfer/CliResponder.php @@ -18,7 +18,7 @@ class CliResponder implements TransferInterface public function __invoke(ResourceObject $resourceObject, array $server) { unset($server); - $body = (string) $resourceObject; + $body = $resourceObject->toString(); // code $statusText = (new Code)->statusText[$resourceObject->code]; $ob = $resourceObject->code . ' ' . $statusText . PHP_EOL; @@ -28,7 +28,6 @@ class CliResponder implements TransferInterface } // empty line $ob .= PHP_EOL; - // body $ob .= $body;
replace __string() to toString() for expection thrown
bearsunday_BEAR.Package
train
a85002e0ee88ce0e9c7c46ed655c8730354d5a14
diff --git a/Lib/pyhsm/basic_cmd.py b/Lib/pyhsm/basic_cmd.py index <HASH>..<HASH> 100644 --- a/Lib/pyhsm/basic_cmd.py +++ b/Lib/pyhsm/basic_cmd.py @@ -146,7 +146,7 @@ class YHSM_Cmd_Temp_Key_Load(YHSM_Cmd): status = None def __init__(self, stick, nonce, key_handle, aead): - self.nonce = pyhsm.util.input_validate_nonce(nonce) + self.nonce = pyhsm.util.input_validate_nonce(nonce, pad = True) self.key_handle = pyhsm.util.input_validate_key_handle(key_handle) aead = pyhsm.util.input_validate_aead(aead) # typedef struct { @@ -215,7 +215,8 @@ class YHSM_NonceResponse(): # The power-up count can be deduced from the nonce =) self.volatile = struct.unpack("<L", nonce[0:4])[0] self.pu_count = struct.unpack("<H", nonce[4:6])[0] - self.nonce = (self.pu_count << 32) + self.volatile + self.nonce_int = (self.pu_count << 32) + self.volatile + self.nonce = nonce def __repr__(self): return '<%s instance at %s: nonce=%i, pu_count=%i, volatile=%i>' % (
Remember nonce as 6 byte string too, for convenience.
Yubico_python-pyhsm
train
6a9fd8772f72e569693f6e4750bbec37ea3120ef
diff --git a/dark/reads.py b/dark/reads.py index <HASH>..<HASH> 100644 --- a/dark/reads.py +++ b/dark/reads.py @@ -3,6 +3,7 @@ from collections import Counter from Bio.Seq import translate from Bio.Data.IUPACData import ( ambiguous_dna_complement, ambiguous_rna_complement) +from warnings import warn from dark.filter import TitleFilter from dark.aa import PROPERTIES, PROPERTY_DETAILS, NONE @@ -133,6 +134,27 @@ class Read(object): readOffset += 1 subjectOffset += 1 + def nucleotideOrAa(self): + """ + A function which checks whether it is a nucleotide or amino acid read. + Note that if an amino acid read consists of only A, T, G, C, amino + acids, it will still be classified as a nucleotide read. In this case, + a warning will be issued. + + @param read: A C{dark.Read} object. + @return: C{True} if the read is AA or C{False} if the read is + nucleotide. + """ + ntLetters = {'A', 'T', 'G', 'C'} + readLetters = set(self.sequence.upper()) + subset = readLetters.issubset(ntLetters) + if subset: + warn('This is considered as a nucleotide read. Note that it might ' + 'still be an amino acid read which only contains the letters ' + '"A", "T", "G", "C".', RuntimeWarning) + return False + return True + class _NucleotideRead(Read): """ diff --git a/test/test_reads.py b/test/test_reads.py index <HASH>..<HASH> 100644 --- a/test/test_reads.py +++ b/test/test_reads.py @@ -2,6 +2,7 @@ from unittest import TestCase from mock import patch, call from cStringIO import StringIO from os import stat +import warnings from mocking import mockOpen from dark.reads import ( @@ -263,6 +264,37 @@ class TestRead(TestCase): (13, 'T', False)], list(read.walkHSP(hsp))) + def testAAReadReturnTrue(self): + """ + If an AA read is passed in, the function must return True. + """ + read = AARead('id', 'ARSTGATGC') + self.assertEqual(True, read.nucleotideOrAa()) + + def testNucleotideReadSomeNtReturnFalse(self): + """ + If a nucleotide read is passed in that contains A, T, the + function must return False. + """ + read = AARead('id', 'AAATCTT') + self.assertEqual(False, read.nucleotideOrAa()) + + def testNucleotideReadIssueWarning(self): + """ + If a nucleotide read is passed in, a warning must be issued. + """ + read = AARead('id', 'AATTGGCC') + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + result = read.nucleotideOrAa() + self.assertEqual(1, len(w)) + self.assertEqual(w[0].category, RuntimeWarning) + error = ('This is considered as a nucleotide read. Note that it ' + 'might still be an amino acid read which only contains ' + 'the letters "A", "T", "G", "C".') + self.assertIn(error, str(w[0].message)) + self.assertEqual(False, result) + class TestDNARead(TestCase): """ diff --git a/test/test_sequence.py b/test/test_sequence.py index <HASH>..<HASH> 100644 --- a/test/test_sequence.py +++ b/test/test_sequence.py @@ -1,5 +1,5 @@ from unittest import TestCase -from dark.sequence import findPrimer, findPrimerBidi, findPrimerBidiLimits +from dark.sequence import (findPrimer, findPrimerBidi, findPrimerBidiLimits) from Bio.Seq import Seq from Bio.Alphabet import IUPAC
Added function to test whether a read is aa or nt.
acorg_dark-matter
train
12314626af40878b101adb82ff5c094adae143e6
diff --git a/code/libraries/koowa/components/com_activities/databases/rows/activity.php b/code/libraries/koowa/components/com_activities/databases/rows/activity.php index <HASH>..<HASH> 100644 --- a/code/libraries/koowa/components/com_activities/databases/rows/activity.php +++ b/code/libraries/koowa/components/com_activities/databases/rows/activity.php @@ -108,15 +108,34 @@ class ComActivitiesDatabaseRowActivity extends KDatabaseRowDefault implements Co /** * Strategy getter. * - * @return ComActivitiesDatabaseRowActivityStrategyInterface The row strategy. + * @param mixed An optional object that implements KObjectInterface, KObjectIdentifier object + * or valid identifier string + * + * @return ComActivitiesDatabaseRowActivityStrategyInterface|null The row strategy, null if the current + * row object is new or modified. */ - public function getStrategy() + public function getStrategy($identifier = null) { - $strategy = clone $this->getIdentifier(); - $strategy->path = array('database', 'row', 'activity', 'strategy'); - $strategy->name = $this->isNew() ? 'new' : $this->package; + $strategy = null; + + if (!$this->isNew() && !$this->getModified()) + { + if (is_null($identifier)) + { + $identifier = clone $this->getIdentifier(); + $identifier->path = array('database', 'row', 'activity', 'strategy'); + $identifier->name = $this->package; + } + + if (!$identifier instanceof KObjectIdentifier) + { + $identifier = $this->getIdentifier($identifier); + } + + $strategy = $this->getObject($identifier, array('row' => $this)); + } - return $this->getObject($strategy, array('row' => $this)); + return $strategy; } /**
re #<I> Improved strategy getter. The strategy now returns null if the activity object isn't new or is modified. It also now accepts an argument which may hold an identifier for forcing a given strategy. This may be useful when overriding.
joomlatools_joomlatools-framework-activities
train
f61650d4b38a665e25417dbf7899f90b85d2793c
diff --git a/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb b/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb index <HASH>..<HASH> 100644 --- a/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb +++ b/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb @@ -143,7 +143,6 @@ module MerchCalendar return date.year + 1 end end - ### IMPORTANT ADD MORE GOOD TESTS FOR THIS METHOD ^^^^^^ # Converts a merch month to the correct julian month # @@ -184,7 +183,7 @@ module MerchCalendar merch_months_combos = merch_month_combo_from_dates(start_date, end_date) merch_months_combos.map { | merch_month_combo | start_of_month(merch_month_combo[0], merch_month_combo[1]) } end - + # Returns an array of Merch Weeks that pertains to the Julian Month of a Fiscal Year # # @param year [Fixnum] the fiscal year @@ -209,17 +208,18 @@ module MerchCalendar }) end end + ### IMPORTANT ADD MORE GOOD TESTS FOR THIS METHOD ^^^^^^ private def merch_month_combo_from_dates(start_date, end_date) merch_months = [] - first_of_start = Date.new(start_date.year, start_date.month, 14) - first_of_end = Date.new(end_date.year, end_date.month, 14) - date = first_of_start + middle_of_start_month = Date.new(start_date.year, start_date.month, 14) + middle_of_end_month = Date.new(end_date.year, end_date.month, 14) + date = middle_of_start_month - while date <= first_of_end do + while date <= middle_of_end_month do merch_months.push(date_conversion(date)) date = date >> 1 end @@ -227,9 +227,9 @@ module MerchCalendar end # This isn't a true date conversion, only used for merch_month_combo_from_dates - # It wouldn't give you a true date coversion for dates that its julian month actually falls in the wrong merch year + # when its julian month actually falls in the wrong merch year # EX: The true date_conversion of July 1, 2018 => [ 2019, 1 ] - # BUT this method here will return [2018, 12] because July is merch_month 12 for fiscal year + # BUT this method here will return [2019, 12] because July is merch_month 12 for fiscal year def date_conversion(date) [ merch_year_from_date(date), julian_to_merch(date.month) ] end diff --git a/spec/merch_calendar/stitch_fix_fiscal_year_calendar_spec.rb b/spec/merch_calendar/stitch_fix_fiscal_year_calendar_spec.rb index <HASH>..<HASH> 100644 --- a/spec/merch_calendar/stitch_fix_fiscal_year_calendar_spec.rb +++ b/spec/merch_calendar/stitch_fix_fiscal_year_calendar_spec.rb @@ -215,6 +215,20 @@ RSpec.describe MerchCalendar::StitchFixFiscalYearCalendar do end end + describe "#merch_year_from_date" do + it "converts julian dates to its fiscal year" do + expect(subject.merch_year_from_date(Date.new(2018, 7, 24))).to eq 2018 + expect(subject.merch_year_from_date(Date.new(2018, 7, 29))).to eq 2019 + expect(subject.merch_year_from_date(Date.new(2018, 8, 1))).to eq 2019 + expect(subject.merch_year_from_date(Date.new(2019, 8, 1))).to eq 2019 + expect(subject.merch_year_from_date(Date.new(2019, 8, 4))).to eq 2020 + expect(subject.merch_year_from_date(Date.new(2024, 2, 3))).to eq 2024 + expect(subject.merch_year_from_date(Date.new(2024, 7, 30))).to eq 2024 + expect(subject.merch_year_from_date(Date.new(2024, 8, 4))).to eq 2025 + end + end + + describe "#merch_months_in" do it "returns merch date for start_date if start_date is the same as end_date" do start_date = Date.new(2020,8,2) @@ -292,28 +306,4 @@ RSpec.describe MerchCalendar::StitchFixFiscalYearCalendar do expect { subject.merch_to_julian(0) }.to raise_error ArgumentError end end - - describe "fiscal_year_from_date" do - it "converts julian dates to its fiscal year" do - expect(subject.merch_year_from_date(Date.new(2018, 8, 1))).to eq 2019 - expect(subject.merch_year_from_date(Date.new(2018, 7, 1))).to eq 2018 - end - end - - describe "#date_conversion" do - let(:date) { Date.new(2018,7,24) } - let(:date_one) { Date.new(2018,7,1) } - let(:date_two) { Date.new(2018,8,1) } - let(:date_three) { Date.new(2019,8,1) } - let(:date_four) { Date.new(2019,8,4) } - it "returns the correct fiscal year and merch month combination" do - expect(subject.date_conversion(date)).to eq [2018,12] - expect(subject.date_conversion(date_one)).to eq [2019,1] - expect(subject.date_conversion(date_two)).to eq [2019,1] - expect(subject.date_conversion(date_three)).to eq [2019,12] - expect(subject.date_conversion(date_four)).to eq [2020,4] - end - end - - end
added more tests to the merch_year_from_date method looking solid :)
stitchfix_merch_calendar
train
d43af0d51533a28e5fb089074cffed1fa1d6cab0
diff --git a/app/lib/staypuft/seeder.rb b/app/lib/staypuft/seeder.rb index <HASH>..<HASH> 100644 --- a/app/lib/staypuft/seeder.rb +++ b/app/lib/staypuft/seeder.rb @@ -323,7 +323,7 @@ module Staypuft 'mysql_host' => mysql_host, 'swift_shared_secret' => swift_shared_secret, 'swift_ringserver_ip' => '', - 'swift_storage_ips' => [], + 'swift_storage_ips' => '<%= @host.deployment.ips.controller_ips %>', 'cinder_nfs_shares' => [], 'cinder_gluster_shares' => [], 'controller_admin_host' => controller_host, @@ -386,7 +386,7 @@ module Staypuft 'mysql_host' => mysql_host, 'swift_shared_secret' => swift_shared_secret, 'swift_ringserver_ip' => '', - 'swift_storage_ips' => [], + 'swift_storage_ips' => '<%= @host.deployment.ips.controller_ips %>', 'cinder_nfs_shares' => [], 'cinder_gluster_shares' => [], 'controller_admin_host' => controller_host,
Add at least some fake IPs to swift_storage_ips param
theforeman_staypuft
train
be7251f185513a26167d2abb6fc131ee9feb0376
diff --git a/builder/proxmox/config.go b/builder/proxmox/config.go index <HASH>..<HASH> 100644 --- a/builder/proxmox/config.go +++ b/builder/proxmox/config.go @@ -53,6 +53,7 @@ type Config struct { Agent bool `mapstructure:"qemu_agent"` SCSIController string `mapstructure:"scsi_controller"` Onboot bool `mapstructure:"onboot"` + DisableKVM bool `mapstructure:"disable_kvm"` TemplateName string `mapstructure:"template_name"` TemplateDescription string `mapstructure:"template_description"` diff --git a/builder/proxmox/config.hcl2spec.go b/builder/proxmox/config.hcl2spec.go index <HASH>..<HASH> 100644 --- a/builder/proxmox/config.hcl2spec.go +++ b/builder/proxmox/config.hcl2spec.go @@ -96,6 +96,7 @@ type FlatConfig struct { Agent *bool `mapstructure:"qemu_agent" cty:"qemu_agent" hcl:"qemu_agent"` SCSIController *string `mapstructure:"scsi_controller" cty:"scsi_controller" hcl:"scsi_controller"` Onboot *bool `mapstructure:"onboot" cty:"onboot" hcl:"onboot"` + DisableKVM *bool `mapstructure:"disable_kvm" cty:"disable_kvm" hcl:"disable_kvm"` TemplateName *string `mapstructure:"template_name" cty:"template_name" hcl:"template_name"` TemplateDescription *string `mapstructure:"template_description" cty:"template_description" hcl:"template_description"` UnmountISO *bool `mapstructure:"unmount_iso" cty:"unmount_iso" hcl:"unmount_iso"` @@ -202,6 +203,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "qemu_agent": &hcldec.AttrSpec{Name: "qemu_agent", Type: cty.Bool, Required: false}, "scsi_controller": &hcldec.AttrSpec{Name: "scsi_controller", Type: cty.String, Required: false}, "onboot": &hcldec.AttrSpec{Name: "onboot", Type: cty.Bool, Required: false}, + "disable_kvm": &hcldec.AttrSpec{Name: "disable_kvm", Type: cty.Bool, Required: false}, "template_name": &hcldec.AttrSpec{Name: "template_name", Type: cty.String, Required: false}, "template_description": &hcldec.AttrSpec{Name: "template_description", Type: cty.String, Required: false}, "unmount_iso": &hcldec.AttrSpec{Name: "unmount_iso", Type: cty.Bool, Required: false}, diff --git a/builder/proxmox/config_test.go b/builder/proxmox/config_test.go index <HASH>..<HASH> 100644 --- a/builder/proxmox/config_test.go +++ b/builder/proxmox/config_test.go @@ -98,6 +98,7 @@ func TestBasicExampleFromDocsIsValid(t *testing.T) { // Agent not set, default is true // SCSI controller not set, using default 'lsi' // Firewall toggle not set, using default: 0 + // Disable KVM not set, using default: 0 if b.config.Memory != 512 { t.Errorf("Expected Memory to be 512, got %d", b.config.Memory) @@ -126,6 +127,9 @@ func TestBasicExampleFromDocsIsValid(t *testing.T) { if b.config.Agent != true { t.Errorf("Expected Agent to be true, got %t", b.config.Agent) } + if b.config.DisableKVM != false { + t.Errorf("Expected Disable KVM toggle to be false, got %t", b.config.DisableKVM) + } if b.config.SCSIController != "lsi" { t.Errorf("Expected SCSI controller to be 'lsi', got %s", b.config.SCSIController) }
add option to disable kvm hardware virtualization
hashicorp_packer
train
8e3e27b0a0b93d5c8b7bf682f7fd515be14e1315
diff --git a/dynamic_dynamodb/core/table.py b/dynamic_dynamodb/core/table.py index <HASH>..<HASH> 100644 --- a/dynamic_dynamodb/core/table.py +++ b/dynamic_dynamodb/core/table.py @@ -285,8 +285,6 @@ def __ensure_provisioning_reads(table_name, key_name, num_consec_read_checks): # Increase needed due to high CU consumption if consumed_calculated_provisioning: - logger.info('Percent (new method) increase is by {0:.2f}%'.format(consumed_calculated_provisioning)) - if increase_consumed_reads_unit == 'percent': consumed_calculated_provisioning = calculators.increase_reads_in_percent( current_read_units, @@ -305,8 +303,6 @@ def __ensure_provisioning_reads(table_name, key_name, num_consec_read_checks): elif reads_upper_threshold and consumed_read_units_percent > reads_upper_threshold \ and not increase_consumed_reads_scale: - logger.info('Percent (old method) increase is by {0:.2f}%'.format(increase_consumed_reads_with)) - if increase_consumed_reads_unit == 'percent': consumed_calculated_provisioning = calculators.increase_reads_in_percent( current_read_units,
Removed debugging log entries from core/table.py
sebdah_dynamic-dynamodb
train
b42ede40e2699a9993520ec029decb4d7059e8f6
diff --git a/base64.js b/base64.js index <HASH>..<HASH> 100644 --- a/base64.js +++ b/base64.js @@ -1,7 +1,7 @@ ;(function () { var - object = typeof window != 'undefined' ? window : exports, + object = typeof exports != 'undefined' ? exports : window, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', INVALID_CHARACTER_ERR = (function () { // fabricate a suitable error object diff --git a/base64.min.js b/base64.min.js index <HASH>..<HASH> 100644 --- a/base64.min.js +++ b/base64.min.js @@ -1 +1 @@ -(function(){var t="undefined"!=typeof window?window:exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n=function(){try{document.createElement("$")}catch(t){return t}}();t.btoa||(t.btoa=function(t){for(var o,e,a=0,c=r,f="";t.charAt(0|a)||(c="=",a%1);f+=c.charAt(63&o>>8-8*(a%1))){if(e=t.charCodeAt(a+=.75),e>255)throw n;o=o<<8|e}return f}),t.atob||(t.atob=function(t){if(t=t.replace(/=+$/,""),1==t.length%4)throw n;for(var o,e,a=0,c=0,f="";e=t.charAt(c++);~e&&(o=a%4?64*o+e:e,a++%4)?f+=String.fromCharCode(255&o>>(6&-2*a)):0)e=r.indexOf(e);return f})})(); \ No newline at end of file +(function(){var t="undefined"!=typeof exports?exports:window,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o=function(){try{document.createElement("$")}catch(t){return t}}();t.btoa||(t.btoa=function(t){for(var e,n,a=0,c=r,f="";t.charAt(0|a)||(c="=",a%1);f+=c.charAt(63&e>>8-8*(a%1))){if(n=t.charCodeAt(a+=.75),n>255)throw o;e=e<<8|n}return f}),t.atob||(t.atob=function(t){if(t=t.replace(/=+$/,""),1==t.length%4)throw o;for(var e,n,a=0,c=0,f="";n=t.charAt(c++);~n&&(e=a%4?64*e+n:n,a++%4)?f+=String.fromCharCode(255&e>>(6&-2*a)):0)n=r.indexOf(n);return f})})(); \ No newline at end of file
Add compatibility with client side CommonJS
davidchambers_Base64.js
train
9904517576bef4d2835b089a8b29a80862762c6a
diff --git a/xwiki-rendering-macros/xwiki-rendering-macro-message/src/main/java/org/xwiki/rendering/internal/macro/message/AbstractMessageMacro.java b/xwiki-rendering-macros/xwiki-rendering-macro-message/src/main/java/org/xwiki/rendering/internal/macro/message/AbstractMessageMacro.java index <HASH>..<HASH> 100644 --- a/xwiki-rendering-macros/xwiki-rendering-macro-message/src/main/java/org/xwiki/rendering/internal/macro/message/AbstractMessageMacro.java +++ b/xwiki-rendering-macros/xwiki-rendering-macro-message/src/main/java/org/xwiki/rendering/internal/macro/message/AbstractMessageMacro.java @@ -44,8 +44,6 @@ public abstract class AbstractMessageMacro extends AbstractBoxMacro<BoxMacroPara */ public static final String CONTENT_MISSING_ERROR = "The required content is missing."; - private MacroTransformationContext currentContext; - /** * Create and initialize the descriptor of the macro. * @@ -66,7 +64,6 @@ public abstract class AbstractMessageMacro extends AbstractBoxMacro<BoxMacroPara if (StringUtils.isEmpty(content)) { throw new MacroExecutionException(CONTENT_MISSING_ERROR); } - this.currentContext = context; return super.execute(parameters, content, context); } @@ -88,6 +85,6 @@ public abstract class AbstractMessageMacro extends AbstractBoxMacro<BoxMacroPara @Override protected String getClassProperty() { - return super.getClassProperty() + ' ' + this.currentContext.getCurrentMacroBlock().getId() + "message"; + return super.getClassProperty() + ' ' + this.getDescriptor().getId() + "message"; } }
XRENDERING-<I>: Message macro should rely on AbstractBoxMacro * Use the macro id instead of relying on the context
xwiki_xwiki-rendering
train
7fa5149934352c6d2019e7ce3258eb31644cef2f
diff --git a/tasky/loop.py b/tasky/loop.py index <HASH>..<HASH> 100644 --- a/tasky/loop.py +++ b/tasky/loop.py @@ -126,8 +126,11 @@ class Tasky(object): elif task != self.all_tasks[task.name]: raise Exception('Duplicate task %s' % task.name) - task.task = asyncio.ensure_future(self.start_task(task)) - self.running_tasks.add(task) + if task.enabled: + task.task = asyncio.ensure_future(self.start_task(task)) + self.running_tasks.add(task) + else: + task.task = None return task @@ -228,6 +231,7 @@ class Tasky(object): finally: self.running_tasks.discard(task) + task.task = None after = time.time() total = after - before
Track but don't start disabled tasks
jreese_tasky
train
f52f2397af0a3dda05bf52d4aee9d22f9891f643
diff --git a/crispy_forms/tests/test_settings_bootstrap.py b/crispy_forms/tests/test_settings_bootstrap.py index <HASH>..<HASH> 100644 --- a/crispy_forms/tests/test_settings_bootstrap.py +++ b/crispy_forms/tests/test_settings_bootstrap.py @@ -25,3 +25,4 @@ MIDDLEWARE_CLASSES = ( ROOT_URLCONF = 'urls' CRISPY_TEMPLATE_PACK = 'bootstrap' +SECRET_KEY = 'secretkey'
Added compulsory SECRET_KEY to test settings
django-crispy-forms_django-crispy-forms
train
a6bc141d460138da463f1108ff0c5388fed92db8
diff --git a/Bundle/InstallableInterface.php b/Bundle/InstallableInterface.php index <HASH>..<HASH> 100644 --- a/Bundle/InstallableInterface.php +++ b/Bundle/InstallableInterface.php @@ -6,8 +6,8 @@ use Symfony\Component\HttpKernel\Bundle\BundleInterface; interface InstallableInterface extends BundleInterface { - public function getPreInstallationAction($version = null); + public function getPreInstallationAction($environment, $version = null); public function hasMigrations(); - public function getRequiredFixturesDirectory($version = null); - public function getOptionalFixturesDirectory($version = null); + public function getRequiredFixturesDirectory($environment, $version = null); + public function getOptionalFixturesDirectory($environment, $version = null); }
[InstallationBundle] Added environment argument
claroline_Distribution
train
b02e9fbbc01497688faadeec5bb0f952421d732e
diff --git a/src/python/twitter/pants/tasks/task.py b/src/python/twitter/pants/tasks/task.py index <HASH>..<HASH> 100644 --- a/src/python/twitter/pants/tasks/task.py +++ b/src/python/twitter/pants/tasks/task.py @@ -303,7 +303,11 @@ class Task(object): from twitter.pants.tasks.ivy_utils import IvyUtils from twitter.pants.binary_util import runjava_indivisible - java_runner = java_runner or runjava_indivisible + # TODO(pl): Fix the ivy resolution lock so that Ivy can be run within + # a nailgun server + # java_runner = java_runner or runjava_indivisible + java_runner = runjava_indivisible + ivy_args = ivy_args or [] targets = set(targets)
Temporary fix to the nailgun/ivy deadlock Auditors: benjy (sapling split of <I>d9e6a<I>c<I>a<I>ba<I>c6b0bafbaac3d)
pantsbuild_pants
train
dbb01029ec6f7f02ba47250a78fe5cba60825aa8
diff --git a/sgp4/exporter.py b/sgp4/exporter.py index <HASH>..<HASH> 100644 --- a/sgp4/exporter.py +++ b/sgp4/exporter.py @@ -24,10 +24,13 @@ def export_tle(satrec): append(str(satrec.satnum).zfill(5)) # Add classification code (use "U" if empty) - append((satrec.classification.strip() or "U") + " ") + classification = getattr(satrec, 'classification', 'U') + append(classification.strip() or 'U') + append(' ') # Add int'l designator and pad to 8 chars - append(satrec.intldesg.ljust(8, " ") + " ") + intldesg = getattr(satrec, 'intldesg', '') + append('{0:8} '.format(intldesg)) # Add epoch year and days in YYDDD.DDDDDDDD format epochyr = satrec.epochyr @@ -48,7 +51,9 @@ def export_tle(satrec): append("{0: 4.4e}".format(satrec.bstar * 10).replace(".", "").replace("e+00", "+0").replace("e-0", "-") + " ") # Add Ephemeris Type and Element Number - append("{} ".format(satrec.ephtype) + str(satrec.elnum).rjust(4, " ")) + ephtype = getattr(satrec, 'ephtype', 0) + elnum = getattr(satrec, 'elnum', 0) + append('{0} {1:4}'.format(ephtype, elnum)) # Join all the parts and add the Checksum line1 = ''.join(pieces)
Fix test failing locally: exporter AttributeError Alas! I had hoped that Travis CI Python <I> testing would fail exactly when “tox” Python <I> fails locally, but the two are apparently not the same, so I accepted this code from a PR when it in fact broke the tests for me. Here’s a fix that hopefully works in both cases.
brandon-rhodes_python-sgp4
train
0faf7ff33dba59b7e040cf551132b36371ec672e
diff --git a/simpleauth2/adapters/gae_webapp2.py b/simpleauth2/adapters/gae_webapp2.py index <HASH>..<HASH> 100644 --- a/simpleauth2/adapters/gae_webapp2.py +++ b/simpleauth2/adapters/gae_webapp2.py @@ -119,6 +119,14 @@ class NDBOpenIDStore(ndb.Model, interface.OpenIDStore): if entity: return association.Association.deserialize(entity.serialized) + + + @classmethod + def removeAssociation(cls, server_url, handle): + key = ndb.Key('ServerUrl', server_url, cls, handle) + if key.get(): + key.delete() + return True class GAEWebapp2Adapter(BaseAdapter): diff --git a/tests/test_adapters/test_gae_webapp2.py b/tests/test_adapters/test_gae_webapp2.py index <HASH>..<HASH> 100644 --- a/tests/test_adapters/test_gae_webapp2.py +++ b/tests/test_adapters/test_gae_webapp2.py @@ -200,8 +200,39 @@ class TestNDBOpenIDStore(object): # test for non existent url association = NDBOpenIDStore.getAssociation('non_existent_url') assert association is None + + + def test_removeAssociation(self): + + # create and store some associations + associations = [] + + for i in range(3): + assoc = Association(handle='handle-{}'.format(i), + secret='secret', + issued=int(time.time()), + lifetime=3600, + assoc_type='HMAC-SHA1') + associations.append(assoc) + NDBOpenIDStore.storeAssociation('server_url', assoc) + + # remove existing association + removed = NDBOpenIDStore.removeAssociation('server_url', 'handle-1') + # check whether the method returned True + assert removed is True + # check whether there is one less association in the datastore + assert NDBOpenIDStore.query().count() == 2 + + # check whether the right association was deleted + assert NDBOpenIDStore.getAssociation('server_url', 'handle-1') is None + + # check whether the remaining are there + assert NDBOpenIDStore.getAssociation('server_url', 'handle-0') == associations[0] + assert NDBOpenIDStore.getAssociation('server_url', 'handle-2') == associations[2] + +
Implemented the removeAssociation() with test.
authomatic_authomatic
train
5c2d3233bf933c1a24a0c28e1e5356294269217b
diff --git a/upload/admin/controller/common/filemanager.php b/upload/admin/controller/common/filemanager.php index <HASH>..<HASH> 100644 --- a/upload/admin/controller/common/filemanager.php +++ b/upload/admin/controller/common/filemanager.php @@ -29,7 +29,7 @@ class ControllerCommonFileManager extends Controller { if ($directories) { // Split the array based on current page number and max number of items per page of 10 - $images = array_splice($directories, ($page - 1) * 16, 16); + $images = array_slice($directories, ($page - 1) * 16, 16); foreach ($images as $image) { if (substr(str_replace('\\', '/', realpath($image)), 0, utf8_strlen(DIR_IMAGE . 'catalog')) == DIR_IMAGE . 'catalog') { @@ -67,7 +67,7 @@ class ControllerCommonFileManager extends Controller { if ($files) { // Split the array based on current page number and max number of items per page of 10 - $images = array_splice($files, ($page - 1) * 16, 16 - count($data['images'])); + $images = array_slice($files, ($page - 1) * 16, 16 - count($data['directories'])); foreach ($images as $image) { if (substr(str_replace('\\', '/', realpath($image)), 0, utf8_strlen(DIR_IMAGE . 'catalog')) == DIR_IMAGE . 'catalog') {
Update Pagination in Filemanager Replace function array_splice to array_slice
opencart_opencart
train
4394cc39af961a9b988d974df2351855ce385065
diff --git a/chainregistry.go b/chainregistry.go index <HASH>..<HASH> 100644 --- a/chainregistry.go +++ b/chainregistry.go @@ -785,6 +785,7 @@ func initNeutrinoBackend(cfg *Config, chainDir string) (*neutrino.ChainService, neutrino.MaxPeers = 8 neutrino.BanDuration = time.Hour * 48 + neutrino.UserAgentName = cfg.NeutrinoMode.UserAgentName neutrinoCS, err := neutrino.NewChainService(config) if err != nil { diff --git a/docs/INSTALL.md b/docs/INSTALL.md index <HASH>..<HASH> 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -197,6 +197,7 @@ neutrino: --neutrino.maxpeers= Max number of inbound and outbound peers --neutrino.banduration= How long to ban misbehaving peers. Valid time units are {s, m, h}. Minimum 1 second --neutrino.banthreshold= Maximum allowed ban score before disconnecting and banning misbehaving peers. + --neutrino.useragentname= Used to help identify ourselves to other bitcoin peers. ``` ## Bitcoind Options diff --git a/lncfg/neutrino.go b/lncfg/neutrino.go index <HASH>..<HASH> 100644 --- a/lncfg/neutrino.go +++ b/lncfg/neutrino.go @@ -12,4 +12,5 @@ type Neutrino struct { BanThreshold uint32 `long:"banthreshold" description:"Maximum allowed ban score before disconnecting and banning misbehaving peers."` FeeURL string `long:"feeurl" description:"Optional URL for fee estimation. If a URL is not specified, static fees will be used for estimation."` AssertFilterHeader string `long:"assertfilterheader" description:"Optional filter header in height:hash format to assert the state of neutrino's filter header chain on startup. If the assertion does not hold, then the filter header chain will be re-synced from the genesis block."` + UserAgentName string `long:"useragentname" description:"Used to help identify ourselves to other bitcoin peers"` }
lnd: expose user agent name as config option Expose the neutrino `UserAgentName` config option. This can be set by starting lnd with the `--neutrino.useragentname=` flag.
lightningnetwork_lnd
train
d675075b9798b4da1f13a547fbf44e3dcb79c01a
diff --git a/engine/src/test/java/org/camunda/bpm/engine/test/api/authorization/history/HistoricIdentityLinkLogAuthorizationTest.java b/engine/src/test/java/org/camunda/bpm/engine/test/api/authorization/history/HistoricIdentityLinkLogAuthorizationTest.java index <HASH>..<HASH> 100644 --- a/engine/src/test/java/org/camunda/bpm/engine/test/api/authorization/history/HistoricIdentityLinkLogAuthorizationTest.java +++ b/engine/src/test/java/org/camunda/bpm/engine/test/api/authorization/history/HistoricIdentityLinkLogAuthorizationTest.java @@ -17,7 +17,7 @@ public class HistoricIdentityLinkLogAuthorizationTest extends AuthorizationTest protected String deploymentId; public void setUp() throws Exception { - deploymentId = createDeployment(null, "org/camunda/bpm/engine/test/api/authorization/OneTaskProcess.bpmn20.xml", + deploymentId = createDeployment(null, "org/camunda/bpm/engine/test/api/authorization/oneTaskProcess.bpmn20.xml", "org/camunda/bpm/engine/test/api/authorization/oneTaskCase.cmmn").getId(); super.setUp(); }
fix(engine): Changed case sensitive xml file name related to #CAM-<I>
camunda_camunda-bpm-platform
train
18f096b6a38d4274cf0479be6132d8dcedd9231b
diff --git a/pkg/client/deploymentconfigs.go b/pkg/client/deploymentconfigs.go index <HASH>..<HASH> 100644 --- a/pkg/client/deploymentconfigs.go +++ b/pkg/client/deploymentconfigs.go @@ -159,7 +159,12 @@ func (c *deploymentConfigs) UpdateStatus(deploymentConfig *deployapi.DeploymentC // Instantiate instantiates a new build from build config returning new object or an error func (c *deploymentConfigs) Instantiate(request *deployapi.DeploymentRequest) (*deployapi.DeploymentConfig, error) { result := &deployapi.DeploymentConfig{} - err := c.r.Post().Namespace(c.ns).Resource("deploymentConfigs").Name(request.Name).SubResource("instantiate").Body(request).Do().Into(result) + resp := c.r.Post().Namespace(c.ns).Resource("deploymentConfigs").Name(request.Name).SubResource("instantiate").Body(request).Do() + var statusCode int + if resp.StatusCode(&statusCode); statusCode == 204 { + return nil, nil + } + err := resp.Into(result) return result, err } diff --git a/pkg/deploy/controller/generictrigger/controller.go b/pkg/deploy/controller/generictrigger/controller.go index <HASH>..<HASH> 100644 --- a/pkg/deploy/controller/generictrigger/controller.go +++ b/pkg/deploy/controller/generictrigger/controller.go @@ -46,9 +46,7 @@ func (c *DeploymentTriggerController) Handle(config *deployapi.DeploymentConfig) } func (c *DeploymentTriggerController) handleErr(err error, key interface{}) { - // TODO: "empty data" comes from the protobuf serializer when instantiate - // returns a 204. This should be a typed error we ignore in this controller. - if err == nil || err.Error() == "empty data" { + if err == nil { c.queue.Forget(key) return }
client: fix instantiate call to handle <I>
openshift_origin
train
d13b3ecfd7e8194fd45fc51274202b7ff61c6c6f
diff --git a/packages/veritone-react-common/src/components/FilePicker/index.js b/packages/veritone-react-common/src/components/FilePicker/index.js index <HASH>..<HASH> 100644 --- a/packages/veritone-react-common/src/components/FilePicker/index.js +++ b/packages/veritone-react-common/src/components/FilePicker/index.js @@ -1,5 +1,4 @@ import React, { Component } from 'react'; -import Modal from 'react-modal'; import FileUploader from './FileUploader'; import FileList from './FileList'; import FilePickerHeader from './FilePickerHeader/FilePickerHeader'; @@ -10,6 +9,7 @@ import styles from './styles.scss'; import _ from 'lodash'; import { DragDropContext, DragDropContextProvider } from 'react-dnd'; import HTML5Backend, { NativeTypes } from 'react-dnd-html5-backend'; +import Dialog from 'material-ui/Dialog'; import { shape, @@ -79,8 +79,7 @@ class FilePicker extends Component { let pickerOptions = this.props.options || {}; const { FILE } = NativeTypes; return ( - <Modal isOpen={this.state.isOpen} - className={styles.modalContainer}> + <Dialog open={this.state.isOpen}> <div className={styles.filePicker} style={{ @@ -116,7 +115,7 @@ class FilePicker extends Component { } <FilePickerFooter onCloseModal={this.handleCloseModal}/> </div> - </Modal> + </Dialog> ); } };
Remove react-modal and use Material UI Dialog component instead.
veritone_veritone-sdk
train
cce101bb173a7f79e2559d4bd88305034b15d914
diff --git a/inc/class-public-scripts.php b/inc/class-public-scripts.php index <HASH>..<HASH> 100644 --- a/inc/class-public-scripts.php +++ b/inc/class-public-scripts.php @@ -105,13 +105,23 @@ class CareLib_Public_Scripts extends CareLib_Scripts { /** * Register front-end stylesheets for the framework. * - * @since 1.5.0 + * @since 0.2.0 * @access public * @return void */ public function register_styles() { - wp_register_style( "{$this->prefix}-parent", $this->get_parent_stylesheet_uri() ); - wp_register_style( "{$this->prefix}-style", get_stylesheet_uri() ); + wp_register_style( + "{$this->prefix}-parent", + $this->get_parent_stylesheet_uri(), + array(), + $this->theme_version() + ); + wp_register_style( + "{$this->prefix}-style", + get_stylesheet_uri(), + array(), + $this->theme_version() + ); } /** @@ -136,30 +146,28 @@ class CareLib_Public_Scripts extends CareLib_Scripts { } /** - * Filters the 'stylesheet_uri' to allow theme developers to offer a - * minimized version of their main 'style.css' file. It will detect if a - * 'style.min.css' file is available and use it if SCRIPT_DEBUG is disabled. + * Filter the 'stylesheet_uri' to load a minified version of 'style.css' + * file if it is available. * - * @since 1.5.0 + * @since 0.2.0 * @access public * @param string $stylesheet_uri The URI of the active theme's stylesheet. * @param string $stylesheet_dir_uri The directory URI of the active theme's stylesheet. * @return string $stylesheet_uri */ public function min_stylesheet_uri( $stylesheet_uri, $stylesheet_dir_uri ) { - // Use the .min stylesheet if available. - if ( $this->suffix ) { + if ( ! $this->suffix ) { + return $stylesheet_uri; + } - // Remove the stylesheet directory URI from the file name. - $stylesheet = str_replace( trailingslashit( $stylesheet_dir_uri ), '', $stylesheet_uri ); + // Remove the stylesheet directory URI from the file name. + $stylesheet = str_replace( trailingslashit( $stylesheet_dir_uri ), '', $stylesheet_uri ); - // Change the stylesheet name to 'style.min.css'. - $stylesheet = str_replace( '.css', "{$this->suffix}.css", $stylesheet ); + // Change the stylesheet name to 'style.min.css'. + $stylesheet = str_replace( '.css', "{$this->suffix}.css", $stylesheet ); - // If the stylesheet exists in the stylesheet directory, set the stylesheet URI to the dev stylesheet. - if ( file_exists( $this->child . $stylesheet ) ) { - $stylesheet_uri = esc_url( trailingslashit( $stylesheet_dir_uri ) . $stylesheet ); - } + if ( file_exists( $this->child . $stylesheet ) ) { + $stylesheet_uri = esc_url( trailingslashit( $stylesheet_dir_uri ) . $stylesheet ); } return $stylesheet_uri; @@ -168,7 +176,7 @@ class CareLib_Public_Scripts extends CareLib_Scripts { /** * Retrieve the theme file with the highest priority that exists. * - * @since 1.5.0 + * @since 0.2.0 * @access public * @link http://core.trac.wordpress.org/ticket/18302 * @param array $file_names The files to search for.
Implemented theme version and simplified another method
cipherdevgroup_carelib
train
0db306a8283b26f605cf995fc283f9b3468b4606
diff --git a/test/test_push_queues.rb b/test/test_push_queues.rb index <HASH>..<HASH> 100644 --- a/test/test_push_queues.rb +++ b/test/test_push_queues.rb @@ -195,7 +195,7 @@ class TestPushQueues < TestBase subscribers.each do |s| p s assert_equal 202, s["status_code"] - assert_equal "retrying", s["status"] + assert_equal "reserved", s["status"] # now let's delete it to say we're done with it puts "Acking subscriber" p s.delete
after <I>s, the msg is reserved again
iron-io_iron_mq_ruby
train
beadaab87d677c8543a9759f5b0883fbdca407a3
diff --git a/imager/models/Imager_ImageModel.php b/imager/models/Imager_ImageModel.php index <HASH>..<HASH> 100644 --- a/imager/models/Imager_ImageModel.php +++ b/imager/models/Imager_ImageModel.php @@ -1,13 +1,50 @@ <?php namespace Craft; +/** + * Imager by André Elvan + * + * @author André Elvan <http://vaersaagod.no> + * @package Imager + * @copyright Copyright (c) 2016, André Elvan + * @license http://opensource.org/licenses/mit-license.php MIT License + * @link https://github.com/aelvan/Imager-Craft + */ + class Imager_ImageModel extends BaseModel { + /** + * Constructor + * + * @param null $imagePath + * @param null $imageUrl + */ + public function __construct($imagePath = null, $imageUrl = null) + { + if ($imagePath != 'null') { + $this['path'] = $imagePath; + + $imageInfo = @getimagesize($imagePath); + $this['width'] = $imageInfo[0]; + $this['height'] = $imageInfo[1]; + + $this['extension'] = IOHelper::getExtension($imagePath); + $this['mimeType'] = IOHelper::getMimeType($imagePath); + } + + if ($imageUrl != 'null') { + $this['url'] = $imageUrl; + } + } + protected function defineAttributes() { return array( + 'path' => array(AttributeType::String), 'url' => array(AttributeType::String), + 'extension' => array(AttributeType::String), + 'mimeType' => array(AttributeType::String), 'width' => array(AttributeType::Number), 'height' => array(AttributeType::Number), ); @@ -18,11 +55,26 @@ class Imager_ImageModel extends BaseModel return Craft::t($this->url); } + function getPath() + { + return $this->path; + } + function getUrl() { return $this->url; } + function getExtension() + { + return $this->extension; + } + + function getMimeType() + { + return $this->mimeType; + } + function getWidth() { return $this->width; @@ -33,5 +85,4 @@ class Imager_ImageModel extends BaseModel return $this->height; } - // todo : implement more methods to make it more similar to AssetFileModel }
Extended the Imager_ImageModel with more properties to make it more similar to AssetFileModel.
aelvan_Imager-Craft
train
cd4999c10ca44cc33dff7d25232784e112b5c735
diff --git a/controller.php b/controller.php index <HASH>..<HASH> 100644 --- a/controller.php +++ b/controller.php @@ -10,7 +10,7 @@ use Brain\Hierarchy\Hierarchy; */ function get_sage_function() { - $function_name = apply_filters('sober/controller/sage-namespace', 'App') . '\sage'; + $function_name = apply_filters('sober/controller/sage_namespace', 'App') . '\sage'; if (function_exists($function_name)) { return $function_name; }
Make filter name snake case (as per wordpress)
soberwp_controller
train
f6dbf210db55c3c2d242a939b9d31bccd3e7d0c6
diff --git a/lib/utils.js b/lib/utils.js index <HASH>..<HASH> 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -44,7 +44,7 @@ exports.dateFormat = function(str) { , defaults = [null, ' 00:00', ':00', ' +0000'] , match = str.match(rx) - if (!match) { + if (!match || str === (new Date(str)).toISOString()) { return false } for (var i = 1; i < 4; i++) { diff --git a/test.js b/test.js index <HASH>..<HASH> 100644 --- a/test.js +++ b/test.js @@ -1702,6 +1702,7 @@ describe('Respectify Unit Tests', function() { , '02-05-2015 00:00' , '02-05-2015 00:00:00' , '02-05-2015 00:00:00 -0800' + , '2015-02-05T00:00:00.000Z' ].forEach(function(x) { var obj = { time: x } assert.ifError(inv(obj, 'time', paramSpec))
Added support for ISO <I> date strings
majorleaguesoccer_respectify
train
6f3ac539478417204864c8e542d8279b8d2ad743
diff --git a/packages/react-server-website/pages/homepage.js b/packages/react-server-website/pages/homepage.js index <HASH>..<HASH> 100644 --- a/packages/react-server-website/pages/homepage.js +++ b/packages/react-server-website/pages/homepage.js @@ -5,7 +5,7 @@ import './homepage.less'; export default class Homepage { getTitle() { - return "React Server"; + return "React Server - Fast Server and Client Side Rendering"; } getElements() {
Change title for home page To get more SEO traffic, we should adjust the title for what people search for. Change recommended by Joe Lei.
redfin_react-server
train
e56fd56ac1bf9455b32cfe7e2a2d94d9f2a09fd0
diff --git a/lib/chef/resource.rb b/lib/chef/resource.rb index <HASH>..<HASH> 100644 --- a/lib/chef/resource.rb +++ b/lib/chef/resource.rb @@ -1116,7 +1116,7 @@ class Chef elsif superclass.respond_to?(:default_action) superclass.default_action else - :nothing + [:nothing] end end def self.default_action=(action_name) diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/resource_spec.rb +++ b/spec/unit/resource_spec.rb @@ -987,6 +987,10 @@ describe Chef::Resource do let(:resource) { resource_class.new('test', nil) } subject { resource.action } + context "with a no action" do + it { is_expected.to eq [:nothing] } + end + context "with a symbol action" do before { resource.action(:one) } it { is_expected.to eq [:one] }
Make sure the default case gives an array too.
chef_chef
train
f82480c0b62dc7769e7e86dc4c2bc2cf80e95468
diff --git a/modules/es.promise.js b/modules/es.promise.js index <HASH>..<HASH> 100644 --- a/modules/es.promise.js +++ b/modules/es.promise.js @@ -1,7 +1,6 @@ 'use strict'; var IS_PURE = require('./_is-pure'); var global = require('./_global'); -var ctx = require('./_ctx'); var classof = require('./_classof'); var $export = require('./_export'); var isObject = require('./_is-object'); @@ -130,8 +129,12 @@ var onHandleUnhandled = function (promise) { } else dispatchEvent(REJECTION_HANDLED, promise, promise._v); }); }; -var $reject = function (value) { - var promise = this; +var bind = function (fn, promise) { + return function (value) { + fn(promise, value); + }; +}; +var $reject = function (promise, value) { if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap @@ -139,21 +142,20 @@ var $reject = function (value) { promise._s = 2; notify(promise, true); }; -var $resolve = function (value) { - var promise = this; - var then; +var $resolve = function (promise, value) { if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap try { if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { + var then = isThenable(value); + if (then) { microtask(function () { var wrapper = { _w: promise, _d: false }; // wrap try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + then.call(value, bind($resolve, wrapper), bind($reject, wrapper)); } catch (e) { - $reject.call(wrapper, e); + $reject(wrapper, e); } }); } else { @@ -162,7 +164,7 @@ var $resolve = function (value) { notify(promise, false); } } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap + $reject({ _w: promise, _d: false }, e); // wrap } }; @@ -174,9 +176,9 @@ if (!USE_NATIVE) { aFunction(executor); Internal.call(this); try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + executor(bind($resolve, this), bind($reject, this)); } catch (err) { - $reject.call(this, err); + $reject(this, err); } }; // eslint-disable-next-line no-unused-vars @@ -209,8 +211,8 @@ if (!USE_NATIVE) { OwnPromiseCapability = function () { var promise = new Internal(); this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); + this.resolve = bind($resolve, promise); + this.reject = bind($reject, promise); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === $Promise || C === Wrapper
unbind internal `resolve` and `reject`
zloirock_core-js
train
eea506218af0d6b4924748dffb7679721f7d9b8b
diff --git a/dimod/binary_quadratic_model/model.py b/dimod/binary_quadratic_model/model.py index <HASH>..<HASH> 100644 --- a/dimod/binary_quadratic_model/model.py +++ b/dimod/binary_quadratic_model/model.py @@ -433,47 +433,12 @@ class BinaryQuadraticModel(object): new = mapping[old] - # acting on all of these in-place - linear[new] = linear[old] - adj[new] = adj[old] - for u in adj[old]: - adj[u][new] = adj[u][old] - del adj[u][old] - - del linear[old] - del adj[old] - - # now rebuild quadratic - for old_u, old_v in list(quadratic): - if old_u not in mapping: - if old_v not in mapping: - # no remap needed - continue - new_u = old_u - else: - new_u = mapping[old_u] - if old_v not in mapping: - new_v = old_v - else: - new_v = mapping[old_v] - - if (old_v, old_u) in quadratic: - quadratic[(new_v, new_u)] = quadratic[(old_v, old_u)] - del quadratic[(old_v, old_u)] - elif (old_u, old_v) in quadratic: - quadratic[(new_u, new_v)] = quadratic[(old_u, old_v)] - del quadratic[(old_u, old_v)] - else: - raise RuntimeError("something went wrong in relabel") - - # update the spin/binary version of self - try: - if self.vartype is Vartype.SPIN and self._binary is not None: - self._binary.relabel_variables(mapping, copy=False) - elif self.vartype is Vartype.BINARY and self._spin is not None: - self._spin.relabel_variables(mapping, copy=False) - except AttributeError: - pass + # get the new interactions that need to be added + new_interactions = [(new, v, adj[old][v]) for v in adj[old]] + + self.add_variable(new, linear[old]) + self.add_interactions_from(new_interactions) + self.remove_variable(old) return self
Change relabel_variables to use the new add/remove methods
dwavesystems_dimod
train
25f705c8c9f20a3b4b28deaa14daaf0675b81677
diff --git a/mediafile.py b/mediafile.py index <HASH>..<HASH> 100644 --- a/mediafile.py +++ b/mediafile.py @@ -1994,18 +1994,27 @@ class MediaFile(object): StorageStyle('MUSICBRAINZ_ALBUMID'), ASFStorageStyle('MusicBrainz/Album Id'), ) - mb_artistid = MediaField( - MP3DescStorageStyle(u'MusicBrainz Artist Id'), - MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Artist Id'), - StorageStyle('MUSICBRAINZ_ARTISTID'), + mb_artistids = ListMediaField( + MP3ListDescStorageStyle(u'MusicBrainz Artist Id', split_v23=True), + MP4ListStorageStyle('----:com.apple.iTunes:MusicBrainz Artist Id'), + ListStorageStyle('MUSICBRAINZ_ARTISTID'), ASFStorageStyle('MusicBrainz/Artist Id'), ) - mb_albumartistid = MediaField( - MP3DescStorageStyle(u'MusicBrainz Album Artist Id'), - MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Artist Id'), - StorageStyle('MUSICBRAINZ_ALBUMARTISTID'), + mb_artistid = mb_artistids.single_field() + + mb_albumartistids = ListMediaField( + MP3ListDescStorageStyle( + u'MusicBrainz Album Artist Id', + split_v23=True, + ), + MP4ListStorageStyle( + '----:com.apple.iTunes:MusicBrainz Album Artist Id', + ), + ListStorageStyle('MUSICBRAINZ_ALBUMARTISTID'), ASFStorageStyle('MusicBrainz/Album Artist Id'), ) + mb_albumartistid = mb_albumartistids.single_field() + mb_releasegroupid = MediaField( MP3DescStorageStyle(u'MusicBrainz Release Group Id'), MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Release Group Id'), diff --git a/test/test_mediafile.py b/test/test_mediafile.py index <HASH>..<HASH> 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -991,8 +991,10 @@ class MediaFieldTest(unittest.TestCase): def test_known_fields(self): fields = list(ReadWriteTestBase.tag_fields) - fields.extend(('encoder', 'images', 'genres', 'albumtype', 'artists', - 'albumartists', 'url')) + fields.extend( + ('encoder', 'images', 'genres', 'albumtype', 'artists', + 'albumartists', 'url', 'mb_artistids', 'mb_albumartistids') + ) assertCountEqual(self, MediaFile.fields(), fields) def test_fields_in_readable_fields(self):
Add multi-value variants of `mb_artistid` and `mb_albumartistid`. Tags are now interpreted as lists. Resolves #<I>
beetbox_mediafile
train
d8d186d7ec98dae72b45ee124cc17ee166617852
diff --git a/spec/factories/transplants/donor_stage_position.rb b/spec/factories/transplants/donor_stage_position.rb index <HASH>..<HASH> 100644 --- a/spec/factories/transplants/donor_stage_position.rb +++ b/spec/factories/transplants/donor_stage_position.rb @@ -2,6 +2,6 @@ FactoryBot.define do factory :donor_stage_position, class: "Renalware::Transplants::DonorStagePosition" do - name { Faker::Lorem.word } + name { SecureRandom.hex(20) } end end diff --git a/spec/factories/transplants/donor_stage_status.rb b/spec/factories/transplants/donor_stage_status.rb index <HASH>..<HASH> 100644 --- a/spec/factories/transplants/donor_stage_status.rb +++ b/spec/factories/transplants/donor_stage_status.rb @@ -2,6 +2,6 @@ FactoryBot.define do factory :donor_stage_status, class: "Renalware::Transplants::DonorStageStatus" do - name { Faker::Lorem.word } + name { SecureRandom.hex(20) } end end
Use a random string rather than Faker::Lorem.word in specs Faker::Lorem.word is causing random ‘Name already taken’ failures on CI because when it serves up a duplicate
airslie_renalware-core
train
78369aef4573578bed55526632db8acb5677f8d1
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -33,6 +33,8 @@ module.exports = function(config) { var questions = new Questions(opts); fn._questions = questions; + questions.on('ask', app.emit.bind(app, 'ask')); + questions.on('answer', app.emit.bind(app, 'answer')); questions.on('error', function(err) { err.reason = 'base-questions error'; self.emit('error', err); @@ -74,7 +76,8 @@ module.exports = function(config) { */ this.define('choices', function() { - return this.questions.choices.apply(this.questions, arguments); + this.questions.choices.apply(this.questions, arguments); + return this; }); /**
bubble up events from `question-store`
base_base-questions
train
ebe320d17f300d41e1b94c79fd62168112a69597
diff --git a/lib/util.js b/lib/util.js index <HASH>..<HASH> 100644 --- a/lib/util.js +++ b/lib/util.js @@ -533,7 +533,7 @@ var util = { each: function each(object, iterFunction) { for (var key in object) { - if (object.hasOwnProperty(key)) { + if (Object.prototype.hasOwnProperty.call(object, key)) { var ret = iterFunction.call(this, key, object[key]); if (ret === util.abort) break; }
Allowing use of bare objects to be passed in to utils.each so that constructors for services may use them.
aws_aws-sdk-js
train
162a19d750d691c87be7783e9a07b69c3e042061
diff --git a/config/unicorn.rb b/config/unicorn.rb index <HASH>..<HASH> 100644 --- a/config/unicorn.rb +++ b/config/unicorn.rb @@ -1,4 +1,4 @@ -app_root = Rails.root +app_root = ENV['APP_PATH'] || Rails.root worker_processes 2
I guess we can't use Rails.root in server unicorn config
cortex-cms_cortex
train
a04fb62f48aa27050b6ebe4f52ea89397c8437ce
diff --git a/salt/modules/zpool.py b/salt/modules/zpool.py index <HASH>..<HASH> 100644 --- a/salt/modules/zpool.py +++ b/salt/modules/zpool.py @@ -875,6 +875,95 @@ def detach(zpool, device): return ret +def split(zpool, newzpool, **kwargs): + ''' + .. versionadded:: Oxygen + + Splits devices off pool creating newpool. + + .. note:: + + All vdevs in pool must be mirrors. At the time of the split, + newpool will be a replica of pool. + + zpool : string + name of storage pool + newzpool : string + name of new storage pool + mountpoint : string + sets the mount point for the root dataset + altroot : string + sets altroot for newzpool + properties : dict + additional pool properties for newzpool + + CLI Example: + + .. code-block:: bash + + salt '*' zpool.split datamirror databackup + salt '*' zpool.split datamirror databackup altroot=/backup + + .. note:: + + Zpool properties can be specified at the time of creation of the pool by + passing an additional argument called "properties" and specifying the properties + with their respective values in the form of a python dictionary:: + + properties="{'property1': 'value1', 'property2': 'value2'}" + + Example: + + .. code-block:: bash + + salt '*' zpool.split datamirror databackup properties="{'readonly': 'on'}" + ''' + ret = {} + + # Check if the pool_name is already being used + if exists(newzpool): + ret[newzpool] = 'storage pool already exists' + return ret + + if not exists(zpool): + ret[zpool] = 'storage pool does not exists' + return ret + + zpool_cmd = _check_zpool() + altroot = kwargs.get('altroot', None) + properties = kwargs.get('properties', None) + cmd = '{0} split'.format(zpool_cmd) + + # apply extra arguments from kwargs + if properties: # create "-o property=value" pairs + optlist = [] + for prop in properties: + if isinstance(properties[prop], bool): + value = 'on' if properties[prop] else 'off' + else: + if ' ' in properties[prop]: + value = "'{0}'".format(properties[prop]) + else: + value = properties[prop] + optlist.append('-o {0}={1}'.format(prop, value)) + opts = ' '.join(optlist) + cmd = '{0} {1}'.format(cmd, opts) + if altroot: # set altroot + cmd = '{0} -R {1}'.format(cmd, altroot) + cmd = '{0} {1} {2}'.format(cmd, zpool, newzpool) + + # Create storage pool + res = __salt__['cmd.run_all'](cmd, python_shell=False) + + # Check and see if the pools is available + if res['retcode'] != 0: + ret[newzpool] = res['stderr'] if 'stderr' in res else res['stdout'] + else: + ret[newzpool] = 'split off from {}'.format(zpool) + + return ret + + def replace(zpool, old_device, new_device=None, force=False): ''' .. versionchanged:: 2016.3.0
Add support for zpool.split
saltstack_salt
train
4176de52e715d74410b0ad1c8e7aa7d79716d378
diff --git a/classes/Connection.php b/classes/Connection.php index <HASH>..<HASH> 100644 --- a/classes/Connection.php +++ b/classes/Connection.php @@ -16,6 +16,20 @@ class Connection implements Contract\Connection protected $pdo; /** + * PDO query wrapper + * + * @var \Closure + */ + protected $query; + + /** + * PDO exec wrapper + * + * @var \Closure + */ + protected $exec; + + /** * Constructor * * @param PDO $pdo @@ -123,7 +137,8 @@ class Connection implements Contract\Connection } $query = $this->merge($query, $data); - $statement = $this->{"query"}($query); + $method = $this->query; + $statement = $method($query); return new Result($statement); } @@ -141,9 +156,10 @@ class Connection implements Contract\Connection $data = array_slice(func_get_args(), 1); } - $query = $this->merge($query, $data); + $query = $this->merge($query, $data); + $method = $this->exec; - return $this->{"exec"}($query); + return $method($query); } /** diff --git a/classes/Result.php b/classes/Result.php index <HASH>..<HASH> 100644 --- a/classes/Result.php +++ b/classes/Result.php @@ -76,7 +76,7 @@ class Result implements Contract\Result */ public function value($column = 0) { - return $this->statement->fetch(PDO::FETCH_COLUMN, $column); + return $this->statement->fetchColumn($column); } /**
Fix query/execute methods and fetching single values by column index.
neat-php_database
train
13db69bf41a7dfda2900165200836f02da932ab5
diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java @@ -31,9 +31,7 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.annotation.Order; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; @@ -143,7 +141,6 @@ public class EntityScanPackages { * {@link ImportBeanDefinitionRegistrar} to store the base package from the importing * configuration. */ - @Order(Ordered.HIGHEST_PRECEDENCE) static class Registrar implements ImportBeanDefinitionRegistrar { @Override
Drop superfluous `@Order` annotation Remove `@Order` which has no effect on `ImportBeanDefinitionRegistrar`. Fixes gh-<I>
spring-projects_spring-boot
train
b449fcb5f01f3d75c9816e353c4bcc3457b912f7
diff --git a/lib/core/builder.js b/lib/core/builder.js index <HASH>..<HASH> 100644 --- a/lib/core/builder.js +++ b/lib/core/builder.js @@ -34,7 +34,7 @@ function build (dataFilePath, presskit, { console.log(`- "${presskit.title}" -> ${chalk.blue(htmlFilePath)}`) // Templates and images. - const template = createTemplate(presskit.type) + const template = createTemplate(presskit.type, pageFolder) const assetsSource = getImagesFolder(dataFilePath) const images = getImages(assetsSource) diff --git a/lib/core/template.js b/lib/core/template.js index <HASH>..<HASH> 100644 --- a/lib/core/template.js +++ b/lib/core/template.js @@ -16,7 +16,7 @@ const console = require('../helpers/color-console') // Create a template object from a template of the assets folder. // Use the type to determine which template must be selected. -function createTemplate (type) { +function createTemplate (type, destination) { const templatePath = getTemplatePath(assets, type) if (!templatePath) { @@ -24,7 +24,7 @@ function createTemplate (type) { } registerPartials(assets) - registerHelpers() + registerHelpers(destination) const template = fs.readFileSync(templatePath, 'utf-8') return handlebars.compile(template) @@ -59,7 +59,7 @@ function registerPartials (folder) { handlebars.registerPartial(partials) } -function registerHelpers () { +function registerHelpers (destination) { handlebars.registerHelper({ rawText: function (data) { // Not a string? Try to recover and show a warning.
Give access to destination in template helpers
pixelnest_presskit.html
train
7f997e81dbd3b132d5831065af48122e7a009a1d
diff --git a/docs/changelog.md b/docs/changelog.md index <HASH>..<HASH> 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -4,7 +4,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [0.32.0] -- unreleased - +- unify exceptions related to remote YAML file reading in `read_yaml` function. Now always a `RemoteYAMLError` is thrown. ## [0.31.1] -- 2021-04-15 diff --git a/peppy/exceptions.py b/peppy/exceptions.py index <HASH>..<HASH> 100644 --- a/peppy/exceptions.py +++ b/peppy/exceptions.py @@ -15,6 +15,7 @@ __all__ = [ "MissingAmendmentError", "InvalidConfigFileException", "SampleTableFileException", + "RemoteYAMLError", ] @@ -45,6 +46,12 @@ class InvalidSampleTableFileException(SampleTableFileException): pass +class RemoteYAMLError(PeppyError): + """Remote YAML file cannot be accessed""" + + pass + + class MissingAmendmentError(PeppyError): """Error when project config lacks a requested subproject.""" diff --git a/peppy/utils.py b/peppy/utils.py index <HASH>..<HASH> 100644 --- a/peppy/utils.py +++ b/peppy/utils.py @@ -2,12 +2,13 @@ import logging import os -from urllib.error import HTTPError from urllib.request import urlopen import yaml from ubiquerg import expandpath, is_url +from peppy import exceptions + from .const import CONFIG_KEY _LOGGER = logging.getLogger(__name__) @@ -105,28 +106,26 @@ def make_list(arg, obj_class): def load_yaml(filepath): - """Load a yaml file into a Python dict""" - - def read_yaml_file(filepath): - """ - Read a YAML file - - :param str filepath: path to the file to read - :return dict: read data - """ - filepath = os.path.abspath(filepath) - with open(filepath, "r") as f: - data = yaml.safe_load(f) - return data + """ + Load a local or remote YAML file into a Python dict + :param str filepath: path to the file to read + :raises RemoteYAMLError: if the remote YAML file reading fails + :return dict: read data + """ if is_url(filepath): _LOGGER.debug(f"Got URL: {filepath}") try: response = urlopen(filepath) - except HTTPError as e: - raise e - data = response.read() # a `bytes` object - text = data.decode("utf-8") - return yaml.safe_load(text) + except Exception as e: + raise exceptions.RemoteYAMLError( + f"Could not load remote file: {filepath}. " + f"Original exception: {getattr(e, 'message', repr(e))}" + ) + else: + data = response.read().decode("utf-8") + return yaml.safe_load(data) else: - return read_yaml_file(filepath) + with open(os.path.abspath(filepath), "r") as f: + data = yaml.safe_load(f) + return data
unify exceptions related to remote YAML file reading in function
pepkit_peppy
train
6a7ab57b0c52ac859155426d86ee587869a52742
diff --git a/lib/migrator.js b/lib/migrator.js index <HASH>..<HASH> 100644 --- a/lib/migrator.js +++ b/lib/migrator.js @@ -1,7 +1,7 @@ 'use strict'; const TurndownService = require('turndown'); -const request = require('request-promise-native'); +const got = require('got'); const { parse } = require('url'); const { readFile } = require('hexo-fs'); const parseFeed = require('./feed'); @@ -28,7 +28,7 @@ module.exports = async function(args) { } if (/^http(s)?:\/\//i.test(source)) { - input = await request(source); + input = await got(source, { resolveBodyOnly: true, retry: 0 }); } else { input = await readFile(source); } diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -32,8 +32,7 @@ "dependencies": { "camaro": "^4.1.2", "hexo-fs": "^2.0.0", - "request": "^2.36.0", - "request-promise-native": "^1.0.8", + "got": "^10.2.1", "turndown": "^5.0.3" }, "devDependencies": { diff --git a/test/index.js b/test/index.js index <HASH>..<HASH> 100644 --- a/test/index.js +++ b/test/index.js @@ -7,7 +7,9 @@ const Hexo = require('hexo'); const hexo = new Hexo(__dirname); const m = require('../lib/migrator.js').bind(hexo); -describe('migrator', () => { +describe('migrator', function() { + this.timeout(5000); + before(() => hexo.init()); it('default - file', async () => {
refactor: replace 'request' with 'got'
hexojs_hexo-migrator-rss
train