问:
SonarQube with Postgres DB
I have searched and read many post on this but can not find an solution to my particular problem.

When running Sonar on a centos lonux box i get an error:

```<code>JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
</code>```

I have verified that the sonar user (I am using sonarqube) has access to the DB, it is the owner of its own schema and I have granted it all rights to every thing just to make sure its not a permissions thing.

I am using Postgres 9.4.

Full log is as blow, when trying to view the sonar GUI it just displays a page with the following text:

```<code>org.jruby.rack.RackInitializationException: ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227:in `log'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183:in `execute'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109:in `create_table'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371:in `initialize_schema_migrations_table'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441:in `initialize'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401:in `up'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383:in `migrate'
    from /opt/sonar/web/WEB-INF/lib/database_version.rb:62:in `upgrade_and_start'
    from /opt/sonar/web/WEB-INF/lib/database_version.rb:73:in `automatic_setup'
    from /opt/sonar/web/WEB-INF/config/environment.rb:272:in `(root)'
    from org/jruby/RubyKernel.java:1094:in `load'
    from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1:in `(root)'
    from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25:in `load_environment'
    from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79:in `load_environment'

    at org.jruby.rack.RackInitializationException.wrap(RackInitializationException.java:29)
    at org.jruby.rack.RackApplicationFactoryDecorator.init(RackApplicationFactoryDecorator.java:98)
    at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletContextListener.java:50)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4720)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.jruby.exceptions.RaiseException: (StatementInvalid) ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
    at RUBY.log(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227)
    at RUBY.execute(/opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183)
    at RUBY.create_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109)
    at RUBY.initialize_schema_migrations_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371)
    at RUBY.initialize(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441)
    at RUBY.up(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401)
    at RUBY.migrate(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383)
    at RUBY.upgrade_and_start(/opt/sonar/web/WEB-INF/lib/database_version.rb:62)
    at RUBY.automatic_setup(/opt/sonar/web/WEB-INF/lib/database_version.rb:73)
    at RUBY.(root)(/opt/sonar/web/WEB-INF/config/environment.rb:272)
    at org.jruby.RubyKernel.load(org/jruby/RubyKernel.java:1094)
    at RUBY.(root)(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1)
    at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25)
    at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79)
</code>```

FULL LOG

```<code>Starting SonarQube...
Started SonarQube.
--> Wrapper Started as Daemon
Launching a JVM...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

2015.06.11 10:48:26 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[search]: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.45-28.b13.el6_6.x86_64/jre/bin/java -Djava.awt.headless=true -Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/opt/sonar/temp -cp ./lib/common/*:./lib/search/* org.sonar.search.SearchServer /tmp/sq-process5828587312976552037properties
2015.06.11 10:48:27 INFO   es[o.s.p.ProcessEntryPoint]  Starting search
2015.06.11 10:48:27 INFO   es[o.s.s.SearchServer]  Starting Elasticsearch[sonarqube] on port 9001
2015.06.11 10:48:27 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] version[1.4.4], pid[9441], build[c88f77f/2015-02-19T13:05:36Z]
2015.06.11 10:48:27 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] initializing ...
2015.06.11 10:48:27 INFO   es[o.e.plugins]  [sonar-1434016106548] loaded [], sites []
2015.06.11 10:48:29 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] initialized
2015.06.11 10:48:29 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] starting ...
2015.06.11 10:48:29 INFO   es[o.e.transport]  [sonar-1434016106548] bound_address {inet[/0.0.0.0:9001]}, publish_address {inet[/10.124.36.4:9001]}
2015.06.11 10:48:29 INFO   es[o.e.discovery]  [sonar-1434016106548] sonarqube/FEFMEfLcSuCppleivZ6mEA
2015.06.11 10:48:32 INFO   es[o.e.cluster.service]  [sonar-1434016106548] new_master [sonar-1434016106548][FEFMEfLcSuCppleivZ6mEA][sixdsbox03][inet[/10.124.36.4:9001]]{rack_id=sonar-1434016106548}, reason: zen-disco-join (elected_as_master)
2015.06.11 10:48:33 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] started
2015.06.11 10:48:33 INFO   es[o.e.gateway]  [sonar-1434016106548] recovered [1] indices into cluster_state
OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=160m; support was removed in 8.0
2015.06.11 10:48:34 INFO  app[o.s.p.m.Monitor] Process[search] is up
2015.06.11 10:48:34 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[web]: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.45-28.b13.el6_6.x86_64/jre/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djruby.management.enabled=false -Djruby.compile.invokedynamic=false -Xmx768m -XX:MaxPermSize=160m -XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=true -Djava.io.tmpdir=/opt/sonar/temp -cp ./lib/common/*:./lib/server/*:/opt/sonar/lib/jdbc/postgresql/postgresql-9.3-1102-jdbc41.jar org.sonar.server.app.WebServer /tmp/sq-process2367145408484339873properties
2015.06.11 10:48:34 INFO  web[o.s.p.ProcessEntryPoint] Starting web
2015.06.11 10:48:35 INFO  web[o.s.s.app.Webapp] Webapp directory: /opt/sonar/web
2015.06.11 10:48:35 INFO  web[o.a.c.h.Http11NioProtocol] Initializing ProtocolHandler ["http-nio-0.0.0.0-9000"]
2015.06.11 10:48:35 INFO  web[o.a.t.u.n.NioSelectorPool] Using a shared selector for servlet write/read
2015.06.11 10:48:36 INFO  web[o.e.plugins] [sonar-1434016106548] loaded [], sites []
2015.06.11 10:48:36 INFO  web[o.s.s.p.ServerImpl] SonarQube Server / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:36 INFO  web[o.s.c.p.Database] Create JDBC datasource for jdbc:postgresql://localhost/sonarqube
2015.06.11 10:48:37 INFO  web[o.s.s.p.DefaultServerFileSystem] SonarQube home: /opt/sonar
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Install plugins
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Email notifications / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Core / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Java / 3.0 / 65396a609ddface8b311a6a665aca92a7da694f1
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Git / 1.0 / 9ce9d330c313c296fab051317cc5ad4b26319e07
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin English Pack / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin SVN / 1.0 / 213fc8a8b582ff530b12dd4a59a6512be1071234
2015.06.11 10:48:38 INFO  web[o.s.s.p.RailsAppsDeployer] Deploy Ruby on Rails applications
2015.06.11 10:48:38 INFO  web[jruby.rack] jruby 1.7.9 (ruby-1.8.7p370) 2013-12-06 87b108a on OpenJDK 64-Bit Server VM 1.8.0_45-b13 [linux-amd64]
2015.06.11 10:48:38 INFO  web[jruby.rack] using a shared (threadsafe!) runtime
2015.06.11 10:48:47 INFO  web[jruby.rack] An exception happened during JRuby-Rack startup
ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
--- System
jruby 1.7.9 (ruby-1.8.7p370) 2013-12-06 87b108a on OpenJDK 64-Bit Server VM 1.8.0_45-b13 [linux-amd64]
Time: Thu Jun 11 10:48:47 +0100 2015
Server: Apache Tomcat/8.0.18
jruby.home: file:/opt/sonar/lib/server/jruby-complete-1.7.9.jar!/META-INF/jruby.home

--- Context Init Parameters:
jruby.compat.version = 1.8
jruby.max.runtimes = 1
jruby.min.runtimes = 1
jruby.rack.logging = slf4j
process.index = 1
process.key = web
process.sharedDir = /opt/sonar/temp
process.terminationTimeout = 60000
public.root = /
rails.env = production
sonar.cluster.name = sonarqube
sonar.jdbc.driverPath = /opt/sonar/lib/jdbc/postgresql/postgresql-9.3-1102-jdbc41.jar
sonar.jdbc.maxActive = 50
sonar.jdbc.maxIdle = 5
sonar.jdbc.maxWait = 5000
sonar.jdbc.minEvictableIdleTimeMillis = 600000
sonar.jdbc.minIdle = 2
sonar.jdbc.password = sonarqube
sonar.jdbc.timeBetweenEvictionRunsMillis = 30000
sonar.jdbc.url = jdbc:postgresql://localhost/sonarqube
sonar.jdbc.username = sonarqube
sonar.node.name = sonar-1434016106548
sonar.path.data = /opt/sonar/data
sonar.path.home = /opt/sonar
sonar.path.logs = /opt/sonar/logs
sonar.path.temp = /opt/sonar/temp
sonar.path.web = /opt/sonar/web
sonar.search.javaAdditionalOpts =
sonar.search.javaOpts = -Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError
sonar.search.port = 9001
sonar.search.type = TRANSPORT
sonar.web.javaAdditionalOpts =
sonar.web.javaOpts = -Xmx768m -XX:MaxPermSize=160m -XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=true

--- Backtrace
ActiveRecord::StatementInvalid: ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
                                 log at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227
                             execute at /opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183
                        create_table at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109
  initialize_schema_migrations_table at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371
                          initialize at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441
                                  up at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401
                             migrate at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383
                   upgrade_and_start at /opt/sonar/web/WEB-INF/lib/database_version.rb:62
                     automatic_setup at /opt/sonar/web/WEB-INF/lib/database_version.rb:73
                              (root) at /opt/sonar/web/WEB-INF/config/environment.rb:272
                                load at org/jruby/RubyKernel.java:1094
                              (root) at file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1
                    load_environment at file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25
                    load_environment at file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79

--- RubyGems
Gem.dir: /opt/sonar/web/WEB-INF/gems
Gem.path:
/opt/sonar/web/WEB-INF/gems
Activated gems:
  activesupport-2.3.15
  activerecord-2.3.15
  rack-1.1.6
  actionpack-2.3.15
  rails-2.3.15
  color-tools-1.3.0
  i18n-0.4.2
  json-jruby-1.2.3-universal-java-1.6
  activerecord-jdbc-adapter-1.1.3
  fastercsv-1.4.0

--- Bundler
undefined method `bundle_path' for Bundler:Module

