Q: Error with gem install sqlite3 on MacOS Monterey with Ruby 3.0.2 on Apple Silicon M1 I’m getting errors when I try to gem install sqlite3 under a fresh rbenv installation of Ruby 3.0.2. The sqlite3 gem installs successfully under Ruby 2.7.4. What is the fix for this?
I’m using MacOS Monterey on an Apple Silicon M1 machine.
➜  ~ > rbenv shell 3.0.2
➜  ~ > gem install sqlite3
Fetching sqlite3-1.4.2.gem
Building native extensions. This could take a while…
ERROR:  Error installing sqlite3:
    ERROR: Failed to build gem native extension.

    current directory: /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3
/Users/brian/.rbenv/versions/3.0.2/bin/ruby -I /Users/brian/.rbenv/versions/3.0.2/lib/ruby/3.0.0 -r ./siteconf20211119-57074-7hi3f4.rb extconf.rb
checking for sqlite3.h… yes
checking for pthread_create() in -lpthread… yes
checking for -ldl… yes
checking for sqlite3_libversion_number() in -lsqlite3… yes
checking for rb_proc_arity()… yes
checking for rb_integer_pack()… yes
checking for sqlite3_initialize()… yes
checking for sqlite3_backup_init()… yes
checking for sqlite3_column_database_name()… yes
checking for sqlite3_enable_load_extension()… yes
checking for sqlite3_load_extension()… yes
checking for sqlite3_open_v2()… yes
checking for sqlite3_prepare_v2()… yes
checking for sqlite3_int64 in sqlite3.h… yes
checking for sqlite3_uint64 in sqlite3.h… yes
creating Makefile

current directory: /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3
make DESTDIR\= clean

current directory: /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3
make DESTDIR\=
compiling aggregator.c
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/defines.h:73:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/backward/2/attributes.h:43:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/pure.h:25:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/assert.h:132:1: error: '__declspec' attributes are not enabled; use '-fdeclspec' or '-fms-extensions' to enable support for __declspec attributes
RBIMPL_ATTR_NORETURN()
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noreturn.h:29:33: note: expanded from macro 'RBIMPL_ATTR_NORETURN'
# define RBIMPL_ATTR_NORETURN() __declspec(noreturn)
                                ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:24:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/anyargs.h:77:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/intern/vm.h:64:1: error: '__declspec' attributes are not enabled; use '-fdeclspec' or '-fms-extensions' to enable support for __declspec attributes
RBIMPL_ATTR_NORETURN()
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noreturn.h:29:33: note: expanded from macro 'RBIMPL_ATTR_NORETURN'
# define RBIMPL_ATTR_NORETURN() __declspec(noreturn)
                                ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/int.h:26:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/long.h:70:1: error: '__declspec' attributes are not enabled; use '-fdeclspec' or '-fms-extensions' to enable support for __declspec attributes
RBIMPL_ATTR_NORETURN()
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noreturn.h:29:33: note: expanded from macro 'RBIMPL_ATTR_NORETURN'
# define RBIMPL_ATTR_NORETURN() __declspec(noreturn)
                                ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:28:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:46:14: error: expected parameter declarator
RUBY_ALIGNAS(SIZEOF_VALUE)
             ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value.h:41:23: note: expanded from macro 'SIZEOF_VALUE'
# define SIZEOF_VALUE SIZEOF_LONG
                      ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/arm64-darwin21/ruby/config.h:61:21: note: expanded from macro 'SIZEOF_LONG'
#define SIZEOF_LONG 8
                    ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:28:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:46:14: error: expected ')'
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value.h:41:23: note: expanded from macro 'SIZEOF_VALUE'
# define SIZEOF_VALUE SIZEOF_LONG
                      ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/arm64-darwin21/ruby/config.h:61:21: note: expanded from macro 'SIZEOF_LONG'
#define SIZEOF_LONG 8
                    ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:46:1: note: to match this '('
RUBY_ALIGNAS(SIZEOF_VALUE)
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/backward/2/stdalign.h:27:22: note: expanded from macro 'RUBY_ALIGNAS'
#define RUBY_ALIGNAS RBIMPL_ALIGNAS
                     ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/stdalign.h:66:44: note: expanded from macro 'RBIMPL_ALIGNAS'
# define RBIMPL_ALIGNAS(_) __declspec(align(_))
                                           ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:28:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:47:1: error: expected function body after function declarator
