hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
8382c1522465cf2fda1e753eb0bcb67a63d1fb99
diff --git a/src/Type/Enum.php b/src/Type/Enum.php index <HASH>..<HASH> 100644 --- a/src/Type/Enum.php +++ b/src/Type/Enum.php @@ -40,7 +40,11 @@ class Enum extends Type { * @return mixed */ public function &getValue(){ - return $this->mixValue->getValue(); + if(is_object($this->mixValue)){ + return $this->mixValue->getValue(); + } + + return null; } /**
Checking that the enum has been created or else returning null.
frozensheep_synthesize
train
156ed6bd5605c430a88023473fea9fbcb07aba33
diff --git a/lib/custom/src/MW/View/Engine/Blade.php b/lib/custom/src/MW/View/Engine/Blade.php index <HASH>..<HASH> 100644 --- a/lib/custom/src/MW/View/Engine/Blade.php +++ b/lib/custom/src/MW/View/Engine/Blade.php @@ -42,7 +42,7 @@ class Blade implements Iface * @return string Output generated by the template * @throws \Aimeos\MW\View\Exception If the template isn't found */ - public function render( \Aimeos\MW\View\Iface $view, $filename, array $values ) + public function render( \Aimeos\MW\View\Iface $view, string $filename, array $values ) : string { $factory = $this->factory; $lv = $factory->file( $filename, $values ); diff --git a/lib/custom/src/MW/View/Helper/Request/Laravel5.php b/lib/custom/src/MW/View/Helper/Request/Laravel5.php index <HASH>..<HASH> 100644 --- a/lib/custom/src/MW/View/Helper/Request/Laravel5.php +++ b/lib/custom/src/MW/View/Helper/Request/Laravel5.php @@ -47,7 +47,7 @@ class Laravel5 * * @return string Client IP address */ - public function getClientAddress() + public function getClientAddress() : string { return $this->request->ip(); } @@ -58,11 +58,13 @@ class Laravel5 * * @return string|null Current page or route name */ - public function getTarget() + public function getTarget() : ?string { if( ( $route = $this->request->route() ) !== null ) { return $route->getName(); } + + return null; } @@ -72,7 +74,7 @@ class Laravel5 * @param \Illuminate\Http\Request $nativeRequest Laravel request object * @return \Psr\Http\Message\ServerRequestInterface PSR-7 request object */ - protected function createRequest( \Illuminate\Http\Request $nativeRequest ) + protected function createRequest( \Illuminate\Http\Request $nativeRequest ) : \Psr\Http\Message\ServerRequestInterface { $files = ServerRequestFactory::normalizeFiles( $this->getFiles( $nativeRequest->files->all() ) ); $server = ServerRequestFactory::normalizeServer( $nativeRequest->server->all() ); @@ -102,7 +104,7 @@ class Laravel5 * @param array $files Multi-dimensional list of uploaded files from Symfony request * @return array Multi-dimensional list of uploaded files as PSR-7 objects */ - protected function getFiles( array $files ) + protected function getFiles( array $files ) : array { $list = []; diff --git a/lib/custom/src/MW/View/Helper/Url/Laravel5.php b/lib/custom/src/MW/View/Helper/Url/Laravel5.php index <HASH>..<HASH> 100644 --- a/lib/custom/src/MW/View/Helper/Url/Laravel5.php +++ b/lib/custom/src/MW/View/Helper/Url/Laravel5.php @@ -52,7 +52,8 @@ class Laravel5 * @param array $config Additional configuration parameter per URL * @return string Complete URL that can be used in the template */ - public function transform( $target = null, $controller = null, $action = null, array $params = [], array $trailing = [], array $config = [] ) + public function transform( string $target = null, string $controller = null, string $action = null, + array $params = [], array $trailing = [], array $config = [] ) : string { $params = $this->sanitize( $params ); $values = $this->getValues( $config ); @@ -68,7 +69,7 @@ class Laravel5 * @param array $config Associative list of key/value pairs * @return array Associative list of sanitized key/value pairs */ - protected function getValues( array $config ) + protected function getValues( array $config ) : array { $values = array( 'absoluteUri' => false,
Use PHP <I> type hints for view adapters and helpers
aimeos_ai-laravel
train
111e1d41471244780a4649e827dee848028fafd2
diff --git a/sdk/spring/spring-cloud-azure-service/src/main/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandler.java b/sdk/spring/spring-cloud-azure-service/src/main/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandler.java index <HASH>..<HASH> 100644 --- a/sdk/spring/spring-cloud-azure-service/src/main/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandler.java +++ b/sdk/spring/spring-cloud-azure-service/src/main/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandler.java @@ -29,6 +29,7 @@ import static org.apache.kafka.clients.CommonClientConfigs.BOOTSTRAP_SERVERS_CON public class KafkaOAuth2AuthenticateCallbackHandler implements AuthenticateCallbackHandler { private static final Duration ACCESS_TOKEN_REQUEST_BLOCK_TIME = Duration.ofSeconds(30); + private static final String TOKEN_AUDIENCE_FORMAT = "%s://%s/.default"; private final AzureKafkaProperties properties; private final AzureTokenCredentialResolver tokenCredentialResolver; @@ -59,7 +60,7 @@ public class KafkaOAuth2AuthenticateCallbackHandler implements AuthenticateCallb throw new IllegalArgumentException("Invalid bootstrap server configured for Azure Event Hubs for Kafka! The format should be {YOUR.EVENTHUBS.FQDN}:9093."); } URI uri = URI.create("https://" + bootstrapServer); - this.tokenAudience = uri.getScheme() + "://" + uri.getHost(); + this.tokenAudience = String.format(TOKEN_AUDIENCE_FORMAT, uri.getScheme(), uri.getHost()); credential = (TokenCredential) configs.get(AZURE_TOKEN_CREDENTIAL); AzureKafkaPropertiesUtils.convertConfigMapToAzureProperties(configs, properties); } diff --git a/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandlerTest.java b/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandlerTest.java index <HASH>..<HASH> 100644 --- a/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandlerTest.java +++ b/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/kafka/KafkaOAuth2AuthenticateCallbackHandlerTest.java @@ -30,6 +30,7 @@ class KafkaOAuth2AuthenticateCallbackHandlerTest { private static final List<String> KAFKA_BOOTSTRAP_SERVER = Arrays.asList("namespace.servicebus.windows.net:9093"); private static final String TOKEN_CREDENTIAL_FIELD_NAME = "credential"; + private static final String TOKEN_AUDIENCE_FIELD_NAME = "tokenAudience"; private static final String AZURE_THIRD_PARTY_SERVICE_PROPERTIES_FIELD_NAME = "properties"; private static final String GET_TOKEN_CREDENTIAL_METHOD_NAME = "getTokenCredential"; @@ -41,6 +42,18 @@ class KafkaOAuth2AuthenticateCallbackHandlerTest { }; @Test + void testTokenAudienceShouldConfig() { + Map<String, Object> configs = new HashMap<>(); + configs.put(BOOTSTRAP_SERVERS_CONFIG, KAFKA_BOOTSTRAP_SERVER); + + KafkaOAuth2AuthenticateCallbackHandler handler = new KafkaOAuth2AuthenticateCallbackHandler(); + handler.configure(configs, null, null); + + String tokenAudience = (String) ReflectionTestUtils.getField(handler, TOKEN_AUDIENCE_FIELD_NAME); + assertEquals("https://namespace.servicebus.windows.net/.default", tokenAudience); + } + + @Test void testTokenCredentialShouldConfig() { Map<String, Object> configs = new HashMap<>(); configs.put(BOOTSTRAP_SERVERS_CONFIG, KAFKA_BOOTSTRAP_SERVER);
fix scope for kafka token request (#<I>)
Azure_azure-sdk-for-java
train
713dd82d2f13d2b6d979c50c06f5cb16e886be4b
diff --git a/telemetry/telemetry/core/command_line.py b/telemetry/telemetry/core/command_line.py index <HASH>..<HASH> 100644 --- a/telemetry/telemetry/core/command_line.py +++ b/telemetry/telemetry/core/command_line.py @@ -46,13 +46,13 @@ class Command(ArgumentHandlerMixIn): raise NotImplementedError() @classmethod - def main(cls): + def main(cls, args=None): """Main method to run this command as a standalone script.""" parser = argparse.ArgumentParser() cls.AddCommandLineArgs(parser) - args = parser.parse_args() + args = parser.parse_args(args=args) cls.ProcessCommandLineArgs(parser, args) - return cls().Run(args) + return min(cls().Run(args), 255) # TODO: Convert everything to argparse. @@ -68,14 +68,14 @@ class OptparseCommand(Command): raise NotImplementedError() @classmethod - def main(cls): + def main(cls, args=None): """Main method to run this command as a standalone script.""" parser = cls.CreateParser() cls.AddCommandLineArgs(parser) - options, args = parser.parse_args() + options, args = parser.parse_args(args=args) options.positional_args = args cls.ProcessCommandLineArgs(parser, options) - return cls().Run(options) + return min(cls().Run(options), 255) class SubcommandCommand(Command):
[telemetry] Let main() take args as a parameter in addition to command-line. BUG=None. TEST=Run something. R=<EMAIL> Review URL: <URL>
catapult-project_catapult
train
bb61a9d0f9e3824139188896b1818f9fe5ada2ae
diff --git a/library/android-mvc/src/main/java/com/shipdream/lib/android/mvc/MvcActivity.java b/library/android-mvc/src/main/java/com/shipdream/lib/android/mvc/MvcActivity.java index <HASH>..<HASH> 100644 --- a/library/android-mvc/src/main/java/com/shipdream/lib/android/mvc/MvcActivity.java +++ b/library/android-mvc/src/main/java/com/shipdream/lib/android/mvc/MvcActivity.java @@ -33,6 +33,7 @@ import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import javax.inject.Inject; @@ -40,8 +41,9 @@ public abstract class MvcActivity extends AppCompatActivity { private Logger logger = LoggerFactory.getLogger(getClass()); static final String STATE_PREFIX = "$$$mvc:state:"; private static final String FRAGMENT_TAG_PREFIX = "__--AndroidMvc:Fragment:"; - private DelegateFragment delegateFragment; + protected DelegateFragment delegateFragment; boolean toPrintAppExitMessage = false; + private List<Runnable> actionsOnDestroy = new CopyOnWriteArrayList<>(); String getDelegateFragmentTag() { return FRAGMENT_TAG_PREFIX + getDelegateFragmentClass().getName(); @@ -87,6 +89,12 @@ public abstract class MvcActivity extends AppCompatActivity { Mvc.graph().getRootComponent().getCache()); toPrintAppExitMessage = false; } + + if (actionsOnDestroy != null) { + for (Runnable runnable : actionsOnDestroy) { + runnable.run(); + } + } } void performSuperBackKeyPressed() { @@ -664,7 +672,14 @@ public abstract class MvcActivity extends AppCompatActivity { NavLocation currentLoc = event.getCurrentValue(); if (currentLoc == null) { - destroyNavigator(event.getNavigator()); + MvcActivity act = (MvcActivity) getActivity(); + act.actionsOnDestroy.add(new Runnable() { + @Override + public void run() { + destroyNavigator(event.getNavigator()); + pendingNavActions.remove(this); + } + }); MvcActivity mvcActivity = ((MvcActivity) getActivity()); //Back to null which should finish the current activity
Delay calling onSettle of fragment last removed after the activity is destroyed
kejunxia_AndroidMvc
train
805a0b6a6010b3332da1b54e14f623e7795266df
diff --git a/src/org/jgroups/protocols/TP.java b/src/org/jgroups/protocols/TP.java index <HASH>..<HASH> 100644 --- a/src/org/jgroups/protocols/TP.java +++ b/src/org/jgroups/protocols/TP.java @@ -801,7 +801,11 @@ public abstract class TP extends Protocol { @ManagedOperation(description="Evicts elements in the logical address cache which have expired") public void evictLogicalAddressCache() { - logical_addr_cache.removeMarkedElements(); + evictLogicalAddressCache(false); + } + + public void evictLogicalAddressCache(boolean force) { + logical_addr_cache.removeMarkedElements(force); fetchLocalAddresses(); }
added evictLogicalAddressCache(boolean force)
belaban_JGroups
train
18cb8b1d9f5e870ebc57a1d2ddb520f44c324cf1
diff --git a/delocate/tests/test_libsana.py b/delocate/tests/test_libsana.py index <HASH>..<HASH> 100644 --- a/delocate/tests/test_libsana.py +++ b/delocate/tests/test_libsana.py @@ -168,13 +168,13 @@ def test_wheel_libs(): assert_equal(wheel_libs(PURE_WHEEL), {}) mod2 = pjoin('fakepkg1', 'subpkg', 'module2.cpython-39-darwin.so') rp_stray = realpath(STRAY_LIB_DEP) - assert_equal(wheel_libs(PLAT_WHEEL), - {rp_stray: {mod2: rp_stray}, - realpath(LIBSYSTEMB): {mod2: LIBSYSTEMB}}) + assert (wheel_libs(PLAT_WHEEL) == + {rp_stray: {mod2: rp_stray}, + realpath(LIBSYSTEMB): {mod2: LIBSYSTEMB}}) def filt(fname): return not fname.endswith(mod2) - assert_equal(wheel_libs(PLAT_WHEEL, filt), {}) + assert wheel_libs(PLAT_WHEEL, filt) == {} def test_resolve_rpath(): diff --git a/delocate/tests/test_scripts.py b/delocate/tests/test_scripts.py index <HASH>..<HASH> 100644 --- a/delocate/tests/test_scripts.py +++ b/delocate/tests/test_scripts.py @@ -77,8 +77,7 @@ def test_listdeps(): code, stdout, stderr = run_command( ['delocate-listdeps', 'pure', 'plat']) rp_stray = realpath(STRAY_LIB_DEP) - assert_equal(stdout, - ['pure:', 'plat:', rp_stray]) + assert stdout == ['pure:', 'plat:', rp_stray] assert_equal(code, 0) # With -d flag, get list of dependending modules code, stdout, stderr = run_command(
Try Kyle's suggestion of assert == for debugging
matthew-brett_delocate
train
6a6ed0e91d85b2eafc96bb519a687afa259611f9
diff --git a/src/sos/workflow_executor.py b/src/sos/workflow_executor.py index <HASH>..<HASH> 100755 --- a/src/sos/workflow_executor.py +++ b/src/sos/workflow_executor.py @@ -914,7 +914,7 @@ class Base_Executor: # and node._node_index == runnable._node_index + 1: node._context.update(env.sos_dict.clone_selected_vars( node._context['__signature_vars__'] | node._context['__environ_vars__'] - | {'_input', '__step_output__', '__default_output__', '__args__'})) + | {'_input', '__step_output__', '__args__'})) node._context.update(svar) node._context['__completed__'].append( res['__step_name__']) diff --git a/test/test_execute.py b/test/test_execute.py index <HASH>..<HASH> 100644 --- a/test/test_execute.py +++ b/test/test_execute.py @@ -1325,5 +1325,43 @@ print(_input) Base_Executor(wf).run() + def testMultiDepends(self): + '''Test a step with multiple depdendend steps''' + for file in ('dbsnp.vcf', 'hg19.fa', 'f1.fastq', 'f2.fastq', 'f1.bam', 'f2.bam', 'f1.bam.idx', 'f2.bam.idx'): + if os.path.isfile(file): + os.remove(file) + self.touch(['f1.fastq', 'f2.fastq']) + script = SoS_Script(''' +import time + +[refseq: provides='hg19.fa'] +time.sleep(1) +_output.touch() + +[dbsnp: provides='dbsnp.vcf'] +_output.touch() + +[align_10] +depends: 'hg19.fa' +input: 'f1.fastq', 'f2.fastq', group_by=1, concurrent=True +output: _input.with_suffix('.bam') +_output.touch() + +[align_20] +input: group_by=1, concurrent=True +output: _input.with_suffix('.bam.idx') +_output.touch() + +[call_10] +depends: 'dbsnp.vcf', 'hg19.fa' + +[call_20] +''') + wf = script.workflow('align+call') + Base_Executor(wf).run() + for file in ('dbsnp.vcf', 'hg19.fa', 'f1.bam', 'f2.bam', 'f1.bam.idx', 'f2.bam.idx'): + self.assertTrue(os.path.isfile(file)) + + if __name__ == '__main__': unittest.main()
Stop passing __default_output__ from auxiliary step to the next
vatlab_SoS
train
b1dc6c8f99478d887378fdf5bb791462e73ef38f
diff --git a/tests/WithDb/SelectTest.php b/tests/WithDb/SelectTest.php index <HASH>..<HASH> 100644 --- a/tests/WithDb/SelectTest.php +++ b/tests/WithDb/SelectTest.php @@ -81,6 +81,8 @@ class SelectTest extends AtkPhpunit\TestCase protected function tearDown(): void { $this->dropDbIfExists(); + + $this->c = null; } private function q($table = null, $alias = null) diff --git a/tests/WithDb/TransactionTest.php b/tests/WithDb/TransactionTest.php index <HASH>..<HASH> 100644 --- a/tests/WithDb/TransactionTest.php +++ b/tests/WithDb/TransactionTest.php @@ -81,6 +81,8 @@ class TransactionTest extends AtkPhpunit\TestCase protected function tearDown(): void { $this->dropDbIfExists(); + + $this->c = null; } private function q($table = null, $alias = null)
[fix] destroy connection on test teardown (#<I>)
atk4_dsql
train
baab29e2d5a050dc1b118e1b769b8f3e454f5a52
diff --git a/lib/Less/Tree/Ruleset.php b/lib/Less/Tree/Ruleset.php index <HASH>..<HASH> 100755 --- a/lib/Less/Tree/Ruleset.php +++ b/lib/Less/Tree/Ruleset.php @@ -315,13 +315,7 @@ class Less_Tree_Ruleset extends Less_Tree{ Less_Environment::$lastRule = true; } - if( is_object($rule) ){ - if( method_exists($rule,'genCSS') ){ - $rule->genCSS( $output ); - }elseif( property_exists($rule,'value') && $rule->value ){ - $output->add( (string)$rule->value ); - } - } + $rule->genCSS( $output ); if( !Less_Environment::$lastRule ){ $output->add( Less_Environment::$compress ? '' : ("\n" . $tabRuleStr) );
$rule always has genCSS()
oyejorge_less.php
train
27c3c5415f6b3ab1b1f0f4496a1ac78e6195e3db
diff --git a/cmd/web.go b/cmd/web.go index <HASH>..<HASH> 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -372,7 +372,7 @@ func runWeb(ctx *cli.Context) { }, reqSignIn) m.Group("/org", func() { m.Get("/:org", org.Home) - }, middleware.OrgAssignment(true)) + }, ignSignIn, middleware.OrgAssignment(true)) // Repository. m.Group("/repo", func() {
#<I> Anyone can see organization pages even without logging in when sign in required
gogs_gogs
train
acc30505d9da1a440ff7424ff8db64464157a14d
diff --git a/jython/src/main/java/cucumber/runtime/jython/JythonBackend.java b/jython/src/main/java/cucumber/runtime/jython/JythonBackend.java index <HASH>..<HASH> 100644 --- a/jython/src/main/java/cucumber/runtime/jython/JythonBackend.java +++ b/jython/src/main/java/cucumber/runtime/jython/JythonBackend.java @@ -36,7 +36,7 @@ public class JythonBackend implements Backend { this.jython = jython; jython.set("backend", this); - for (Resource resource : resourceLoader.resources("classpath:cucumber/runtime/jython", ".py")) { + for (Resource resource : resourceLoader.resources("classpath:cucumber/runtime/jython", "dsl.py")) { runScript(resource); } }
Only load the dsl.py when initializing the JythonBackend The jython build will fail if a cucumber/runtime/jython/i<I>n/<i<I>n>.py file is loaded before the dsl.py.
cucumber_cucumber-jvm
train
351045bd1c191f59f61594f30ab734f98292fbd4
diff --git a/core/FramebackController.js b/core/FramebackController.js index <HASH>..<HASH> 100644 --- a/core/FramebackController.js +++ b/core/FramebackController.js @@ -102,7 +102,7 @@ class FramebackController { setTitleFromFrame(){ var doc = this.frame.contentDocument; - if (doc.readyState === 'complete' && this.active){ + if (doc.title && this.active){ document.title = doc.title; } }
Direct title cutover without loading unset
redfin_react-server
train
1e0b98ed0e431d0f82b57906ff21627656596b2d
diff --git a/generator/classes/propel/engine/builder/om/php5/PHP5BasicObjectBuilder.php b/generator/classes/propel/engine/builder/om/php5/PHP5BasicObjectBuilder.php index <HASH>..<HASH> 100644 --- a/generator/classes/propel/engine/builder/om/php5/PHP5BasicObjectBuilder.php +++ b/generator/classes/propel/engine/builder/om/php5/PHP5BasicObjectBuilder.php @@ -602,34 +602,6 @@ abstract class ".$this->getClassname()." extends ".ClassTools::classname($this-> { try { "; -/* - - const CHAR = "CHAR"; - const VARCHAR = "VARCHAR"; - const LONGVARCHAR = "LONGVARCHAR"; - const CLOB = "CLOB"; - const NUMERIC = "NUMERIC"; - const DECIMAL = "DECIMAL"; - const TINYINT = "TINYINT"; - const SMALLINT = "SMALLINT"; - const INTEGER = "INTEGER"; - const BIGINT = "BIGINT"; - const REAL = "REAL"; - const FLOAT = "FLOAT"; - const DOUBLE = "DOUBLE"; - const BINARY = "BINARY"; - const VARBINARY = "VARBINARY"; - const LONGVARBINARY = "LONGVARBINARY"; - const BLOB = "BLOB"; - const DATE = "DATE"; - const TIME = "TIME"; - const TIMESTAMP = "TIMESTAMP"; - - const BU_DATE = "BU_DATE"; - const BU_TIMESTAMP = "BU_TIMESTAMP"; - - const BOOLEAN = "BOOLEAN"; -*/ $n = 0; foreach($table->getColumns() as $col) { if(!$col->isLazyLoad()) {
Removed left-over hints from changeset:<I>
propelorm_Propel
train
00c59d1b4fa0d696cee3dd4714d5fff1633649fb
diff --git a/sync.js b/sync.js index <HASH>..<HASH> 100644 --- a/sync.js +++ b/sync.js @@ -50,9 +50,13 @@ exports.sync = (function() { if(!itemToPull) { localStorage.setItem('_shadowSyncStatus', 'idle'); } else { - backend.get(itemToPull, function(msg) { - console.log('error retrieving "'+itemToPull+'":'+msg); - if((itemToPull == '_shadowIndex') && (msg==404)) { + var remoteKeyName = itemToPull; + if(itemToPull != '_shadowIndex') { + remoteKeyName += '_'+JSON.parse(localStorage.getItem('_shadowIndex'))[itemToPull]; + } + backend.get(remoteKeyName, function(msg) { + console.log('error retrieving "'+remoteKeyName+'":'+msg); + if((remoteKeyName == '_shadowIndex') && (msg==404)) { console.log('virgin remote'); localStorage.setItem('_shadowRemote', JSON.stringify({})); localStorage.setItem('_shadowSyncStatus', 'idle');
append timestamps when pulling, too
remotestorage_remotestorage.js
train
456ac01890d532ceefdfa99e94983971f554f894
diff --git a/lib/jekyll/configuration.rb b/lib/jekyll/configuration.rb index <HASH>..<HASH> 100644 --- a/lib/jekyll/configuration.rb +++ b/lib/jekyll/configuration.rb @@ -102,7 +102,10 @@ module Jekyll def config_files(override) # Get configuration from <source>/_config.yml or <source>/<config_file> config_files = override.delete('config') - config_files = File.join(source(override), "_config.yml") if config_files.to_s.empty? + if config_files.to_s.empty? + config_files = File.join(source(override), "_config.yml") + @default_config_file = true + end config_files = [config_files] unless config_files.is_a? Array config_files end @@ -117,6 +120,14 @@ module Jekyll raise "Configuration file: (INVALID) #{file}".yellow if !next_config.is_a?(Hash) Jekyll.logger.info "Configuration file:", file next_config + rescue SystemCallError + if @default_config_file + Jekyll::Logger.warn "Configuration file:", "none" + {} + else + Jekyll::Logger.error "Fatal:", "The configuration file '#{file}' could not be found." + exit(1) + end end # Public: Read in a list of configuration files and merge with this hash @@ -133,9 +144,6 @@ module Jekyll new_config = read_config_file(config_file) configuration = configuration.deep_merge(new_config) end - rescue SystemCallError - # Errno:ENOENT = file not found - Jekyll.logger.warn "Configuration file:", "none" rescue => err Jekyll.logger.warn "WARNING:", "Error reading configuration. " + "Using defaults (and options)."
Crash if a config file isn't there. If a configuration file is specified via the command line but does not exist, fail loudly and crash to preserve the current state. Do not fail if the requested file is the default configuration file, _config.yml. In that case, fall back on the defaults.
jekyll_jekyll
train
312b234ddb7c447a38acac409bf545f8e16ed367
diff --git a/integration/connection.py b/integration/connection.py index <HASH>..<HASH> 100644 --- a/integration/connection.py +++ b/integration/connection.py @@ -45,10 +45,11 @@ class Connection_(Spec): # Most Unix systems should have stty, which asplodes when not run # under a pty, and prints useful info otherwise result = Connection('localhost').run( - 'stty -a', hide=True, pty=True, + 'stty size', hide=True, pty=True, ) + found = result.stdout.strip().split() cols, rows = pty_size() - ok_("{0} rows; {1} columns;".format(rows, cols) in result.stdout) + eq_(tuple(map(int, found)), (rows, cols)) # PTYs use \r\n, not \n, line separation ok_("\r\n" in result.stdout) eq_(result.pty, True)
stty -a behaves differently xplatform; stty size appears not to
fabric_fabric
train
1e2e3167e9b38aea47dd6721f49cbfe80b48a664
diff --git a/structr-ui/src/test/java/org/structr/test/web/advanced/PerformanceTest.java b/structr-ui/src/test/java/org/structr/test/web/advanced/PerformanceTest.java index <HASH>..<HASH> 100644 --- a/structr-ui/src/test/java/org/structr/test/web/advanced/PerformanceTest.java +++ b/structr-ui/src/test/java/org/structr/test/web/advanced/PerformanceTest.java @@ -119,7 +119,7 @@ public class PerformanceTest extends IndexingTest { Double rate = number / ((t1 - t0) / 1000.0); logger.info("Created {} nodes in {} seconds ({} per s)", number, decimalFormat.format(time), decimalFormat.format(rate) ); - assertTrue("Creation rate of nodes too low, expected > 100, was " + rate, rate > 50); + assertTrue("Creation rate of nodes too low, expected > 40, was " + rate, rate > 40); } /** @@ -372,7 +372,7 @@ public class PerformanceTest extends IndexingTest { Double rate = number / ((t1 - t0) / 1000.0); logger.info("Deleted {} nodes in {} seconds ({} per s)", number, decimalFormat.format(time), decimalFormat.format(rate) ); - assertTrue("Deletion rate of nodes too low, expected > 100, was " + rate, rate > 50); + assertTrue("Deletion rate of nodes too low, expected > 40, was " + rate, rate > 40); } // ----- private methods -----
Trying to fix performance test by lowering performance expectations.
structr_structr
train
ca79aa5efdc6592f4f2002ed37fd28cdbb5ec901
diff --git a/phoebe/backend/universe.py b/phoebe/backend/universe.py index <HASH>..<HASH> 100644 --- a/phoebe/backend/universe.py +++ b/phoebe/backend/universe.py @@ -2580,6 +2580,7 @@ class BodyBag(Body): @param list_of_bodies: list of bodies @type list_of_bodies: list """ + self.signals = {} self.label = None if not isinstance(list_of_bodies,list): list_of_bodies = [list_of_bodies] @@ -4147,17 +4148,7 @@ class BinaryRocheStar(PhysicalBody): ld_law = 5 ldbol_law = 5 new_dtypes = [] - if self.mesh is None: - dim = 3 - ft = 'f8' - old_dtypes = [('_o_center',ft,(dim,)),('_o_size',ft),('_o_triangle',ft,(3*dim,)),('_o_normal_',ft,(dim,)), - ('center',ft,(dim,)),('size',ft),('triangle',ft,(3*dim,)),('normal_',ft,(dim,)), - ('_o_velo___bol_',ft,(dim,)),('velo___bol_',ft,(dim,)),('mu',ft), - ('partial',bool),('hidden',bool),('visible',bool)] - self.mesh = np.zeros(0,dtype=old_dtypes) - old_dtypes = self.mesh.dtype.names - #-- check if the following required labels are in the mesh, if they # are not, we'll have to add them required = [('ld___bol','f8',(5,)),('proj___bol','f8'), @@ -4655,15 +4646,6 @@ class MisalignedBinaryRocheStar(BinaryRocheStar): ld_law = 5 ldbol_law = 5 new_dtypes = [] - if self.mesh is None: - dim = 3 - ft = 'f8' - old_dtypes = [('_o_center',ft,(dim,)),('_o_size',ft),('_o_triangle',ft,(3*dim,)),('_o_normal_',ft,(dim,)), - ('center',ft,(dim,)),('size',ft),('triangle',ft,(3*dim,)),('normal_',ft,(dim,)), - ('_o_velo___bol_',ft,(dim,)),('velo___bol_',ft,(dim,)),('mu',ft), - ('partial',bool),('hidden',bool),('visible',bool)] - self.mesh = np.zeros(0,dtype=old_dtypes) - old_dtypes = self.mesh.dtype.names #-- check if the following required labels are in the mesh, if they # are not, we'll have to add them
mesh view updating is now hooked to system.set_time, so should update when running a model or calling set_time
phoebe-project_phoebe2
train
03cb1c6d74572764642e755ee3e8bddf8990ccae
diff --git a/crosspm/cpm.py b/crosspm/cpm.py index <HASH>..<HASH> 100644 --- a/crosspm/cpm.py +++ b/crosspm/cpm.py @@ -244,7 +244,7 @@ class CrossPM: return self._output.output_type_module(cpm_downloader.get_tree_packages()) else: # self._output.write(params, packages) - self._output.write(params, cpm_downloader.get_tree_packages()) + self._output.write_output(params, cpm_downloader.get_tree_packages()) return '' def lock(self):
write_output in cpm.py
devopshq_crosspm
train
7360452d2a4f6f45224562bb00aedda8abdd9222
diff --git a/python/ray/data/_internal/compute.py b/python/ray/data/_internal/compute.py index <HASH>..<HASH> 100644 --- a/python/ray/data/_internal/compute.py +++ b/python/ray/data/_internal/compute.py @@ -184,6 +184,8 @@ class ActorPoolStrategy(ComputeStrategy): self.min_size = min_size self.max_size = max_size or float("inf") self.max_tasks_in_flight_per_actor = max_tasks_in_flight_per_actor + self.num_workers = 0 + self.ready_to_total_workers_ratio = 0.8 def _apply( self, @@ -265,7 +267,7 @@ class ActorPoolStrategy(ComputeStrategy): block, block_fn, input_files, self.fn, *fn_args, **fn_kwargs ) - if not remote_args: + if "num_cpus" not in remote_args: remote_args["num_cpus"] = 1 if "scheduling_strategy" not in remote_args: @@ -295,7 +297,8 @@ class ActorPoolStrategy(ComputeStrategy): if not ready: if ( len(workers) < self.max_size - and len(ready_workers) / len(workers) > 0.8 + and len(ready_workers) / len(workers) + > self.ready_to_total_workers_ratio ): w = BlockWorker.remote( *fn_constructor_args, **fn_constructor_kwargs @@ -351,6 +354,7 @@ class ActorPoolStrategy(ComputeStrategy): tasks_in_flight[worker] += 1 map_bar.close() + self.num_workers += len(workers) new_blocks, new_metadata = [], [] # Put blocks in input order. results.sort(key=block_indices.get) diff --git a/python/ray/data/tests/test_dataset.py b/python/ray/data/tests/test_dataset.py index <HASH>..<HASH> 100644 --- a/python/ray/data/tests/test_dataset.py +++ b/python/ray/data/tests/test_dataset.py @@ -4219,7 +4219,7 @@ def test_polars_lazy_import(shutdown_only): ctx.use_polars = original_use_polars -def test_actorpoolstrategy_apply_interrupt(): +def test_actor_pool_strategy_apply_interrupt(shutdown_only): """Test that _apply kills the actor pool if an interrupt is raised.""" ray.init(include_dashboard=False, num_cpus=1) @@ -4244,6 +4244,26 @@ def test_actorpoolstrategy_apply_interrupt(): wait_for_condition(lambda: (ray.available_resources().get("CPU", 0) == cpus)) +def test_actor_pool_strategy_default_num_actors(shutdown_only): + def f(x): + import time + + time.sleep(1) + return x + + num_cpus = 5 + ray.init(num_cpus=num_cpus) + compute_strategy = ray.data.ActorPoolStrategy() + ray.data.range(10, parallelism=10).map_batches(f, compute=compute_strategy) + expected_max_num_workers = math.ceil( + num_cpus * (1 / compute_strategy.ready_to_total_workers_ratio) + ) + assert ( + compute_strategy.num_workers >= num_cpus + and compute_strategy.num_workers <= expected_max_num_workers + ), "Number of actors is out of the expected bound" + + if __name__ == "__main__": import sys
[Datasets] Fix max number of actors for default actor pool strategy (#<I>)
ray-project_ray
train
c8c24fd7a0e6d72d336682233cf87850e0fabc9f
diff --git a/aioimaplib/aioimaplib.py b/aioimaplib/aioimaplib.py index <HASH>..<HASH> 100644 --- a/aioimaplib/aioimaplib.py +++ b/aioimaplib/aioimaplib.py @@ -444,7 +444,7 @@ def _split_responses(data): return [] match_fetch_message = fetch_message_with_literal_data_re.match(data) if match_fetch_message: - head, _, tail = data.partition(CRLF) + head, crlf, tail = data.partition(CRLF) msg_size = match_fetch_message.group('size') # we want to cut ----------------------- # ...here | @@ -452,7 +452,7 @@ def _split_responses(data): # b'* 3 FETCH (UID 3 RFC822 {4}\r\nmail)\r\n... end_message_index_with_parenthesis = int(msg_size) + 1 - fetch_line = b'* FETCH ' + tail[0:end_message_index_with_parenthesis] + fetch_line = head + crlf + tail[0:end_message_index_with_parenthesis] after_fetch = tail[end_message_index_with_parenthesis:].strip() return [fetch_line] + _split_responses(after_fetch) diff --git a/aioimaplib/tests/test_aioimaplib.py b/aioimaplib/tests/test_aioimaplib.py index <HASH>..<HASH> 100644 --- a/aioimaplib/tests/test_aioimaplib.py +++ b/aioimaplib/tests/test_aioimaplib.py @@ -36,16 +36,16 @@ class TestAioimaplibUtils(unittest.TestCase): _split_responses(b'* BYE Logging out\r\nCAPB2 OK LOGOUT completed\r\n')) def test_split_responses_with_message_data(self): - self.assertEquals([b'* FETCH ...\r\n(mail content)\r\n...\r\n)', + self.assertEquals([b'* 1 FETCH (UID 1 RFC822 {26}\r\n...\r\n(mail content)\r\n...\r\n)', b'TAG OK FETCH completed.'], _split_responses( b'* 1 FETCH (UID 1 RFC822 {26}\r\n...\r\n(mail content)\r\n...\r\n)\r\n' b'TAG OK FETCH completed.')) def test_split_responses_with_two_messages_data(self): - self.assertEquals([b'* FETCH mail 1\r\n)', + self.assertEquals([b'* 3 FETCH (UID 3 RFC822 {8}\r\nmail 1\r\n)', b'* 1 FETCH (UID 10 FLAGS (FOO))', - b'* FETCH mail 2\r\n)', + b'* 4 FETCH (UID 4 RFC822 {8}\r\nmail 2\r\n)', b'TAG OK FETCH completed.'], _split_responses( b'* 3 FETCH (UID 3 RFC822 {8}\r\nmail 1\r\n)\r\n'
[fix] _split_responses was destructive
bamthomas_aioimaplib
train
59b0f7973f70fef1066cb206a31deadbb4620b65
diff --git a/rating/rate.php b/rating/rate.php index <HASH>..<HASH> 100644 --- a/rating/rate.php +++ b/rating/rate.php @@ -49,13 +49,14 @@ if (!confirm_sesskey() || $USER->id==$rateduserid) { die(); } +$rm = new rating_manager(); + //check the module rating permissions $pluginrateallowed = true; $pluginpermissionsarray = null; if ($context->contextlevel==CONTEXT_MODULE) { $plugintype = 'mod'; $pluginname = $cm->modname; - $rm = new rating_manager(); $pluginpermissionsarray = $rm->get_plugin_permissions_array($context->id, $plugintype, $pluginname); $pluginrateallowed = $pluginpermissionsarray['rate'];
rating MDL-<I> instantiate rating manager outside the "if" brackets because it is used in different "if" brackets
moodle_moodle
train
8d323fd26a77be6e52ea1a854bf94a8913e9f863
diff --git a/src/Concerns/ManagesInvoices.php b/src/Concerns/ManagesInvoices.php index <HASH>..<HASH> 100644 --- a/src/Concerns/ManagesInvoices.php +++ b/src/Concerns/ManagesInvoices.php @@ -65,6 +65,45 @@ trait ManagesInvoices } /** + * Add an invoice item for a specific Price ID to the customer's upcoming invoice. + * + * @param string $price + * @param int $quantity + * @param array $options + * @return \Stripe\InvoiceItem + */ + public function tabPrice($price, $quantity = 1, array $options = []) + { + $this->assertCustomerExists(); + + $options = array_merge([ + 'customer' => $this->stripe_id, + 'price' => $price, + 'quantity' => $quantity, + ], $options); + + return $this->stripe()->invoiceItems->create($options); + } + + /** + * Invoice the customer for the given Price ID and generate an invoice immediately. + * + * @param string $price + * @param int $quantity + * @param array $tabOptions + * @param array $invoiceOptions + * @return \Laravel\Cashier\Invoice|bool + * + * @throws \Laravel\Cashier\Exceptions\IncompletePayment + */ + public function invoicePrice($price, $quantity = 1, array $tabOptions = [], array $invoiceOptions = []) + { + $this->tabPrice($price, $quantity, $tabOptions); + + return $this->invoice($invoiceOptions); + } + + /** * Invoice the customer outside of the regular billing cycle. * * @param array $options diff --git a/tests/Feature/InvoicesTest.php b/tests/Feature/InvoicesTest.php index <HASH>..<HASH> 100644 --- a/tests/Feature/InvoicesTest.php +++ b/tests/Feature/InvoicesTest.php @@ -42,6 +42,26 @@ class InvoicesTest extends FeatureTestCase $this->assertEquals(49900, $response->total); } + public function test_customer_can_be_invoiced_with_a_price() + { + $user = $this->createCustomer('customer_can_be_invoiced'); + $user->createAsStripeCustomer(); + $user->updateDefaultPaymentMethod('pm_card_visa'); + + $price = $user->stripe()->prices->create([ + 'currency' => $user->preferredCurrency(), + 'product_data' => [ + 'name' => 'Laravel T-shirt', + ], + 'unit_amount' => 499, + ]); + + $response = $user->invoicePrice($price, 2); + + $this->assertInstanceOf(Invoice::class, $response); + $this->assertEquals(998, $response->total); + } + public function test_find_invoice_by_id() { $user = $this->createCustomer('find_invoice_by_id');
Add invoicePrice method (#<I>)
laravel_cashier
train
d750883929826782ea4ad966451eacdea4e0ae5a
diff --git a/models/classes/class.ReportService.php b/models/classes/class.ReportService.php index <HASH>..<HASH> 100755 --- a/models/classes/class.ReportService.php +++ b/models/classes/class.ReportService.php @@ -189,7 +189,7 @@ extends taoResults_models_classes_StatisticsService $graph->drawRoundedRectangle(5,5,655,225,5,230,230,230); $graph->drawGraphArea(255,255,255,true); - $graph->drawScale($dataSet->GetData(),$dataSet->GetDataDescription(), SCALE_START0,150,150,150,TRUE,0,2,TRUE); + $graph->drawScale($dataSet->GetData(),$dataSet->GetDataDescription(), SCALE_START0,150,150,150,true,0,2,true); $graph->drawGrid(4,true,230,230,230,50); // Draw the 0 line @@ -199,7 +199,7 @@ extends taoResults_models_classes_StatisticsService // Draw the bar graph switch ($type){ - case "bar":{$graph->drawBarGraph($dataSet->GetData(),$dataSet->GetDataDescription(),TRUE);break;} + case "bar":{$graph->drawBarGraph($dataSet->GetData(),$dataSet->GetDataDescription(),true);break;} case "line":{ $graph->drawLineGraph($dataSet->GetData(),$dataSet->GetDataDescription()); $graph->drawPlotGraph($dataSet->GetData(),$dataSet->GetDataDescription(),3,2,255,255,255); break; @@ -243,7 +243,7 @@ extends taoResults_models_classes_StatisticsService // Draw the radar graph - $graph->drawRadarAxis($dataSet->GetData(),$dataSet->GetDataDescription(),TRUE,20,120,120,120,5,5,5); + $graph->drawRadarAxis($dataSet->GetData(),$dataSet->GetDataDescription(),true,20,120,120,120,5,5,5); $graph->drawFilledRadar($dataSet->GetData(),$dataSet->GetDataDescription(),50,20); // Finish the graph
TRUE, FALSE and NULL must be lowercase; expected "false" but found "FALSE" git-svn-id: <URL>
oat-sa_extension-tao-outcomeui
train
cb4999966f9fdf9e3c12b55a96599a90328c5ab7
diff --git a/spec/dragonfly/image_magick/processor_spec.rb b/spec/dragonfly/image_magick/processor_spec.rb index <HASH>..<HASH> 100644 --- a/spec/dragonfly/image_magick/processor_spec.rb +++ b/spec/dragonfly/image_magick/processor_spec.rb @@ -118,10 +118,10 @@ describe Dragonfly::ImageMagick::Processor do image1 = @processor.crop(@image, :x => '10', :y => '10', :width => '100', :height => '100') @image1 = Dragonfly::TempObject.new(image1) image2 = @processor.crop(@image1, :x => '0' , :y => '0' , :width => '50' , :height => '50' ) - image_properties(image2)[:width].to_i.should eql(50) - image_properties(image2)[:height].to_i.should eql(50) - # image2.should have_width(50) - # image2.should have_height(50) + image2.should_not have_width(40) + image2.should_not have_height(40) + image2.should have_width(50) + image2.should have_height(50) end end
adjust test to use more readable matchers
markevans_dragonfly
train
44fb6564ce585657883cc12bae2124e59777bcbb
diff --git a/routey.js b/routey.js index <HASH>..<HASH> 100644 --- a/routey.js +++ b/routey.js @@ -29,10 +29,14 @@ module.exports = function (config, app) { var routeInitalizer = new RouteInitalizer(config, app); + + var defaultParentRoute = '/'; + var parentRoute = config.parentRoute || defaultParentRoute; + var routeConfigDir = { name: path.basename(config.routeConfigPath), path: config.routeConfigPath, - parentRoute: '/', + parentRoute: parentRoute, isRoot: true, }; diff --git a/routey.spec.js b/routey.spec.js index <HASH>..<HASH> 100644 --- a/routey.spec.js +++ b/routey.spec.js @@ -62,9 +62,11 @@ describe('routey', function () { var parentDir = 'parent'; var childDir = 'child'; var fullPath = parentDir + '/' + childDir; + var parentRoute = '/myparent'; var config = { routeConfigPath: fullPath, + parentRoute: parentRoute, }; var app = {}; @@ -73,9 +75,29 @@ describe('routey', function () { expect(mockRouteyInit._processDirectory).toHaveBeenCalledWith({ name: childDir, path: fullPath, - parentRoute: '/', + parentRoute: parentRoute, isRoot: true, }); }); + it('parent route is defaulted when not specified', function () { + + var parentDir = 'parent'; + var childDir = 'child'; + var fullPath = parentDir + '/' + childDir; + + var config = { + routeConfigPath: fullPath, + }; + var app = {}; + + routey(config, app); + + expect(mockRouteyInit._processDirectory).toHaveBeenCalledWith({ + name: childDir, + path: fullPath, + parentRoute: '/', + isRoot: true, + }); + }); }); \ No newline at end of file
Parent route is now passed in through external interface, it defaults when not specified.
ashleydavis_routey
train
a1b95202344145cdcacc05ef1f5b0850057e309b
diff --git a/src/Voucher.php b/src/Voucher.php index <HASH>..<HASH> 100644 --- a/src/Voucher.php +++ b/src/Voucher.php @@ -35,6 +35,9 @@ class Voucher if(isset($options['cardNumber'])){ $api->setCardNumber($options['cardNumber']); } + if(isset($options['pincode'])){ + $api->setPincode($options['pincode']); + } $result = $api->doRequest(); return $result['balance'] / 100; @@ -88,4 +91,4 @@ class Voucher return $result['request']['result'] == 1; } -} \ No newline at end of file +}
add pincode optional for voucher balance checks fashioncheque requires a pincode to retrieve the balance. this is currently unsupported.
paynl_sdk
train
4455fa9b2e295d36a9b4a8702a022de1d4cb0f76
diff --git a/pingparsing/cli.py b/pingparsing/cli.py index <HASH>..<HASH> 100644 --- a/pingparsing/cli.py +++ b/pingparsing/cli.py @@ -12,11 +12,11 @@ from datetime import datetime from textwrap import dedent import humanreadable as hr -import logbook from subprocrunner import CommandError +from pingparsing._logger import logger, set_logger + from .__version__ import __version__ -from ._logger import set_log_level from ._pingparsing import PingParsing from ._pingtransmitter import PingTransmitter @@ -28,7 +28,7 @@ except ImportError: DEFAULT_COUNT = 10 -QUIET_LOG_LEVEL = logbook.NOTSET +QUIET_LOG_LEVEL = "QUIET" TIMESTAMP_TYPES = (int, float, str) @@ -39,7 +39,12 @@ class TimestampFormat: LIST = (NONE, EPOCH, DATETIME) -def _get_unit_help_msg(): +class LogLevel: + DEBUG = "DEBUG" + INFO = "INFO" + + +def _get_unit_help_msg() -> str: return ", ".join(["/".join(values) for values in hr.Time.get_text_units().values()]) @@ -94,8 +99,8 @@ def parse_option(): "--debug", dest=loglevel_dest, action="store_const", - const=logbook.DEBUG, - default=logbook.INFO, + const=LogLevel.DEBUG, + default=LogLevel.INFO, help="for debug print.", ) group.add_argument( @@ -103,7 +108,7 @@ def parse_option(): dest=loglevel_dest, action="store_const", const=QUIET_LOG_LEVEL, - default=logbook.INFO, + default=LogLevel.INFO, help="suppress execution log messages.", ) @@ -164,24 +169,23 @@ def parse_option(): return parser.parse_args() -def initialize_log_handler(log_level): - from logbook.more import ColorizedStderrHandler +def initialize_logger(log_level): + logger.remove() - debug_level_format_str = ( - "[{record.level_name}] {record.channel} {record.func_name} " - "({record.lineno}): {record.message}" - ) - if log_level == logbook.DEBUG: - info_level_format_str = debug_level_format_str + if log_level == QUIET_LOG_LEVEL: + set_logger(is_enable=False) + return + + if log_level == "DEBUG": + log_format = ( + "<level>{level: <8}</level> | " + "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>" + ) else: - info_level_format_str = "[{record.level_name}] {record.channel}: {record.message}" + log_format = "<level>[{level}]</level> {message}" - ColorizedStderrHandler( - level=logbook.DEBUG, format_string=debug_level_format_str - ).push_application() - ColorizedStderrHandler( - level=logbook.INFO, format_string=info_level_format_str - ).push_application() + logger.add(sys.stdout, colorize=True, format=log_format, level=log_level, enqueue=True) + set_logger(is_enable=True) def is_use_stdin(): @@ -193,9 +197,7 @@ def is_use_stdin(): return (len(sys.argv) == 1 or found_stdin_specifier, found_stdin_specifier) -def parse_ping( - logger, dest_or_file, interface, count, deadline, timeout, is_parse_icmp_reply, timestamp -): +def parse_ping(dest_or_file, interface, count, deadline, timeout, is_parse_icmp_reply, timestamp): if os.path.isfile(dest_or_file): with open(dest_or_file) as f: ping_result_text = f.read() @@ -299,11 +301,7 @@ def dumps_dict(obj, timestamp_format, indent=0): def main(): options = parse_option() - initialize_log_handler(options.log_level) - - logger = logbook.Logger("pingparsing cli") - logger.level = options.log_level - set_log_level(options.log_level) + initialize_logger(options.log_level) output = {} use_stdin, found_stdin_specifier = is_use_stdin() @@ -324,11 +322,9 @@ def main(): with futures.ProcessPoolExecutor(max_workers) as executor: future_list = [] for dest_or_file in options.destination_or_file: - logger.debug("start {}".format(dest_or_file)) future_list.append( executor.submit( parse_ping, - logger, dest_or_file, options.interface, count, @@ -343,7 +339,6 @@ def main(): key, ping_data = future.result() output[key] = ping_data finally: - logger.debug("shutdown ProcessPoolExecutor") executor.shutdown() else: ping_result_text = sys.stdin.read()
Replace the logging library of the CLI tool
thombashi_pingparsing
train
ccd37de6f976a52e8de6edd0555881b47de8e5e1
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,9 @@ post, it can be solved by explicitly install the `matplotlib` dependency `dvipng ### Update History +##### 0.24.2 +* Fixing bug in `get_correlations`. + ##### 0.24.1 * Changing default colour order. * Improving behaviour of `shade_gradient`. diff --git a/chainconsumer/analysis.py b/chainconsumer/analysis.py index <HASH>..<HASH> 100644 --- a/chainconsumer/analysis.py +++ b/chainconsumer/analysis.py @@ -170,7 +170,7 @@ class Analysis(object): """ parameters, cov = self.get_covariance(chain=chain, parameters=parameters) diag = np.sqrt(np.diag(cov)) - divisor = np.sqrt(diag[None, :] * diag[:, None]) + divisor = diag[None, :] * diag[:, None] correlations = cov / divisor return parameters, correlations diff --git a/chainconsumer/chainconsumer.py b/chainconsumer/chainconsumer.py index <HASH>..<HASH> 100644 --- a/chainconsumer/chainconsumer.py +++ b/chainconsumer/chainconsumer.py @@ -18,7 +18,7 @@ class ChainConsumer(object): figures, tables, diagnostics, you name it. """ - __version__ = "0.24.1" + __version__ = "0.24.2" def __init__(self): logging.basicConfig() diff --git a/tests/test_analysis.py b/tests/test_analysis.py index <HASH>..<HASH> 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -599,8 +599,21 @@ class TestChain(object): assert np.abs(cor[0, 2] - 0.5) < 0.01 assert np.abs(cor[1, 2] - 0.2) < 0.01 + def test_correlations_2d_non_unitary(self): + data = np.random.multivariate_normal([0, 0], [[4, 0], [0, 4]], size=100000) + parameters = ["x", "y"] + c = ChainConsumer() + c.add_chain(data, parameters=parameters) + p, cor = c.analysis.get_correlations() + assert p[0] == "x" + assert p[1] == "y" + assert np.isclose(cor[0, 0], 1, atol=1e-2) + assert np.isclose(cor[1, 1], 1, atol=1e-2) + assert np.abs(cor[0, 1]) < 0.01 + assert cor.shape == (2, 2) + def test_correlation_latex_table(self): - data = np.random.multivariate_normal([0, 0, 1], [[1, 0.5, 0.2], [0.5, 1, 0.3], [0.2, 0.3, 1.0]], size=100000) + data = np.random.multivariate_normal([0, 0, 1], [[1, 0.5, 0.2], [0.5, 1, 0.3], [0.2, 0.3, 1.0]], size=1000000) parameters = ["x", "y", "z"] c = ChainConsumer() c.add_chain(data, parameters=parameters) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index <HASH>..<HASH> 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -5,7 +5,7 @@ from chainconsumer.helpers import get_extents def test_extents(): - xs = np.random.normal(size=100000) + xs = np.random.normal(size=1000000) weights = np.ones(xs.shape) low, high = get_extents(xs, weights) threshold = 0.5 @@ -14,7 +14,7 @@ def test_extents(): def test_extents_weighted(): - xs = np.random.uniform(low=-4, high=4, size=100000) + xs = np.random.uniform(low=-4, high=4, size=1000000) weights = norm.pdf(xs) low, high = get_extents(xs, weights) threshold = 0.5 @@ -23,7 +23,7 @@ def test_extents_weighted(): def test_extents_summary(): - xs = np.random.normal(size=100000) + xs = np.random.normal(size=1000000) low, high = get_extents(xs, np.ones(xs.shape), plot=True, wide_extents=False) threshold = 0.1 assert np.abs(low + 1.644855) < threshold
Fixing bug in `get_correlations`
Samreay_ChainConsumer
train
c4f6bf6afbf075a64751a091bad640dac3b49f8d
diff --git a/src/test/java/net/masterthought/cucumber/generators/integrations/FeatureReportPageIntegrationTest.java b/src/test/java/net/masterthought/cucumber/generators/integrations/FeatureReportPageIntegrationTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/net/masterthought/cucumber/generators/integrations/FeatureReportPageIntegrationTest.java +++ b/src/test/java/net/masterthought/cucumber/generators/integrations/FeatureReportPageIntegrationTest.java @@ -398,6 +398,7 @@ public class FeatureReportPageIntegrationTest extends PageTest { Hook[] hooks = feature.getElements()[0].getSteps()[1].getAfter(); assertThat(afterHooks).hasSameSizeAs(hooks); + assertThat(afterHooks[0].getBrief().getLocation()).isEqualTo(hooks[0].getMatch().getLocation()); afterHooks[0].getBrief().hasDuration(hooks[0].getResult().getDuration()); } diff --git a/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/BriefAssertion.java b/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/BriefAssertion.java index <HASH>..<HASH> 100644 --- a/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/BriefAssertion.java +++ b/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/BriefAssertion.java @@ -18,6 +18,10 @@ public class BriefAssertion extends ReportAssertion { return oneByClass("name", WebAssertion.class).text(); } + public String getLocation() { + return oneByClass("location", WebAssertion.class).text(); + } + public void hasDuration(long duration) { String found = oneByClass("duration", WebAssertion.class).text(); assertThat(found).isEqualTo(Util.formatDuration(duration)); diff --git a/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/ReportAssertion.java b/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/ReportAssertion.java index <HASH>..<HASH> 100644 --- a/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/ReportAssertion.java +++ b/src/test/java/net/masterthought/cucumber/generators/integrations/helpers/ReportAssertion.java @@ -21,10 +21,6 @@ public abstract class ReportAssertion extends WebAssertion { return childByClass("collapsable-control", clazz); } - protected <T extends WebAssertion> T getCollapseDetails(Class<T> clazz) { - return childByClass("collapsable-details", clazz); - } - public LinkAssertion getLink() { return oneBySelector("a", LinkAssertion.class); }
Adds integration test for location attribute (#<I>)
damianszczepanik_cucumber-reporting
train
c74722077bb3eceab3a5435f22b0a0e98ca02e7c
diff --git a/Kwf/Component/Abstract/ContentSender/Lightbox.php b/Kwf/Component/Abstract/ContentSender/Lightbox.php index <HASH>..<HASH> 100644 --- a/Kwf/Component/Abstract/ContentSender/Lightbox.php +++ b/Kwf/Component/Abstract/ContentSender/Lightbox.php @@ -109,13 +109,13 @@ class Kwf_Component_Abstract_ContentSender_Lightbox extends Kwf_Component_Abstra " <div class=\"kwfLightboxContent\">\n". " $lightboxContent\n". " </div>\n". + " <a class=\"closeButton\" href=\"$parent->url\"><span class=\"innerCloseButton\">". trlKwf('Close') ."</span></a>\n". " </div>\n". " </div>\n". " </div>\n". " </div>\n". " <div class=\"kwfLightboxMask kwfLightboxMaskOpen\"></div>\n". " </div>\n". - " <a class=\"closeButton\" href=\"$parent->url\"></a>\n". "</div>\n"; return preg_replace('#(<body[^>]*>)#', "\\1\n".$lightboxContent, $parentContent); } else { diff --git a/Kwf_js/EyeCandy/Lightbox/Lightbox.js b/Kwf_js/EyeCandy/Lightbox/Lightbox.js index <HASH>..<HASH> 100644 --- a/Kwf_js/EyeCandy/Lightbox/Lightbox.js +++ b/Kwf_js/EyeCandy/Lightbox/Lightbox.js @@ -284,12 +284,12 @@ Kwf.EyeCandy.Lightbox.Lightbox.prototype = { '<div class="kwfLightboxContent"></div>' ); this.closeButtonEl = $( - '<a href="#" class="closeButton"></a>' + '<a href="#" class="closeButton"><span class="innerCloseButton">'+trlKwf("Close")+'</span></a>' ); var self = this; var appendContent = function() { self.innerLightboxEl.append(self.contentEl); - self.lightboxEl.append(self.closeButtonEl); + self.innerLightboxEl.append(self.closeButtonEl); self.style.updateContent(responseText); diff --git a/Kwf_js/EyeCandy/Lightbox/Lightbox.scss b/Kwf_js/EyeCandy/Lightbox/Lightbox.scss index <HASH>..<HASH> 100644 --- a/Kwf_js/EyeCandy/Lightbox/Lightbox.scss +++ b/Kwf_js/EyeCandy/Lightbox/Lightbox.scss @@ -57,6 +57,7 @@ body { } .kwfLightboxInner { + @include box-sizing(border-box); display: inline-block; position: relative; text-align: left; @@ -232,16 +233,21 @@ body { .kwfLightbox .closeButton { background: url('/assets/kwf/Kwf_js/EyeCandy/Lightbox/close.png') no-repeat center center; - position: fixed; + position: absolute; display: block; height: 42px; z-index: 102; width: 42px; - right: 10px; - top: 10px; + right: -25px; + top: -25px; +} + +.kwfUp-kwfLightbox .kwfUp-innerCloseButton { + display: none; } .kwfLightbox.mobile .closeButton { + position: fixed; right: 2px; top: 2px; }
move closeButton in new lightbox back to kwfLightboxContent and reset styling Conflicts: Kwf/Component/Abstract/ContentSender/Lightbox.php Kwf_js/EyeCandy/Lightbox/Lightbox.js Kwf_js/EyeCandy/Lightbox/Lightbox.scss
koala-framework_koala-framework
train
52c11032df66c362665e01fe35475d410e458048
diff --git a/lib/fastlane/actions/testmunk.rb b/lib/fastlane/actions/testmunk.rb index <HASH>..<HASH> 100644 --- a/lib/fastlane/actions/testmunk.rb +++ b/lib/fastlane/actions/testmunk.rb @@ -67,7 +67,7 @@ module Fastlane end def self.author - "mposchen & johannesberdin" + ["mposchen", "johannesberdin"] end def self.is_supported?(platform)
Updated testmunk action to use new multi authors feature
fastlane_fastlane
train
2ea30df96b5156e3a2a67fcf7ad0f57464b84807
diff --git a/tests/HttpProfilingTest.php b/tests/HttpProfilingTest.php index <HASH>..<HASH> 100644 --- a/tests/HttpProfilingTest.php +++ b/tests/HttpProfilingTest.php @@ -25,10 +25,11 @@ class HttpProfilingTest extends TestCase /** @test */ public function it_is_disabled_for_local_environment_if_no_vvv_request_param_set() { - // $this->assertTrue($this->app->isLocal()); - // $this->visit('/'); - // - // $this->see('Home page!'); - // $this->dontSee('select * from posts'); + $this->setApplicationEnvironment('local'); + $this->assertTrue($this->app->isLocal()); + $this->visit('/'); + + $this->see('Home page!'); + $this->dontSee('select * from posts'); } }
DBP: Local env tests added.
dmitry-ivanov_laravel-db-profiler
train
8a2958fbf89d61620e81593056df6a67192167eb
diff --git a/pymysql/connections.py b/pymysql/connections.py index <HASH>..<HASH> 100644 --- a/pymysql/connections.py +++ b/pymysql/connections.py @@ -888,6 +888,7 @@ class Connection(object): def _get_server_information(self): i = 0 packet = MysqlPacket(self) + packet.check_error() data = packet.get_all_data() if DEBUG: dump_packet(data) diff --git a/pymysql/err.py b/pymysql/err.py index <HASH>..<HASH> 100644 --- a/pymysql/err.py +++ b/pymysql/err.py @@ -107,7 +107,7 @@ _map_error(IntegrityError, ER.DUP_ENTRY, ER.NO_REFERENCED_ROW, ER.CANNOT_ADD_FOREIGN) _map_error(NotSupportedError, ER.WARNING_NOT_COMPLETE_ROLLBACK, ER.NOT_SUPPORTED_YET, ER.FEATURE_DISABLED, ER.UNKNOWN_STORAGE_ENGINE) -_map_error(OperationalError, ER.DBACCESS_DENIED_ERROR, ER.ACCESS_DENIED_ERROR, +_map_error(OperationalError, ER.DBACCESS_DENIED_ERROR, ER.ACCESS_DENIED_ERROR, ER.CON_COUNT_ERROR, ER.TABLEACCESS_DENIED_ERROR, ER.COLUMNACCESS_DENIED_ERROR) del _map_error, ER
handle connection errors properly (fixes petehunt/PyMySQL/#<I>)
aio-libs_aiomysql
train
291c9a069417b8ec35ca3d2abf50c38d2082458f
diff --git a/support/cas-server-support-azure/src/main/java/org/apereo/cas/config/support/authentication/AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration.java b/support/cas-server-support-azure/src/main/java/org/apereo/cas/config/support/authentication/AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration.java index <HASH>..<HASH> 100644 --- a/support/cas-server-support-azure/src/main/java/org/apereo/cas/config/support/authentication/AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration.java +++ b/support/cas-server-support-azure/src/main/java/org/apereo/cas/config/support/authentication/AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration.java @@ -62,7 +62,7 @@ public class AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration imp throw new FileNotFoundException(cfg.getAbsolutePath() + " does not exist or is not a directory"); } final PFAuth pf = new PFAuth(); - pf.setDebug(azure.isDebugEnabled()); + pf.setDebug(true); pf.setAllowInternationalCalls(azure.isAllowInternationalCalls()); final String dir = StringUtils.appendIfMissing(azure.getConfigDir(), "/");
Added Azure MFACheckstyle and test fixes
apereo_cas
train
f1a2769fafdf09d3f5f48966a5d75330db874e72
diff --git a/clientManagement.py b/clientManagement.py index <HASH>..<HASH> 100644 --- a/clientManagement.py +++ b/clientManagement.py @@ -60,7 +60,7 @@ class ClientController(remote_controller.RemoteController): # Prefer using a context manager, but this cleans most other cases. self.close() ############################################################################ - def connect(self, url=c.LOCALHOST, port=None, timeout=120): + def connect(self, url=c.LOCALHOST, port=None, timeout=c.INITIAL_TIMEOUT): """socket connect to an already running starcraft2 process""" if port != None: # force a selection to a new port if self._port!=None: # if previously allocated port, return it
- used constant c.INITIAL_TIMEOUT rather than magic number
ttinies_sc2gameLobby
train
dc4b97b8514943abbdcc72556ea01d68f2230b40
diff --git a/cmd/dex/serve.go b/cmd/dex/serve.go index <HASH>..<HASH> 100644 --- a/cmd/dex/serve.go +++ b/cmd/dex/serve.go @@ -147,15 +147,6 @@ func serve(cmd *cobra.Command, args []string) error { s = storage.WithStaticPasswords(s, passwords) } - if c.EnablePasswordDB { - c.StaticConnectors = append(c.StaticConnectors, Connector{ - ID: server.LocalConnector, - Name: "Email", - Type: server.LocalConnector, - }) - logger.Infof("config connector: local passwords enabled") - } - storageConnectors := make([]storage.Connector, len(c.StaticConnectors)) for i, c := range c.StaticConnectors { if c.ID == "" || c.Name == "" || c.Type == "" { @@ -174,6 +165,16 @@ func serve(cmd *cobra.Command, args []string) error { storageConnectors[i] = conn } + + if c.EnablePasswordDB { + storageConnectors = append(storageConnectors, storage.Connector{ + ID: server.LocalConnector, + Name: "Email", + Type: server.LocalConnector, + }) + logger.Infof("config connector: local passwords enabled") + } + s = storage.WithStaticConnectors(s, storageConnectors) if len(c.OAuth2.ResponseTypes) > 0 {
cmd/dex/serve: add local connector directly to static connectors in storage
dexidp_dex
train
527013d992f8f781693e4924e65523845d446808
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -59,36 +59,36 @@ exports.indexes = function (geom, limits) { }; function getLocked (geom, limits) { - var locked, - i, + var locked, i, tile, id, + coords = geom.coordinates, tileHash = {}; if (geom.type === 'Point') { - locked = [tilebelt.pointToTile(geom.coordinates[0], geom.coordinates[1], limits.max_zoom)]; + locked = [tilebelt.pointToTile(coords[0], coords[1], limits.max_zoom)]; + } else if (geom.type === 'MultiPoint') { - var quadkeys = {}; locked = []; - for(i = 0; i < geom.coordinates.length; i++) { - var tile = tilebelt.pointToTile(geom.coordinates[i][0], geom.coordinates[i][1], limits.max_zoom); - var quadkey = tilebelt.tileToQuadkey(tile); - if(!quadkeys[quadkey]) { - quadkeys[quadkey] = true; + for(i = 0; i < coords.length; i++) { + tile = tilebelt.pointToTile(coords[i][0], coords[i][1], limits.max_zoom); + id = toID(tile[0], tile[1], tile[2]); + if (!tileHash[id]) { + tileHash[id] = true; locked.push(tile); } } } else if (geom.type === 'LineString') { - lineCover(tileHash, geom.coordinates, limits.max_zoom); + lineCover(tileHash, coords, limits.max_zoom); } else if (geom.type === 'MultiLineString') { - for(i = 0; i < geom.coordinates.length; i++) { - lineCover(tileHash, geom.coordinates[i], limits.max_zoom); + for(i = 0; i < coords.length; i++) { + lineCover(tileHash, coords[i], limits.max_zoom); } } else if (geom.type === 'Polygon') { - polyRingCover(tileHash, geom.coordinates, limits.max_zoom); + polyRingCover(tileHash, coords, limits.max_zoom); } else if (geom.type === 'MultiPolygon') { - for(i = 0; i < geom.coordinates.length; i++) { - polyRingCover(tileHash, geom.coordinates[i], limits.max_zoom); + for(i = 0; i < coords.length; i++) { + polyRingCover(tileHash, coords[i], limits.max_zoom); } } else { throw new Error('Geometry type not implemented');
clean up getLocked and use the same hashing function everywhere for consistency
mapbox_tile-cover
train
a4ffa6351132f9c585b4b5ed2c93c5bf27496156
diff --git a/lib/aasm/aasm.rb b/lib/aasm/aasm.rb index <HASH>..<HASH> 100644 --- a/lib/aasm/aasm.rb +++ b/lib/aasm/aasm.rb @@ -106,27 +106,7 @@ module AASM events = self.class.aasm_events.values.select {|event| event.transitions_from_state?(state) } events.map {|event| event.name} end - - # def human_state - # defaults = self.class.lookup_ancestors.map do |klass| - # klass_human = klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore - # :"#{self.class.i18n_scope}.attributes.#{klass_human}.#{aasm_current_state}" - # end - # defaults << aasm_current_state.to_s.humanize - # - # I18n.translate(defaults.shift, :default => defaults, :raise => true) - # end - # - # def human_event_name(event) - # defaults = self.class.lookup_ancestors.map do |klass| - # klass_human = klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore - # :"#{self.class.i18n_scope}.events.#{klass_human}.#{event}" - # end - # defaults << event.to_s.humanize - # - # I18n.translate(defaults.shift, :default => defaults, :raise => true) - # end - + private def set_aasm_current_state_with_persistence(state)
woopse. forgot to delete this
aasm_aasm
train
a2f3c29379700fd0be907afbab94ab29698d126e
diff --git a/worker/uniter/runner/context.go b/worker/uniter/runner/context.go index <HASH>..<HASH> 100644 --- a/worker/uniter/runner/context.go +++ b/worker/uniter/runner/context.go @@ -270,7 +270,19 @@ func (ctx *HookContext) Storage(tag names.StorageTag) (jujuc.ContextStorage, boo } func (ctx *HookContext) AddUnitStorage(cons map[string]params.StorageConstraints) { - ctx.storageAddConstraints = cons + // Storage constraints are accumulative before context is flushed. + // TODO (anastasiamac 2015-05-26): + // what happens if more than one call is made about the same store? + // with this implementation, the latest call arrived will be taken + // into consideration. + if ctx.storageAddConstraints == nil { + ctx.storageAddConstraints = make( + map[string]params.StorageConstraints, + len(cons)) + } + for k, v := range cons { + ctx.storageAddConstraints[k] = v + } } func (ctx *HookContext) OpenPorts(protocol string, fromPort, toPort int) error { diff --git a/worker/uniter/runner/unitStorage_test.go b/worker/uniter/runner/unitStorage_test.go index <HASH>..<HASH> 100644 --- a/worker/uniter/runner/unitStorage_test.go +++ b/worker/uniter/runner/unitStorage_test.go @@ -70,7 +70,7 @@ func makeStorageCons(pool string, size, count uint64) state.StorageConstraints { return state.StorageConstraints{Pool: pool, Size: size, Count: count} } -func (s *unitStorageSuite) assertUnitStorageAdded(c *gc.C, cons params.StorageConstraints) { +func (s *unitStorageSuite) assertUnitStorageAdded(c *gc.C, cons ...params.StorageConstraints) { before, err := s.State.AllStorageInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(before, gc.HasLen, 1) @@ -79,7 +79,9 @@ func (s *unitStorageSuite) assertUnitStorageAdded(c *gc.C, cons params.StorageCo ctx := s.getHookContext(c, s.State.EnvironUUID(), -1, "", noProxies) c.Assert(ctx.UnitName(), gc.Equals, "storage-block/0") - ctx.AddUnitStorage(map[string]params.StorageConstraints{"allecto": cons}) + for _, one := range cons { + ctx.AddUnitStorage(map[string]params.StorageConstraints{"allecto": one}) + } // Flush the context with a success. err = ctx.FlushContext("success", nil) @@ -104,3 +106,10 @@ func (s *unitStorageSuite) TestAddUnitStorageZeroCount(c *gc.C) { size := uint64(1) s.assertUnitStorageAdded(c, params.StorageConstraints{Size: &size}) } + +func (s *unitStorageSuite) TestAddUnitStorageAccumulated(c *gc.C) { + n := uint64(1) + s.assertUnitStorageAdded(c, + params.StorageConstraints{Size: &n}, + params.StorageConstraints{Count: &n}) +}
Added check for storage instance count 0.
juju_juju
train
cda76115ec305e8f85a0490273d29e61762c9313
diff --git a/alpaca_trade_api/entity.py b/alpaca_trade_api/entity.py index <HASH>..<HASH> 100644 --- a/alpaca_trade_api/entity.py +++ b/alpaca_trade_api/entity.py @@ -130,25 +130,27 @@ class BarSet(dict): class _Timestamped(object): + _tskeys = ('timestamp',) + def __getattr__(self, key): if key in self._raw: val = self._raw[key] - if key == 'timestamp': - return pd.Timestamp(val, tz=NY, unit=self.unit) + if key in self._tskeys: + return pd.Timestamp(val, tz=NY, unit=self._unit) return val return getattr(super(), key) class _NanoTimestamped(_Timestamped): - unit = 'ns' + _unit = 'ns' class _MilliTimestamped(_Timestamped): - unit = 'ms' + _unit = 'ms' class Agg(_MilliTimestamped, Entity): - pass + _tskeys = ('timestamp', 'start', 'end') class Aggs(list): @@ -288,4 +290,7 @@ agg_mapping = { "e": "end", "vw": "vwap", "av": "totalvolume", + + # this is extra alias in the client side + "t": "timestamp", } diff --git a/alpaca_trade_api/stream2.py b/alpaca_trade_api/stream2.py index <HASH>..<HASH> 100644 --- a/alpaca_trade_api/stream2.py +++ b/alpaca_trade_api/stream2.py @@ -131,6 +131,8 @@ class _StreamConn(object): return Quote({quote_mapping[k]: v for k, v in msg.items() if k in quote_mapping}) if channel.startswith('A.') or channel.startswith('AM.'): + # to be compatible with REST Agg + msg['t'] = msg['s'] return Agg({agg_mapping[k]: v for k, v in msg.items() if k in agg_mapping}) return Entity(msg)
Add an alias for timestamp for streaming Agg
alpacahq_alpaca-trade-api-python
train
b667ed3c89545f60035d3e13b71eda2d9cf1bfdd
diff --git a/lib/jsdom.js b/lib/jsdom.js index <HASH>..<HASH> 100644 --- a/lib/jsdom.js +++ b/lib/jsdom.js @@ -96,12 +96,12 @@ exports.jsdom = function (html, options) { virtualConsole: options.virtualConsole }); + documentFeatures.applyDocumentFeatures(window.document, options.features); + if (options.created) { - options.created(null, window); + options.created(null, window.document.defaultView); } - documentFeatures.applyDocumentFeatures(window.document, options.features); - if (options.parsingMode === "html") { if (html === undefined || html === "") { html = "<html><head></head><body></body></html>"; diff --git a/test/jsdom/env.js b/test/jsdom/env.js index <HASH>..<HASH> 100644 --- a/test/jsdom/env.js +++ b/test/jsdom/env.js @@ -560,3 +560,60 @@ exports["done should be called only once, after all src scripts have executed"] } }); }; + +exports["window instances should be initialized when provided to callbacks"] = t => { + t.expect(5); + + env({ + html: "<div></div>", + features: { + ProcessExternalResources: ["script"] + }, + created(err, window) { + t.ifError(err); + t.notEqual(window.Array, undefined); + }, + onload(window) { + t.notEqual(window.Array, undefined); + }, + done(err, window) { + t.ifError(err); + t.notEqual(window.Array, undefined); + t.done(); + } + }); +}; + +exports["window instances provided to callbacks always refer to the same object"] = t => { + t.expect(3 + 2); + + const instances = []; + + function finish() { + for (let i = 0; i < instances.length; ++i) { + for (let j = 0; j < i; ++j) { + t.strictEqual(instances[i], instances[j], `instances ${i} and ${j} should be equal`); + } + } + t.done(); + } + + env({ + html: "<div></div>", + features: { + ProcessExternalResources: ["script"] + }, + created(err, window) { + t.ifError(err); + instances.push(window); + }, + onload(window) { + instances.push(window); + }, + done(err, window) { + t.ifError(err); + instances.push(window); + finish(); + } + }); +};
Fix windows not being fully initialized when calling created
jsdom_jsdom
train
aa40a31b4766991dc91eb50f97b26253a06b9f1e
diff --git a/lib/oxcelix/nf.rb b/lib/oxcelix/nf.rb index <HASH>..<HASH> 100644 --- a/lib/oxcelix/nf.rb +++ b/lib/oxcelix/nf.rb @@ -1,7 +1,6 @@ module Oxcelix module Numformats - def fmtarr - return [ + Formatarray = [ {:id => '0', :xl => 'General', :ostring => nil, :cls => 'string'}, {:id => '1', :xl => '0', :ostring => '%1d', :cls => 'numeric'}, {:id => '2', :xl => '0.00', :ostring => '%1.2f', :cls => 'numeric'}, @@ -168,6 +167,5 @@ module Oxcelix {:id => '163', :xl => '', :ostring => nil, :cls => 'string'}, {:id => '163', :xl => '', :ostring => nil, :cls => 'string'} ] - end - end + end end diff --git a/lib/oxcelix/workbook.rb b/lib/oxcelix/workbook.rb index <HASH>..<HASH> 100644 --- a/lib/oxcelix/workbook.rb +++ b/lib/oxcelix/workbook.rb @@ -21,7 +21,7 @@ module Oxcelix include Workbookhelper include Numformats - attr_accessor :sheets, :numformats + attr_accessor :sheets ## @@ -72,14 +72,13 @@ module Oxcelix Ox.sax_parse(styles, f) end - @numformats = fmtarr styles.temparray.sort_by!{|st| st[:numFmtId].to_i} # styles.temparray.each{|st| styles.defined_formats << st[:formatCode]} # styles.temparray.each{|st| styles.formats << st[:formatCode]} add styles.temparray # styles.formats += styles.defined_formats # styles.styleary.map!{|s| styles.formats[s.to_i]} #??? - styles.styleary.map!{|s| @numformats[s.to_i][:id].to_i} #??? + styles.styleary.map!{|s| Numformats::Formatarray[s.to_i][:id].to_i} #??? @sheets.each do |x|
Cleared @numformats from Workbook. Formatarray is now a Numformats module constant available to any class including it.
gbiczo_oxcelix
train
78bc87263c02d75131cba5fd9ded1f9f748e659e
diff --git a/src/model/Auth/LoggedUserTokenAuthorization.php b/src/model/Auth/LoggedUserTokenAuthorization.php index <HASH>..<HASH> 100644 --- a/src/model/Auth/LoggedUserTokenAuthorization.php +++ b/src/model/Auth/LoggedUserTokenAuthorization.php @@ -13,13 +13,13 @@ use Nette\Security\IAuthorizator; class LoggedUserTokenAuthorization implements ApiAuthorizationInterface { - private $accessTokensRepository; + protected $accessTokensRepository; - private $emitter; + protected $emitter; - private $errorMessage = false; + protected $errorMessage = false; - private $authorizedData = []; + protected $authorizedData = []; public function __construct(AccessTokensRepository $accessTokensRepository, Emitter $emitter) {
Extend user/info endpoint with wordpress author - Wordpress API Client is dummy implementation. Will be connected to wordpress later. - Created new WordpressModule (as extension). - WordpressUserTokenAuthorization extends LoggedUserTokenAuthorization. In case source is not wordpress, parent Authorization is called. remp/crm#<I>
remp2020_crm-users-module
train
b0064536147014f4125615020843ee73dc693d4f
diff --git a/bugwarrior/services/gitlab.py b/bugwarrior/services/gitlab.py index <HASH>..<HASH> 100644 --- a/bugwarrior/services/gitlab.py +++ b/bugwarrior/services/gitlab.py @@ -83,6 +83,8 @@ class GitlabClient(ServiceClient): self.host = host self.token = token + self.repo_cache = {} + def _base_url(self): return f"{self.scheme}://{self.host}/api/v4/" @@ -177,9 +179,11 @@ class GitlabClient(ServiceClient): if only_owned: querystring['owned'] = True all_repos = self._fetch_paged('projects' + '?' + urlencode(querystring)) + for item in all_repos: + self.repo_cache[item['id']] = item return all_repos - def get_repo(self, repo_id: int) -> dict: + def _get_repo(self, repo_id: int) -> dict: """Queries information about a single repository as JSON dictionary :param repo_id: Project ID in the Gitlab instance @@ -188,6 +192,19 @@ class GitlabClient(ServiceClient): """ return self._fetch('projects/' + str(repo_id)) + def get_repo_cached(self, repo_id: int) -> dict: + """Get repo information with a repo cache. Repo information will only be fetched the first + time information about a certain repository is fetched. + + :param repo_id: numeric id of the project on the Gitlab server + :type repo_id: int + :rtype: dict + """ + if repo_id not in self.repo_cache: + self.repo_cache[repo_id] = self._get_repo(repo_id) + + return self.repo_cache[repo_id] + def get_notes(self, rid: int, issue_type: str, issueid: int) -> list: """Get notes attached to a certain issue / merge_request as list of JSON dictionaries @@ -555,7 +572,7 @@ class GitlabService(IssueService): type_plural = issue_type + 's' for rid, issue in issues: - repo = repo_map[rid] + repo = self.gitlab_client.get_repo_cached(rid) issue['repo'] = repo['path'] projectName = repo['path'] if self.config.project_owner_prefix: @@ -574,6 +591,9 @@ class GitlabService(IssueService): def include(self, issue): """ Return true if the issue in question should be included """ + if not self.filter_repos(self.gitlab_client.get_repo_cached(issue[0])): + return False + if self.config.only_if_assigned: owner = self.get_owner(issue) include_owners = [self.config.only_if_assigned] diff --git a/tests/test_gitlab.py b/tests/test_gitlab.py index <HASH>..<HASH> 100644 --- a/tests/test_gitlab.py +++ b/tests/test_gitlab.py @@ -321,7 +321,7 @@ class TestGitlabClient(ServiceTest): self.add_response( 'https://my-git.org/api/v4/projects/8', json=self.data.arbitrary_project) - result = self.client.get_repo(repo_id=8) + result = self.client.get_repo_cached(repo_id=8) self.assertEqual(result, self.data.arbitrary_project) @responses.activate
gitlab: Implement repo_cache. This allows refactoring things into more functions without the need of either passing the repo list around all the time nor querying repo information more than once.
ralphbean_bugwarrior
train
84700be04a6c85b0cd4fdffba3026e63f95b00ee
diff --git a/pyqode/core/modes/filewatcher.py b/pyqode/core/modes/filewatcher.py index <HASH>..<HASH> 100644 --- a/pyqode/core/modes/filewatcher.py +++ b/pyqode/core/modes/filewatcher.py @@ -60,6 +60,7 @@ class FileWatcherMode(Mode, QtCore.QObject): self.editor.new_text_set.connect(self._update_mtime) self.editor.new_text_set.connect(self._timer.start) self.editor.text_saving.connect(self._cancel_next_change) + self.editor.text_saved.connect(self._update_mtime) self.editor.text_saved.connect(self._restart_monitoring) self.editor.focused_in.connect(self._check_for_pending) else: @@ -148,7 +149,7 @@ class FileWatcherMode(Mode, QtCore.QObject): # See OpenCobolIDE/OpenCobolIDE#97 Cache().set_cursor_position( self.editor.file.path, - TextHelper(self.editor).cursor_position()) + self.editor.textCursor().position()) self.editor.file.open(self.editor.file.path) self.file_reloaded.emit()
Fix filewatcher notification when saving big files
pyQode_pyqode.core
train
ff39b13075130de549a3ce79d8f172763c7f904c
diff --git a/src/main/java/com/google/jimfs/path/PathType.java b/src/main/java/com/google/jimfs/path/PathType.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/google/jimfs/path/PathType.java +++ b/src/main/java/com/google/jimfs/path/PathType.java @@ -56,9 +56,18 @@ public abstract class PathType { /** * Returns a Windows-style path type. The canonical separator character is "\". "/" is also - * treated as a separator when parsing paths. Any initial name in the path consisting of a single - * alphabet letter followed by ":" is considered to be a root. Paths are case insensitive for - * ASCII characters. + * treated as a separator when parsing paths. Paths are case insensitive for ASCII characters. + * + * <p>As much as possible, this implementation follows the information provided in + * <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx"> + * this article</a>. Paths with drive-letter roots (e.g. "C:\") and paths with UNC roots (e.g. + * "\\host\share\") are supported. + * + * <p>One thing in particular is not currently supported: relative paths containing a drive-letter + * root, for example "C:" or "C:foo\bar". Such paths have a root component and optionally have + * names, but are <i>relative</i> paths, relative to the working directory of the drive identified + * by the root. This has some fundamental conflicts with how JIMFS handles paths and file lookups, + * and so is not currently supported. */ public static PathType windows() { return WindowsPathType.INSTANCE; @@ -66,9 +75,18 @@ public abstract class PathType { /** * Returns a Windows-style path type. The canonical separator character is "\". "/" is also - * treated as a separator when parsing paths. Any initial name in the path consisting of a single - * alphabet letter followed by ":" is considered to be a root. Paths use the given case - * sensitivity setting. + * treated as a separator when parsing paths. Paths use the given case sensitivity setting. + * + * <p>As much as possible, this implementation follows the information provided in + * <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx"> + * this article</a>. Paths with drive-letter roots (e.g. "C:\") and paths with UNC roots (e.g. + * "\\host\share\") are supported. + * + * <p>One thing in particular is not currently supported: relative paths containing a drive-letter + * root, for example "C:" or "C:foo\bar". Such paths have a root component and optionally have + * names, but are <i>relative</i> paths, relative to the working directory of the drive identified + * by the root. This has some fundamental conflicts with how JIMFS handles paths and file lookups, + * and so is not currently supported. */ public static PathType windows(CaseSensitivity caseSensitivity) { return new WindowsPathType(caseSensitivity); @@ -300,9 +318,7 @@ public abstract class PathType { /** * Checks if c is one of the reserved characters that aren't allowed in Windows file names. - * See <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions">this article</a>. */ - // TODO(cgdecker): consider making this an overridable method in PathType itself? private static boolean isReserved(char c) { switch (c) { case '<': @@ -318,10 +334,6 @@ public abstract class PathType { } } - private static boolean isLetter(char c) { - return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); - } - @Override public String toString(@Nullable String root, Iterable<String> names) { StringBuilder builder = new StringBuilder(); diff --git a/src/test/java/com/google/jimfs/path/PathTypeTest.java b/src/test/java/com/google/jimfs/path/PathTypeTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/google/jimfs/path/PathTypeTest.java +++ b/src/test/java/com/google/jimfs/path/PathTypeTest.java @@ -100,6 +100,19 @@ public class PathTypeTest { } @Test + public void testWindows_relativePathsWithDriveRoot_unsupported() { + try { + windows().parsePath("C:"); + fail(); + } catch (InvalidPathException expected) {} + + try { + windows().parsePath("C:foo\\bar"); + fail(); + } catch (InvalidPathException expected) {} + } + + @Test public void testWindows_uncPaths() { PathType windows = PathType.windows(); ParseResult path = windows.parsePath("\\\\host\\share");
Add tests that Windows relative-with-drive-letter paths (e.g. "C:foo\bar") are not supported. Also update javadoc for PathType.windows() methods to explain what works and doesn't work for Windows-style paths.
google_jimfs
train
f33c74572b530d3ab92d8fc7dfe86dedcb89b0a0
diff --git a/login.php b/login.php index <HASH>..<HASH> 100644 --- a/login.php +++ b/login.php @@ -171,11 +171,17 @@ default: <div> <input type="submit" value="', WT_I18N::translate('Login'), '"> </div> - <div> - <a href="#" id="passwd_click">', WT_I18N::translate('Request new password'), '</a> - </div>'; - if (WT_Site::preference('USE_REGISTRATION_MODULE')) { - echo '<div><a href="'.WT_LOGIN_URL.'?action=register">', WT_I18N::translate('Request new user account'), '</a></div>'; + '; + // Emails are sent from a TREE, not from a SITE. Therefore if there is no + // tree available (initial setup or all trees private), then we can't send email. + if ($WT_TREE) { + echo ' + <div> + <a href="#" id="passwd_click">', WT_I18N::translate('Request new password'), '</a> + </div>'; + if (WT_Site::preference('USE_REGISTRATION_MODULE')) { + echo '<div><a href="'.WT_LOGIN_URL.'?action=register">', WT_I18N::translate('Request new user account'), '</a></div>'; + } } echo '</form>';
#<I> - "Request new user account" fails when all trees are private
fisharebest_webtrees
train
71e811c3899104c89495f83f66fa487076e01620
diff --git a/src/main/java/com/brettonw/bag/BagObject.java b/src/main/java/com/brettonw/bag/BagObject.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/brettonw/bag/BagObject.java +++ b/src/main/java/com/brettonw/bag/BagObject.java @@ -238,6 +238,17 @@ public class BagObject { } /** + * Return whether or not the requested key is present in the BagObject. + * + * @param key A string value used to index an element. + * @return A boolean value, true if the key is present in the underlying store. Note that null + * values are not stored (design decision), so this equivalent to checking for null. + */ + public boolean has (String key) { + return (binarySearch (key) >= 0); + } + + /** * Returns an array of the keys contained in the underlying map. * * @return The keys in the underlying map as an array of Strings. diff --git a/src/test/java/com/brettonw/bag/BagObjectTest.java b/src/test/java/com/brettonw/bag/BagObjectTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/brettonw/bag/BagObjectTest.java +++ b/src/test/java/com/brettonw/bag/BagObjectTest.java @@ -125,6 +125,8 @@ public class BagObjectTest { String jsonString = " { Married:\"true\", \"Children\": [] , \"First Name\": \"Bretton\" , \"Last Name\" : \"Wade\" , \"Weight\":\"220.5\", Size:8 }"; bagObject = BagObject.fromString (jsonString); AppTest.report (bagObject.getString ("Last Name"), "Wade", "BagObject - reconstitute from a hand-crafted string should pass"); + AppTest.report (bagObject.has ("Married"), true, "BagObject - check that a tag is present"); + AppTest.report (bagObject.has ("Junk"), false, "BagObject - check that a tag is not present"); AppTest.report (bagObject.getBoolean ("Married"), true, "BagObject - reconstitute from a hand-crafted string with bare names should pass"); AppTest.report (bagObject.getInteger ("Size"), 8, "BagObject - reconstitute from a hand-crafted string with bare values should pass"); AppTest.report (bagObject.getBagArray ("Children").getCount (), 0, "BagObject - reconstitute from a hand-crafted string with empty array should be size 0");
add "has" to allow a user to see if an element is in the BagObject, along with corresponding tests.
brettonw_Bag
train
3504979c4a52e03272e586f21e8e158d03d3ce5f
diff --git a/lib/rack/proxy.rb b/lib/rack/proxy.rb index <HASH>..<HASH> 100644 --- a/lib/rack/proxy.rb +++ b/lib/rack/proxy.rb @@ -84,9 +84,6 @@ module Rack target_request.body_stream.rewind end - # Create a streaming response (the actual network communication is deferred, a.k.a. streamed) - target_response = HttpStreamingResponse.new(target_request, source_request.host, source_request.port) - backend = @backend || source_request use_ssl = backend.scheme == "https" ssl_verify_none = (env.delete('rack.ssl_verify_none') || @ssl_verify_none) == true
remove redundant HttpStreamingResponse.new call This local variable is redefined next in code, so this assignment looks redundant
ncr_rack-proxy
train
46347ac95e1fb01591254434807b95c1f9887b34
diff --git a/bcbio/variation/multiallelic.py b/bcbio/variation/multiallelic.py index <HASH>..<HASH> 100644 --- a/bcbio/variation/multiallelic.py +++ b/bcbio/variation/multiallelic.py @@ -29,13 +29,13 @@ from bcbio.pipeline import datadict as dd from bcbio.provenance import do from bcbio.variation import effects, vcfutils -def to_single(in_file, data): +def to_single(in_file, data, passonly=False): """Convert multi-allelic inputs in the original VCF file into single alleles. """ out_file = "%s-nomultiallelic%s" % utils.splitext_plus(in_file) if not utils.file_exists(out_file): if vcfutils.vcf_has_variants(in_file): - ready_ma_file = _decompose(in_file, data) + ready_ma_file = _decompose(in_file, data, passonly=passonly) ann_ma_file, _ = effects.add_to_vcf(ready_ma_file, data) if ann_ma_file: ready_ma_file = ann_ma_file @@ -44,19 +44,26 @@ def to_single(in_file, data): utils.symlink_plus(in_file, out_file) return vcfutils.bgzip_and_index(out_file, data["config"]) -def _decompose(in_file, data): +def _decompose(in_file, data, passonly=False): """Convert multi-allelic variants into single allelic. + + vt normalize has the -n flag passed (skipping reference checks) because + of errors where the reference genome has non GATCN ambiguous bases. These + are not supported in VCF, so you'll have a mismatch of N in VCF versus R + (or other ambiguous bases) in the genome. """ out_file = "%s-decompose%s" % utils.splitext_plus(in_file) if not utils.file_exists(out_file): ref_file = dd.get_ref_file(data) assert out_file.endswith(".vcf.gz") + sample_filter = "| bcftools view -f 'PASS,.' " if passonly else "" with file_transaction(data, out_file) as tx_out_file: cmd = ("gunzip -c %s | " "sed 's/ID=AD,Number=./ID=AD,Number=R/' | " "vt decompose -s - " - "| vt normalize -r %s - " + "| vt normalize -n -r %s - " """| awk '{ gsub("./-65", "./."); print $0 }'""" + "%s" "| bgzip -c > %s") - do.run(cmd % (in_file, ref_file, tx_out_file), "Multi-allelic to single allele") + do.run(cmd % (in_file, ref_file, sample_filter, tx_out_file), "Multi-allelic to single allele") return vcfutils.bgzip_and_index(out_file, data["config"]) diff --git a/bcbio/variation/population.py b/bcbio/variation/population.py index <HASH>..<HASH> 100644 --- a/bcbio/variation/population.py +++ b/bcbio/variation/population.py @@ -25,7 +25,8 @@ def prep_gemini_db(fnames, call_info, samples, extras): name, caller, is_batch = call_info gemini_db = os.path.join(out_dir, "%s-%s.db" % (name, caller)) multisample_vcf = get_multisample_vcf(fnames, name, caller, data) - gemini_vcf = multiallelic.to_single(multisample_vcf, data) + passonly = all("gemini_allvariants" not in dd.get_tools_on(d) for d in samples) + gemini_vcf = multiallelic.to_single(multisample_vcf, data, passonly=passonly) use_gemini = do_db_build(samples) and any(vcfutils.vcf_has_variants(f) for f in fnames) if not utils.file_exists(gemini_db) and use_gemini: ped_file = create_ped_file(samples + extras, gemini_vcf)
GEMINI prep: normalization fix and pass only - Pass `-n` argument to `vt normalize` since it will fail on genomes with non-NGATC IUPAC bases, since there will be a conflict between the VCF REF base (N), and the reference genome base (R, or some other ambiguous base).
bcbio_bcbio-nextgen
train
6a6c75212d9dbd70d963c3806803ba71a97a7fe6
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -386,13 +386,46 @@ gulp.task('watch', function() { /** * --------------------------------------------------------- * DEFAULT TASK : 'gulp' command or ctrl+shift+B (in VSCode) + * -> build app only * --------------------------------------------------------- */ gulp.task('default', [ - 'clean:app:scripts_css', - 'build', - 'scripts:clientMVC:dev', - 'scripts:clientMVC_dragDrop:dev', - 'lib' + //cleanings + 'stepway:clean', + 'dragdropway:clean', + //app tasks + 'stepway:templatecache', + 'dragdropway:templatecache', + 'app:sass:stepway', + 'app:sass:dragdropway', + 'app:js:stepway', + 'app:js:dragdropway' ]); + +/** + * ------------------------------------------------------------ + * BUILD:ALL TASK : 'gulp build:all' refresh all (vendors + app) + * ------------------------------------------------------------ + */ +gulp.task('build:all', [ + //cleanings + 'public:clean', + 'stepway:clean', + 'dragdropway:clean', + //vendor tasks + 'vendor:css:minifyOnly', + 'vendor:css:minifyAndClean', + 'vendor:css', + 'vendor:fonts', + 'vendor:header:js', + 'vendor:footer:js', + 'vendor:map', + //app tasks + 'stepway:templatecache', + 'dragdropway:templatecache', + 'app:sass:stepway', + 'app:sass:dragdropway', + 'app:js:stepway', + 'app:js:dragdropway' + ]); \ No newline at end of file
gulpfileNEW default and build all task done (not tested yet)
MacKentoch_easyFormGenerator
train
16a475b32ec4413305679868c445beb95c796f53
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -21,8 +21,14 @@ if (isClient) { var page = require('page') , qs = require('qs') - window.Arkansas = { + window.arkansas = { State: exports.State, + navigate: function(path) { + var ctx = new page.Context(path, null) + page.dispatch(ctx) + if (!ctx.unhandled) + ctx.pushState() + }, areas: { byRoute: {} } diff --git a/lib/routing.js b/lib/routing.js index <HASH>..<HASH> 100644 --- a/lib/routing.js +++ b/lib/routing.js @@ -81,7 +81,7 @@ var route = function(conf, method, path, action, rdy, options) { } } while((route = route.parent)) } - app.path.traversing = true + if (initialized) app.path.traversing = true } // call parent first @@ -93,7 +93,7 @@ var route = function(conf, method, path, action, rdy, options) { else action(req, app, cb) } - if (utils.isClient && rdy) rdy(window.app, req.params) + if (initialized && utils.isClient && rdy) rdy(window.app, req.params) } done.render = function(viewName) { // catch last recent render @@ -143,8 +143,8 @@ var route = function(conf, method, path, action, rdy, options) { done.render = function(viewName) { if (app.path.route.pattern === path) return done() app.path = { route: about, requested: req.path } - if (typeof window.Arkansas === 'undefined') return done() - var areas = window.Arkansas.areas + if (typeof window.arkansas === 'undefined') return done() + var areas = window.arkansas.areas , render = function(result) { Object.keys(areas.byRoute[path]).forEach(function(key) { var fragment = app.areas[key]
Fix Client-Side Routing Initialization The route tree will now be properly traversed up to execute the JavaScript functions to initialize after the initial request.
rkusa_swac
train
d9733da7e1021e2a96a2c1ccd70b35dacd2e12bf
diff --git a/mousedb/localsettings_empty.py b/mousedb/localsettings_empty.py index <HASH>..<HASH> 100644 --- a/mousedb/localsettings_empty.py +++ b/mousedb/localsettings_empty.py @@ -24,7 +24,7 @@ STATIC_URL = '/mousedb-static/' # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. -TIME_ZONE = 'America/Detriot' +TIME_ZONE = 'America/Detroit' DATABASES = { 'default': {
Fixed typo in TIME_ZONE
davebridges_mousedb
train
126fc26da6de0b00809dc1ae4767b501a02975fa
diff --git a/mythril/analysis/call_helpers.py b/mythril/analysis/call_helpers.py index <HASH>..<HASH> 100644 --- a/mythril/analysis/call_helpers.py +++ b/mythril/analysis/call_helpers.py @@ -18,7 +18,7 @@ def get_call_from_state(state: GlobalState) -> Union[Call, None]: op = instruction["opcode"] stack = state.mstate.stack - if op in ("CALL", "CALLCODE", "STATICCALL"): + if op in ("CALL", "CALLCODE"): gas, to, value, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), diff --git a/mythril/laser/ethereum/instructions.py b/mythril/laser/ethereum/instructions.py index <HASH>..<HASH> 100644 --- a/mythril/laser/ethereum/instructions.py +++ b/mythril/laser/ethereum/instructions.py @@ -1789,7 +1789,6 @@ class Instruction: :param global_state: :return: """ - call_value, mem_offset, mem_size = global_state.mstate.pop(3) return self._create_transaction_helper( @@ -1801,12 +1800,10 @@ class Instruction: call_value, mem_offset, mem_size = global_state.mstate.pop(3) call_data = get_call_data(global_state, mem_offset, mem_offset + mem_size) if global_state.last_return_data: - global_state.mstate.stack.append( - symbol_factory.BitVecVal(int(global_state.last_return_data, 16), 256) - ) + return_val = symbol_factory.BitVecVal(int(global_state.last_return_data, 16), 256) else: - global_state.mstate.stack.append(symbol_factory.BitVecVal(0, 256)) - + return_val = symbol_factory.BitVecVal(0, 256) + global_state.mstate.stack.append(return_val) return [global_state] @StateTransition(is_state_mutation_instruction=True) @@ -1827,11 +1824,10 @@ class Instruction: call_value, mem_offset, mem_size, salt = global_state.mstate.pop(4) call_data = get_call_data(global_state, mem_offset, mem_offset + mem_size) if global_state.last_return_data: - global_state.mstate.stack.append( - symbol_factory.BitVecVal(int(global_state.last_return_data), 256) - ) + return_val = symbol_factory.BitVecVal(int(global_state.last_return_data), 256) else: - global_state.mstate.stack.append(symbol_factory.BitVecVal(0, 256)) + return_val = symbol_factory.BitVecVal(0, 256) + global_state.mstate.stack.append(return_val) return [global_state] @StateTransition() @@ -2287,6 +2283,7 @@ class Instruction: ) raise TransactionStartSignal(transaction, self.op_code, global_state) + @StateTransition() def staticcall_post(self, global_state: GlobalState) -> List[GlobalState]: return self.post_handler(global_state, function_name="staticcall") @@ -2294,8 +2291,9 @@ class Instruction: instr = global_state.get_current_instruction() try: + with_value = function_name is not "staticcall" callee_address, callee_account, call_data, value, gas, memory_out_offset, memory_out_size = get_call_parameters( - global_state, self.dynamic_loader, True + global_state, self.dynamic_loader, with_value ) except ValueError as e: log.debug( diff --git a/mythril/laser/ethereum/transaction/transaction_models.py b/mythril/laser/ethereum/transaction/transaction_models.py index <HASH>..<HASH> 100644 --- a/mythril/laser/ethereum/transaction/transaction_models.py +++ b/mythril/laser/ethereum/transaction/transaction_models.py @@ -201,7 +201,7 @@ class ContractCreationTransaction(BaseTransaction): callee_account = world_state.create_account( 0, concrete_storage=True, creator=caller.value, address=contract_address ) - callee_account.contract_name = contract_name + callee_account.contract_name = contract_name or callee_account.contract_name # init_call_data "should" be false, but it is easier to model the calldata symbolically # and add logic in codecopy/codesize/calldatacopy/calldatasize than to model code "correctly" super().__init__(
Cleaned up some logic. Fixed issue with VMException and freezing on staticcall.
ConsenSys_mythril-classic
train
056d53c6428bee674d9091d576e0050b03899491
diff --git a/client/protocols/analytics.py b/client/protocols/analytics.py index <HASH>..<HASH> 100644 --- a/client/protocols/analytics.py +++ b/client/protocols/analytics.py @@ -1,6 +1,7 @@ """Implements the AnalyticsProtocol, which keeps track of configuration for the ok grading session. """ +import logging import re from client.protocols.common import models @@ -24,12 +25,12 @@ class AnalyticsProtocol(models.Protocol): # TODO(denero) Get the canonical name of the question statistics['question'] = self.args.question - # TODO(Jack) start from here: for adding the file analysis - statistics['started'] = self.analyze_file(messages['file_contents']) + statistics['started'] = self.check_start(messages['file_contents']) + print("DEBUG:" + statistics['started']) messages['analytics'] = statistics - def analyze_file(self, files): + def check_start(self, files): """returns a dictionary where the key is question number, and the value signals whether the question has been started. """ @@ -47,10 +48,6 @@ class AnalyticsProtocol(models.Protocol): q_status = {} - # tags = [i for i in range(len(lines)) if - # begin.match(lines[i]) or end.match(lines[i])] - # - # if len(tag) for path in files: lines = files[path].splitlines() if len(lines) == 0: @@ -58,36 +55,34 @@ class AnalyticsProtocol(models.Protocol): line_num = 0 started = False in_block = False - prev_q_tag = None + prev_begin_tag = None + while line_num < len(lines): line = lines[line_num] begin_match = begin.match(line) end_match = end.match(line) if begin_match: q_tag = begin_match.group(1) - prev_q_tag = q_tag - started = True if not in_block: in_block = True else: - # write current q_tag, started to dictionary - if not (q_tag in q_status and q_status[q_tag]): - q_status[q_tag] = started - started = True - in_block = True + if not (prev_begin_tag in q_status and q_status[prev_begin_tag]): + q_status[prev_begin_tag] = True + prev_begin_tag = q_tag + started = False elif end_match: q_tag = end_match.group(1) if not (q_tag in q_status and q_status[q_tag]): - if q_tag == prev_q_tag: + if q_tag == prev_begin_tag: q_status[q_tag] = started else: q_status[q_tag] = True - started = False in_block = False - prev_q_tag = None else: if in_block: - if not replace.search(line) or not line.strip(): + if not (replace.search(line) or (not line.strip())): started = True line_num += 1 return q_status + +protocol = AnalyticsProtocol diff --git a/client/protocols/grading.py b/client/protocols/grading.py index <HASH>..<HASH> 100644 --- a/client/protocols/grading.py +++ b/client/protocols/grading.py @@ -43,7 +43,8 @@ class GradingProtocol(models.Protocol): for test in self.assignment.specified_tests: log.info('Check if tests for {} need to run'.format(test.name)) - if started[test.name]: + # run test if the question is not detected, or question detected and started + if test.name not in started or started[test.name]: log.info('Running tests for {}'.format(test.name)) results = test.run() passed += results['passed']
fixed bugs in file scan code, need unittest
okpy_ok-client
train
d7e0e1d406b707285c9f74ca7dbd768a3d3e21fe
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -104,16 +104,17 @@ exports.toLtgt = function (range, _range, map, lower, upper) { else _range.gte = map(range[lb]) } else if(defaults) - _range.gte = lower + _range.gte = map(lower) if(ub) { if(ub === 'lt') _range.lt = map(range.lt) else _range.lte = map(range[ub]) } else if(defaults) - _range.lte = upper + _range.lte = map(upper) - _range.reverse = !!range.reverse + if(range.reverse != null) + _range.reverse = !!range.reverse return _range }
implement ltgt with mapped lower and upper bounds
dominictarr_ltgt
train
47983549026cd682656ffa4fedd772ede5625a68
diff --git a/classes/Gems/Model/Translator/AppointmentTranslator.php b/classes/Gems/Model/Translator/AppointmentTranslator.php index <HASH>..<HASH> 100644 --- a/classes/Gems/Model/Translator/AppointmentTranslator.php +++ b/classes/Gems/Model/Translator/AppointmentTranslator.php @@ -181,11 +181,12 @@ class Gems_Model_Translator_AppointmentTranslator extends Gems_Model_Translator_ if ($id) { $row['gap_id_user'] = $id; - } else { - // No user no import - return false; } } + if (! isset($row['gap_id_user'])) { + // No user no import if still not set + return false; + } } if (isset($row['gas_name_attended_by'])) {
Better position for appointment import abort = but no need to change <I>
GemsTracker_gemstracker-library
train
475fed8c515d4e3ad34efd601d800eacbe1604bb
diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java index <HASH>..<HASH> 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptManager.java @@ -31,6 +31,7 @@ import org.jivesoftware.smack.XMPPConnectionRegistry; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.MessageTypeFilter; +import org.jivesoftware.smack.filter.NotFilter; import org.jivesoftware.smack.filter.StanzaFilter; import org.jivesoftware.smack.filter.StanzaExtensionFilter; import org.jivesoftware.smack.filter.StanzaTypeFilter; @@ -232,6 +233,16 @@ public class DeliveryReceiptManager extends Manager { receiptReceivedListeners.remove(listener); } + /** + * A filter for stanzas to request delivery receipts for. Notably those are message stanzas of type normal, chat or + * headline, which <b>do not</b>contain a delivery receipt, i.e. are ack messages. + * + * @see <a href="http://xmpp.org/extensions/xep-0184.html#when-ack">XEP-184 § 5.4 Ack Messages</a> + */ + private static final StanzaFilter MESSAGES_TO_REQUEST_RECEIPTS_FOR = new AndFilter( + MessageTypeFilter.NORMAL_OR_CHAT_OR_HEADLINE, new NotFilter(new StanzaExtensionFilter( + DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE))); + private static final StanzaListener AUTO_ADD_DELIVERY_RECEIPT_REQUESTS_LISTENER = new StanzaListener() { @Override public void processPacket(Stanza packet) throws NotConnectedException { @@ -247,8 +258,8 @@ public class DeliveryReceiptManager extends Manager { * @see #dontAutoAddDeliveryReceiptRequests() */ public void autoAddDeliveryReceiptRequests() { - connection().addPacketSendingListener(AUTO_ADD_DELIVERY_RECEIPT_REQUESTS_LISTENER, - MessageTypeFilter.NORMAL_OR_CHAT_OR_HEADLINE); + connection().addPacketInterceptor(AUTO_ADD_DELIVERY_RECEIPT_REQUESTS_LISTENER, + MESSAGES_TO_REQUEST_RECEIPTS_FOR); } /** @@ -258,7 +269,7 @@ public class DeliveryReceiptManager extends Manager { * @see #autoAddDeliveryReceiptRequests() */ public void dontAutoAddDeliveryReceiptRequests() { - connection().removePacketSendingListener(AUTO_ADD_DELIVERY_RECEIPT_REQUESTS_LISTENER); + connection().removePacketInterceptor(AUTO_ADD_DELIVERY_RECEIPT_REQUESTS_LISTENER); } /**
Fix DeliveryReceiptsManager.autoAddDeliveryReceiptRequests Must use interceptors instead of sending listeners, as those are invoked *after* the stanza has been put on the wire. Also use the correct filter, which excludes ack messages. Fixes SMACK-<I>.
igniterealtime_Smack
train
74ea57622af211534e2fc833781b00f0427373aa
diff --git a/website/data/version.js b/website/data/version.js index <HASH>..<HASH> 100644 --- a/website/data/version.js +++ b/website/data/version.js @@ -1,6 +1,6 @@ -export const VERSION = '1.7.2' +export const VERSION = '1.7.3' export const CHANGELOG_URL = - 'https://github.com/hashicorp/vault/blob/master/CHANGELOG.md#172' + 'https://github.com/hashicorp/vault/blob/master/CHANGELOG.md#173' // HashiCorp officially supported package managers export const packageManagers = [
Update website latest version (#<I>)
hashicorp_vault
train
bb822f214f57f1141cdd3cf8f5d88166296f3de8
diff --git a/api.js b/api.js index <HASH>..<HASH> 100644 --- a/api.js +++ b/api.js @@ -789,7 +789,7 @@ var limitClientWithExt = function(client, ext) { } // Validate certificate scopes are subset of client - if (!utils.scopeMatch(client.scopes, scopesets)) { + if (!utils.scopeMatch(client.scopes, [cert.scopes])) { throw new Error("ext.certificate issuer doesn't have sufficient scopes"); } diff --git a/test/testing/mockauthserver_test.js b/test/testing/mockauthserver_test.js index <HASH>..<HASH> 100644 --- a/test/testing/mockauthserver_test.js +++ b/test/testing/mockauthserver_test.js @@ -55,6 +55,22 @@ suite('testing.createMockAuthServer', function() { }); }); + test("Can getCredentials w. auth:credentials (authorizedScopes)", function() { + return request + .get('http://localhost:1207/v1/client/authed-client/credentials') + .hawk({ + id: 'authed-client', + key: 'test-token', + algorithm: 'sha256', + ext: new Buffer(JSON.stringify({ + authorizedScopes: ['auth:credentials'] + })).toString('base64') + }) + .end().then(function(res) { + assert(res.ok, "Failed to get credentials"); + }); + }); + test("Can getCredentials w. auth:credentials (bewit)", function() { var reqUrl = 'http://localhost:1207/v1/client/authed-client/credentials'; var bewit = (hawk.client.getBewit || hawk.client.bewit)(reqUrl, { @@ -86,6 +102,26 @@ suite('testing.createMockAuthServer', function() { }); }); + test("Can't ... without auth:credentials (authorizedScopes)", function() { + var reqUrl = 'http://localhost:1207/v1/client/authed-client/credentials'; + var header = hawk.client.header(reqUrl, 'GET', { + credentials: { + id: 'authed-client', + key: 'test-token', + algorithm: 'sha256', + }, + ext: new Buffer(JSON.stringify({ + authorizedScopes: ['auth:credential-'] + })).toString('base64') + }); + return request + .get(reqUrl) + .set('Authorization', header.field) + .end().then(function(res) { + assert(!res.ok, "Request should have failed"); + }); + }); + test("Can fetch azureTableSAS", function() { return request .get('http://localhost:1207/v1/azure/' + cfg.get('azure:accountName') +
More tests for auth -- note this is tested in multiple libraries
taskcluster_taskcluster-base
train
4ffa460466e9d1adf38b9d119c94fd436b32077b
diff --git a/code/media/lib_koowa/js/koowa.js b/code/media/lib_koowa/js/koowa.js index <HASH>..<HASH> 100644 --- a/code/media/lib_koowa/js/koowa.js +++ b/code/media/lib_koowa/js/koowa.js @@ -19,6 +19,9 @@ if(!Koowa) var Koowa = {}; Koowa.version = 0.7; +//Legacy +if(!window.$each) window.$each = Object.each; + /* Section: onDomReady */ window.addEvent('domready', function() { @@ -259,7 +262,7 @@ Koowa.Controller = new Class({ return this; } result = events[type].keys.map(function(fn){ - return fn.create({'bind': this, 'delay': delay, 'arguments': args})() !== false; + return fn.call(this, args) !== false; }, this).every(function(v){ return v;}); return result; },
re #<I> <I> is no longer loading the mootools compat layer.
timble_kodekit
train
b7d544103384239ac05609e76b0826dc251d5273
diff --git a/Admin/Model/UserAdmin.php b/Admin/Model/UserAdmin.php index <HASH>..<HASH> 100644 --- a/Admin/Model/UserAdmin.php +++ b/Admin/Model/UserAdmin.php @@ -137,7 +137,7 @@ class UserAdmin extends Admin if (!$this->getSubject()->hasRole('ROLE_SUPER_ADMIN')) { $formMapper ->with('Management') - ->add('roles', 'sonata_security_roles', array( + ->add('realRoles', 'sonata_security_roles', array( 'expanded' => true, 'multiple' => true, 'required' => false diff --git a/CHANGELOG.txt b/CHANGELOG.txt index <HASH>..<HASH> 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,6 +1,16 @@ CHANGELOG ========= +### [BC BREAK] 2013-05-06 + +* User's groups roles are not merged anymore when editing `User` entity. A `getRealRoles()` method has been + added in `Sonata\UserBundle\Model\User` and is now used in `Sonata\UserBundle\Admin\UserAdmin`. + + If you still want to merge user's groups roles, you can: + + * add a `getRealRoles()` in your entity by overriding `Sonata\UserBundle\Model\User` method and + referencing `getRoles()` parent method + ### 2012-09-24 * changed service parameters into options that come through the configuration with the old values as the new defaults. diff --git a/Model/User.php b/Model/User.php index <HASH>..<HASH> 100644 --- a/Model/User.php +++ b/Model/User.php @@ -552,4 +552,20 @@ abstract class User extends AbstractedUser implements UserInterface { return sprintf("%s %s", $this->getFirstname(), $this->getLastname()); } + + /** + * @return array + */ + public function getRealRoles() + { + return $this->roles; + } + + /** + * @param array $roles + */ + public function setRealRoles(array $roles) + { + $this->setRoles($roles); + } }
Add a real roles method because of FOSUserBundle
sonata-project_SonataUserBundle
train
55ac84c46398563d8f1b3e2ee5b17bfa7ffbfa3a
diff --git a/consul/fsm_test.go b/consul/fsm_test.go index <HASH>..<HASH> 100644 --- a/consul/fsm_test.go +++ b/consul/fsm_test.go @@ -940,3 +940,46 @@ func TestFSM_ACL_Set_Delete(t *testing.T) { t.Fatalf("should be destroyed") } } + +func TestFSM_TombstoneReap(t *testing.T) { + path, err := ioutil.TempDir("", "fsm") + if err != nil { + t.Fatalf("err: %v", err) + } + fsm, err := NewFSM(nil, path, os.Stderr) + if err != nil { + t.Fatalf("err: %v", err) + } + defer fsm.Close() + + // Create some tombstones + fsm.state.KVSSet(11, &structs.DirEntry{ + Key: "/remove", + Value: []byte("foo"), + }) + fsm.state.KVSDelete(12, "/remove") + + // Create a new reap request + req := structs.TombstoneRequest{ + Datacenter: "dc1", + Op: structs.TombstoneReap, + ReapIndex: 12, + } + buf, err := structs.Encode(structs.TombstoneRequestType, req) + if err != nil { + t.Fatalf("err: %v", err) + } + resp := fsm.Apply(makeLog(buf)) + if err, ok := resp.(error); ok { + t.Fatalf("resp: %v", err) + } + + // Verify the tombstones are gone + _, res, err := fsm.state.tombstoneTable.Get("id") + if err != nil { + t.Fatalf("err: %v", err) + } + if len(res) != 0 { + t.Fatalf("bad: %v", res) + } +}
consul: Test FSM Reap operations
hashicorp_consul
train
90d375d14e8c2c2211247be695fef1231189fd3a
diff --git a/tests/integration/states/pip.py b/tests/integration/states/pip.py index <HASH>..<HASH> 100644 --- a/tests/integration/states/pip.py +++ b/tests/integration/states/pip.py @@ -40,7 +40,10 @@ class PipStateTest(integration.ModuleCase, integration.SaltReturnAssertsMixIn): self.assertSaltCommentRegexpMatches( ret, 'Error installing \'supervisor\': .* ' - '[nN]o such file or directory' + # If SHELL is set in the environ the error is: + '([nN]o such file or directory|' + # if there's no SHELL in the environ, the error is different + '/tmp/pip-installed-errors: not found)' ) # We now create the missing virtualenv
If `SHELL` is not in the environ, the error message is different.
saltstack_salt
train
18f60a121d98c6ce1669365da252aea3cf889264
diff --git a/openquake/server/static/js/engine.js b/openquake/server/static/js/engine.js index <HASH>..<HASH> 100644 --- a/openquake/server/static/js/engine.js +++ b/openquake/server/static/js/engine.js @@ -195,13 +195,13 @@ type: "POST", error: function (jqXHR, textStatus, errorThrown) { if (jqXHR.status == 403) { - diaerror.show(false, "Error", "" + JSON.parse(jqXHR.responseText).error); + diaerror.show(false, "Error", JSON.parse(jqXHR.responseText).error); } }, success: function(data, textStatus, jqXHR) { err = data.error; if(!err) { - err = "removed."; + err = "has been removed."; } diaerror.show(false, "Calculation removed", "The calculation:<br><b>(" + calc_id + ") " + calc_desc + "</b> " + err ); view.calculations.remove([view.calculations.get(calc_id)]);
fixed some error [skip CI]
gem_oq-engine
train
c3b3f17134f84d12e755103ab9b012ad08eb72fd
diff --git a/src/python/test/test_dx_completion.py b/src/python/test/test_dx_completion.py index <HASH>..<HASH> 100755 --- a/src/python/test/test_dx_completion.py +++ b/src/python/test/test_dx_completion.py @@ -67,6 +67,9 @@ class TestDXTabCompletion(unittest.TestCase): os.environ['DX_PROJECT_CONTEXT_ID'] = cls.project_id dxpy.set_workspace_id(cls.project_id) os.environ['IFS'] = IFS + os.environ['_ARGCOMPLETE'] = '1' + os.environ['_DX_ARC_DEBUG'] = '1' + os.environ['COMP_WORDBREAKS'] = '"\'@><=;|&(:' @classmethod def tearDownClass(cls): @@ -77,13 +80,13 @@ class TestDXTabCompletion(unittest.TestCase): def tearDown(self): dxpy.api.project_remove_folder(dxpy.WORKSPACE_ID, {"folder": "/", "recurse": True}) + for var in 'IFS', '_ARGCOMPLETE', '_DX_ARC_DEBUG', 'COMP_WORDBREAKS': + if var in os.environ: + del os.environ[var] def get_bash_completions(self, line, point=None, stderr_contains=""): - os.environ['_ARGCOMPLETE'] = '1' os.environ['COMP_LINE'] = line os.environ['COMP_POINT'] = point if point else str(len(line)) - os.environ['COMP_WORDBREAKS'] = '"\'@><=;|&(:' - os.environ['_DX_ARC_DEBUG'] = '1' p = subprocess.Popen('dx', stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate()
Try to clean up environment after tab completion tests
dnanexus_dx-toolkit
train
2e96bd79e988f5f34e7d4a6bdaf98675e6d78bfb
diff --git a/godet.go b/godet.go index <HASH>..<HASH> 100644 --- a/godet.go +++ b/godet.go @@ -67,6 +67,8 @@ var ( ErrorNoWsURL = errors.New("no websocket URL") // ErrorNoResponse is returned if a method was expecting a response but got nil instead ErrorNoResponse = errors.New("no response") + // ErrorClose is returned if a method is called after the connection has been close + ErrorClose = errors.New("closed") MaxReadBufferSize = 0 // default gorilla/websocket buffer size MaxWriteBufferSize = 100 * 1024 // this should be large enough to send large scripts @@ -179,7 +181,7 @@ func (err EvaluateError) Error() string { type NavigationError string func (err NavigationError) Error() string { - return "NavigationError:" + string(err) + return "NavigationError:" + string(err) } // RemoteDebugger implements an interface for Chrome DevTools. @@ -330,6 +332,7 @@ func (remote *RemoteDebugger) Close() (err error) { remote.Unlock() if ws != nil { // already closed + close(remote.requests) close(remote.closed) err = ws.Close() } @@ -360,11 +363,15 @@ func (remote *RemoteDebugger) SendRequest(method string, params Params) (map[str // sendRawReplyRequest sends a request and returns the reply bytes. func (remote *RemoteDebugger) sendRawReplyRequest(method string, params Params) ([]byte, error) { - responseChann := make(chan json.RawMessage, 1) - remote.Lock() + if remote.ws == nil { + remote.Unlock() + return nil, ErrorClose + } + + responseChan := make(chan json.RawMessage, 1) reqID := remote.reqID - remote.responses[reqID] = responseChann + remote.responses[reqID] = responseChan remote.reqID++ remote.Unlock() @@ -375,7 +382,7 @@ func (remote *RemoteDebugger) sendRawReplyRequest(method string, params Params) } remote.requests <- command - reply := <-responseChann + reply := <-responseChan remote.Lock() delete(remote.responses, reqID) @@ -653,9 +660,9 @@ func (remote *RemoteDebugger) Navigate(url string) (string, error) { return "", err } - if errorText, ok := res["errorText"]; ok { - return "", NavigationError(errorText.(string)) - } + if errorText, ok := res["errorText"]; ok { + return "", NavigationError(errorText.(string)) + } frameID, ok := res["frameId"] if !ok {
Fix for <URL> so that sender gorouting can terminate.
raff_godet
train
edb42ab1ec6ce93d3ad9fa648722a308d7f950bd
diff --git a/src/http/CookieBag.php b/src/http/CookieBag.php index <HASH>..<HASH> 100644 --- a/src/http/CookieBag.php +++ b/src/http/CookieBag.php @@ -40,10 +40,21 @@ class CookieBag extends Object implements IteratorAggregate } /** + * Returns all cookies. + * + * @return Cookie[] + * @since 0.3.0 + */ + public function all() + { + return $this->cookies; + } + + /** * Returns a cookie by name. * * @param $name - * @return null + * @return Cookie|null */ public function get($name) {
Added CookieBag::all() to return all cookies closes #<I>
bixuehujin_blink
train
e6c210a2fc1fed6b867f73665f015674b281dc1a
diff --git a/tests/unit/sagemaker/workflow/helpers.py b/tests/unit/sagemaker/workflow/helpers.py index <HASH>..<HASH> 100644 --- a/tests/unit/sagemaker/workflow/helpers.py +++ b/tests/unit/sagemaker/workflow/helpers.py @@ -41,7 +41,10 @@ class CustomStep(Step): super(CustomStep, self).__init__( name, display_name, description, StepTypeEnum.TRAINING, depends_on ) - self._properties = Properties(path=f"Steps.{name}") + # for testing property reference, we just use DescribeTrainingJobResponse shape here. + self._properties = Properties( + path=f"Steps.{name}", shape_name="DescribeTrainingJobResponse" + ) @property def arguments(self): diff --git a/tests/unit/sagemaker/workflow/test_transform_step.py b/tests/unit/sagemaker/workflow/test_transform_step.py index <HASH>..<HASH> 100644 --- a/tests/unit/sagemaker/workflow/test_transform_step.py +++ b/tests/unit/sagemaker/workflow/test_transform_step.py @@ -23,10 +23,13 @@ from sagemaker.estimator import Estimator from sagemaker.parameter import IntegerParameter from sagemaker.tuner import HyperparameterTuner from sagemaker.workflow.pipeline_context import PipelineSession +from tests.unit.sagemaker.workflow.helpers import CustomStep from sagemaker.workflow.steps import TransformStep, TransformInput from sagemaker.workflow.pipeline import Pipeline from sagemaker.workflow.parameters import ParameterString +from sagemaker.workflow.functions import Join +from sagemaker.workflow import is_pipeline_variable from sagemaker.transformer import Transformer @@ -53,6 +56,7 @@ def client(): client_mock._client_config.user_agent = ( "Boto3/1.14.24 Python/3.8.5 Linux/5.4.0-42-generic Botocore/1.17.24 Resource" ) + client_mock.describe_model.return_value = {"PrimaryContainer": {}, "Containers": {}} return client_mock @@ -80,18 +84,44 @@ def pipeline_session(boto_session, client): ) -def test_transform_step_with_transformer(pipeline_session): - model_name = ParameterString("ModelName") +@pytest.mark.parametrize( + "model_name", + [ + "my-model", + ParameterString("ModelName"), + ParameterString("ModelName", default_value="my-model"), + Join(on="-", values=["my", "model"]), + CustomStep(name="custom-step").properties.RoleArn, + ], +) +@pytest.mark.parametrize( + "data", + [ + "s3://my-bucket/my-data", + ParameterString("MyTransformInput"), + ParameterString("MyTransformInput", default_value="s3://my-model"), + Join(on="/", values=["s3://my-bucket", "my-transform-data", "input"]), + CustomStep(name="custom-step").properties.OutputDataConfig.S3OutputPath, + ], +) +@pytest.mark.parametrize( + "output_path", + [ + "s3://my-bucket/my-output-path", + ParameterString("MyOutputPath"), + ParameterString("MyOutputPath", default_value="s3://my-output"), + Join(on="/", values=["s3://my-bucket", "my-transform-data", "output"]), + CustomStep(name="custom-step").properties.OutputDataConfig.S3OutputPath, + ], +) +def test_transform_step_with_transformer(model_name, data, output_path, pipeline_session): transformer = Transformer( model_name=model_name, instance_type="ml.m5.xlarge", instance_count=1, - output_path=f"s3://{pipeline_session.default_bucket()}/Transform", + output_path=output_path, sagemaker_session=pipeline_session, ) - data = ParameterString( - name="Data", default_value=f"s3://{pipeline_session.default_bucket()}/batch-data" - ) transform_inputs = TransformInput(data=data) with warnings.catch_warnings(record=True) as w: @@ -123,13 +153,27 @@ def test_transform_step_with_transformer(pipeline_session): parameters=[model_name, data], sagemaker_session=pipeline_session, ) - step_args.args["ModelName"] = model_name.expr - step_args.args["TransformInput"]["DataSource"]["S3DataSource"]["S3Uri"] = data.expr - assert json.loads(pipeline.definition())["Steps"][0] == { - "Name": "MyTransformStep", - "Type": "Transform", - "Arguments": step_args.args, - } + step_args = step_args.args + step_def = json.loads(pipeline.definition())["Steps"][0] + step_args["ModelName"] = model_name.expr if is_pipeline_variable(model_name) else model_name + step_args["TransformInput"]["DataSource"]["S3DataSource"]["S3Uri"] = ( + data.expr if is_pipeline_variable(data) else data + ) + step_args["TransformOutput"]["S3OutputPath"] = ( + output_path.expr if is_pipeline_variable(output_path) else output_path + ) + + del ( + step_args["ModelName"], + step_args["TransformInput"]["DataSource"]["S3DataSource"]["S3Uri"], + step_args["TransformOutput"]["S3OutputPath"], + ) + del ( + step_def["Arguments"]["ModelName"], + step_def["Arguments"]["TransformInput"]["DataSource"]["S3DataSource"]["S3Uri"], + step_def["Arguments"]["TransformOutput"]["S3OutputPath"], + ) + assert step_def == {"Name": "MyTransformStep", "Type": "Transform", "Arguments": step_args} @pytest.mark.parametrize(
add parameterized tests to transformer (#<I>) add parameterized tests to transformer
aws_sagemaker-python-sdk
train
93dd95c82b87e9159b6ce552c335bd9f7da94589
diff --git a/.gitignore b/.gitignore index <HASH>..<HASH> 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .classpath .project .settings +*.log # Package Files # *.jar diff --git a/client/src/main/java/org/craftercms/profile/services/impl/ProfileServiceRestClient.java b/client/src/main/java/org/craftercms/profile/services/impl/ProfileServiceRestClient.java index <HASH>..<HASH> 100644 --- a/client/src/main/java/org/craftercms/profile/services/impl/ProfileServiceRestClient.java +++ b/client/src/main/java/org/craftercms/profile/services/impl/ProfileServiceRestClient.java @@ -298,15 +298,7 @@ public class ProfileServiceRestClient extends AbstractProfileRestClientBase impl String url = getAbsoluteUrl(BASE_URL_PROFILE + URL_PROFILE_GET_BY_TICKET); url = addQueryParams(url, params, false); - try { - return doGetForObject(url, Profile.class); - } catch (ProfileRestServiceException e) { - if (e.getStatus() == HttpStatus.NOT_FOUND) { - return null; - } else { - throw e; - } - } + return doGetForObject(url, Profile.class); } @Override diff --git a/integration-tests/src/test/java/org/craftercms/profile/services/ProfileServiceIT.java b/integration-tests/src/test/java/org/craftercms/profile/services/ProfileServiceIT.java index <HASH>..<HASH> 100644 --- a/integration-tests/src/test/java/org/craftercms/profile/services/ProfileServiceIT.java +++ b/integration-tests/src/test/java/org/craftercms/profile/services/ProfileServiceIT.java @@ -555,19 +555,18 @@ public class ProfileServiceIT { assertNull(profile); } - @Test + @Test(expected = ProfileRestServiceException.class) public void testGetProfileByTicket() throws Exception { Ticket ticket = authenticationService.authenticate(DEFAULT_TENANT, ADMIN_USERNAME, ADMIN_PASSWORD); - Profile profile = profileService.getProfileByTicket(ticket.getId()); + assertNotNull(ticket); + Profile profile = profileService.getProfileByTicket(ticket.getId()); assertAdminProfile(profile); authenticationService.invalidateTicket(ticket.getId()); // Try with invalid ticket - profile = profileService.getProfileByTicket("507c7f79bcf86cd7994f6c0e"); - - assertNull(profile); + profileService.getProfileByTicket("507c7f79bcf86cd7994f6c0e"); } @Test
Fix to show login page on ticket timeout
craftercms_profile
train
8d1fc9355fa30b100f360af158acfd8a32433943
diff --git a/main.go b/main.go index <HASH>..<HASH> 100644 --- a/main.go +++ b/main.go @@ -453,27 +453,34 @@ func expandPaths(paths []string) []string { } func doInstall() { - for name, target := range installMap { - cmd := "go get" - if *debugFlag { - cmd += " -v" - } - if *updateFlag { - cmd += " -u" - } - if *forceFlag { - cmd += " -f" - } + cmd := "go get" + if *debugFlag { + cmd += " -v" + } + if *updateFlag { + cmd += " -u" + } + if *forceFlag { + cmd += " -f" + } - cmd += " " + target - fmt.Printf("Installing %s -> %s\n", name, cmd) - arg0, arg1 := exArgs() - c := exec.Command(arg0, arg1, cmd) - c.Stdout = os.Stdout - c.Stderr = os.Stderr - err := c.Run() - kingpin.CommandLine.FatalIfError(err, "failed to install %s: %s", name, err) + names := make([]string, 0, len(installMap)) + targets := make([]string, 0, len(installMap)) + for name, target := range installMap { + names = append(names, name) + targets = append(targets, target) } + namesStr := strings.Join(names, " ") + targetsStr := strings.Join(targets, " ") + cmd += " " + targetsStr + fmt.Printf("Installing %s -> %s\n", namesStr, cmd) + + arg0, arg1 := exArgs() + c := exec.Command(arg0, arg1, cmd) + c.Stdout = os.Stdout + c.Stderr = os.Stderr + err := c.Run() + kingpin.CommandLine.FatalIfError(err, "failed to install %s: %s", namesStr, err) } func maybeSortIssues(issues chan *Issue) chan *Issue {
Speed up install step go get can takes multiple packages so install them at the same time. Since many binaries use the same packages it saves us rechecking packages multiple times. More important during a --update step.
alecthomas_gometalinter
train
599c1137bbc2927c7f0d387ccd65daa2a30a6bf4
diff --git a/searx/search.py b/searx/search.py index <HASH>..<HASH> 100644 --- a/searx/search.py +++ b/searx/search.py @@ -311,9 +311,6 @@ class Search(object): if not self.request_data.get('q'): raise Exception('noquery') - # set query - self.query = self.request_data['q'] - # set pagenumber pageno_param = self.request_data.get('pageno', '1') if not pageno_param.isdigit() or int(pageno_param) < 1: @@ -322,8 +319,11 @@ class Search(object): self.pageno = int(pageno_param) # parse query, if tags are set, which change the serch engine or search-language - query_obj = Query(self.query, self.blocked_engines) - query_obj.parse_query() + query_obj = Query(self.request_data['q'], self.blocked_engines) + query_obj.parse_query() + + # set query + self.query = query_obj.getSearchQuery() # get last selected language in query, if possible # TODO support search with multible languages
[fix] the bang was included in the search string
asciimoo_searx
train
b20dba9197f6ace5f0e312811983f70999c0958b
diff --git a/src/Controller/AppController.php b/src/Controller/AppController.php index <HASH>..<HASH> 100644 --- a/src/Controller/AppController.php +++ b/src/Controller/AppController.php @@ -290,7 +290,7 @@ class AppController extends BaseController */ public function batch() { - $this->request->allowMethod(['post', 'delete', 'put']); + $this->request->allowMethod(['post', 'delete']); if ($this->request->is('delete')) { $conditions = [
Remove unsupported http method (task #<I>)
QoboLtd_cakephp-csv-migrations
train
1390f203a7f07e82347896ec6b65e0ed999f5637
diff --git a/mod/forum/index.php b/mod/forum/index.php index <HASH>..<HASH> 100644 --- a/mod/forum/index.php +++ b/mod/forum/index.php @@ -85,7 +85,7 @@ if ($learningforums) { $currentsection = ""; - foreach ($learningforums as $forum) { + foreach ($learningforums as $key => $forum) { $count = count_records("forum_discussions", "forum", "$forum->id"); $forum->intro = forum_shorten_post($forum->intro); @@ -94,6 +94,7 @@ if (!$forum->section) { // forums in the "0" section => generaltable $generalforums[] = $forum; + unset($learningforums[$key]); continue; }
Dont print learning forums table if there aren't any
moodle_moodle
train
ce1b3f0293abc07948cda494efef1cd2cc7e0333
diff --git a/hooks.php b/hooks.php index <HASH>..<HASH> 100644 --- a/hooks.php +++ b/hooks.php @@ -345,6 +345,12 @@ add_filter( 'init', [ '\Pressbooks\BookDirectory', 'init' ], 10, 2 ); // ------------------------------------------------------------------------------------------------------------------- // Sentry initializer - Only for staging and production environments // ------------------------------------------------------------------------------------------------------------------- -if ( defined( 'WP_ENV' ) && WP_ENV !== 'development' ) { +if ( + defined( 'WP_ENV' ) && + WP_ENV !== 'development' && + defined( 'SENTRY_KEY' ) && + defined( 'SENTRY_ORGANIZATION' ) && + defined( 'SENTRY_PROJECT' ) +) { add_action( 'init', '\Pressbooks\Utility\initialize_sentry', 9999 ); }
Add Sentry action only if env variables are defined
pressbooks_pressbooks
train
cd47e2e678edc4254c7c582c62ebebc7c7df9eb0
diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java @@ -449,6 +449,10 @@ public abstract class AbstractMastersListener implements Listener { return currentReadOnlyAsked; } + public boolean inTransaction() { + return currentProtocol.inTransaction(); + } + public boolean isMasterConnection() { return true; } diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java b/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java @@ -94,6 +94,7 @@ public class FailoverProxy implements InvocationHandler { private static final String METHOD_GET_CATALOG = "getCatalog"; private static final String METHOD_GET_TIMEOUT = "getTimeout"; private static final String METHOD_GET_MAJOR_VERSION = "getMajorServerVersion"; + private static final String METHOD_IN_TRANSACTION = "inTransaction"; private static final Logger logger = LoggerFactory.getLogger(FailoverProxy.class); @@ -199,6 +200,8 @@ public class FailoverProxy implements InvocationHandler { return null; case METHOD_GET_READ_ONLY: return this.listener.isReadOnly(); + case METHOD_IN_TRANSACTION: + return this.listener.inTransaction(); case METHOD_IS_MASTER_CONNECTION: return this.listener.isMasterConnection(); case METHOD_ABORT: diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java b/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java @@ -119,6 +119,8 @@ public interface Listener { boolean isReadOnly(); + boolean inTransaction(); + int getMajorServerVersion(); boolean isMasterConnection(); diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java @@ -1006,6 +1006,13 @@ public class MastersSlavesListener extends AbstractMastersSlavesListener { return masterProtocol != null && masterProtocol.isConnected(); } + public boolean inTransaction() { + if (masterProtocol != null) { + return masterProtocol.inTransaction(); + } + return true; + } + /** * Check master status. *
[misc] internal inTransaction() failover method when master is allowed to be down
MariaDB_mariadb-connector-j
train
286fc89513cbb4905fa83d284b29d976f19ada3d
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ **Version 5.1** - Fixed recordNumberRecode item in base 18 dictionary to have Tumor instead of Patient as its ParentXmlTag. +- Added missing validation on record type attribute when loading a dictionary. - Updated embedded version of Java to 11.0.2. **Version 5.0** diff --git a/src/main/java/com/imsweb/naaccrxml/NaaccrFormat.java b/src/main/java/com/imsweb/naaccrxml/NaaccrFormat.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/imsweb/naaccrxml/NaaccrFormat.java +++ b/src/main/java/com/imsweb/naaccrxml/NaaccrFormat.java @@ -103,6 +103,9 @@ public final class NaaccrFormat { _SUPPORTED_REC_TYPES.add(NAACCR_REC_TYPE_INCIDENCE); } + // default value if a record type is not provided + public static final String ALL_RECORD_TYPES = "A,M,C,I"; + public static boolean isRecordTypeSupported(String recordType) { return _SUPPORTED_REC_TYPES.contains(recordType); } diff --git a/src/main/java/com/imsweb/naaccrxml/NaaccrXmlDictionaryUtils.java b/src/main/java/com/imsweb/naaccrxml/NaaccrXmlDictionaryUtils.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/imsweb/naaccrxml/NaaccrXmlDictionaryUtils.java +++ b/src/main/java/com/imsweb/naaccrxml/NaaccrXmlDictionaryUtils.java @@ -265,9 +265,16 @@ public final class NaaccrXmlDictionaryUtils { try { NaaccrDictionary dictionary = (NaaccrDictionary)instanciateXStream().fromXML(reader); + // default value for specifications if (dictionary.getSpecificationVersion() == null) dictionary.setSpecificationVersion(SpecificationVersion.SPEC_1_0); + // default value for record types + if (dictionary.getItems() != null) + for (NaaccrDictionaryItem item : dictionary.getItems()) + if (item.getRecordTypes() == null) + item.setRecordTypes(NaaccrFormat.ALL_RECORD_TYPES); + // let's not validate the internal dictionaries, we know they are valid String uri = dictionary.getDictionaryUri(); if (uri == null || uri.trim().isEmpty()) @@ -408,6 +415,10 @@ public final class NaaccrXmlDictionaryUtils { && !NaaccrXmlUtils.NAACCR_XML_TAG_TUMOR.equals(item.getParentXmlElement())) errors.add("invalid value for 'parentXmlElement' attribute: " + item.getParentXmlElement()); + // validate record type (null means all types, so that's OK) + if (item.getRecordTypes() != null && !item.getRecordTypes().matches("[AMCI](,[AMCI])*")) + errors.add("invalid value for 'recordTypes' attribute: " + item.getRecordTypes()); + // validate data type String type = item.getDataType(); if (type != null && (!NAACCR_DATA_TYPE_ALPHA.equals(type) && !NAACCR_DATA_TYPE_DIGITS.equals(type) && !NAACCR_DATA_TYPE_MIXED.equals(type)) && !NAACCR_DATA_TYPE_NUMERIC.equals(type)
Fixed record type validation (#<I>)
imsweb_naaccr-xml
train
d347c4b5e2584f51bd7ed6defa8fe24d0033e186
diff --git a/src/main/resources/SparkContext.js b/src/main/resources/SparkContext.js index <HASH>..<HASH> 100644 --- a/src/main/resources/SparkContext.js +++ b/src/main/resources/SparkContext.js @@ -283,20 +283,20 @@ with (imported) { */ SparkContext.prototype.accumulator = function() { var initialValue = arguments[0]; - var name = null; + var name; var param = new FloatAccumulatorParam(); this.logger.debug("accumulator " + initialValue); - if (typeof arguments[1] === "string" ) { - name = arguments[1]; - if (arguments[2]) { - param = arguments[2]; - } - } else { - if (arguments[1]) { + if (arguments[1]) { + if (typeof arguments[1] === "string") { + name = arguments[1]; + if (arguments[2]) { + param = arguments[2]; + } + } else { param = arguments[1]; } - } + } return new Accumulator(initialValue, param, name); };
#<I> name should be undefined instead of null
EclairJS_eclairjs-nashorn
train
e275af5fae10d77e891f62488f355f91f9eb478e
diff --git a/samcli/lib/schemas/schemas_api_caller.py b/samcli/lib/schemas/schemas_api_caller.py index <HASH>..<HASH> 100644 --- a/samcli/lib/schemas/schemas_api_caller.py +++ b/samcli/lib/schemas/schemas_api_caller.py @@ -181,7 +181,7 @@ class SchemasApiCaller: Parameters ---------- runtime: - Code binding runtime e.g: Java, Python + Code binding runtime e.g: Java, Python, Go registry_name: Registry Name schema_name: @@ -208,7 +208,7 @@ class SchemasApiCaller: Parameters ---------- runtime: - Code binding runtime e.g: Java, Python + Code binding runtime e.g: Java, Python, Go registry_name: Registry Name schema_name: @@ -236,7 +236,7 @@ class SchemasApiCaller: Parameters ---------- schemas_runtime: - Code binding runtime e.g: Java, Python + Code binding runtime e.g: Java, Python, Go registry_name: Registry Name schema_name: diff --git a/samcli/local/common/runtime_template.py b/samcli/local/common/runtime_template.py index <HASH>..<HASH> 100644 --- a/samcli/local/common/runtime_template.py +++ b/samcli/local/common/runtime_template.py @@ -143,4 +143,5 @@ SAM_RUNTIME_TO_SCHEMAS_CODE_LANG_MAPPING = { "python3.8": "Python36", "python3.9": "Python36", "dotnet6": "dotnetcore3.1", + "go1.x": "Go1", } diff --git a/tests/integration/init/schemas/test_init_with_schemas_command.py b/tests/integration/init/schemas/test_init_with_schemas_command.py index <HASH>..<HASH> 100644 --- a/tests/integration/init/schemas/test_init_with_schemas_command.py +++ b/tests/integration/init/schemas/test_init_with_schemas_command.py @@ -220,6 +220,37 @@ Y self.assertTrue(expected_output_folder.is_dir()) self.assertTrue(Path(expected_output_folder, "hello_world_function", "schema").is_dir()) + def test_init_interactive_with_event_bridge_app_aws_schemas_go(self): + # WHEN the user follows interactive init prompts + # 1: AWS Quick Start Templates + # 7: Infrastructure event management - Use case + # 1: Go 1.x + # 2: select event-bridge app from scratch + # eb-app-go: response to name + # Y: Use default aws configuration + # 4: select aws.events as registries + # 1: select aws schema + + user_input = """ +1 +7 +1 +2 +eb-app-go +Y +4 +1 + """ + with tempfile.TemporaryDirectory() as temp: + runner = CliRunner() + result = runner.invoke(init_cmd, ["--output-dir", temp], input=user_input) + + self.assertFalse(result.exception) + expected_output_folder = Path(temp, "eb-app-go") + self.assertTrue(expected_output_folder.exists) + self.assertTrue(expected_output_folder.is_dir()) + self.assertTrue(Path(expected_output_folder, "HelloWorld", "schema").is_dir()) + def test_init_interactive_with_event_bridge_app_non_default_profile_selection(self): self._init_custom_config("mynewprofile", "us-west-2") # WHEN the user follows interactive init prompts
feat: Add Go code generation option to Eventbridge Schemas workflow (#<I>)
awslabs_aws-sam-cli
train
b5d534b767510afb53adc304a4b5f36c784cc7dc
diff --git a/src/contrib/langcheck.php b/src/contrib/langcheck.php index <HASH>..<HASH> 100644 --- a/src/contrib/langcheck.php +++ b/src/contrib/langcheck.php @@ -407,7 +407,7 @@ if(!$error_abort) { if(!is_integer($kw_key)) { report_error(TYPE_WARNING, "Language file contains an key '$kw_key' in \$language_data['KEYWORDS'] that is not integer!"); } else if (!is_array($kw_value)) { - report_error(TYPE_ERROR, "Language file contains a \$language_data['CASE_SENSITIVE']['$kw_value'] structure which is not an array!"); + report_error(TYPE_ERROR, "Language file contains a \$language_data['KEYWORDS']['$kw_value'] structure which is not an array!"); } } }
fix: Fixed a minor typo with the LangCheck script mixing up CASE_SENSITIVE and KEYWORDS in one error message
GeSHi_geshi-1.0
train
3d8c2245cb09e0db917648f2cf57f99fd10caca1
diff --git a/pkg_resources/__init__.py b/pkg_resources/__init__.py index <HASH>..<HASH> 100644 --- a/pkg_resources/__init__.py +++ b/pkg_resources/__init__.py @@ -861,7 +861,7 @@ class WorkingSet(object): result = [] if req in extra_req_mapping: - for extra in extra_req_mapping[req]: + for extra in extra_req_mapping[req] or ['']: result.append(req.marker.evaluate({'extra': extra})) else: result.append(req.marker.evaluate()) diff --git a/pkg_resources/tests/test_resources.py b/pkg_resources/tests/test_resources.py index <HASH>..<HASH> 100644 --- a/pkg_resources/tests/test_resources.py +++ b/pkg_resources/tests/test_resources.py @@ -186,6 +186,12 @@ class TestDistro: res = ws.resolve(parse_requirements("Foo;python_version>='2'"), ad) assert list(res) == [Foo] + def test_environment_marker_evaluation_called(self): + ws = WorkingSet([]) + req, = parse_requirements("bar;python_version<'4'") + extra_req_mapping = {req: ()} + assert ws._markers_pass(req, extra_req_mapping) == True + def test_marker_evaluation_with_extras(self): """Extras are also evaluated as markers at resolution time.""" ad = pkg_resources.Environment([])
Reinstate the or guard in WorkingSet._markers_pass
pypa_setuptools
train
4a37907346257c10d3b072cf63ce94f3ef65aee6
diff --git a/gui/chooseLanguage.py b/gui/chooseLanguage.py index <HASH>..<HASH> 100644 --- a/gui/chooseLanguage.py +++ b/gui/chooseLanguage.py @@ -23,7 +23,10 @@ class chooseLanguageDialog(QtGui.QDialog): QObject.connect(self.ui.OKButton, SIGNAL("clicked(bool)"), self.onOkButton) for lang_xx in self._main.interface_langs: - item = QListWidgetItem(Languages.xx2name(lang_xx)) + languageName = Languages.xx2name(lang_xx) + if not languageName: + languageName = lang_xx + item = QListWidgetItem(languageName) item.setData(Qt.UserRole, QVariant(lang_xx)) self.ui.languagesList.addItem(item) if lang_xx == user_locale:
if the locale name is not in our languageNames list, just show the locale string
subdownloader_subdownloader
train
7281b77a7245c1f57089db27501aca45842e7c4e
diff --git a/lib/rbjs.rb b/lib/rbjs.rb index <HASH>..<HASH> 100644 --- a/lib/rbjs.rb +++ b/lib/rbjs.rb @@ -36,7 +36,7 @@ module Rbjs def evaluate function_parameters = nil instance_exec *function_parameters, &@_block - @_called_expressions.map(&:last_childs).flatten.reject(&:is_argument).map(&:to_s).join(";\n") + @_called_expressions.map(&:last_childs).flatten.reject(&:is_argument).map(&:to_s).join(";\n")+";\n" end def method_missing name, *args, &block diff --git a/lib/rbjs/version.rb b/lib/rbjs/version.rb index <HASH>..<HASH> 100644 --- a/lib/rbjs/version.rb +++ b/lib/rbjs/version.rb @@ -1,3 +1,3 @@ module Rbjs - VERSION = "0.10.4" + VERSION = "0.10.5" end
added trailing semicolon at end of output
buhrmi_rbjs
train
eb3c4cec7a39957ed4b828074d211d096bb87d62
diff --git a/lib/review/epubmaker.rb b/lib/review/epubmaker.rb index <HASH>..<HASH> 100644 --- a/lib/review/epubmaker.rb +++ b/lib/review/epubmaker.rb @@ -133,7 +133,7 @@ module ReVIEW def copy_images(resdir, destdir, allow_exts=nil) return nil unless File.exist?(resdir) allow_exts = @params["image_ext"] if allow_exts.nil? - FileUtils.mkdir_p(destdir) unless FileTest.directory?(destdir) + FileUtils.mkdir_p(destdir) if !@params["epubmaker"]["verify_target_images"].nil? @params["epubmaker"]["force_include_images"].each do |file| unless File.exist?(file) @@ -141,7 +141,7 @@ module ReVIEW next end basedir = File.dirname(file) - FileUtils.mkdir_p("#{destdir}/#{basedir}") unless FileTest.directory?("#{destdir}/#{basedir}") + FileUtils.mkdir_p("#{destdir}/#{basedir}") log("Copy #{file} to the temporary directory.") FileUtils.cp(file, "#{destdir}/#{basedir}") end @@ -153,7 +153,7 @@ module ReVIEW def copy_resources(resdir, destdir, allow_exts=nil) return nil unless File.exist?(resdir) allow_exts = @params["image_ext"] if allow_exts.nil? - FileUtils.mkdir_p(destdir) unless FileTest.directory?(destdir) + FileUtils.mkdir_p(destdir) recursive_copy_files(resdir, destdir, allow_exts) end @@ -165,7 +165,7 @@ module ReVIEW recursive_copy_files("#{resdir}/#{fname}", "#{destdir}/#{fname}", allow_exts) else if fname =~ /\.(#{allow_exts.join("|")})\Z/i - FileUtils.mkdir_p(destdir) unless File.exist?(destdir) + FileUtils.mkdir_p(destdir) log("Copy #{resdir}/#{fname} to the temporary directory.") FileUtils.cp("#{resdir}/#{fname}", destdir) end
refactor: mkdir_p also do directory-checking, so no need to FileTest.directory? cf: <URL>
kmuto_review
train
4907b21ba4d7ce4a485f7ff32ea3880aad8e6edd
diff --git a/commands/command_filter_process.go b/commands/command_filter_process.go index <HASH>..<HASH> 100644 --- a/commands/command_filter_process.go +++ b/commands/command_filter_process.go @@ -200,7 +200,7 @@ func filterCommand(cmd *cobra.Command, args []string) { } if len(malformedOnWindows) > 0 { - fmt.Fprintf(os.Stderr, "Encountered %d file(s) that may not have been copied correctly on Windows:\n") + fmt.Fprintf(os.Stderr, "Encountered %d file(s) that may not have been copied correctly on Windows:\n", len(malformedOnWindows)) for _, m := range malformedOnWindows { fmt.Fprintf(os.Stderr, "\t%s\n", m)
commands: fill in missing printf arg
git-lfs_git-lfs
train
4ddc8d1c7141d63a4b25bca2fd6e0b0051582987
diff --git a/src/Vendor/Model/ManagerInterface.php b/src/Vendor/Model/ManagerInterface.php index <HASH>..<HASH> 100644 --- a/src/Vendor/Model/ManagerInterface.php +++ b/src/Vendor/Model/ManagerInterface.php @@ -34,6 +34,7 @@ interface ManagerInterface VendorInterface $vendor, array $miraklData ); + /** * @param VendorInterface[] $vendors * @return mixed @@ -41,6 +42,12 @@ interface ManagerInterface public function saveAll(array $vendors); /** + * @param VendorInterface $vendor + * @return mixed + */ + public function save($vendor); + + /** * @param int $miraklShopId * @return VendorInterface|null if not found */ diff --git a/src/Vendor/Processor.php b/src/Vendor/Processor.php index <HASH>..<HASH> 100644 --- a/src/Vendor/Processor.php +++ b/src/Vendor/Processor.php @@ -458,4 +458,20 @@ class Processor extends AbstractProcessor } } } + + /** + * To record a wallet in the database in the case there was an error + * + * @param $email + * @param $miraklId + */ + public function recordWallet($email, $miraklId) + { + $vendor = $this->vendorManager->create( + $email, + $miraklId, + $this->hipay->getWalletId($email) + ); + $this->vendorManager->save($vendor); + } } \ No newline at end of file
Add new function to record a wallet in db
hipay_hipay-wallet-cashout-mirakl-library
train
b103ca9be5a863cbb99b8a57dc50ec08d321123e
diff --git a/phpfastcache/3.0.0/drivers/sqlite.php b/phpfastcache/3.0.0/drivers/sqlite.php index <HASH>..<HASH> 100644 --- a/phpfastcache/3.0.0/drivers/sqlite.php +++ b/phpfastcache/3.0.0/drivers/sqlite.php @@ -43,7 +43,7 @@ class phpfastcache_sqlite extends BasePhpFastCache implements phpfastcache_drive $db->exec('drop table if exists "balancing"'); $db->exec('CREATE TABLE "balancing" ("keyword" VARCHAR PRIMARY KEY NOT NULL UNIQUE, "db" INTEGER)'); $db->exec('CREATE INDEX "db" ON "balancing" ("db")'); - $db->exec('CREATE UNIQUE INDEX "lookup" ON "balacing" ("keyword")'); + $db->exec('CREATE UNIQUE INDEX "lookup" ON "balancing" ("keyword")'); }
Fix typo in table name "balacing"
PHPSocialNetwork_phpfastcache
train
e7eab82f8dca5c47cb7d19da4109782f5b5da31c
diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -6,7 +6,7 @@ require 'shoulda' require 'libxml' -require File.dirname(__FILE__) + '/../lib/xero_gateway.rb' +require File.dirname(__FILE__) + '/../lib/xero_gateway.rb' unless defined?(XeroGateway) module TestHelper # The integration tests can be run against the Xero test environment. You mush have a company set up in the test
Fix already defined constant warning when running tests
xero-gateway_xero_gateway
train
30098fd73f19e324eef41832a9971c17eccbea1d
diff --git a/test/e2e/network/network_policy.go b/test/e2e/network/network_policy.go index <HASH>..<HASH> 100644 --- a/test/e2e/network/network_policy.go +++ b/test/e2e/network/network_policy.go @@ -560,7 +560,7 @@ func createNetworkClientPod(f *framework.Framework, namespace *v1.Namespace, pod Args: []string{ "/bin/sh", "-c", - fmt.Sprintf("for i in $(seq 1 5); do wget -q -T 8 %s.%s:%d && exit 0 || sleep 1; done; exit 1", + fmt.Sprintf("for i in $(seq 1 5); do nc -vz -w 8 %s.%s %d && exit 0 || sleep 1; done; exit 1", targetService.Name, targetService.Namespace, targetPort), }, },
Make use of nc for Linux and Windows compatibility
kubernetes_kubernetes
train
57fb24d60656bc99192c9768ff04dd78de9ef695
diff --git a/ez_setup.py b/ez_setup.py index <HASH>..<HASH> 100644 --- a/ez_setup.py +++ b/ez_setup.py @@ -36,7 +36,7 @@ try: except ImportError: USER_SITE = None -DEFAULT_VERSION = "12.0.1" +DEFAULT_VERSION = "12.0.2" DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" def _python_cmd(*args): diff --git a/setuptools/version.py b/setuptools/version.py index <HASH>..<HASH> 100644 --- a/setuptools/version.py +++ b/setuptools/version.py @@ -1 +1 @@ -__version__ = '12.0.1' +__version__ = '12.0.2'
Bumped to <I> in preparation for next release.
pypa_setuptools
train
8a5ac83b8d86051a86d6abdab6864aadee4c5870
diff --git a/h2o-algos/src/main/java/hex/glm/GLM.java b/h2o-algos/src/main/java/hex/glm/GLM.java index <HASH>..<HASH> 100644 --- a/h2o-algos/src/main/java/hex/glm/GLM.java +++ b/h2o-algos/src/main/java/hex/glm/GLM.java @@ -513,7 +513,7 @@ public class GLM extends ModelBuilder<GLMModel,GLMParameters,GLMOutput> { private void fitIRLSM() { LineSearchSolver ls = (_state.l1pen() == 0 && !_state.activeBC().hasBounds()) ? new MoreThuente(_state.gslvr(),_state.beta(), _state.ginfo()) - : new SimpleBacktrackingLS(_state.gslvr(),_state.beta().clone(), _state.l1pen(), _state.ginfo(),.5); + : new SimpleBacktrackingLS(_state.gslvr(),_state.beta().clone(), _state.l1pen(), _state.ginfo()); GLMWeightsFun glmw = new GLMWeightsFun(_parms); while(true) { long t1 = System.currentTimeMillis(); @@ -523,7 +523,7 @@ public class GLM extends ModelBuilder<GLMModel,GLMParameters,GLMOutput> { if(betaCnd.length < ls.getX().length) { ls = (_state.l1pen() == 0 && !_state.activeBC().hasBounds()) ? new MoreThuente(_state.gslvr(),_state.beta(), _state.ginfo()) - : new SimpleBacktrackingLS(_state.gslvr(),_state.beta().clone(), _state.l1pen(), _state.ginfo(),.5); + : new SimpleBacktrackingLS(_state.gslvr(),_state.beta().clone(), _state.l1pen(), _state.ginfo()); } long t3 = System.currentTimeMillis(); if (!ls.evaluate(ArrayUtils.subtract(betaCnd, ls.getX(), betaCnd))) { diff --git a/h2o-algos/src/main/java/hex/optimization/OptimizationUtils.java b/h2o-algos/src/main/java/hex/optimization/OptimizationUtils.java index <HASH>..<HASH> 100644 --- a/h2o-algos/src/main/java/hex/optimization/OptimizationUtils.java +++ b/h2o-algos/src/main/java/hex/optimization/OptimizationUtils.java @@ -59,22 +59,21 @@ public class OptimizationUtils { public static final class SimpleBacktrackingLS implements LineSearchSolver { private double [] _beta; - final double _stepDec; + final double _stepDec = .33; private double _step; private final GradientSolver _gslvr; private GradientInfo _ginfo; // gradient info excluding l1 penalty private double _objVal; // objective including l1 penalty final double _l1pen; - int _maxfev = 5; + int _maxfev = 10; double _minStep = 1e-4; public SimpleBacktrackingLS(GradientSolver gslvr, double [] betaStart, double l1pen) { - this(gslvr, betaStart, l1pen, gslvr.getObjective(betaStart),.5); + this(gslvr, betaStart, l1pen, gslvr.getObjective(betaStart)); } - public SimpleBacktrackingLS(GradientSolver gslvr, double [] betaStart, double l1pen, GradientInfo ginfo, double stepDec) { + public SimpleBacktrackingLS(GradientSolver gslvr, double [] betaStart, double l1pen, GradientInfo ginfo) { _gslvr = gslvr; - _stepDec = stepDec; _beta = betaStart; _ginfo = ginfo; _l1pen = l1pen; @@ -95,8 +94,13 @@ public class OptimizationUtils { @Override public boolean evaluate(double[] direction) { double step = 1; + double minStep = 1; + for(double d:direction) { + d = Math.abs(1e-4/d); + if(d < minStep) minStep = d; + } double [] newBeta = direction.clone(); - for(int i = 0; i < _maxfev && step >= _minStep; ++i, step*= _stepDec) { + for(int i = 0; i < _maxfev && step >= minStep; ++i, step*= _stepDec) { GradientInfo ginfo = _gslvr.getObjective(ArrayUtils.wadd(_beta,direction,newBeta,step)); double objVal = ginfo._objVal + _l1pen * ArrayUtils.l1norm(newBeta,true); if(objVal < _objVal){ @@ -106,6 +110,7 @@ public class OptimizationUtils { _step = step; return true; } + } return false; }
updated line search in GLM, decreased step size, increased max number of steps.
h2oai_h2o-3
train
fd198b8776ebfac86b079cc105e8b07e5c4d641b
diff --git a/mod/quiz/backuplib.php b/mod/quiz/backuplib.php index <HASH>..<HASH> 100644 --- a/mod/quiz/backuplib.php +++ b/mod/quiz/backuplib.php @@ -754,6 +754,8 @@ fwrite ($bf,full_tag("PASSWORD",4,false,$quiz->password)); fwrite ($bf,full_tag("SUBNET",4,false,$quiz->subnet)); fwrite ($bf,full_tag("POPUP",4,false,$quiz->popup)); + fwrite ($bf,full_tag("DELAY1",4,false,$quiz->delay1)); + fwrite ($bf,full_tag("DELAY2",4,false,$quiz->delay2)); //Now we print to xml question_instances (Course Level) $status = backup_quiz_question_instances($bf,$preferences,$quiz->id); //Now we print to xml question_versions (Course Level) diff --git a/mod/quiz/restorelib.php b/mod/quiz/restorelib.php index <HASH>..<HASH> 100644 --- a/mod/quiz/restorelib.php +++ b/mod/quiz/restorelib.php @@ -1352,7 +1352,8 @@ $quiz->password = backup_todb($info['MOD']['#']['PASSWORD']['0']['#']); $quiz->subnet = backup_todb($info['MOD']['#']['SUBNET']['0']['#']); $quiz->popup = backup_todb($info['MOD']['#']['POPUP']['0']['#']); - + $quiz->delay1 = backup_todb($info['MOD']['#']['DELAY1']['0']['#']); + $quiz->delay2 = backup_todb($info['MOD']['#']['DELAY2']['0']['#']); //We have to recode the questions field (a list of questions id and pagebreaks) $quiz->questions = quiz_recode_layout($quiz->questions, $restore);
Adding new feature: Time delay between quiz attempts
moodle_moodle
train
641868fc5913bddea877fa7dc261ab7e15addec1
diff --git a/js/qryptos.js b/js/qryptos.js index <HASH>..<HASH> 100644 --- a/js/qryptos.js +++ b/js/qryptos.js @@ -319,8 +319,13 @@ module.exports = class qryptos extends Exchange { }; if (typeof limit !== 'undefined') request['limit'] = limit; + let queryByTimestamp = false; + if (typeof since !== 'undefined') { + request['timestamp'] = since; + queryByTimestamp = true; + } let response = await this.publicGetExecutions (this.extend (request, params)); - return this.parseTrades (response['models'], market, since, limit); + return this.parseTrades((queryByTimestamp ? response : response['models']), market, since, limit); } async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) { diff --git a/python/ccxt/qryptos.py b/python/ccxt/qryptos.py index <HASH>..<HASH> 100644 --- a/python/ccxt/qryptos.py +++ b/python/ccxt/qryptos.py @@ -305,8 +305,10 @@ class qryptos (Exchange): } if limit is not None: request['limit'] = limit + if since is not None: + request['timestamp'] = since response = self.publicGetExecutions(self.extend(request, params)) - return self.parse_trades(response['models'], market, since, limit) + return self.parse_trades(response['models'] if since is None else response, market, since, limit) def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}): self.load_markets()
BugFixed: Get Executions by Timestamp lossing timestamp paramter and parse error.
ccxt_ccxt
train
6c4749b33c604576ca89cb58b398f973010b3e1a
diff --git a/cmd/minikube/cmd/config/profile.go b/cmd/minikube/cmd/config/profile.go index <HASH>..<HASH> 100644 --- a/cmd/minikube/cmd/config/profile.go +++ b/cmd/minikube/cmd/config/profile.go @@ -22,7 +22,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" "io/ioutil" - "k8s.io/kubernetes/cmd/kube-scheduler/app/config" + minikubeConfig "k8s.io/minikube/pkg/minikube/config" pkgConfig "k8s.io/minikube/pkg/minikube/config" "k8s.io/minikube/pkg/minikube/console" "k8s.io/minikube/pkg/minikube/constants" @@ -124,7 +124,7 @@ func isValidProfile(profilePath string) bool { fileContent := string(bytes) fmt.Println(fileContent) - var configObject config.Config + var configObject minikubeConfig.Config errUnmarshal := json.Unmarshal(bytes, &configObject)
Bugfix: Imported wrong configname
kubernetes_minikube
train
eba999b5ed79beb5ece67b491b30f84d30ef2659
diff --git a/admin_users.php b/admin_users.php index <HASH>..<HASH> 100644 --- a/admin_users.php +++ b/admin_users.php @@ -177,7 +177,15 @@ case 'loadrows': $ORDER_BY = '1 ASC'; } - $sql = "SELECT SQL_CACHE SQL_CALC_FOUND_ROWS '', u.user_id, user_name, real_name, email, us1.setting_value, us2.setting_value, us2.setting_value, us3.setting_value, us3.setting_value, us4.setting_value, us5.setting_value" . " FROM `##user` u" . " LEFT JOIN `##user_setting` us1 ON (u.user_id=us1.user_id AND us1.setting_name='language')" . " LEFT JOIN `##user_setting` us2 ON (u.user_id=us2.user_id AND us2.setting_name='reg_timestamp')" . " LEFT JOIN `##user_setting` us3 ON (u.user_id=us3.user_id AND us3.setting_name='sessiontime')" . " LEFT JOIN `##user_setting` us4 ON (u.user_id=us4.user_id AND us4.setting_name='verified')" . " LEFT JOIN `##user_setting` us5 ON (u.user_id=us5.user_id AND us5.setting_name='approved')" . $WHERE . $ORDER_BY . $LIMIT; + $sql = + "SELECT SQL_CACHE SQL_CALC_FOUND_ROWS '', u.user_id, user_name, real_name, email, us1.setting_value, us2.setting_value, us2.setting_value, us3.setting_value, us3.setting_value, us4.setting_value, us5.setting_value" . + " FROM `##user` u" . + " LEFT JOIN `##user_setting` us1 ON (u.user_id=us1.user_id AND us1.setting_name='language')" . + " LEFT JOIN `##user_setting` us2 ON (u.user_id=us2.user_id AND us2.setting_name='reg_timestamp')" . + " LEFT JOIN `##user_setting` us3 ON (u.user_id=us3.user_id AND us3.setting_name='sessiontime')" . + " LEFT JOIN `##user_setting` us4 ON (u.user_id=us4.user_id AND us4.setting_name='verified')" . + " LEFT JOIN `##user_setting` us5 ON (u.user_id=us5.user_id AND us5.setting_name='verified_by_admin')" . + $WHERE . $ORDER_BY . $LIMIT; // This becomes a JSON list, not array, so need to fetch with numeric keys. $data = WT_DB::prepare($sql)->execute($ARGS)->fetchAll(PDO::FETCH_NUM);
verified_by_admin always shown as 'no' on user list
fisharebest_webtrees
train
b63d99b7919185b36de3eb6a06e8e37c53981887
diff --git a/tasks/fest.js b/tasks/fest.js index <HASH>..<HASH> 100644 --- a/tasks/fest.js +++ b/tasks/fest.js @@ -77,6 +77,8 @@ module.exports = function (grunt) { } grunt.file.write(dest, contents); grunt.log.ok(); + } else { + grunt.fail.fatal('Can\'t compile ' + src); } }); });
Update fest.js Die, if you can't compile file
eprev_grunt-fest
train
9957e88e5ca6c572656d75abbf5d066069c4ff1b
diff --git a/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java b/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java index <HASH>..<HASH> 100644 --- a/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java +++ b/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java @@ -774,10 +774,14 @@ public class GenJsCodeVisitor extends AbstractSoyNodeVisitor<List<String>> { if (node instanceof TemplateElementNode) { TemplateElementNode elementNode = (TemplateElementNode) node; for (TemplateStateVar stateVar : elementNode.getStateVars()) { - bodyStatements.add( - VariableDeclaration.builder(stateVar.name()) - .setRhs(getExprTranslator().exec(stateVar.defaultValue())) - .build()); + Expression expr = getExprTranslator().exec(stateVar.defaultValue()); + // A state variable can be something like ns.foo.FooProto|null. Without + // this cast, access to this variable can trigger JS conformance errors + // due to unknown type. + if (!stateVar.type().equals(stateVar.defaultValue().getType())) { + expr = expr.castAs(JsType.forJsSrc(stateVar.type()).typeExpr()); + } + bodyStatements.add(VariableDeclaration.builder(stateVar.name()).setRhs(expr).build()); } } // Generate statement to ensure data is defined, if necessary.
Cast state variables in jssrc to avoid issues like where the state var is a proto. GITHUB_BREAKING_CHANGES=n/a ------------- Created by MOE: <URL>
google_closure-templates
train
6cf3006baf8ec9d3bb120315bd749bb6116ce9b0
diff --git a/design/dsl/attribute.go b/design/dsl/attribute.go index <HASH>..<HASH> 100644 --- a/design/dsl/attribute.go +++ b/design/dsl/attribute.go @@ -1,6 +1,7 @@ package dsl import ( + "reflect" "regexp" "strconv" "strings" @@ -322,28 +323,8 @@ func Minimum(val interface{}) { } else { var f float64 switch v := val.(type) { - case float32: - f = float64(v) - case float64: - f = v - case int: - f = float64(v) - case int8: - f = float64(v) - case int16: - f = float64(v) - case int32: - f = float64(v) - case int64: - f = float64(v) - case uint8: - f = float64(v) - case uint16: - f = float64(v) - case uint32: - f = float64(v) - case uint64: - f = float64(v) + case float32, float64, int, int8, int16, int32, int64, uint8, uint16, uint32, uint64: + f = reflect.ValueOf(v).Convert(reflect.TypeOf(float64(0.0))).Float() case string: var err error f, err = strconv.ParseFloat(v, 64) @@ -369,28 +350,8 @@ func Maximum(val interface{}) { } else { var f float64 switch v := val.(type) { - case float32: - f = float64(v) - case float64: - f = v - case int: - f = float64(v) - case int8: - f = float64(v) - case int16: - f = float64(v) - case int32: - f = float64(v) - case int64: - f = float64(v) - case uint8: - f = float64(v) - case uint16: - f = float64(v) - case uint32: - f = float64(v) - case uint64: - f = float64(v) + case float32, float64, int, int8, int16, int32, int64, uint8, uint16, uint32, uint64: + f = reflect.ValueOf(v).Convert(reflect.TypeOf(float64(0.0))).Float() case string: var err error f, err = strconv.ParseFloat(v, 64)
Reduce Max/Min cyclomatic complexity, #<I>
goadesign_goa
train