--- JRuby-Rack Config
compat_version = RUBY1_8
default_logger = org.jruby.rack.logging.StandardOutLogger@238dcac9
equals = <error: >
err = java.io.PrintStream@2ca0e62a
filter_adds_html = true
filter_verifies_resource = false
ignore_environment = false
initial_memory_buffer_size =
initial_runtimes = 1
jms_connection_factory =
jms_jndi_properties =
logger = org.jruby.rack.logging.Slf4jLogger@64935b57
logger_class_name = slf4j
logger_name = jruby.rack
maximum_memory_buffer_size =
maximum_runtimes = 1
num_initializer_threads =
out = java.io.PrintStream@4a8c212
rackup =
rackup_path =
rewindable = true
runtime_arguments =
runtime_environment =
runtime_timeout_seconds =
serial_initialization = false
servlet_context = org.apache.catalina.core.ApplicationContextFacade@2eaa81c7
throw_init_exception = false

2015.06.11 10:48:47 ERROR web[jruby.rack] initialization failed
org.jruby.rack.RackInitializationException: ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227:in `log'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183:in `execute'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109:in `create_table'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371:in `initialize_schema_migrations_table'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441:in `initialize'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401:in `up'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383:in `migrate'
        from /opt/sonar/web/WEB-INF/lib/database_version.rb:62:in `upgrade_and_start'
        from /opt/sonar/web/WEB-INF/lib/database_version.rb:73:in `automatic_setup'
        from /opt/sonar/web/WEB-INF/config/environment.rb:272:in `(root)'
        from org/jruby/RubyKernel.java:1094:in `load'
        from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1:in `(root)'
        from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25:in `load_environment'
        from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79:in `load_environment'

        at org.jruby.rack.RackInitializationException.wrap(RackInitializationException.java:29) ~[jruby-rack-1.1.13.2.jar:na]
        at org.jruby.rack.RackApplicationFactoryDecorator.init(RackApplicationFactoryDecorator.java:98) ~[jruby-rack-1.1.13.2.jar:na]
        at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletContextListener.java:50) ~[jruby-rack-1.1.13.2.jar:na]
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4720) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_45]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_45]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_45]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]
Caused by: org.jruby.exceptions.RaiseException: (StatementInvalid) ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
        at RUBY.log(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227) ~[na:na]
        at RUBY.execute(/opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183) ~[na:na]
        at RUBY.create_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109) ~[na:na]
        at RUBY.initialize_schema_migrations_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371) ~[na:na]
        at RUBY.initialize(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441) ~[na:na]
        at RUBY.up(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401) ~[na:na]
        at RUBY.migrate(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383) ~[na:na]
        at RUBY.upgrade_and_start(/opt/sonar/web/WEB-INF/lib/database_version.rb:62) ~[na:na]
        at RUBY.automatic_setup(/opt/sonar/web/WEB-INF/lib/database_version.rb:73) ~[na:na]
        at RUBY.(root)(/opt/sonar/web/WEB-INF/config/environment.rb:272) ~[na:na]
        at org.jruby.RubyKernel.load(org/jruby/RubyKernel.java:1094) ~[jruby-complete-1.7.9.jar:na]
        at RUBY.(root)(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1) ~[na:na]
        at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25) ~[na:na]
        at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79) ~[na:na]