RBasic {
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:82:23: error: incomplete definition of type 'struct RBasic'
    return RBASIC(obj)->klass;
           ~~~~~~~~~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:82:12: note: forward declaration of 'struct RBasic'
    return RBASIC(obj)->klass;
           ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro 'RBASIC'
#define RBASIC(obj)          RBIMPL_CAST((struct RBasic *)(obj))
                                                 ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:35:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value_type.h:157:28: error: incomplete definition of type 'struct RBasic'
    VALUE ret = RBASIC(obj)->flags & RUBY_T_MASK;
                ~~~~~~~~~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value_type.h:157:17: note: forward declaration of 'struct RBasic'
    VALUE ret = RBASIC(obj)->flags & RUBY_T_MASK;
                ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro 'RBASIC'
#define RBASIC(obj)          RBIMPL_CAST((struct RBasic *)(obj))
                                                 ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:237:23: error: incomplete definition of type 'struct RBasic'
    return RBASIC(obj)->flags & flags;
           ~~~~~~~~~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:237:12: note: forward declaration of 'struct RBasic'
    return RBASIC(obj)->flags & flags;
           ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro ‘RBASIC’
#define RBASIC(obj)          RBIMPL_CAST((struct RBasic *)(obj))
                                                 ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:285:1: error: ‘__declspec’ attributes are not enabled; use ‘-fdeclspec’ or ‘-fms-extensions’ to enable support for __declspec attributes
RBIMPL_ATTR_NOALIAS()
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noalias.h:53:32: note: expanded from macro ‘RBIMPL_ATTR_NOALIAS’
# define RBIMPL_ATTR_NOALIAS() __declspec(noalias)
                               ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:288:30: warning: declaration of ‘struct RBasic’ will not be visible outside of this function [-Wvisibility]
rbimpl_fl_set_raw_raw(struct RBasic *obj, VALUE flags)
                             ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:290:8: error: incomplete definition of type 'struct RBasic'
    obj->flags |= flags;
    ~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:288:30: note: forward declaration of ‘struct RBasic’
rbimpl_fl_set_raw_raw(struct RBasic *obj, VALUE flags)
                             ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:298:27: warning: incompatible pointer types passing ‘struct RBasic *’ to parameter of type ‘struct RBasic *’ [-Wincompatible-pointer-types]
    rbimpl_fl_set_raw_raw(RBASIC(obj), flags);
                          ^~~~~~~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:30: note: expanded from macro ‘RBASIC’
#define RBASIC(obj)          RBIMPL_CAST((struct RBasic *)(obj))
                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/cast.h:33:28: note: expanded from macro ‘RBIMPL_CAST’
# define RBIMPL_CAST(expr) (expr)
                           ^~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:288:38: note: passing argument to parameter ‘obj’ here
rbimpl_fl_set_raw_raw(struct RBasic *obj, VALUE flags)
                                     ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:310:1: error: ‘__declspec’ attributes are not enabled; use ‘-fdeclspec’ or ‘-fms-extensions’ to enable support for __declspec attributes
RBIMPL_ATTR_NOALIAS()
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noalias.h:53:32: note: expanded from macro ‘RBIMPL_ATTR_NOALIAS’
# define RBIMPL_ATTR_NOALIAS() __declspec(noalias)
                               ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:313:32: warning: declaration of ‘struct RBasic’ will not be visible outside of this function [-Wvisibility]
rbimpl_fl_unset_raw_raw(struct RBasic *obj, VALUE flags)
                               ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:315:8: error: incomplete definition of type 'struct RBasic'
    obj->flags &= ~flags;
    ~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:313:32: note: forward declaration of ‘struct RBasic’
rbimpl_fl_unset_raw_raw(struct RBasic *obj, VALUE flags)
                               ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:323:29: warning: incompatible pointer types passing ‘struct RBasic *’ to parameter of type ‘struct RBasic *’ [-Wincompatible-pointer-types]
    rbimpl_fl_unset_raw_raw(RBASIC(obj), flags);
                            ^~~~~~~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:30: note: expanded from macro ‘RBASIC’
#define RBASIC(obj)          RBIMPL_CAST((struct RBasic *)(obj))
                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/cast.h:33:28: note: expanded from macro ‘RBIMPL_CAST’
# define RBIMPL_CAST(expr) (expr)
                           ^~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:313:40: note: passing argument to parameter ‘obj’ here
rbimpl_fl_unset_raw_raw(struct RBasic *obj, VALUE flags)
                                       ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:335:1: error: ‘__declspec’ attributes are not enabled; use ‘-fdeclspec’ or ‘-fms-extensions’ to enable support for __declspec attributes
RBIMPL_ATTR_NOALIAS()
^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noalias.h:53:32: note: expanded from macro ‘RBIMPL_ATTR_NOALIAS’
# define RBIMPL_ATTR_NOALIAS() __declspec(noalias)
                               ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:338:34: warning: declaration of ‘struct RBasic’ will not be visible outside of this function [-Wvisibility]
rbimpl_fl_reverse_raw_raw(struct RBasic *obj, VALUE flags)
                                 ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:340:8: error: incomplete definition of type 'struct RBasic'
    obj->flags ^= flags;
    ~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:338:34: note: forward declaration of ‘struct RBasic’
rbimpl_fl_reverse_raw_raw(struct RBasic *obj, VALUE flags)
                                 ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:348:31: warning: incompatible pointer types passing ‘struct RBasic *’ to parameter of type ‘struct RBasic *’ [-Wincompatible-pointer-types]
    rbimpl_fl_reverse_raw_raw(RBASIC(obj), flags);
                              ^~~~~~~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:30: note: expanded from macro 'RBASIC'
#define RBASIC(obj)          RBIMPL_CAST((struct RBasic *)(obj))
                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/cast.h:33:28: note: expanded from macro 'RBIMPL_CAST'
# define RBIMPL_CAST(expr) (expr)
                           ^~~~~~
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:338:42: note: passing argument to parameter 'obj' here
rbimpl_fl_reverse_raw_raw(struct RBasic *obj, VALUE flags)
                                         ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:465:43: error: incomplete definition of type 'struct RBasic'
        if (RBASIC_CLASS(x) && !(RBASIC(x)->flags & RUBY_FL_SINGLETON)) {
                                 ~~~~~~~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:465:34: note: forward declaration of 'struct RBasic'
        if (RBASIC_CLASS(x) && !(RBASIC(x)->flags & RUBY_FL_SINGLETON)) {
                                 ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro 'RBASIC'
#define RBASIC(obj)          RBIMPL_CAST((struct RBasic *)(obj))
                                                 ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:19: error: field has incomplete type 'struct RBasic'
    struct RBasic basic;
                  ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:12: note: forward declaration of 'struct RBasic'
    struct RBasic basic;
           ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:109:26: error: incomplete definition of type 'struct RBasic'
    VALUE f = RBASIC(str)->flags;
              ~~~~~~~~~~~^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:12: note: forward declaration of ‘struct RBasic’
    struct RBasic basic;
           ^
In file included from aggregator.c:1:
In file included from ./aggregator.h:4:
In file included from ./sqlite3_ruby.h:4:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:26:
In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core.h:23:
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rarray.h:88:19: error: field has incomplete type ‘struct RBasic’
    struct RBasic basic;
                  ^
/Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:12: note: forward declaration of ‘struct RBasic’
    struct RBasic basic;
           ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
6 warnings and 20 errors generated.
make: *** [aggregator.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2 for inspection.
Results logged to /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/extensions/arm64-darwin-21/3.0.0/sqlite3-1.4.2/gem_make.out

➜  ~ >

A: I figured out the answer. It works if I prepend the gem install command with CC='clang -fdeclspec'.
Like this:
CC='clang -fdeclspec' gem install sqlite3


Q: D3.js Brush controls with Ordinal Crossfilter Scales I'm aiming to subset my choropleth like this wonderful example. I've reviewed the API documentation and Mike's Ordinal Brushing example.
Unfortunately,  I'm still not getting my thick head around how brushes are supposed to work.
The examples are sophisticated and somewhat inaccessible for newcomers (lots of turnery operators and arrays of chart objects etc).
I've chosen not to use dc.js due to lack of support for things I'll have to deal with later. Nice work though and props to Nick Qi Zhu.
Can someone pls review my (native d3) approach and show me what I'm doing wrong?
I've setup my bar chart which renders fine. Basically a count of values in a normal distribution.
// Setup Crossfilter dimensions and groups
var nation      = crossfilter(MSPB),
    byScr       = nation.dimension(function(d){ return d.score; }),
    byScrGrp    = byScr.group().reduceCount(),
    byHosp      = nation.dimension(function(d){ return d.FIPS; });

// Histogram X-Axis ordinal scale
var x = d3.scale.ordinal()
        .domain(d3.range(0,2,0.1))
        .rangeBands([0, width, 0.5, 0.5 ]);

// Histogram Y-Axis linear scale
var y = d3.scale.linear()
        .domain([0, d3.max(byScrGrp.all(), function(d){ return d.value; })])
        .range([height/2, 0]);

// Histogram SVG containiner
var svg = d3.select("#histogram").append("svg:svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height/2 + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // Histogram bars
    svg.selectAll("rect")
        .data(byScrGrp.all())
        .enter().append("rect")
        .attr("x", function(d,i){ return i * (width / byScrGrp.size() ); })
        .attr("width", width / byScrGrp.size() - barPadding )
        .attr("y", function(d){ return  y(d.value) ; })
        .attr("height", function(d){ return ((height/2) -y(d.value)); })
        .attr("fill", function(d){ return color(d.key); })
        .on("mouseover", function(d){ d3.select(this).attr("fill", "teal"); })
        .on("mouseout", function(d) { d3.select(this).attr("fill", function(d){return color(d.key);}) } );

Immediately after, I try to add my brush controls like this. Initially I just want to get the drag selection working on the bar chart. I'll worry about getting xAxis extent values for filtering the choropleth later.
 var brush = d3.svg.brush()
            .x(x)
            .on("brushstart", brushstart)
            .on("brush", brushmove)
            .on("brushend", brushend)

var brushg = svg.append("g")
            .attr("class", "brush")
            .call(brush)

    brushg.selectAll("rect")
                .attr("height", height/2)
                .attr("width", width);

function brushstart() {
  svg.classed("selecting", true);
}

function brushmove() {
  var s = brush.extent();
  brushg.classed("selected", function(d) { return s[0] <= (d = x(d)) && d <= s[1]; });
}

function brushend() {
  svg.classed("selecting", !d3.event.target.empty());
}

I'm seeing the crosshair drag handles but not seeing what I'd expect and certainly not getting the desired effect.
It's slow on this webserver but the full js file is here and partially working example here.
EDIT: I've tried to create a JSFiddle here.
Any pointers would be much appreciated.
Thanks

A: Hard to say without experimenting (any chance of creating a JSfiddle or similar?). I suspect the issue is that you are setting the width of all the rects in the brush. You only need to set the height, I believe. This is probably what is causing your extents to go all crazy.
Once you get that straightened out, you'll need to filter your Crossfilter dimension based on the brush extent.
Also, Crossfilter's group.reduceCount function doesn't take an argument, and if it is possible you are missing data you need to make sure to test/cast your data in your dimension accessors to make sure they always return naturally ordered numbers or strings.


Q: HazelCast - How to insert records through a Map to a table with auto sequence field as PK I am using HazelCast to do read/write operations on MS SQL server database.
I have a database table whose primary key is an auto increment column.
I read existing data in this table to a Map when my application starts.
The Map has an underlying MapStore implementation.
The key of the map is the auto increment column value. The value of the map is an object containing few fields from the table.
User can insert records to this table through the HazelCast layer.
This insert is performed in a Transaction (TransactionalMap is obtained from HazelCast).
It is at this place i face a problem as i do not have the primary key value (auto increment value) to set to the TransactionalMap instance.
I have the insert to database table logic in the MapStore's store() method and the store() method is called only after commit is called on the Transaction.
I am not getting how to first set the key value (auto increment value) to the map. Auto increment value can be obtained post the insert to the table.
Ideas/Points are most welcome.
Thanks,
s.r.guruprasad

A: You can implement PostProcessingMapStore interface on your MapStore which enables the ability to update the stored entry inside the store() method. You can obtain the auto-generated fields from the database then you can reflect those changes to your entry.
See Post Processing documentation : http://docs.hazelcast.org/docs/latest-dev/manual/html-single/index.html#post-processing-objects-in-map-store

A: The only way I can see to do what you ask is to have your code write a demo record into the database and then read it back before into Hz and making MapStore do an update rather than insert.
Of course this would be slow and cumbersome.
The best solution would be to turn off the autoincrement, but what you could also do is use a different field as the cache key, say have a member called cacheKey and store that in your database record, when you do an insert in MapStore you just need insert where databaserecord.cachekey == cacheKey.


Q: Please explain '%' usage in python I'm learning multithreading in python and I was reading through this answer. I understand most of the code however there is this one line which I simply don't understand and I don't know how to search for it on Google as the '%' sign keeps returning modulo.
req.headers['Range'] = 'bytes=%s-%s' % (start, start+chunk_size)

I thought that req.headers['Range'] would retrieve some 'range' element from an array however here they are assigning it a value of 'bytes=%s-%s' % (start, start+chunk_size). I really just don't understand what is going on in this line. Things like 'bytes=%s-%s' I am assuming is some sort of python syntax which I am unaware of. If you could explain each term in this line that would be very much appreciated.

A: In python there are multiple ways to format strings. using %s inside a string and then a % after the string followed by a tuple (or a single value), allows you to create a new string:
x = 5
y = 8
'my favourite number is %s, but I hate the number %s' % (x, y)

results in:
'my favourite number is 5, but I hate the number 8'

I think they call it C-type string formatting. For more information, you can check out this page.
In my opinion, it is easier to format string using f'strings, or .format(). Check out this page too


Q: Latitude and Longitude are null I'm working on an app getting user's current location  and showing it on map, as well as Latitude and Longitude on the screen, so far everything is going fine, the map's showing my current location as well as displaying latitude and longitude on the screen using this code
@Override
public void onLocationChanged(Location location) {

    TextView tvLocation = (TextView) findViewById(R.id.tv_location);

    // Getting latitude of the current location
    double latitude = location.getLatitude();

    // Getting longitude of the current location
    double longitude = location.getLongitude();

    // Creating a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Showing the current location in Google Map
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    // Setting latitude and longitude in the TextView tv_location
    tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

}

Problem occurs when I want to send this latitude and longitude on server , it throws NUll pointer exception
 01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL
 EXCEPTION: main
  Process: io.xgear.geotag, PID: 29286
  java.lang.NullPointerException
      at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234)
      at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181)
      at android.view.View.performClick(View.java:4633)
      at android.view.View$PerformClick.run(View.java:19270)
      at android.os.Handler.handleCallback(Handler.java:733)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:146)
      at android.app.ActivityThread.main(ActivityThread.java:5602)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:515)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
      at dalvik.system.NativeStart.main(Native Method)

this is the piece of code for getting latitude and longitude to send
 public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private final String shopCode;
       Location location;
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());

        private boolean isConnect;
        GeoTagTask(String shopId) {
            shopCode = shopId;
            isConnect = false;

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean res = false;
     try {
                ContentValues nameValuePairs = new ContentValues();
                nameValuePairs.put("Id", shopCode);
                nameValuePairs.put("lat", lat);
                nameValuePairs.put("lng", lng);
         //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
               Log.i("Latitude", lat+"");

                Post post = new Post(getApplicationContext());
                String result = "";
//                isConnect = post.isConnected();
  //              if(isConnect) {
                    result = post.doPost(nameValuePairs);
                    jsonObj = new JSONObject(result);
                    Log.i("Result", result+"");
                    if(jsonObj.getInt("success") == 1)
                        res = true;
    //            }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return res;
        }

and this is the full code
package io.xgear.geotag;

import android.Manifest;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.support.v4.app.Fragment;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import io.xgear.geotag.helper.Post;

public class MainActivity extends FragmentActivity implements LocationListener {
    GoogleMap googleMap;
    private GeoTagTask mAuthTask = null;
    GPSTracker gps;
    private JSONObject jsonObj;

    // UI references.
    private EditText txtShopCode;
    private EditText lblAddress;
    private View mProgressView;
    private View mGeoTagForm;
    private Button btnGeoTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtShopCode = (EditText) findViewById(R.id.txtShopCode);
        btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
        mGeoTagForm = (View) findViewById(R.id.geoTagForm);
        mProgressView = findViewById(R.id.geoTagProgress);

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }

        btnGeoTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String shopid = txtShopCode.getText().toString();
                boolean cancel = false;
                View focusView = null;

               //txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);

                if (TextUtils.isEmpty(shopid)) {
                    txtShopCode.setError(getString(R.string.error_field_required));
                    focusView = txtShopCode;
                    cancel = true;

                }
                else {

                    showProgress(true);
                    mAuthTask = new GeoTagTask(shopid);
                    mAuthTask.execute((Void) null);
                }
            }

        });

    }