2015.06.11 10:48:47 INFO  web[o.a.c.h.Http11NioProtocol] Starting ProtocolHandler ["http-nio-0.0.0.0-9000"]
2015.06.11 10:48:47 INFO  web[o.s.s.a.TomcatAccessLog] Web server is started
2015.06.11 10:48:47 INFO  web[o.s.s.a.EmbeddedTomcat] HTTP connector enabled on port 9000
2015.06.11 10:48:47 INFO  app[o.s.p.m.Monitor] Process[web] is up
</code>```

答:
Maybe it is too late to response to this, but I recently ran into similar error and it took me a while to debug the problem.

The problem in my case was misunderstanding what needs to be done as you need to have user with password to be set (Sonarqube properties) and configure (in Postgresql DB)

```<code>sonar.jdbc.username=<sonar_user>
sonar.jdbc.password=<sonar_user_password>
</code>```

Then the connection string must be correct

```<code>sonar.jdbc.url=jdbc:postgresql://localhost:5432/<sonar_postgres_db>
</code>```

And then you need to have schema configured and the  must have it set as search_path (I still don't understand all that, so apologies for terminology)

So as @RawToast answer did help me, but I had to do the following:

create schema sonardb (exactly what Sonarqube was expecting)

set search path for  to point to that schema ALTER USER <sonar_user> SET search_path TO sonardb;

ALTER USER sonar SET search_path TO sonardb;

Title: SonarQube with Postgres DB

Body:
I have searched and read many post on this but can not find an solution to my particular problem.

When running Sonar on a centos lonux box i get an error:

JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)

I have verified that the sonar user (I am using sonarqube) has access to the DB, it is the owner of its own schema and I have granted it all rights to every thing just to make sure its not a permissions thing.

I am using Postgres 9.4.

Full log is as blow, when trying to view the sonar GUI it just displays a page with the following text:

org.jruby.rack.RackInitializationException: ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227:in `log'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183:in `execute'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109:in `create_table'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371:in `initialize_schema_migrations_table'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441:in `initialize'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401:in `up'
    from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383:in `migrate'
    from /opt/sonar/web/WEB-INF/lib/database_version.rb:62:in `upgrade_and_start'
    from /opt/sonar/web/WEB-INF/lib/database_version.rb:73:in `automatic_setup'
    from /opt/sonar/web/WEB-INF/config/environment.rb:272:in `(root)'
    from org/jruby/RubyKernel.java:1094:in `load'
    from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1:in `(root)'
    from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25:in `load_environment'
    from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79:in `load_environment'

    at org.jruby.rack.RackInitializationException.wrap(RackInitializationException.java:29)
    at org.jruby.rack.RackApplicationFactoryDecorator.init(RackApplicationFactoryDecorator.java:98)
    at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletContextListener.java:50)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4720)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.jruby.exceptions.RaiseException: (StatementInvalid) ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
    at RUBY.log(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227)
    at RUBY.execute(/opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183)
    at RUBY.create_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109)
    at RUBY.initialize_schema_migrations_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371)
    at RUBY.initialize(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441)
    at RUBY.up(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401)
    at RUBY.migrate(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383)
    at RUBY.upgrade_and_start(/opt/sonar/web/WEB-INF/lib/database_version.rb:62)
    at RUBY.automatic_setup(/opt/sonar/web/WEB-INF/lib/database_version.rb:73)
    at RUBY.(root)(/opt/sonar/web/WEB-INF/config/environment.rb:272)
    at org.jruby.RubyKernel.load(org/jruby/RubyKernel.java:1094)
    at RUBY.(root)(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1)
    at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25)
    at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79)

FULL LOG

Starting SonarQube...
Started SonarQube.
--> Wrapper Started as Daemon
Launching a JVM...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

2015.06.11 10:48:26 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[search]: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.45-28.b13.el6_6.x86_64/jre/bin/java -Djava.awt.headless=true -Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/opt/sonar/temp -cp ./lib/common/*:./lib/search/* org.sonar.search.SearchServer /tmp/sq-process5828587312976552037properties
2015.06.11 10:48:27 INFO   es[o.s.p.ProcessEntryPoint]  Starting search
2015.06.11 10:48:27 INFO   es[o.s.s.SearchServer]  Starting Elasticsearch[sonarqube] on port 9001
2015.06.11 10:48:27 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] version[1.4.4], pid[9441], build[c88f77f/2015-02-19T13:05:36Z]
2015.06.11 10:48:27 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] initializing ...
2015.06.11 10:48:27 INFO   es[o.e.plugins]  [sonar-1434016106548] loaded [], sites []
2015.06.11 10:48:29 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] initialized
2015.06.11 10:48:29 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] starting ...
2015.06.11 10:48:29 INFO   es[o.e.transport]  [sonar-1434016106548] bound_address {inet[/0.0.0.0:9001]}, publish_address {inet[/10.124.36.4:9001]}
2015.06.11 10:48:29 INFO   es[o.e.discovery]  [sonar-1434016106548] sonarqube/FEFMEfLcSuCppleivZ6mEA
2015.06.11 10:48:32 INFO   es[o.e.cluster.service]  [sonar-1434016106548] new_master [sonar-1434016106548][FEFMEfLcSuCppleivZ6mEA][sixdsbox03][inet[/10.124.36.4:9001]]{rack_id=sonar-1434016106548}, reason: zen-disco-join (elected_as_master)
2015.06.11 10:48:33 INFO   es[o.elasticsearch.node]  [sonar-1434016106548] started
2015.06.11 10:48:33 INFO   es[o.e.gateway]  [sonar-1434016106548] recovered [1] indices into cluster_state
OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=160m; support was removed in 8.0
2015.06.11 10:48:34 INFO  app[o.s.p.m.Monitor] Process[search] is up
2015.06.11 10:48:34 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[web]: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.45-28.b13.el6_6.x86_64/jre/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djruby.management.enabled=false -Djruby.compile.invokedynamic=false -Xmx768m -XX:MaxPermSize=160m -XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=true -Djava.io.tmpdir=/opt/sonar/temp -cp ./lib/common/*:./lib/server/*:/opt/sonar/lib/jdbc/postgresql/postgresql-9.3-1102-jdbc41.jar org.sonar.server.app.WebServer /tmp/sq-process2367145408484339873properties
2015.06.11 10:48:34 INFO  web[o.s.p.ProcessEntryPoint] Starting web
2015.06.11 10:48:35 INFO  web[o.s.s.app.Webapp] Webapp directory: /opt/sonar/web
2015.06.11 10:48:35 INFO  web[o.a.c.h.Http11NioProtocol] Initializing ProtocolHandler ["http-nio-0.0.0.0-9000"]
2015.06.11 10:48:35 INFO  web[o.a.t.u.n.NioSelectorPool] Using a shared selector for servlet write/read
2015.06.11 10:48:36 INFO  web[o.e.plugins] [sonar-1434016106548] loaded [], sites []
2015.06.11 10:48:36 INFO  web[o.s.s.p.ServerImpl] SonarQube Server / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:36 INFO  web[o.s.c.p.Database] Create JDBC datasource for jdbc:postgresql://localhost/sonarqube
2015.06.11 10:48:37 INFO  web[o.s.s.p.DefaultServerFileSystem] SonarQube home: /opt/sonar
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Install plugins
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Email notifications / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Core / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Java / 3.0 / 65396a609ddface8b311a6a665aca92a7da694f1
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin Git / 1.0 / 9ce9d330c313c296fab051317cc5ad4b26319e07
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin English Pack / 5.1.1 / 0a231d24c0f1e7ce1d200274b8e9bbe00f9f49fb
2015.06.11 10:48:38 INFO  web[o.s.s.p.ServerPluginJarsInstaller] Deploy plugin SVN / 1.0 / 213fc8a8b582ff530b12dd4a59a6512be1071234
2015.06.11 10:48:38 INFO  web[o.s.s.p.RailsAppsDeployer] Deploy Ruby on Rails applications
2015.06.11 10:48:38 INFO  web[jruby.rack] jruby 1.7.9 (ruby-1.8.7p370) 2013-12-06 87b108a on OpenJDK 64-Bit Server VM 1.8.0_45-b13 [linux-amd64]
2015.06.11 10:48:38 INFO  web[jruby.rack] using a shared (threadsafe!) runtime
2015.06.11 10:48:47 INFO  web[jruby.rack] An exception happened during JRuby-Rack startup
ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
--- System
jruby 1.7.9 (ruby-1.8.7p370) 2013-12-06 87b108a on OpenJDK 64-Bit Server VM 1.8.0_45-b13 [linux-amd64]
Time: Thu Jun 11 10:48:47 +0100 2015
Server: Apache Tomcat/8.0.18
jruby.home: file:/opt/sonar/lib/server/jruby-complete-1.7.9.jar!/META-INF/jruby.home

--- Context Init Parameters:
jruby.compat.version = 1.8
jruby.max.runtimes = 1
jruby.min.runtimes = 1
jruby.rack.logging = slf4j
process.index = 1
process.key = web
process.sharedDir = /opt/sonar/temp
process.terminationTimeout = 60000
public.root = /
rails.env = production
sonar.cluster.name = sonarqube
sonar.jdbc.driverPath = /opt/sonar/lib/jdbc/postgresql/postgresql-9.3-1102-jdbc41.jar
sonar.jdbc.maxActive = 50
sonar.jdbc.maxIdle = 5
sonar.jdbc.maxWait = 5000
sonar.jdbc.minEvictableIdleTimeMillis = 600000
sonar.jdbc.minIdle = 2
sonar.jdbc.password = sonarqube
sonar.jdbc.timeBetweenEvictionRunsMillis = 30000
sonar.jdbc.url = jdbc:postgresql://localhost/sonarqube
sonar.jdbc.username = sonarqube
sonar.node.name = sonar-1434016106548
sonar.path.data = /opt/sonar/data
sonar.path.home = /opt/sonar
sonar.path.logs = /opt/sonar/logs
sonar.path.temp = /opt/sonar/temp
sonar.path.web = /opt/sonar/web
sonar.search.javaAdditionalOpts =
sonar.search.javaOpts = -Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError
sonar.search.port = 9001
sonar.search.type = TRANSPORT
sonar.web.javaAdditionalOpts =
sonar.web.javaOpts = -Xmx768m -XX:MaxPermSize=160m -XX:+HeapDumpOnOutOfMemoryError -Djava.net.preferIPv4Stack=true

--- Backtrace
ActiveRecord::StatementInvalid: ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
                                 log at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227
                             execute at /opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183
                        create_table at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109
  initialize_schema_migrations_table at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371
                          initialize at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441
                                  up at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401
                             migrate at /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383
                   upgrade_and_start at /opt/sonar/web/WEB-INF/lib/database_version.rb:62
                     automatic_setup at /opt/sonar/web/WEB-INF/lib/database_version.rb:73
                              (root) at /opt/sonar/web/WEB-INF/config/environment.rb:272
                                load at org/jruby/RubyKernel.java:1094
                              (root) at file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1
                    load_environment at file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25
                    load_environment at file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79

--- RubyGems
Gem.dir: /opt/sonar/web/WEB-INF/gems
Gem.path:
/opt/sonar/web/WEB-INF/gems
Activated gems:
  activesupport-2.3.15
  activerecord-2.3.15
  rack-1.1.6
  actionpack-2.3.15
  rails-2.3.15
  color-tools-1.3.0
  i18n-0.4.2
  json-jruby-1.2.3-universal-java-1.6
  activerecord-jdbc-adapter-1.1.3
  fastercsv-1.4.0

--- Bundler
undefined method `bundle_path' for Bundler:Module

--- JRuby-Rack Config
compat_version = RUBY1_8
default_logger = org.jruby.rack.logging.StandardOutLogger@238dcac9
equals = <error: >
err = java.io.PrintStream@2ca0e62a
filter_adds_html = true
filter_verifies_resource = false
ignore_environment = false
initial_memory_buffer_size =
initial_runtimes = 1
jms_connection_factory =
jms_jndi_properties =
logger = org.jruby.rack.logging.Slf4jLogger@64935b57
logger_class_name = slf4j
logger_name = jruby.rack
maximum_memory_buffer_size =
maximum_runtimes = 1
num_initializer_threads =
out = java.io.PrintStream@4a8c212
rackup =
rackup_path =
rewindable = true
runtime_arguments =
runtime_environment =
runtime_timeout_seconds =
serial_initialization = false
servlet_context = org.apache.catalina.core.ApplicationContextFacade@2eaa81c7
throw_init_exception = false

2015.06.11 10:48:47 ERROR web[jruby.rack] initialization failed
org.jruby.rack.RackInitializationException: ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227:in `log'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183:in `execute'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109:in `create_table'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371:in `initialize_schema_migrations_table'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441:in `initialize'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401:in `up'
        from /opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383:in `migrate'
        from /opt/sonar/web/WEB-INF/lib/database_version.rb:62:in `upgrade_and_start'
        from /opt/sonar/web/WEB-INF/lib/database_version.rb:73:in `automatic_setup'
        from /opt/sonar/web/WEB-INF/config/environment.rb:272:in `(root)'
        from org/jruby/RubyKernel.java:1094:in `load'
        from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1:in `(root)'
        from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25:in `load_environment'
        from file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79:in `load_environment'

        at org.jruby.rack.RackInitializationException.wrap(RackInitializationException.java:29) ~[jruby-rack-1.1.13.2.jar:na]
        at org.jruby.rack.RackApplicationFactoryDecorator.init(RackApplicationFactoryDecorator.java:98) ~[jruby-rack-1.1.13.2.jar:na]
        at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletContextListener.java:50) ~[jruby-rack-1.1.13.2.jar:na]
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4720) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) [tomcat-embed-core-8.0.18.jar:8.0.18]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_45]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_45]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_45]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]
Caused by: org.jruby.exceptions.RaiseException: (StatementInvalid) ActiveRecord::JDBCError: ERROR: no schema has been selected to create in: CREATE TABLE "schema_migrations" ("version" varchar(10485760) NOT NULL)
        at RUBY.log(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract_adapter.rb:227) ~[na:na]
        at RUBY.execute(/opt/sonar/web/WEB-INF/gems/gems/activerecord-jdbc-adapter-1.1.3/lib/arjdbc/jdbc/adapter.rb:183) ~[na:na]
        at RUBY.create_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:109) ~[na:na]
        at RUBY.initialize_schema_migrations_table(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/connection_adapters/abstract/schema_statements.rb:371) ~[na:na]
        at RUBY.initialize(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:441) ~[na:na]
        at RUBY.up(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:401) ~[na:na]
        at RUBY.migrate(/opt/sonar/web/WEB-INF/gems/gems/activerecord-2.3.15/lib/active_record/migration.rb:383) ~[na:na]
        at RUBY.upgrade_and_start(/opt/sonar/web/WEB-INF/lib/database_version.rb:62) ~[na:na]
        at RUBY.automatic_setup(/opt/sonar/web/WEB-INF/lib/database_version.rb:73) ~[na:na]
        at RUBY.(root)(/opt/sonar/web/WEB-INF/config/environment.rb:272) ~[na:na]
        at org.jruby.RubyKernel.load(org/jruby/RubyKernel.java:1094) ~[jruby-complete-1.7.9.jar:na]
        at RUBY.(root)(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:1) ~[na:na]
        at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails/environment2.rb:25) ~[na:na]
        at RUBY.load_environment(file:/opt/sonar/lib/server/jruby-rack-1.1.13.2.jar!/jruby/rack/rails_booter.rb:79) ~[na:na]
2015.06.11 10:48:47 INFO  web[o.a.c.h.Http11NioProtocol] Starting ProtocolHandler ["http-nio-0.0.0.0-9000"]
2015.06.11 10:48:47 INFO  web[o.s.s.a.TomcatAccessLog] Web server is started
2015.06.11 10:48:47 INFO  web[o.s.s.a.EmbeddedTomcat] HTTP connector enabled on port 9000
2015.06.11 10:48:47 INFO  app[o.s.p.m.Monitor] Process[web] is up

Body:
Maybe it is too late to response to this, but I recently ran into similar error and it took me a while to debug the problem.

The problem in my case was misunderstanding what needs to be done as you need to have user with password to be set (Sonarqube properties) and configure (in Postgresql DB)

sonar.jdbc.username=<sonar_user>
sonar.jdbc.password=<sonar_user_password>

Then the connection string must be correct

sonar.jdbc.url=jdbc:postgresql://localhost:5432/<sonar_postgres_db>