//

//    public void btnGeoTag_Click(View v){
//
//    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
            mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private final String shopCode;
       Location location;
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());

        private boolean isConnect;
        GeoTagTask(String shopId) {
            shopCode = shopId;
            isConnect = false;

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean res = false;
     try {
                ContentValues nameValuePairs = new ContentValues();
                nameValuePairs.put("Id", shopCode);
                nameValuePairs.put("lat", lat);
                nameValuePairs.put("lng", lng);
         //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
               Log.i("Latitude", lat+"");

                Post post = new Post(getApplicationContext());
                String result = "";
//                isConnect = post.isConnected();
  //              if(isConnect) {
                    result = post.doPost(nameValuePairs);
                    jsonObj = new JSONObject(result);
                    Log.i("Result", result+"");
                    if(jsonObj.getInt("success") == 1)
                        res = true;
    //            }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return res;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                intent.putExtra("jsonObj", jsonObj.toString());
//                startActivity(intent);
                txtShopCode.getText().clear();
                txtShopCode.requestFocus();
                Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();

            } else {
//                if(isConnect){
//                    mPasswordView.setError(getString(R.string.error_incorrect_password));
//                    mPasswordView.requestFocus();

//                }
//                else
                    Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        TextView tvLocation = (TextView) findViewById(R.id.tv_location);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        // Setting latitude and longitude in the TextView tv_location
        tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.activity_main, menu);
//        return true;
//    }
}

UPDATE
I have added thes lines in GeoTagTask the button is working the app is not crashing but I'm not sure if it's going to work if location is changed because
 if( location != null){
            onLocationChanged(location);
       }
     locationManager.requestLocationUpdates(provider, 20000, 0, this);

is giving me errors .
The lines I have added
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);

        Location location = locationManager.getLastKnownLocation(provider);

A: inside GeoTagTask location object  is different one and also doesn't initilized.
    Location location;
    private String lat = Double.toString(location.getLatitude());
    private String lng = Double.toString(location.getLongitude());

A: Problem
Problem is inside GeoTagTask ,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());

You are accessing an uninitialized variable.
Solution
Make onCreate location a global variable,
public class MainActivity extends FragmentActivity implements LocationListener {
    Location location;
    void onCreate() {
        ....
        location = locationManager.getLastKnownLocation(provider);
        ....
    }
}

Use the global variable inside GeoTagTask,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());
        ...
}


Q: Merge multiple mutually exclusive factor columns into a single column Say I have three columns in a data frame.  I want to merge these into a single column.  Each of the three columns is a binary attribute such as green/yellow, red/blue, black/white, etc.
I want to merge all of these into a single column with multiple
 row1=c(0,0,1)
 row2=c(1,0,0)
 row3=c(0,1,0)
 df=data.frame(rbind(row1,row2,row3))

Is there a way to merge each of these columns into a single column?  The single column would now have to have six different factors instead of the two it already has.
Can anyone show me how to code this?

A: You can encode these as you would encode a binary number, by assigning increasing powers of two for each column.  You want to multiply each row by c(1,2,4) and then take the sum.
# The multiplier, powers of two
x <- 2^(seq(ncol(df))-1)
x
## [1] 1 2 4

# The values
apply(df, 1, function(row) sum(row*x))
## row1 row2 row3
## 4    1    2

To add this as a new column:
df$new <- apply(df, 1, function(row) sum(row*x))
df
##      X1 X2 X3 new
## row1  0  0  1   4
## row2  1  0  0   1
## row3  0  1  0   2

A: Try:
> df
     X1 X2 X3
row1  0  0  1
row2  1  0  0
row3  0  1  0
>
>
> mm = melt(df)
No id variables; using all as measure variables
>
> mm$new = paste(mm$variable,mm$value,sep='_')
>
> mm
  variable value  new
1       X1     0 X1_0
2       X1     1 X1_1
3       X1     0 X1_0
4       X2     0 X2_0
5       X2     0 X2_0
6       X2     1 X2_1
7       X3     1 X3_1
8       X3     0 X3_0
9       X3     0 X3_0

mm$new is the column you want.

A: Maybe this is what you want:
> df$X1 = ifelse(df$X1==0,'green','yellow')
> df$X2 = ifelse(df$X2==0,'red','blue')
> df$X3 = ifelse(df$X3==0,'black','white')
>
> df
         X1   X2    X3
row1  green  red white
row2 yellow  red black
row3  green blue black
>
> unlist(df)
     X11      X12      X13      X21      X22      X23      X31      X32      X33
 "green" "yellow"  "green"    "red"    "red"   "blue"  "white"  "black"  "black"


Q: Why doesn't the ttf fonts work with Vue CLI? I am working with Vue CLI, and I want to use a font downloaded from the Internet. I think I have configured everything but it just doesn't work.
The structure of the project is like this:
+--node_modules
+--public
|  +--index.html
+--src
|  +--assets
|  |  +--css
|  |  +--font
|  |  |  +--font.css
|  |  |  +--FZYXJW.ttf
|  +--components
|  +--App.vue
|  +--main.js
+--babel.config.js
+--vue.config.js
+--package.json

Here are the relative codes:
// font.css
@font-face {
  font-family: 'Youxian';
  src: url("FZYXJW.ttf");
}

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
        .rule('font')
        .test(/\.(woff2?|eot|ttf|otf)(\?.*)?$/)
        .use('url-loader')
        .loader('url-loader')
        .end()
  }
};

// App.vue
<template>
  <div id="app">
      <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'app'
}

</script>

<style>
  @import "/assets/font/font.css";

  #app {
    font-family: 'Youxian';
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }

</style>

I expected the font to change to "Youxian", but actually nothing happened.


Q: Cannot upload chunked video to twitter I have been trying to upload video chunks to twitter using twurl as in the example on the page: https://blog.twitter.com/2015/rest-api-now-supports-native-video-upload
However, I get the "unsupported video" error. I am able to upload smaller sized videos without breaking them into chunks.
I am running twurl on Ubuntu 12.04