And then you need to have schema configured and the  must have it set as search_path (I still don't understand all that, so apologies for terminology)

So as @RawToast answer did help me, but I had to do the following:

create schema sonardb (exactly what Sonarqube was expecting)

set search path for  to point to that schema ALTER USER <sonar_user> SET search_path TO sonardb;

ALTER USER sonar SET search_path TO sonardb;


来源: stackexchange

问:
Angular 9 Mat-Paginator - Translation
How can I translate the Paginator in Angular 9?

When I add

```<code>paginatorRefresh() {
    setTimeout(() => this.dataSourceAma.paginator = this.paginator);
    this.dataSourceAma.sort = this.sort;
    this.paginator._intl.itemsPerPageLabel = 'Einträge pro Seite';
    this.paginator._intl.getRangeLabel = germanRangeLabel;
    // this.loading = false;
}
</code>```

I get an error in the console:

** TypeError: Cannot read property '_intl' of undefined**

答:
Only two actions are required:

in your module, add:

```<code>providers:[
{ provide: MatPaginatorIntl, useValue: getPortuguesPaginatorIntl() }
]
</code>```

Create a file paginator.translate.ts

```<code>import { MatPaginatorIntl } from "@angular/material/paginator";

const portuguesRangeLabel = (page: number, pageSize: number, length: number) => {
  if (length == 0 || pageSize == 0) { return `0 de ${length}`; }

  length = Math.max(length, 0);

  const startIndex = page * pageSize;

  // If the start index exceeds the list length, do not try and fix the end index to the end.
  const endIndex = startIndex < length ?
    Math.min(startIndex + pageSize, length) :
    startIndex + pageSize;

  return `${startIndex + 1} - ${endIndex} de ${length}`;
}

export function getPortuguesPaginatorIntl() {
  const paginatorIntl = new MatPaginatorIntl();
  paginatorIntl.itemsPerPageLabel = 'Items por página:';
  paginatorIntl.nextPageLabel = 'Próxima página';
  paginatorIntl.previousPageLabel = 'Página anterior';
  paginatorIntl.firstPageLabel = 'Primeira página';
  paginatorIntl.lastPageLabel = 'Ultima página';
  paginatorIntl.getRangeLabel = portuguesRangeLabel;
  return paginatorIntl;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular 9 Mat-Paginator - Translation

Body:
How can I translate the Paginator in Angular 9?

When I add

paginatorRefresh() {
    setTimeout(() => this.dataSourceAma.paginator = this.paginator);
    this.dataSourceAma.sort = this.sort;
    this.paginator._intl.itemsPerPageLabel = 'Einträge pro Seite';
    this.paginator._intl.getRangeLabel = germanRangeLabel;
    // this.loading = false;
}

I get an error in the console:

** TypeError: Cannot read property '_intl' of undefined**

Body:
Only two actions are required:

in your module, add:

providers:[
{ provide: MatPaginatorIntl, useValue: getPortuguesPaginatorIntl() }
]

Create a file paginator.translate.ts

import { MatPaginatorIntl } from "@angular/material/paginator";

const portuguesRangeLabel = (page: number, pageSize: number, length: number) => {
  if (length == 0 || pageSize == 0) { return `0 de ${length}`; }

  length = Math.max(length, 0);

  const startIndex = page * pageSize;

  // If the start index exceeds the list length, do not try and fix the end index to the end.
  const endIndex = startIndex < length ?
    Math.min(startIndex + pageSize, length) :
    startIndex + pageSize;

  return `${startIndex + 1} - ${endIndex} de ${length}`;
}

export function getPortuguesPaginatorIntl() {
  const paginatorIntl = new MatPaginatorIntl();
  paginatorIntl.itemsPerPageLabel = 'Items por página:';
  paginatorIntl.nextPageLabel = 'Próxima página';
  paginatorIntl.previousPageLabel = 'Página anterior';
  paginatorIntl.firstPageLabel = 'Primeira página';
  paginatorIntl.lastPageLabel = 'Ultima página';
  paginatorIntl.getRangeLabel = portuguesRangeLabel;
  return paginatorIntl;
}


问:
Add list to Pandas Dateframe, but keep NaNs at the top
I think this has probably been answered, but I cant find the answer anywhere. It is pretty trivial. How can I add a list to a pandas dataframe as a column, but keep the NaNs at the top?

This is the code i have:

```<code>df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d
print(df)
</code>```

which returns this:

```<code>   a  b    c    d
0  1  2  2.0  1.0
1  2  3  3.0  2.0
2  3  5  5.0  3.0
3  4  6  6.0  4.0
4  5  4  4.0  NaN
5  6  3  3.0  NaN
6  7  2  NaN  NaN
</code>```

However, I would like it to return this instead:

```<code>  a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0
</code>```

答:
the way how to do it! just reset index and put na values first.</p>

```<code>df.reset_index()
df2 = df.sort_values(by =['a','b','c','d'], ascending = False, na_position='first')

#Result
   a  b    c    d
6  7  2  NaN  NaN
5  6  3  3.0  NaN
4  5  4  4.0  NaN
3  4  6  6.0  4.0
2  3  5  5.0  3.0
1  2  3  3.0  2.0
0  1  2  2.0  1.0
</code>```

Body:
I think this has probably been answered, but I cant find the answer anywhere. It is pretty trivial. How can I add a list to a pandas dataframe as a column, but keep the NaNs at the top?

This is the code i have:

df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d
print(df)

which returns this:

   a  b    c    d
0  1  2  2.0  1.0
1  2  3  3.0  2.0
2  3  5  5.0  3.0
3  4  6  6.0  4.0
4  5  4  4.0  NaN
5  6  3  3.0  NaN
6  7  2  NaN  NaN

However, I would like it to return this instead:

  a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0

Body:
the way how to do it! just reset index and put na values first.

df.reset_index()
df2 = df.sort_values(by =['a','b','c','d'], ascending = False, na_position='first')

#Result
   a  b    c    d
6  7  2  NaN  NaN
5  6  3  3.0  NaN
4  5  4  4.0  NaN
3  4  6  6.0  4.0
2  3  5  5.0  3.0
1  2  3  3.0  2.0
0  1  2  2.0  1.0


问:
Cinda CUDA Driver Problem when trying to Install CartoPy
I've been trying to install CartoPy recently. I have all the dependencies that CartoPy requires, but when I try to install through the Anaconda Navigator, I'm given this message:

```<code>UnsatisfiableError: The following specifications were found to be incompatible with the existing python installation in your
environment:

Specifications:

- cartopy -> python[version='>=2.7,<2.8.0a0|>=3.7,<3.8.0a0|>=3.6,<3.7.0a0|>=3.5,<3.6.0a0']

Your python: python=3.8

If python is on the left-most side of the chain, that's the version
you've asked for.

When python appears to the right, that indicates that the thing on the
left is somehow not available for the python version you are constrained to. Note that conda will not change your python version to a different minor version unless you explicitly specify that.

The following specifications were found to be incompatible with your CUDA driver:

- feature:/win-64::__cuda==11.0=0

Your installed CUDA driver is: 11.0
</code>```

I'm confused with the last part of the error message, because the CUDA drivers are matching versions (11.0). I've googled around, and have seen similar problems, but none that explicitly mention CartoPy, and the responses are a bit over my head.

How do I fix this error? Thanks for the help!

答:
It looks like the main channel for Anaconda doesn't currently have a build of CartoPy for Python 3.8. You'll either need to change to Python 3.7, or install from conda-forge--but I don't know how to add a channel to Anaconda Navigator. So the path I'd take would be:

```<code>conda create -n myenv python=3.8 cartopy
conda activate myenv
</code>```

To create a new environment with cartopy and activate it from the command line.

Body:
I've been trying to install CartoPy recently. I have all the dependencies that CartoPy requires, but when I try to install through the Anaconda Navigator, I'm given this message:

UnsatisfiableError: The following specifications were found to be incompatible with the existing python installation in your
environment:

Specifications:

- cartopy -> python[version='>=2.7,<2.8.0a0|>=3.7,<3.8.0a0|>=3.6,<3.7.0a0|>=3.5,<3.6.0a0']

Your python: python=3.8

If python is on the left-most side of the chain, that's the version
you've asked for.

When python appears to the right, that indicates that the thing on the
left is somehow not available for the python version you are constrained to. Note that conda will not change your python version to a different minor version unless you explicitly specify that.

The following specifications were found to be incompatible with your CUDA driver:

- feature:/win-64::__cuda==11.0=0

Your installed CUDA driver is: 11.0

I'm confused with the last part of the error message, because the CUDA drivers are matching versions (11.0). I've googled around, and have seen similar problems, but none that explicitly mention CartoPy, and the responses are a bit over my head.

How do I fix this error? Thanks for the help!

Body:
It looks like the main channel for Anaconda doesn't currently have a build of CartoPy for Python 3.8. You'll either need to change to Python 3.7, or install from conda-forge--but I don't know how to add a channel to Anaconda Navigator. So the path I'd take would be:

conda create -n myenv python=3.8 cartopy
conda activate myenv

To create a new environment with cartopy and activate it from the command line.


问:
How can I change a PostgreSQL user password?
How do I change the password for a PostgreSQL user?</p>

答:
TLDR:

On many systems, a user's account often contains a period, or some sort of punctuation (user: john.smith, horise.johnson).  In these cases, a modification will have to be made to the accepted answer above.  The change requires the username to be double-quoted.

Example

```<code>ALTER USER "username.lastname" WITH PASSWORD 'password';
</code>```

Rationale:

PostgreSQL is quite picky on when to use a 'double quote' and when to use a 'single quote'.  Typically, when providing a string, you would use a single quote.

Body:
TLDR:

On many systems, a user's account often contains a period, or some sort of punctuation (user: john.smith, horise.johnson).  In these cases, a modification will have to be made to the accepted answer above.  The change requires the username to be double-quoted.

Example

ALTER USER "username.lastname" WITH PASSWORD 'password';

Rationale:

PostgreSQL is quite picky on when to use a 'double quote' and when to use a 'single quote'.  Typically, when providing a string, you would use a single quote.


问:
Issue with metatags and sharing on LinkedIn
Help with meta tags please.
I have set the next :

```<code><meta property="og:title" content="{{ object_post.title }}" >
<meta property="og:description" content="{{ object_post.description }}">
<meta property="og:url" content="http://some_site.com/blog/post/{{ object_post.id }}" />
<meta property="og:image" content="http://some_site.com{% static "content/blog/images/" %}{{ object_post.id }}.jpg" />
<meta property="og:type" content="article" class="meta-article">
</code>```

And them is correctly. I checked on facebook developers site.
But I have an issue and question.

1) Issue - why it still showing not correct title, description and image? But url and type are correct.
2) What is must be the sharing link? I mean if we are using meta tags. Which one must be link on only simple sharing this post?

Thanks

答:
As of 2020, LinkedIn appears to be much better at doing caching well.  But there are two well-known ways to force LinkedIn to update the cache...

Technique 1: If you are normally sharing www.example.com, try sharing www.example.com?randomItem=huzzah.  Because the URL is different, it will not have it in cache, though the page will fundamentally behave the same  -- unless you use randomItem as a GET param.  Make sure that the fake param here is not actually used!

Technique 2: Load your site into the LinkedIn Post Inspector, and check to see how it looks.  Since you are debugging with the inspector, it knows to refresh the cache automatically.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
Help with meta tags please.
I have set the next :

<meta property="og:title" content="{{ object_post.title }}" >
<meta property="og:description" content="{{ object_post.description }}">
<meta property="og:url" content="http://some_site.com/blog/post/{{ object_post.id }}" />
<meta property="og:image" content="http://some_site.com{% static "content/blog/images/" %}{{ object_post.id }}.jpg" />
<meta property="og:type" content="article" class="meta-article">

And them is correctly. I checked on facebook developers site.
But I have an issue and question.

1) Issue - why it still showing not correct title, description and image? But url and type are correct.
2) What is must be the sharing link? I mean if we are using meta tags. Which one must be link on only simple sharing this post?

Thanks


答:
```<code>l = df.apply(sorted, key = lambda s: (~np.isnan(s), s), axis = 0)
</code>```

You can sort the dataframe rows using a key argument to keep NaNs first

Title: Add list to Pandas Dateframe, but keep NaNs at the top

Body:
l = df.apply(sorted, key = lambda s: (~np.isnan(s), s), axis = 0)

You can sort the dataframe rows using a key argument to keep NaNs first


问:
Laravel flatten and pluck from multidimensional collection
I have to retrieve just an array of id from the given collection, something like [10,54,61,21,etc].
I've tried flatten, pluck, but nothing seems to work apart from a foreach which is something I would like to remove at this step.

```<code>// Model
class Children extends Eloquent {
    public function directChildrens(){
        return $this->hasMany('App\Children','father_id','id')->select('id','father_id');
    }

    public function childrens(){
        return $this->directChildrens()->with('childrens');
    }
}

// Controller
return $children->childrens()->get();
</code>```

As expected it works fine. Here a result:

```<code>[{
"id": 10,
"father_id": 2,
"childrens": [
    {
        "id": 54,
        "father_id": 10,
        "childrens": [
            {
                "id": 61,
                "father_id": 54,
                "childrens": []
            }
        ]
    },
    {
        "id": 21,
        "father_id": 10,
        "childrens": []
    }
]
}]
</code>```

How can I perform a pluck('id') of this collection in order to get [10,54,61,21] ?

答:
```<code>$result = [
            [
                "id" => 10,
                "father_id" => 2,
                "childrens" => [
                    [
                        "id" => 54,
                        "father_id" => 10,
                        "childrens" => [
                            [
                                "id" => 61,
                                "father_id" => 54,
                                "childrens" => []
                            ]
                        ]
                    ],
                    [
                        "id" => 21,
                        "father_id" => 10,
                        "childrens" => []
                    ]
                ]
            ]
        ];
</code>```

```<code>return collect($result)
        ->map(function ($value) {
            return Arr::dot($value); // converts it to the dot notation version (added the example at the end)
        })
        ->collapse() // collapse them into a single one
        ->filter(function ($value, $key) {
            return $key === 'id' || Str::endsWith($key, '.id'); // filter first id + patterns of .id
        })
        ->values() // discard dot notation keys
        ->toArray();
</code>```

Arr::dot() method turned collection into the following format which flattens all into the same level.

```<code>[
  {
    "id": 10,
    "father_id": 2,
    "childrens.0.id": 54,
    "childrens.0.father_id": 10,
    "childrens.0.childrens.0.id": 61,
    "childrens.0.childrens.0.father_id": 54,
    "childrens.0.childrens.0.childrens": [],
    "childrens.1.id": 21,
    "childrens.1.father_id": 10,
    "childrens.1.childrens": []
  }
]
</code>```

Thanks to @Dan warning about deprecated/removed function array_dot. Replaced with Arr::dot()

Body:
I have to retrieve just an array of id from the given collection, something like [10,54,61,21,etc].
I've tried flatten, pluck, but nothing seems to work apart from a foreach which is something I would like to remove at this step.

// Model
class Children extends Eloquent {
    public function directChildrens(){
        return $this->hasMany('App\Children','father_id','id')->select('id','father_id');
    }

    public function childrens(){
        return $this->directChildrens()->with('childrens');
    }
}

// Controller
return $children->childrens()->get();

As expected it works fine. Here a result:

[{
"id": 10,
"father_id": 2,
"childrens": [
    {
        "id": 54,
        "father_id": 10,
        "childrens": [
            {
                "id": 61,
                "father_id": 54,
                "childrens": []
            }
        ]
    },
    {
        "id": 21,
        "father_id": 10,
        "childrens": []
    }
]
}]

How can I perform a pluck('id') of this collection in order to get [10,54,61,21] ?

Body:
$result = [
            [
                "id" => 10,
                "father_id" => 2,
                "childrens" => [
                    [
                        "id" => 54,
                        "father_id" => 10,
                        "childrens" => [
                            [
                                "id" => 61,
                                "father_id" => 54,
                                "childrens" => []
                            ]
                        ]
                    ],
                    [
                        "id" => 21,
                        "father_id" => 10,
                        "childrens" => []
                    ]
                ]
            ]
        ];

return collect($result)
        ->map(function ($value) {
            return Arr::dot($value); // converts it to the dot notation version (added the example at the end)
        })
        ->collapse() // collapse them into a single one
        ->filter(function ($value, $key) {
            return $key === 'id' || Str::endsWith($key, '.id'); // filter first id + patterns of .id
        })
        ->values() // discard dot notation keys
        ->toArray();

Arr::dot() method turned collection into the following format which flattens all into the same level.

[
  {
    "id": 10,
    "father_id": 2,
    "childrens.0.id": 54,
    "childrens.0.father_id": 10,
    "childrens.0.childrens.0.id": 61,
    "childrens.0.childrens.0.father_id": 54,
    "childrens.0.childrens.0.childrens": [],
    "childrens.1.id": 21,
    "childrens.1.father_id": 10,
    "childrens.1.childrens": []
  }
]

Thanks to @Dan warning about deprecated/removed function array_dot. Replaced with Arr::dot()


问:
CSS for Show full width card below each small card for each row
I have scenario, where I have design of 3 column/row cards of multiple row. When user click on any card then a full width card will show just below that row with more details. As per my CSS, full width card is showing just below the row. But I have issue that.

When I click on first small card then full width data show just below that row, but Other cards in that row shifted below that row.  The below image will describe more clearly.

答:
You could add an extra row of row-length cards below each normal row. Inside those extra rows, you could include 3 row-length cards with the extra details, all of which are not normally displayed. Then, when each card is clicked, the corresponding row-length card of that card could be displayed.

This is just one example of how to solve this. I hope this helps.


问:
Why is the ratio between height and width maintained in the  element?
If i just write a simple code like this:

```<code><img src="mycat.jpg" height="300px";>
</code>```

Now, if the image is very large, the height will get reduced to 300px, and automatically the width will get reduced too to fit the height size. Why is that? I thought that, if the width is not specified, it remains on "auto" which means, the width of the element adjusts to the width of the content, in this case, the width of the original image size. When i change the height of the element, the height of the image changes too to fit the element size, but why is the width changes too? It must be because the ratio is fixed. Is that the case?

Yes, i know that, if i set the width to 100%, the image will expand to fill in the entire width of the element block, but why is it that if its set on auto, it adjusts to the height of the element rather than stay with the original size of the image since the width of the element has not been changed?

Also, is there an actual way to change the size of the content, i.e. the image itself rather than changing the size of the element which contains the image? I could use display:flex and change the space between the element and the image, so is there a way to target just the image and not the entire element itself?

答:
an image is scaled by default when you try to give it height but not the width in order to maintain its looks suppose an image is 2160px of height and 3840px of width and  you change it to width to 300px only this will affect the height and make the height to 168px
and for more understanding try to resize the image in paint where the initial scale will looks like this

and when you resize it to 300px of wide it will also look like this

Title: Why is the ratio between height and width maintained in the <img> element?

Body:
If i just write a simple code like this:

Now, if the image is very large, the height will get reduced to 300px, and automatically the width will get reduced too to fit the height size. Why is that? I thought that, if the width is not specified, it remains on "auto" which means, the width of the element adjusts to the width of the content, in this case, the width of the original image size. When i change the height of the element, the height of the image changes too to fit the element size, but why is the width changes too? It must be because the ratio is fixed. Is that the case?

Yes, i know that, if i set the width to 100%, the image will expand to fill in the entire width of the element block, but why is it that if its set on auto, it adjusts to the height of the element rather than stay with the original size of the image since the width of the element has not been changed?

Also, is there an actual way to change the size of the content, i.e. the image itself rather than changing the size of the element which contains the image? I could use display:flex and change the space between the element and the image, so is there a way to target just the image and not the entire element itself?


问:
Open a new tab with javascript but stay on current tab
Is it possible to open a new tab in Firefox (in background) using window.open("http://www.google.com") function, and remain the current tab?

Thanks for any help

答:
You can't open tabs in the background using javascript because this is set in the user's preferences in about:config, which you have no control over. The setting is:

```<code>browser.tabs.loadDivertedInBackground=true
</code>```

Body:
You can't open tabs in the background using javascript because this is set in the user's preferences in about:config, which you have no control over. The setting is:

browser.tabs.loadDivertedInBackground=true


问:
Why does old value not passed to vue component?
why does old value not passed to vue component?

passed old value here

<autocomplete-region-component :query="old('regionName')"></autocomplete-region-component>```
</div>
</div>
</p>

<p>my code from vue component</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div>
        <input
            type="text"
            autocomplete="off"
            v-model="query"
            v-on:keyup="autoComplete"
            class="form-control js-region-name"
            name="regionName"
            value=""
        >
        <input
            type="hidden"
            class="form-control js-region-id"
            name="regionId"
            value="enteredRegion">
        <div class="panel-footer" v-if="results.length">
            <ul class="list-group select-region">
                <li class="list-group-item list-region" v-for="result in results" v-on:click="selectRegion(result)">
                    {{ result.name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                results: [],
                query: '',
            }
        },
        methods: {
            autoComplete() {
                this.results = [];
                if(this.query.length > 2){
                    axios.get('/api/regions',{params: {_limit: 2, query: this.query}}).then(response => {
                        this.results = response.data;
                    });
                }
            },
            selectRegion(result) {
                let inputWithRegionName = document.querySelector('.js-region-name');
                let inputWithRegionId = document.querySelector('.js-region-id');
                let listRegions = document.querySelector('.panel-footer');

                inputWithRegionName.value = result.name;
                inputWithRegionId.value = result.id;
                listRegions.hidden = true;
            }
        }
    }
</script></code>```

console not have mistakes

Please help with a detailed answer since I am a beginner and really need your help. thanks

UPDATE

答:
Mustache syntax is to interpolate text, not to pass props.

To pass props or set attributes to child components (including native HTML elements), you need to use v-bind directive (doc).

 element is good to remember this rule.

{{ linkText }}
```
<p>Then, your code should look like this:</p>
<pre class="lang-html prettyprint-override"><code><autocomplete-region-component :query="json_encode(old('regionName'))">
</autocomplete-region-component>
</code>```

Body:
why does old value not passed to vue component?

passed old value here

<autocomplete-region-component :query="old('regionName')"></autocomplete-region-component>

my code from vue component

<template>

        <input
            type="text"
            autocomplete="off"
            v-model="query"
            v-on:keyup="autoComplete"
            class="form-control js-region-name"
            name="regionName"
            value=""
        >
        <input
            type="hidden"
            class="form-control js-region-id"
            name="regionId"
            value="enteredRegion">

                    {{ result.name }}

</template>

console not have mistakes

Please help with a detailed answer since I am a beginner and really need your help. thanks

UPDATE

Body:
Mustache syntax is to interpolate text, not to pass props.

To pass props or set attributes to child components (including native HTML elements), you need to use v-bind directive (doc).

<a> element is good to remember this rule.

<a :href="myUrl">{{ linkText }}</a>

Then, your code should look like this:

<autocomplete-region-component :query="json_encode(old('regionName'))">
</autocomplete-region-component>


问:
How to override a Python module's default logging level?
I have a utility module (let's call it "uapi.py") which provides me access to an API. My module contains several functions which perform various calls to the API in different ways. I have written a Pytest script for it ("uapi-pytest.py"), which exercises each of the functions, and hence the different calls supported by the API.

Module uapi.py uses the standard 'logging' module to log events. The default config is defined 'globally' within uapi.py, right below the import statements, and is set to a level of WARN. This level is fine when I use the module interactively (through main, which incorporates a CLI). However, I would also like to be able to import the module into my Pytest script and override the default log level to something lower (e.g. INFO or DEBUG), so that if any tests fail I can see the more detailed output, and figure out what went wrong.

So far the only way I've figured out how to do this is by editing uapi.py and setting the level to INFO before each Pytest run, then setting it back afterwards. Since my Pytest script imports uapi.py, I think I should be able to override its default logging behavior, but so far I haven't been able to figure out how. I tried directly setting the module's logging attribute but I end up getting this error (when run as "pytest -v uapi_pytest.py"):

```<code>============================================= ERRORS =============================================
________________________________ ERROR collecting uapi_pytest.py _________________________________
uapi_pytest.py:5: in <module>
    u.logging.Logger.setLevel(logging.INFO)