A: It means exactly "unsupported video".
Twitter has a strict video format requirement: https://dev.twitter.com/rest/public/uploading-media#videorecs.
Example: sample mp4 files containing 6-channel audio won't be supported.
Check out my project: https://github.com/mtrung/TwitterVideoUpload.


Q: Android Studio, on Windows: ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click 'Restart' I downloaded Android Studio on windows, and I am trying to run the default HelloWorld application. However, when I run that app, I get a dialog box with the following:
ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click 'Restart'

I've searched for solutions online and most of it was to kill the adb server and start it again manually, but when I do so in the command line I get:
sdk\platform-tools>adb kill-server
* server not running *

sdk\platform-tools>adb start-server
adb server is out of date.  killing...
ADB server didn't ACK
* failed to start daemon *

And the first error keeps showing. I restarted my machine, and the problem is still there. Any ideas? Thanks.
I tried this fix: http://visualgdb.com/adbfix/#adbfix_download but it did not work. It showed: "No Conflicts Found".
Note: I need the app to run on my device. Not on emulator

A: I was also facing same issue and I followed these steps and problem went away:
1.close all program in your system then
2.then go to start button and search for %temp% then delete all files inside this folder
3.install Cclean software and clean your system.
4.restart your system

A: I was facing same issue in win7 and I took these steps to resolve the problem:
When starting Android Studio, it warns you with ADB not responding.
If you'd like to retry, then please manually kill the process. You should enter cmd, and input adb kill-server for ten times or more.
When the building has finished, input adb start-server and you will see
daemon not running.
starting it now on port 5037
daemon started successfully


Q: Query regarding looping a response data array using async await I am working with an existing class components based React application and was dumbfounded when I spent almost 3 hours to figure out the root cause of the following code snippet.
In componentDidMount which is async btw, I am calling backend API designed with Node.js using axios like this
(Note state below is in Class Component which I skipped for obvious reasons)
state = {
  grades = [];
}

try {
    const res = await axios.get(
      `/assignments/getStudentAssignment/${this.props.studentId}`
    );

    const assignments = res.data.assignment.assignments;

    assignments.forEach((assignment) => {
       this.setState({grades: [...this.state.grades, assignment.grade]})
    }))

} catch (err) {
    'some logic'
}

Where res.data.assignment.assignments is an array of each student assignments, and from each assignment I am pushing a new grade in grades array state. In console.log using Chrome browser I saw that the grades array had 8 elements but I couldn't view them in console.log, and the length of array was also set to 0.
I consoled assignment within forEach array and also set a counter in order to see that is forEach looping through the entire array or just first element. Console.log only printed first counter number and also first array element
I figured out that since the assignments is an array of promises that are yet to be resolved, I cannot loop through the entire array, and then I changed my code to this
await assignments.forEach((assignment) => {
       this.setState({grades: [...this.state.grades, assignment.grade]})
}))

And viola, it worked like a charm but I am confused on a couple of things.

*

*Isn't await supposed to resolve promise res.data.assignment.assignments,
meaning I can loop through resolved array data

*Why did forEach work for only first element of
res.data.assignment.assignments if the array was yet to be resolved?

I tried on MDN, by creating a sample array in a promise and then looping through the contents of array in a then chain where each element was printed on console perfectly. Any help will be appreciated
EDIT
I have changed the original code, axios returns an assignment object which also contains an array of assignments
I worked with the following code once again without await, and its working fine. This is the second time, I had trouble with React setState, first time setState wasn't firing for some reason, and then after deleting node_modules and installing all required packages it worked, even though it wasted a day
   state = {
     grades = [];
   }

   try {
       const res = await axios.get(
          `/assignments/getStudentAssignment/${this.props.studentId}`
       );

       const assignments = res.data.assignment.assignments;

       assignments.forEach((assignment) => {
         this.setState({grades: [...this.state.grades, assignment.grade]})
       }))
    } catch (err) {
    'some logic'
    }


Q: Adding new variables to existing data that correlate with one or two existing ones How can I add two more variables with the following conditions?

*

*Variable "c" that has a 0.7 correlation with variable "a".

*If possible, variable "d" that correlates simultaneously with "a" and "b".

Simulated data
n = 100

d = tibble(a = rnorm(n, 50, 20),
           b = rnorm(n, 10, 0.4))

d

Tidyverse solutions are much appreciated!