E   TypeError: setLevel() missing 1 required positional argument: 'level'
==================================== short test summary info =====================================
ERROR uapi_pytest.py - TypeError: setLevel() missing 1 required positional argument: 'level'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
======================================== 1 error in 0.64s ========================================
</code>```

Can anyone help me figure this out? Maybe I am missing something obvious, but to be honest, I can't see the forest for the trees with the Python logging module, which seems unnecessarily abstract.

Here is some stripped down code that shows the error I am getting:

uapi.py:

```<code>import logging
import requests
import fire

logging.basicConfig(level=logging.WARN,
                    format='%(asctime)s %(filename)s %(funcName)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

def uapi_get_site_info(site_id, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id})
    logger.info('GET_SITE_INFO_REQUEST response:%s', r)
    return r

def uapi_get_site_version_info(site_id, version, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_version_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id, 'Version': version})
    logger.info('GET_SITE_VERSION_INFO_REQUEST response:%s', r)
    return r

def main():
    # Configure the CLI using Python Fire
    fire.Fire({
        'get_info': uapi_get_site_info,
        'version_info': uapi_get_site_version_info,
    })

if __name__ == "__main__":
    main()
</code>```

uapi_pytest.py:

```<code>import pytest
import logging
import uapi as u

u.logging.Logger.setLevel(logging.INFO)

def test_uapi_get_site_info_before_config_change():
    assert True

def test_uapi_get_site_version_info():
    assert True
</code>```

答:
You are trying to invoke the method on the class, not the instance of Logger you want to configure.

```<code>import pytest
import logging
import uapi as u

# Configure the uapi logger, from which both
# uapi.uapi_get_site_info and uapi.uapi_get_site_version_info
# inherit
logging.getLogger('uapi').setLevel(logging.INFO)

def test_uapi_get_site_info_before_config_change():
    ...

def test_uapi_get_site_version_info():
    ...
</code>```

Body:
I have a utility module (let's call it "uapi.py") which provides me access to an API. My module contains several functions which perform various calls to the API in different ways. I have written a Pytest script for it ("uapi-pytest.py"), which exercises each of the functions, and hence the different calls supported by the API.

Module uapi.py uses the standard 'logging' module to log events. The default config is defined 'globally' within uapi.py, right below the import statements, and is set to a level of WARN. This level is fine when I use the module interactively (through main, which incorporates a CLI). However, I would also like to be able to import the module into my Pytest script and override the default log level to something lower (e.g. INFO or DEBUG), so that if any tests fail I can see the more detailed output, and figure out what went wrong.

So far the only way I've figured out how to do this is by editing uapi.py and setting the level to INFO before each Pytest run, then setting it back afterwards. Since my Pytest script imports uapi.py, I think I should be able to override its default logging behavior, but so far I haven't been able to figure out how. I tried directly setting the module's logging attribute but I end up getting this error (when run as "pytest -v uapi_pytest.py"):

============================================= ERRORS =============================================
________________________________ ERROR collecting uapi_pytest.py _________________________________
uapi_pytest.py:5: in <module>
    u.logging.Logger.setLevel(logging.INFO)
E   TypeError: setLevel() missing 1 required positional argument: 'level'
==================================== short test summary info =====================================
ERROR uapi_pytest.py - TypeError: setLevel() missing 1 required positional argument: 'level'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
======================================== 1 error in 0.64s ========================================

Can anyone help me figure this out? Maybe I am missing something obvious, but to be honest, I can't see the forest for the trees with the Python logging module, which seems unnecessarily abstract.

Here is some stripped down code that shows the error I am getting:

uapi.py:

import logging
import requests
import fire

logging.basicConfig(level=logging.WARN,
                    format='%(asctime)s %(filename)s %(funcName)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

def uapi_get_site_info(site_id, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id})
    logger.info('GET_SITE_INFO_REQUEST response:%s', r)
    return r

def uapi_get_site_version_info(site_id, version, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_version_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id, 'Version': version})
    logger.info('GET_SITE_VERSION_INFO_REQUEST response:%s', r)
    return r

def main():
    # Configure the CLI using Python Fire
    fire.Fire({
        'get_info': uapi_get_site_info,
        'version_info': uapi_get_site_version_info,
    })

if __name__ == "__main__":
    main()

uapi_pytest.py:

import pytest
import logging
import uapi as u

u.logging.Logger.setLevel(logging.INFO)

def test_uapi_get_site_info_before_config_change():
    assert True

def test_uapi_get_site_version_info():
    assert True

Body:
You are trying to invoke the method on the class, not the instance of Logger you want to configure.

import pytest
import logging
import uapi as u

# Configure the uapi logger, from which both
# uapi.uapi_get_site_info and uapi.uapi_get_site_version_info
# inherit
logging.getLogger('uapi').setLevel(logging.INFO)

def test_uapi_get_site_info_before_config_change():
    ...

def test_uapi_get_site_version_info():
    ...


问:
python utc time minus 5 minutes
How to round down a time 5 minutes in Python?

I have this script, but i think this can be easyer, and the full hours the calculation goes wrong. When its 22:03 it returns 21:95 instead of 21:55.

```<code>import datetime
from datetime import date
import time

utc_datetime = datetime.datetime.utcnow()
jaar = date.today().year
maand = time.strftime("%m")
dag = time.strftime("%d")
uurutc = utc_datetime.strftime("%H")
autc = utc_datetime.strftime("%M")
minuututc = int(5 * round(float(autc)/5)-5)
uur = time.strftime("%H")
a = time.strftime("%M")
minuut = int(5 * round(float(a)/5)-5)

timestamp = ''.join(str(x) for x in [jaar, maand, dag, uurutc, minuututc])