A: Here is a small function that take a vector x and a desired rho and returns a vector such that cor(<vector>,x) == rho`).
f <- function(x,rho) {
  orth = lm(runif(length(x))~x)$residuals
  rho*sd(orth)*x + orth*sd(x)*sqrt(1-rho^2)
}

Now we apply the function to column a to create a column c such that cor(a,c) == 0.7
d %>%  mutate(c = f(a,.7))

A: The second is actually more easier (for me at least): just make z-scores out of both a and b and add or average them. It will correlate with both a and b with 0.7
d <- d %>%
  mutate(d=((a - mean(a)) / sd(a)) +
           ((b- mean(b)) / sd(b)))

A: Using the Iman and Conover method (1982) developed in the mc2d package (a rank correlation structure).
library(mc2d)
cc <- rnorm(n,50,20)
cc <- cornode(cbind(d$a,cc), target=0.7)[,"cc"]
d$c <- cc
cor(d)

For more than one variable, you have to build a matrix of correlation.
## Target
(corrTarget <- matrix(c(1, 0.7, 0.7, 0.7, 1, 0.7, 0.7, 0.7, 1), ncol=3))

dd <- rnorm(n,50,20)
dd <- cornode(cbind(a=d$a,b=d$b,dd), target=corrTarget)
cor(dd)
d$b <- dd[,"b"]
d$d <- dd[,"dd"]

cor(d)

The final correlation structure should be checked because it is not always possible to build the target correlation structure.


Q: 'in' operator with boost::python I have a class which .defines the __getitem__, __setitem__ methods (and keys and items as well), and behaves like a dictionary, where keys are strings.
However, the in operator does not behave as expected:
>>> myObject=MyClass()
>>> 'abc' in myObject.keys()
False
>>> 'abc' in myObject
ArgumentError: Python argument types in
    MyClass.__getitem__(MyClass, int)
did not match the C++ signature:
    __getitem__(MyClass {lvalue}, std::string)

Why is python trying to call __getitem__ with int, when I use the str key?

A: It seems that
'abc' in myObject

is being evaluated as:
for i in myObject:
    if myObject[i] == 'abc':
        return true

Where i is an integer.
Try implementing the __contains__(self, value) magic method.


Q: Uncaught TypeError: Cannot read property 'getElementsByClassName' of null | HTML |JS I have an Html page with cards for my memory card game, The user is supposed to match a pair of cards and win an offer mentioned in the card. The offers are for an online grocery shopping application. I get the following error when I flip the card.

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        25 % OFF on
Soft Drinks

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        10 % OFF on
Fruits
&
 Vegetables

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        25 % OFF on
Soft Drinks

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        10 % OFF on
Fruits
&
 Vegetables

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        15 % OFF on
Dairy Products

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        15 % OFF on
Dairy Products

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Buy any can of
Pringles and get
another for FREE!

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Buy any can of
Pringles and get
another for FREE!

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Oreo Party Pack
for only
Rs.1500.00

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Oreo Party Pack
for only
Rs.1500.00

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Get a Free Pack
of Dilmah tea
of your choice.

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Get a Free Pack
of Dilmah tea
of your choice.

and the script to flip the cards and see if they are matched is in the script.js file
class AudioController{
    constructor() {
        this.flipSound = new Audio('Assets/audio/flip.wav');
        this.matchSound = new Audio('Assets/audio/match.wav');

    }
    flip(){
        this.flipSound.play();
    }
    match(){
        this.matchSound.play();
    }
}
let hasFlippedCard = false;
let firstCard, secondCard;
class MixORMatch{
    constructor(totalChances,cards) {
        this.cardsArray = cards;
        this.totalChances = totalChances;
        this.chancesRemaining = totalChances;
        this.chances = document.getElementById('chances-remaining');
        this.audioController = new AudioController();

        //shuffle cards
        this.shuffleCards();

        //start game
        this.cardToCheck = null;
        this.totalClicks = 0;
        this.chancesRemaining = this.totalChances;
        this.matchedCards = [];

    }
    startGame(){
        this.cardToCheck = null;
        this.totalClicks = 0;
        this.chancesRemaining = this.totalChances;
        this.matchedCards = [];

    }

    flipCard(card) {
        if(this.canFlipCard(card)){
            this.audioController.flip();
            this.totalClicks++;
            card.classList.add('visible');

            //first click
            hasFlippedCard = true;
            firstCard = this;

            if (this.canFlipCard(card)){
                this.checkForCardMatch(card);
            }else{
                this.cardToCheck = card;
            }

        }else{
            //second click
            hasFlippedCard = false;
            secondCard = this;
            console.log("flipped")
        }
    }
    hideCards() {
        this.cardsArray.forEach(card=> {
            card.classList.remove('visible');
            card.classList.remove('matched');
        });
    }
    checkForCardMatch(card) {
        if (this.getCardType(card)===this.getCardType(this.cardToCheck)){
            this.cardMatch(card,this.cardToCheck);
        }else{
            this.cardMisMatch(card,this.cardToCheck);
        }
        this.cardToCheck = null;
    }
    cardMatch(card1,card2){
        this.matchedCards.push(card1);
        this.matchedCards.push(card2);
        card1.classList.add('matched');
        card2.classList.add('matched');
        this.audioController.match();
        if(this.matchedCards.length === this.cardsArray.length){
            console.log("win");
        }
    }

    cardMisMatch(card1,card2){
        setTimeout(()=>{
            card1.classList.remove('visible');
            card2.classList.remove('visible');
        },1000);
    }
    shuffleCards(cardsArray){
       let cardscount = cardsArray,length;
        for(let i =cardscount; i>0; i--){
            let randIndex = Math.floor(Math.random() * (i+1));
            cardsArray[randIndex].style.order = i;
            cardsArray[i].style.order = randIndex;
        }
    }

    getCardType(card){
        return card.getElementsByClassName('match-value')[0].src;
    }

    canFlipCard(card){
         return true;//(!this.busy && !this.matchedCards.includes(card) && card!== this.cardToCheck);
    }

}
function ready(){
    let cardDeck = Array.from(document.getElementsByClassName('deck'));
    let cards = Array.from(document.getElementsByClassName('card'));
    let game = new MixORMatch(3,cards);
   /* overlays.forEach(overlay => {
        overlay.addEventListener('click',()=>{
            overlay.classList.remove('visible');
            //game.startGame();
        });
    });*/

    cards.forEach(card =>{
        card.addEventListener('click',()=>{
            //flipping card game
            game.startGame();
            game.flipCard(card);

        });
    });
}

if(document.readyState === 'loading'){
    document.addEventListener('DOMContentLoaded',ready);
}else{
    ready();
}

I'm not sure why I'm getting this error I have defined the cards to match class as "match-value" which is the image, I the get image src and check whether it matches the one the card user has flipped earlier. But when I flip both cards I get the above mentioned error. In the script in "getCardType".
Uncaught TypeError: Cannot read property 'getElementsByClassName' of null

A: The issue is in your getCardType() function. You wrote:
getCardType(card) {
    return card.getElementsByClassName('match-value')[0].src;
}

It should be:
getCardType(card){
    return document.getElementsByClassName('match-value')[0].src;
    //     ^--- you wrote 'card' here
}


Q: How to set the value of the SelectedItem property in devexpress combobox BarItem? It is example Combobox in which everything is working good and selected value varies depending on changes CurrentPlanSet.
       <dxe:ComboBoxEdit ItemsSource="{Binding PlanSets, Mode=TwoWay}"
                               DisplayMember="Name"
                               ValueMember="Name"
                               SelectedItem="{Binding CurrentPlanSet, Mode=TwoWay}"
                               />

In this example the selected value does not change depending on CurrentPlanSet changes.
<dxb:BarEditItem Content="Plan Sets" EditWidth="350">
                <dxb:BarEditItem.EditStyle>
                    <Style TargetType="{x:Type dxe:ComboBoxEdit}">
                        <Setter Property="SelectedIndex" Value="{Binding     CurrentPlanSet, Mode=TwoWay}"/>
                    </Style>
                </dxb:BarEditItem.EditStyle>
                <dxb:BarEditItem.EditSettings  >
                    <dxe:ComboBoxEditSettings ItemsSource="{Binding PlanSets, Mode=TwoWay}" ValueMember="Id" DisplayMember="Name" />
                </dxb:BarEditItem.EditSettings>
            </dxb:BarEditItem>

How to correctly set the value of the SelectedItem property in second code example?

A: SelectedIndex is not the same as SelectedItem.
This is the same as with the default WPF Controls.
SelectedIndex is the Index of the CollectionItem, you have selected/set selected (Integer). The SelectedItem is the Item Object itself.
Example:
Lets take this Collection: new ObservableCollection<string>(){ "String1", "String2", String3"}
If the SelectedItem is/should be String1 the SelectedIndex is 0.
So just replace
<Setter Property="SelectedIndex" Value="{Binding CurrentPlanSet, Mode=TwoWay}"/>

with
<Setter Property="SelectedItem" Value="{Binding CurrentPlanSet, Mode=TwoWay}"/>


Q: Coroutines: Can't return value after finish work In my android app I need after executed some long network operation to return result (e.g. after 10 seconds)
here snippet:
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

 GlobalScope.launch(Dispatchers.Main) {
                lateinit var response: Response<Void>
                response = executeOperations.await()
                return response
            }

but I get compile error in this line:
return response

Error message:
'return' is not allowed here

A: It doesn't work like that. Your return is not allowed there because you are inside a coroutine context on those { }
But actually the best way to do it is to create some method and handle that response instead of returning it. On your case I'm a little confused:
Transform:
GlobalScope.launch(Dispatchers.Main) {
                lateinit var response: Response<Void>
                response = executeOperations.await()
                return response
            }

Into:
GlobalScope.launch(Dispatchers.IO) {
                lateinit var response: Response<Void>
                response = executeOperations.await()
                 withContext(Dispatchers.Main){
                  handleResponse(response)
               }
            }

Plus, your heavy work musn't happen in the Dispatchers.Main but in Dispatchers.IO


Q: How do I do a Quicksearch or autocomplete on a selectbox populated from a database? I have a select box populated a from a database and would like to do a quicksearch or a autocomplete to search the elements inside the select box. Below is my code:
    <?
           print("
");
        print("
");
            print("");
            //print("
");  //
            print("
Search: <input type='text' id='searchFILE' size='33' autocomplete='off' />
");
            print("<select name='lktyp' id='lktypSearch' size='10' >");
            //Create new SQL object
            $db = new NSC_SQL($db2config);
            $db->from($bllcust1,"BCUST#,BNAME");
            $db->order("BCUST#");
            $db->select();
            $results = $db->fetchAssoc();
            $db->dspSQL();
            foreach($results as $row)
            {
                $bcust = trim($row['BCUST#']);
                $bname = trim($row['BNAME']);
                print("<option value='$bcust'>$bcust ~ $bname</option>");
            }
            print("</select>");
            print("
");
            print("	");
        print("
");
        print("
");
            print("");
            //print("<input type='submit' name='search' value='Search'>");
            print("<input type='button' value='Select' onclick='lkp();'>");
            print("<input type='button' name='cancel' value='Cancel' onClick='parent.$.fancybox.close();'>");
            print("	");
        print("
");
    print("
");

?>

A: The simplest way would be to implement Jquery autocomplete. I won't do the code for you but if you find it difficult create a new question posting some of the code you tried and someone will help.

A: Two nice alternatives to jQuery autocomplete which was already mentioned are Chosen and Select2. Both of these require jQuery or another supported JS framework. jQuery autocomplete and Select2 have great support for remote datasets.


Q: How to export summary statistics of a regression from R studio to Excel I have ran a lm function and produced summary results which I wish to export onto a excel document.
Is there a specific package/code that allows me to do this? If so which is best for report presenting?

A: Let's assume we have model called "mod"
mod <- lm(v1 ~ v2, data= df)
You can use "broom" function.
library(broom)

#create dataframes with results
res_mod <- as.data.frame(tidy(mod))
res_mod2 <- as.data.frame(glance(mod))

#then export as two csvs
write.csv(res_mod, "res_mod.csv")
write.csv(res_mod2, "res_mod2.csv")


Q: Heroku Dataclip, How to export date column into XLS When a column contains a Date field, the dataclip displays it. When the "Export/Share" link is clicked and XLS selected, the resulting Date column is treated like a TEXT column in XLS.
Changing the Format in XLS does not seem to have an effect on it.
Is there a proper format for export that will make it into a Date cell?
I have tried 'MM-DD-YYY', 'MM/DD/YYY' and left it as default display (which puts the date and time in the column).
None of these are "dates" in XLS.
Thanks

A: I have done some tests and I think dates are exported as YYYY-MM-DD.
I really don't have Excel installed on this computer right now, but I downloaded an xls file from dataclips and imported it on Googlesheets. Dates were correct without any conversion needed.


Q: WordPress: External call to wp-load.php causes CPU and memory spikes One of my websites on my server is causing big CPU and memory spikes. I've been looking for the cause, and I believe that I've found it.
I've been digging in the access logs and every time a peak occurs, there is an external call to wp-load.php. This call looks like this (I've changed a few values):
52.56.220.94 - - [16/Oct/2018:12:57:20 +0200] "POST /wp-load.php?pubkey=c924c49878aec6f8295874888c0d14c1&bvTime=1539687440&bvVersion=0.1&bvMethod=getdata&sha1=true&sig=6d3a8735567bd7baa7e5e12af885afab0d6a399d HTTP/1.0" 200 4809 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

The calls come from a limited range of IP-addresses:
52.56.220.94
54.179.150.144
45.77.97.238
Does anyone recognize this and/or does anyone know a way to track down to which piece of software this call belongs to?
Any help is highly appreciated.

A: You should add the following to your .htaccess file:
<Files "wp-load.php">
  Order Deny,Allow
  Deny from all
  Allow from localhost
  Allow from 127.0.0.1
</Files>

I can't think of a reason to bootstrap WordPress from an external server ....


Q: count  in div after drop event I have 5 pieces of a image in a div sortable1 which i have to drag and drop in another div sortable2to complete the image. After the image is dropped in another container it will stick to the previous image present in this container.http://jsfiddle.net/binit/JnYB9/
After every drop event i want to check whether all the 5 pieces are collected in 2nd div and if it is yes then change button text. Something like this.
if $('#sortable2').find('img').length == 5:
    document.getElementById('btn-start').text = "end";

But i don't know where to use this logic in my code or what should be the syntax
My code:
javascript
$(function() {

  $( "#sortable1" ).sortable({
  connectWith: "div"
  });

  $( "#sortable2" ).sortable({
  connectWith: "div",
  change: function( event, ui ) {
  var theID = ui.item.attr('id');
  ui.item.addClass(theID + '-style');
 }
 });

 });

HTML

  Start

A: Use stop function of sortable evry time you sort the element from div with id sortable1.
Working Demo
stop: function( event, ui ) {
   if($('#sortable2').find('img').length==5)
   $('#btn-start').html("end");
 }

A: You can write a callback function on the sortable method like the following:
 $( "#sortable1" ).sortable({
   connectWith: "div",
   stop: function() {
           // your logic goes here
   }
 });

You can also use the start callback.


Q: Functions work even when headers have not been included - Visual Studio I routinely notice while working in Visual C++ that some functions work even when their headers have not been included. For example, tolower() works even when ctype.h is not included.
This behaviour causes problems for me when I participate in online programming competitions, the program works fine and dandy when I run it on my computer but on submission, gives a function not defined error. Is there any way to stop this behaviour?

A: Possible explanations:

*

*You have your warning level turned right down.

*You're using precompiled headers that are including the right files.

A: The declaration of your tolower() is in fact included. It could be so in one of the following ways:

*

*<cctype> or <ctype.h> is included in one of the headers (even standard headers) that you have included. The standard does not forbid standard headers to include other standard headers

*one of the headers you have included has the declaration of that funciton. For example, <algorithm> could have int tolower(int); somewhere in its code.
You cannot forbid this behavior. What you can do is learn where the function has to be defined/declared and never rely on inclusion of that header by other headers. You know where tolower is declared, so do include <cctype> every time you use this function.


Q: WPF control similar to ObjectListView I'm writing an application using WPF, and I need to make something that looks like this (see image):

What control should I use for this?

A: If you don’t need the groupings (the “Hire as chef” and “Seek dinner invitation” headings), then DataGrid should get you close. You can bind its ItemsSource to your collection of items, and define custom columns bound to your items’ properties.
For example, you can use a DataGridTextColumn for “Occupation”, DataGridCheckBoxColumn for “Tells Jokes?”, and DataGridTemplateColumn for more complex properties which require a custom DataTemplate to visualize, such as the main “Person” column or “Cooking skill”.
Edi: It appears that the DataGrid does support grouping as well.

A: You should go for ListView
http://msdn.microsoft.com/en-us/library/ms754027(v=vs.90).aspx


Q: React Hook "React.useEffect" is called in function "selectmenu" which is neither a React function component or a custom React Hook function Problem: React Hook "React.useEffect" is called in function "selectmenu" which is neither a React function component or a custom React Hook function.
Target: I want to Mount Component('component DidMount/WillUnmount) (using useEffect()) only when I click on a button, rather than, mounting while the file (or whole Component) is being loaded.

Actual Goal: I want to select(or highlight) a file (custom ) on click. But when the user clicks outside the dimensions of the file (), then the selected file should get deselected (remove highlight).
export default function Academics() {
  let [ ismenuselected, setmenuselection] = useState(0)

  const selectmenu = () => {

    console.log("Menu to Select")

    React.useEffect(() => {
      console.log('Component DidMount/WillUnmount')

      return () => {
         console.log('Component Unmounted')
      }
    }, [isfolderselected]);
  }

  return (

  )
}

Note:

*

*I've tried with the UPPER case of SelectFolder #56462812. Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

*I want to try something like this. But with a click of a button (useEffect() should invoke onClick event).

A: I think I got what you're trying to accomplish. First, you can't define a hook inside a function. What you can do is trigger the effect callback after at least one of its dependencies change.
useEffect(() => {
  // run code whenever deps change
}, [deps])

Though for this particular problem (from what I understood from your description), I'd go something like this:
export default function Academics() {
  let [currentOption, setCurrentOption] = useState()

  function handleSelectOption(i) {
    return () => setCurrentOption(i)
  }

  function clearSelectedOption() {
    return setCurrentOption()
  }

  return (options.map((option, i) =>
    <button
      onClick={handleSelectOption(i)}
      className={i === currentOption ? 'option option--highlight' : 'option'}
      onBlur={clearSelectedOption}
    ></button>
  ))
}


Q: Remove UIBarButtonItem from master view controller when detail view controller is visible I am converting my view controllers into a split view controller with a Universal Storyboard to show two views on screen at the same time, which will only appear on iPad - only one will be visible on iPhone. I have a situation where a UIBarButtonItem is only relevant when only one view controllers is on screen. I want this button removed or hidden when both view controllers in the split view controller are visible.
I cannot use Size Classes to do this, since the button I want removed is in the master view controller (actually I have button in both the master and detail that should be removed), which won't have a size class of Regular w Regular h. Plus Interface Builder doesn't provide an "Installed" option for UIBarButtonItems, and I cannot check size classes in code because the app will also run on iOS 7.
How can I remove/hide a UIBarButtonItem when both the master and detail view controller are on screen? Or I could not add this button in IB, then add it in code when deemed appropriate, but how would I know if both view controllers will be on screen?

A: Here's a nice solution that works great for iOS 8 and iOS 7 on iPhone and iPad. You simply detect if there is a split view controller and if so, check if it's collapsed or not. If it's collapsed you know only one view controller is on screen. Knowing that info you can do anything you need to.
//remove right bar button item if more than one view controller is on screen
if (self.splitViewController) {
    if ([UISplitViewController instancesRespondToSelector:@selector(isCollapsed)]) {
        if (!self.splitViewController.collapsed) {
            self.navigationController.navigationBar.topItem.rightBarButtonItem = nil;
        }
    } else {
        self.navigationController.navigationBar.topItem.rightBarButtonItem = nil;
    }
}


Q: Is it possible to define a scoped callback function in a C struct? The C struct AvCodecContext in libav (ffmpeg) has a callback function called get_format. I have a class where each instance has its own AvCodecContext instance, so each one will have an specific callback.
Is it possible to create different callbacks for each instance?
Here's what the callback should look like:
    enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts)
    {
        const enum AVPixelFormat *p;

        for (p = pix_fmts; *p != -1; p++) {
            if (*p == hw_pix_fmt)
                return *p;
        }

        fprintf(stderr, "Failed to get HW surface format.\n");
        return AV_PIX_FMT_NONE;
    }

each callback should have a different AVPixelFormat hw_pix_fmt.
If the project was C++ only, I could use lambda functions, but it's not.
Is there a way?


Q: How to print value of a Variable using its memory address? Suppose 0xfe2200 is the memory address of a variable var2 and I want to display the value stored in it, E.g
cout<< "Value stored in the given address is :  " << 0xfe2200 << "    ";

I tried following but all in vain
cout << "Value is :  " << *0xfee2200 << " ;
cout << "Value is :  " << &0xfee200 << "  ;

A: Assuming the address points to int, you may do:
cout << "Value is :  " << *reinterpret_cast<int*>(0xfee2200);

as literal 0xfee2200 is an interger type whereas you expected a pointer.

A: You have to decide as what type of data you want to interpret the memory content and cast it accordingly:
const char* tmp = "foofoo"; // Valid ptr for this example
const void* address = tmp; // Set to your address

const int* i = reinterpret_cast<const int*>(address);
const unsigned short* us = reinterpret_cast<const unsigned short*>(address);
const char* c = reinterpret_cast<const char*>(address);

std::cout << "i: " << (*i)
          << "\nus: " << (*us)
          << "\nc: " << (*c);

Output:

i: 1718579046
  us: 28518
  c: f


Q: Publish applet with maker webhook I want to publish my applet with a maker webhook to my raspberry pi. For some reason it doesn't allow me to publish the app when I use a maker webhook in it.I'm not sure why it doesn't allow me or if it's even possible at all.
There isn't any error in the applet either as it works perfectly fine in private mode. I also have seen some applets by other users that use the maker webhooks in their applet. So I think it must be possible.
If somebody could answer this question who has published an applet before with webhooks or what I could be doing wrong. Thanks in advance !


Q: I am getting error as unrecognized rule in this lex program %{
#include<stdio.h>
int vowel=0;
%}

%%

[aeiouAEIOU]
{
vowel++;
}

%%

int main()
{
  char str[200];
  gets(str);
  yylex();
  printf("Vowels:",vowel);
}

A: If that is the way you wrote the program, then the error is correct. In Flex, the action for a rule must start on the same line as the pattern.
From the flex manual:

5.2 Format of the Rules Section
The rules section of the flex input contains a series of rules of the form:
 pattern   action

where the pattern must be unindented and the action must begin on the same line.

As written, you have supplied { as a pattern. That's not a valid pattern, and so flex complains.