print timestamp
</code>```

What the code should actually do:

Our local time is UTC+2, but i only need the UTC time, so the output must be in UTC.
Second, the time needs to be 5 min before current time and then round down.
The output format of the string should be: YYYYMMDDHHMM.

Example:

local time: 12:53 > output script: 10:45

local time: 17:07 > output script: 15:00

local time: 08:24 > output script: 06:15

Who can help me with this out?

Thank you!

答:
```<code>import datetime
time = (datetime.datetime.utcnow() - datetime.timedelta(minutes=5)).strftime('%Y-%m-%dT%H:%M:%SZ')
print(time)
</code>```

Title: python utc time minus 5 minutes

Body:
How to round down a time 5 minutes in Python?

I have this script, but i think this can be easyer, and the full hours the calculation goes wrong. When its 22:03 it returns 21:95 instead of 21:55.

import datetime
from datetime import date
import time

utc_datetime = datetime.datetime.utcnow()
jaar = date.today().year
maand = time.strftime("%m")
dag = time.strftime("%d")
uurutc = utc_datetime.strftime("%H")
autc = utc_datetime.strftime("%M")
minuututc = int(5 * round(float(autc)/5)-5)
uur = time.strftime("%H")
a = time.strftime("%M")
minuut = int(5 * round(float(a)/5)-5)

timestamp = ''.join(str(x) for x in [jaar, maand, dag, uurutc, minuututc])

print timestamp

What the code should actually do:

Our local time is UTC+2, but i only need the UTC time, so the output must be in UTC.
Second, the time needs to be 5 min before current time and then round down.
The output format of the string should be: YYYYMMDDHHMM.

Example:

local time: 12:53 > output script: 10:45

local time: 17:07 > output script: 15:00

local time: 08:24 > output script: 06:15

Who can help me with this out?

Thank you!


问:
How do you add a timer to a C# console application
Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.</p>

答:
I suggest you following Microsoft guidelines (
https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.interval?view=netcore-3.1).

I first tried using System.Threading; with

```<code>var myTimer = new Timer((e) =>
{
   // Code
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

</code>```

but it continuously stopped after ~20 minutes.

With that, I tried the solutions setting

```<code>GC.KeepAlive(myTimer)
</code>```

or

```<code>for (; ; ) { }
}
</code>```

but they didn't work in my case.

Following Microsoft documentation, it worked perfectly:

```<code>using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
// The example displays output like the following:
//       Press the Enter key to exit the program at any time...
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I suggest you following Microsoft guidelines (
https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.interval?view=netcore-3.1).

I first tried using System.Threading; with

var myTimer = new Timer((e) =>
{
   // Code
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

but it continuously stopped after ~20 minutes.

With that, I tried the solutions setting

GC.KeepAlive(myTimer)

or

for (; ; ) { }
}

but they didn't work in my case.

Following Microsoft documentation, it worked perfectly:

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
// The example displays output like the following:
//       Press the Enter key to exit the program at any time...
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM


问:
VSTS / TFVC cli for oracle developer
I am an oracle database developer. My organization is using VSTS repos for code storage. For people who are working with Visual studio, it is easy to check in codes. But for Db people, we always have to check-in the code manually by dragging in.

is there any way to connect to vsts repos source control with oracle tool? We are using TFVC as our version control (and not GIT).

答:
Sounds like you should look at the TF.exe CLI. This CLI lets you pretty much do everything that you can in the VS GUI.

Here's a link to the Microsoft doc's for TF, Use Team Foundation version control commands

Title: VSTS / TFVC cli for oracle developer


问:
Dynamically change the behavior of member functions in C++
For a homework, we need to modify a variety of images with multiple different algorithms and format a document with our answers. I have already coded the algorithms in C++, but I want to write a program that will modify the images and format the document automatically. To do this, I want to have a class of the form

```<code>class A
{
    void f1(Image img)
    {
    // do something to the image
    }
    void f2(Image img)
    {
    // do something else to the image
    }
    public:
       void setFunction(bool choice)
       {
          if(choice)
          {
          // define this.operator() = f1
          }
          else
          {
          // define this.operator() = f2
          }
       }
}
</code>```

The reason I want to do this is because the homework requires us to compute different properties for the images, but most of the properties are repeated accross questions. Therefore, I want to write a single function of the form

```<code>void answerQuestion(Image img, A imgProcessor)
{
    // load img, call imgProcessor(img)
    // and get the necessary properties from
    // img to answer the questions
}
</code>```

This way, I can just do something like imgProcessor.setFunction(choice) before passing the imgProcessor object to answerQuestion. I want to use an object because questions are split into several parts, so I would like the imgProcessor object to hold on to some information required for the rest of the problem.
I don't know how to dynamically define or redefine the operator() method, or if it is even possible. Of course, I am indifferent between overloading the call operator or just declaring my own method, but I want to be able to use this call in the same way accross the code. Is this possible in C++?

答: You'll have to somehow remember the choice.  In C++, function pointers and function objects don't participate in overload resolution so you cannot actually replace operator()() with a different function, but you certainly can write operator()() with some type of conditional that checks the choice selected earlier and decides which function to call.

Body:
For a homework, we need to modify a variety of images with multiple different algorithms and format a document with our answers. I have already coded the algorithms in C++, but I want to write a program that will modify the images and format the document automatically. To do this, I want to have a class of the form

class A
{
    void f1(Image img)
    {
    // do something to the image
    }
    void f2(Image img)
    {
    // do something else to the image
    }
    public:
       void setFunction(bool choice)
       {
          if(choice)
          {
          // define this.operator() = f1
          }
          else
          {
          // define this.operator() = f2
          }
       }
}

The reason I want to do this is because the homework requires us to compute different properties for the images, but most of the properties are repeated accross questions. Therefore, I want to write a single function of the form

void answerQuestion(Image img, A imgProcessor)
{
    // load img, call imgProcessor(img)
    // and get the necessary properties from
    // img to answer the questions
}

This way, I can just do something like imgProcessor.setFunction(choice) before passing the imgProcessor object to answerQuestion. I want to use an object because questions are split into several parts, so I would like the imgProcessor object to hold on to some information required for the rest of the problem.
I don't know how to dynamically define or redefine the operator() method, or if it is even possible. Of course, I am indifferent between overloading the call operator or just declaring my own method, but I want to be able to use this call in the same way accross the code. Is this possible in C++?


问:
How to take a photo in Android, using full image size(not thumbnail) and compress the image to bytes?
I dont know if im doing something wrong maybe im not using the image at all or im compressing the image in the wrong way because when im tring to send it to a server it responds me saying that the size is over 10 MB when my phone takes pictures jpg around 7-9 MB (In the Edit.java I have a comment that I before was using the thumbnail but needed to change it cause the thumbnail has a bad quality when im trying to see it in a Desktop)

Here is my code:

AndroidManifest.xml

```<code>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera"></uses-feature>

<provider
            android:authorities="cam.com.example.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path"/>
        </provider>
</code>```

file_path.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path
        name="external"
        path="/"/>
    <external-files-path
        name="external_files"
        path="/"/>
    <cache-path
        name="cache"
        path="/"/>
    <external-cache-path
        name="external_cache"
        path="/"/>
    <files-path
        name="files"
        path="/"/>

</paths>
</code>```

Edit.java

```<code>btn_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    REQUEST_IMAGE_CAPTURE = 1;
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {

                        File imageFile = null;
                        try{
                            imageFile=getImageFile();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                        if(imageFile!=null){
                            Uri imageUri = FileProvider.getUriForFile(Edit.this,"cam.com.example.fileprovider",imageFile);
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                            startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);

                        }

                    }
                } catch (Exception e) {
                        Toasty.warning(getApplicationContext(), IC, Toast.LENGTH_SHORT, true).show();

                }
            }

        });

public File getImageFile() throws IOException{
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageName = "jpg_"+timeStamp+"_";
        File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        File imageFile = File.createTempFile(imageName,".jpg",storageDir);
        currentImagePath = imageFile.getAbsolutePath();
        return imageFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (imagenString == null) {

                File imgFile = new File(currentImagePath);
                String path = imgFile.getAbsolutePath();
                Bitmap mybitmap = BitmapFactory.decodeFile(path);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                mybitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);

/* **Before I was doing this, but the thumbnail has such a bad quality so needed to change it**

                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);*/
            }
        }
    }
</code>```

答:
You are taking a picture with the user's choice of camera app. Usually, that will be saved as a JPEG image. JPEG images are compressed image formats, optimized for "real-world" images like photos.

You then attempt to read it all into memory. This is not a good plan, as you may not have enough memory to do that, for a full-size photo.

You then attempt to take the resulting Bitmap and encode it in PNG. PNG is a compressed image format, but one that is designed for icons and other artwork. A photo will almost always take more space in PNG than in JPEG. Worse, you are trying to encode it as a PNG into memory — again, you may not have sufficient memory to do this.

You then attempt to convert the encoded PNG into base-64. This will take up even more space than the encoded PNG, and, once again, you may not have sufficient memory for this.

I would expect your app to crash with an OutOfMemoryError a lot.

The best solution is to get rid of most of this, and simply upload the JPEG direct from disk. Do not load it into memory, do not convert it to PNG, and do not convert it to base-64.

Body:
I dont know if im doing something wrong maybe im not using the image at all or im compressing the image in the wrong way because when im tring to send it to a server it responds me saying that the size is over 10 MB when my phone takes pictures jpg around 7-9 MB (In the Edit.java I have a comment that I before was using the thumbnail but needed to change it cause the thumbnail has a bad quality when im trying to see it in a Desktop)

Here is my code:

AndroidManifest.xml

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera"></uses-feature>

<provider
            android:authorities="cam.com.example.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path"/>
        </provider>

file_path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path
        name="external"
        path="/"/>
    <external-files-path
        name="external_files"
        path="/"/>
    <cache-path
        name="cache"
        path="/"/>
    <external-cache-path
        name="external_cache"
        path="/"/>
    <files-path
        name="files"
        path="/"/>

</paths>

Edit.java

btn_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    REQUEST_IMAGE_CAPTURE = 1;
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {

                        File imageFile = null;
                        try{
                            imageFile=getImageFile();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                        if(imageFile!=null){
                            Uri imageUri = FileProvider.getUriForFile(Edit.this,"cam.com.example.fileprovider",imageFile);
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                            startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);

                        }

                    }
                } catch (Exception e) {
                        Toasty.warning(getApplicationContext(), IC, Toast.LENGTH_SHORT, true).show();

                }
            }

        });

public File getImageFile() throws IOException{
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageName = "jpg_"+timeStamp+"_";
        File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        File imageFile = File.createTempFile(imageName,".jpg",storageDir);
        currentImagePath = imageFile.getAbsolutePath();
        return imageFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (imagenString == null) {

                File imgFile = new File(currentImagePath);
                String path = imgFile.getAbsolutePath();
                Bitmap mybitmap = BitmapFactory.decodeFile(path);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                mybitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);

/* **Before I was doing this, but the thumbnail has such a bad quality so needed to change it**

                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);*/
            }
        }
    }