问:
GNU linker: errors if pointer in header file is declared NULL and/or extern
I am testing some patches (C language) for BOINC client (C++ language), and during compilation I got a GNU linker error about GDBusProxy* proxy = NULL; line in file linux/user_idle_time_detection.h (complete file hereunder). So I started doing some attempts to modify the affected line, but I got two different errors (case 1 and 2 hereunder), and I really cannot understand why the linker does not like:

the extern statement

the pointer initialized at NULL;

Thank you

CASE 1

```<code>extern GDBusProxy* proxy;
</code>```

returns error

```<code>/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `create_proxy':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:5: undefined reference to `proxy'
/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `get_user_idle_time':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:21: undefined reference to `proxy'
collect2: error: ld returned 1 exit status
</code>```

CASE 2

Both

```<code>extern GDBusProxy* proxy = NULL;
</code>```

and

```<code>GDBusProxy* proxy = NULL;
</code>```

return error

```<code>/usr/bin/ld: boinc_client-hostinfo_unix.o:/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.h:7: multiple definition of `proxy'; boinc_client-user_idle_time_detection.o:/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.h:7: first defined here
</code>```

CASE 3

The following works good instead

```<code>GDBusProxy* proxy;
</code>```

SOURCE FILES

linux/user_idle_time_detection.h

```<code>#ifndef USER_IDLE_TIME_DETECTION_H
#define USER_IDLE_TIME_DETECTION_H
#include <gio/gio.h>
#include "gnome/gnome_dbus_interface.h"

GDBusProxy* proxy = NULL;
GDBusProxy* create_proxy();
double get_user_idle_time();
#endif /* USER_IDLE_TIME_DETECTION_H */
</code>```

linux/user_idle_time_detection.c

```<code>#include <gio/gio.h>
#include "user_idle_time_detection.h"
GDBusProxy* create_proxy()
{
    proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                           G_DBUS_PROXY_FLAGS_NONE,
                                           NULL,
                                           GNOME_DBUS_SERVICE,
                                           GNOME_DBUS_PATH_SETTINGS,
                                           GNOME_DBUS_INTERFACE_SETTINGS,
                                           NULL, NULL);
    return proxy;
}

double get_user_idle_time()
{
    guint64 user_idle_time;
    double user_idle_time_double;
    GError* error = NULL;
    GVariant* ret = NULL;
    proxy = create_proxy();

    ret = g_dbus_proxy_call_sync(proxy,
                                  GNOME_DBUS_METHOD_SETTINGS,
                                  NULL,
                                  G_DBUS_CALL_FLAGS_NONE, -1,
                                  NULL, &error);
    if (!ret) {
        g_dbus_error_strip_remote_error (error);
        g_print ("GetIdletime failed: %s\n", error->message);
        g_error_free (error);
        return;
    }

    g_variant_get(ret, "(t)", &user_idle_time);
    user_idle_time_double = (double)user_idle_time;
    g_variant_unref (ret);
    return user_idle_time_double;
}
</code>```

linux/gnome/gnome_dbus_interface.h

```<code>#ifndef GNOME_DBUS_INTERFACE_H
#define GNOME_DBUS_INTERFACE_H

#define GNOME_DBUS_SERVICE "org.gnome.Mutter.IdleMonitor"
#define GNOME_DBUS_PATH_SETTINGS "/org/gnome/Mutter/IdleMonitor/Core"
#define GNOME_DBUS_INTERFACE_SETTINGS "org.gnome.Mutter.IdleMonitor"
#define GNOME_DBUS_METHOD_SETTINGS "GetIdletime"
#endif /* GNOME_DBUS_INTERFACE_H */
</code>```

hostinfo_unix.cpp

```<code>#include "linux/user_idle_time_detection.h"
CUT
bool HOST_INFO::users_idle(bool check_all_logins, double idle_time_to_run) {
    double user_idle_time;
    double user_pref_idle_time_in_ms;
    //user_idle_time = get_user_idle_time();
    user_pref_idle_time_in_ms = (idle_time_to_run * 60000);
CUT
</code>```

Makefile.am

```<code>/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `create_proxy':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:5: undefined reference to `proxy'
/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `get_user_idle_time':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:21: undefined reference to `proxy'
collect2: error: ld returned 1 exit status
</code>```0

Makefile.curl.am

```<code>/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `create_proxy':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:5: undefined reference to `proxy'
/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `get_user_idle_time':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:21: undefined reference to `proxy'
collect2: error: ld returned 1 exit status
</code>```1

configure.ac
Cannot insert it here due Stackoverflow characters limit.

答:
You should be getting a warning:

```<code>// This is wrong...
extern GDBusProxy* proxy = NULL;
</code>```

```
warning: ‘proxy’ initialized and declared ‘extern’
 extern GDBusProxy* proxy = NULL;
                    ^~~~~
```

The extern storage class specifier basically means "this is defined somewhere else", but the = NULL is not really somewhere else.

Just like functions, with variables you should:

Declare them in the header file (compiled many times):

```<code>extern GDBusProxy *proxy;
</code>```

This is a declaration and you can have as many declarations of a single object as you like (as long as they are all compatible).

Define them in the C file (compiled once):

```<code>GDBusProxy *proxy = NULL;
</code>```

This is a definition and you can only have one definition in your entire project. So it cannot appear in a header file, unless that header file is only included by one C file.

This not the only way to do it. You can use the following declaration everywhere:

```<code>GDBusProxy *proxy;
</code>```

This is a special case, it counts as a definition but you are allowed to have more than one in your program.

Note that = NULL is redundant. Global variables are zero-initialized by default.

Body:
I am testing some patches (C language) for BOINC client (C++ language), and during compilation I got a GNU linker error about GDBusProxy* proxy = NULL; line in file linux/user_idle_time_detection.h (complete file hereunder). So I started doing some attempts to modify the affected line, but I got two different errors (case 1 and 2 hereunder), and I really cannot understand why the linker does not like:

the extern statement

the pointer initialized at NULL;

Thank you

CASE 1

extern GDBusProxy* proxy;

returns error

/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `create_proxy':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:5: undefined reference to `proxy'
/usr/bin/ld: boinc_client-user_idle_time_detection.o: in function `get_user_idle_time':
/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.c:21: undefined reference to `proxy'
collect2: error: ld returned 1 exit status

CASE 2

Both

extern GDBusProxy* proxy = NULL;

and

GDBusProxy* proxy = NULL;

return error

/usr/bin/ld: boinc_client-hostinfo_unix.o:/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.h:7: multiple definition of `proxy'; boinc_client-user_idle_time_detection.o:/builddir/build/BUILD/boinc-client_release-7.14-7.14.2/client/linux/user_idle_time_detection.h:7: first defined here

CASE 3

The following works good instead

GDBusProxy* proxy;

SOURCE FILES

linux/user_idle_time_detection.h

#ifndef USER_IDLE_TIME_DETECTION_H
#define USER_IDLE_TIME_DETECTION_H
#include <gio/gio.h>
#include "gnome/gnome_dbus_interface.h"

GDBusProxy* proxy = NULL;
GDBusProxy* create_proxy();
double get_user_idle_time();
#endif /* USER_IDLE_TIME_DETECTION_H */

linux/user_idle_time_detection.c

#include <gio/gio.h>
#include "user_idle_time_detection.h"
GDBusProxy* create_proxy()
{
    proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                           G_DBUS_PROXY_FLAGS_NONE,
                                           NULL,
                                           GNOME_DBUS_SERVICE,
                                           GNOME_DBUS_PATH_SETTINGS,
                                           GNOME_DBUS_INTERFACE_SETTINGS,
                                           NULL, NULL);
    return proxy;
}

double get_user_idle_time()
{
    guint64 user_idle_time;
    double user_idle_time_double;
    GError* error = NULL;
    GVariant* ret = NULL;
    proxy = create_proxy();

    ret = g_dbus_proxy_call_sync(proxy,
                                  GNOME_DBUS_METHOD_SETTINGS,
                                  NULL,
                                  G_DBUS_CALL_FLAGS_NONE, -1,
                                  NULL, &error);
    if (!ret) {
        g_dbus_error_strip_remote_error (error);
        g_print ("GetIdletime failed: %s\n", error->message);
        g_error_free (error);
        return;
    }

    g_variant_get(ret, "(t)", &user_idle_time);
    user_idle_time_double = (double)user_idle_time;
    g_variant_unref (ret);
    return user_idle_time_double;
}

linux/gnome/gnome_dbus_interface.h

#ifndef GNOME_DBUS_INTERFACE_H
#define GNOME_DBUS_INTERFACE_H

#define GNOME_DBUS_SERVICE "org.gnome.Mutter.IdleMonitor"
#define GNOME_DBUS_PATH_SETTINGS "/org/gnome/Mutter/IdleMonitor/Core"
#define GNOME_DBUS_INTERFACE_SETTINGS "org.gnome.Mutter.IdleMonitor"
#define GNOME_DBUS_METHOD_SETTINGS "GetIdletime"
#endif /* GNOME_DBUS_INTERFACE_H */

hostinfo_unix.cpp

#include "linux/user_idle_time_detection.h"
CUT
bool HOST_INFO::users_idle(bool check_all_logins, double idle_time_to_run) {
    double user_idle_time;
    double user_pref_idle_time_in_ms;
    //user_idle_time = get_user_idle_time();
    user_pref_idle_time_in_ms = (idle_time_to_run * 60000);
CUT

Makefile.am

## -*- mode: makefile; tab-width: 4 -*-
## $Id$

include $(top_srcdir)/Makefile.incl

if ENABLE_CLIENT_RELEASE
  AM_LDFLAGS += -static-libtool-libs
## for an entirely statically linked library, you may want to try
## -all-static instead.  There's a good chance it won't work properly,
## so we'll use the safer "-static-libtool-libs" by default.
else
if DYNAMIC_CLIENT
## if libtool starts to need flags for dynamic linking, add them here
else
  AM_LDFLAGS += -static
endif
endif ## ENABLE_CLIENT_RELEASE

LIBS += $(CLIENTLIBS)

if OS_DARWIN
   LIBS += -framework IOKit -framework Foundation -framework ScreenSaver -framework Cocoa -framework CoreServices
endif

bin_PROGRAMS = boinc_client boinccmd
if !OS_WIN32
bin_PROGRAMS += switcher
endif

boinccmd_SOURCES = boinc_cmd.cpp
boinccmd_DEPENDENCIES = $(LIBBOINC)
boinccmd_CPPFLAGS = $(AM_CPPFLAGS)
boinccmd_LDFLAGS = $(AM_LDFLAGS) -L$(top_srcdir)/lib
boinccmd_LDADD = $(LIBBOINC) $(BOINC_EXTRA_LIBS) $(PTHREAD_LIBS)

boinc_client_SOURCES = \
    acct_mgr.cpp \
    acct_setup.cpp \
    app.cpp \
    app_config.cpp \
    app_control.cpp \
    app_start.cpp \
    async_file.cpp \
    check_state.cpp \
    client_msgs.cpp \
    client_state.cpp \
    client_types.cpp \
    coproc_sched.cpp \
    cpu_sched.cpp \
    cs_account.cpp \
    cs_apps.cpp \
    cs_benchmark.cpp \
    cs_cmdline.cpp \
    cs_files.cpp \
    cs_notice.cpp \
    cs_platforms.cpp \
    cs_prefs.cpp \
    cs_proxy.cpp \
    cs_scheduler.cpp \
    cs_statefile.cpp \
    cs_trickle.cpp \
    current_version.cpp \
    dhrystone.cpp \
    dhrystone2.cpp \
    file_names.cpp \
    file_xfer.cpp \
    gpu_amd.cpp \
    gpu_detect.cpp \
    gpu_intel.cpp \
    gpu_nvidia.cpp \
    gpu_opencl.cpp \
    gui_http.cpp \
    gui_rpc_server.cpp \
    gui_rpc_server_ops.cpp \
    hostinfo_linux.cpp \
    hostinfo_network.cpp \
    http_curl.cpp \
    log_flags.cpp \
    mac_address.cpp \
    main.cpp \
    net_stats.cpp \
    pers_file_xfer.cpp \
    project.cpp \
    project_list.cpp \
    result.cpp \
    rr_sim.cpp \
    sandbox.cpp \
    scheduler_op.cpp \
    thread.cpp \
    time_stats.cpp \
    whetstone.cpp \
    work_fetch.cpp \
    linux/user_idle_time_detection.c

boinc_client_DEPENDENCIES = $(LIBBOINC)
boinc_client_CPPFLAGS = $(AM_CPPFLAGS) $(GIO_CFLAGS) $(GLIB_CFLAGS)
boinc_client_CXXFLAGS = $(AM_CXXFLAGS) $(SSL_CXXFLAGS)
boinc_client_LDFLAGS = $(AM_LDFLAGS) $(SSL_LDFLAGS) $(GIO_LIBS) $(GLIB_LIBS)  -L$(top_srcdir)/lib
if OS_WIN32
boinc_client_CXXFLAGS += -I$(top_srcdir)/coprocs/NVIDIA/include
boinc_client_SOURCES += hostinfo_win.cpp \
    hostinfo_wsl.cpp \
    sysmon_win.cpp \
    win/boinc_cli.rc \
    win/res/boinc.ico
else
if OS_DARWIN
boinc_client_LDFLAGS += -Wl,-flat_namespace,-undefined,dynamic_lookup
else
boinc_client_SOURCES += hostinfo_unix.cpp
endif
endif
boinc_client_LDADD = $(LIBBOINC) $(LIBBOINC_CRYPT) $(BOINC_EXTRA_LIBS) $(PTHREAD_LIBS)

boinc_clientdir = $(bindir)

if OS_ARM_LINUX
boinc_client_LDADD += libwhetneon.a libwhetvfp.a
noinst_LIBRARIES = libwhetneon.a libwhetvfp.a
libwhetneon_a_SOURCES = whetstone.cpp
libwhetneon_a_CXXFLAGS = $(boinc_client_CXXFLAGS) -DANDROID_NEON -mfloat-abi=softfp -mfpu=neon

libwhetvfp_a_SOURCES = whetstone.cpp
libwhetvfp_a_CXXFLAGS = $(boinc_client_CXXFLAGS) -DANDROID_VFP -mfloat-abi=softfp -mfpu=vfp
endif

switcher_SOURCES = switcher.cpp
switcher_LDFLAGS = $(AM_LDFLAGS) -L../lib
switcher_LDADD = $(LIBBOINC)

## since we are using libtool we need some magic to get boinc and boinc_client
## to both be installed properly.  The next two rules do that...
all-local: boinc$(EXEEXT)

boinc$(EXEEXT): boinc_client$(EXEEXT)
    rm -f boinc$(EXEEXT) .libs/boinc$(EXEEXT)
    $(LN) boinc_client$(EXEEXT) boinc$(EXEEXT)
    if test -f .libs/boinc_client$(EXEEXT) ; then $(LN) .libs/boinc_client$(EXEEXT) .libs/boinc$(EXEEXT) ; fi

install-exec-hook:
    rm -f $(DESTDIR)$(exec_prefix)/bin/boinc$(EXEEXT)
    $(LN) $(DESTDIR)$(exec_prefix)/bin/boinc_client$(EXEEXT) $(DESTDIR)$(exec_prefix)/bin/boinc$(EXEEXT)

## these source files need to be specified because no rule uses them.

EXTRA_DIST = *.h \
    mac \
    translation \
    win

Makefile.curl.am

## -*- mode: make; tab-width: 4 -*-
## $Id$

include $(top_srcdir)/Makefile.incl

# (for a while we used "-static -static-libgcc" on linux, but this is obsolete
# now)
#STATIC_FLAGS=@STATIC_FLAGS@

client-bin: @CLIENT_BIN_FILENAME@

LIBS += @CLIENTLIBS@

bin_PROGRAMS = boinc_client

EXTRA_PROGRAMS = cpu_benchmark

boinc_client_SOURCES = \
    acct_mgr.cpp \
    acct_setup.cpp \
    app.cpp \
    app_control.cpp \
    app_graphics.cpp \
    app_start.cpp \
    check_state.cpp \
    client_msgs.cpp \
    client_state.cpp \
    client_types.cpp \
    cs_account.cpp \
    cs_apps.cpp \
    cs_benchmark.cpp \
    cs_cmdline.cpp \
    cs_data.cpp \
    cs_files.cpp \
    cs_prefs.cpp \
    cs_scheduler.cpp \
    cs_statefile.cpp \
    cs_trickle.cpp \
    dhrystone.cpp \
    dhrystone2.cpp \
    file_names.cpp \
    file_xfer.cpp \
    gui_http.cpp \
    gui_rpc_server.cpp \
    gui_rpc_server_ops.cpp \
    hostinfo_linux.cpp \
    hostinfo_network.cpp \
    hostinfo_unix.cpp \
    http_curl.cpp \
    log_flags.cpp \
    main.cpp \
    net_stats.cpp \
    net_xfer_curl.cpp \
    pers_file_xfer.cpp \
    scheduler_op.cpp \
    time_stats.cpp \
    whetstone.cpp \
    linux/user_idle_time_detection.c

boinc_client_DEPENDENCIES = $(LIBRSA)
boinc_client_CPPFLAGS = -D_USE_CURL -I../../curl-7.14.0/include -I $(srcdir)/win $(AM_CPPFLAGS) -O3
boinc_client_LDFLAGS = -static-libgcc
boinc_client_LDADD = -L/usr/local/ssl/lib -lssl -L../../curl-7.14.0/lib -lcurl -L../lib -lboinc $(RSA_LIBS) $(PTHREAD_LIBS)
#boinc_client_LDFLAGS = $(STATIC_FLAGS)

# the following don't do anything
cpu_benchmark_SOURCES = whetstone.cpp dhrystone.cpp
cpu_benchmark_CFLAGS = -O3 $(AM_CFLAGS)

all-local: client-bin

# make a hard link to the client name.
@CLIENT_BIN_FILENAME@: boinc_client
    rm -f $@
    @LN@ $? $@
    @STRIP@ $@

## these source files need to be specified because no rule uses them.

EXTRA_DIST = *.h \
    mac \
    translation \
    win

clean-local:
    rm -f @CLIENT_BIN_FILENAME@

configure.ac
Cannot insert it here due Stackoverflow characters limit.

Body:
You should be getting a warning:

// This is wrong...
extern GDBusProxy* proxy = NULL;

warning: ‘proxy’ initialized and declared ‘extern’
 extern GDBusProxy* proxy = NULL;
                    ^~~~~

The extern storage class specifier basically means "this is defined somewhere else", but the = NULL is not really somewhere else.

Just like functions, with variables you should:

Declare them in the header file (compiled many times):

extern GDBusProxy *proxy;

This is a declaration and you can have as many declarations of a single object as you like (as long as they are all compatible).

Define them in the C file (compiled once):

GDBusProxy *proxy = NULL;

This is a definition and you can only have one definition in your entire project. So it cannot appear in a header file, unless that header file is only included by one C file.

This not the only way to do it. You can use the following declaration everywhere:

GDBusProxy *proxy;

This is a special case, it counts as a definition but you are allowed to have more than one in your program.

Note that = NULL is redundant. Global variables are zero-initialized by default.


来源: stackexchange

问:
How to rename files useing Terminal
Can anyone recommend a good solution to recursively remove unwanted letters  in file names
remove

```<code>.720p.BluRay.x264-[YTS.AM]
</code>```

For example:

```<code> Yellow Submarine (1968) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Yellow.Submarine.1968.720p.BluRay.x264-[YTS.AM].mp4
├── You Might Be The Killer (2018) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── You.Might.Be.The.Killer.2018.720p.BluRay.x264-[YTS.AM].mp4
├── Your Name (2016) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Your.Name.2016.720p.BluRay.x264-[YTS.AM].mp4

</code>```

becomes:

```<code> Yellow Submarine (1968) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Yellow.Submarine.1968.mp4
├── You Might Be The Killer (2018) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── You.Might.Be.The.Killer.2018.mp4
├── Your Name (2016) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Your.Name.2016.mp4

</code>```

答:
Since the string being removed appears to be the same for each file then you can use find and rename to solve this:

```<code>find . -type f -exec rename 's/\.720p\.BluRay\.x264\-\[YTS\.AM\]//' '{}' \;
</code>```

Run that in whatever the base directory is that holds these folders and it should clean the files up.

To test first you can use the -n flag on that rename command to see what it will do if you allow it to act (without the -n flag):

```<code>find . -type f -exec rename -n 's/\.720p\.BluRay\.x264\-\[YTS\.AM\]//' '{}' \;
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to rename files useing Terminal

Body:
Can anyone recommend a good solution to recursively remove unwanted letters  in file names
remove

.720p.BluRay.x264-[YTS.AM]

For example:

 Yellow Submarine (1968) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Yellow.Submarine.1968.720p.BluRay.x264-[YTS.AM].mp4
├── You Might Be The Killer (2018) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── You.Might.Be.The.Killer.2018.720p.BluRay.x264-[YTS.AM].mp4
├── Your Name (2016) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Your.Name.2016.720p.BluRay.x264-[YTS.AM].mp4

becomes:

 Yellow Submarine (1968) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Yellow.Submarine.1968.mp4
├── You Might Be The Killer (2018) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── You.Might.Be.The.Killer.2018.mp4
├── Your Name (2016) [BluRay] [720p] [YTS.AM]
│   ├── www.YTS.AM.jpg
│   └── Your.Name.2016.mp4

Body:
Since the string being removed appears to be the same for each file then you can use find and rename to solve this:

find . -type f -exec rename 's/\.720p\.BluRay\.x264\-\[YTS\.AM\]//' '{}' \;

Run that in whatever the base directory is that holds these folders and it should clean the files up.

To test first you can use the -n flag on that rename command to see what it will do if you allow it to act (without the -n flag):

find . -type f -exec rename -n 's/\.720p\.BluRay\.x264\-\[YTS\.AM\]//' '{}' \;


答:
In the case 1 you missed to define the variable in a source file, so its definition is missing

In the other cases having

```<code>GDBusProxy* proxy = NULL;
</code>```

in a header file does not declare the variable but define it, so including the header file in several sources define it several times.

replace it by

```<code> extern GDBusProxy* proxy;
</code>```

and define it in one of the source files

Title: GNU linker: errors if pointer in header file is declared NULL and/or extern

Body:
In the case 1 you missed to define the variable in a source file, so its definition is missing

In the other cases having

GDBusProxy* proxy = NULL;

in a header file does not declare the variable but define it, so including the header file in several sources define it several times.

replace it by

 extern GDBusProxy* proxy;

and define it in one of the source files


问:
The second thread in my program is not being executed
I am a beginner in python. I learnt and applied Multi-threading in program but only one thread is being executed.

The program is about calling function which returns the distance value using Ultrasonic sensor and saving the frames of video from webcam with time stamps. I have tried the code without threading and it works fine but the number of frames are reduced due to time taken in distance measurement so I thought to execute them in parallel using Multi-threading in python.

```<code>import threading
import thread
video = cv2.VideoCapture(0)
class u1Thread(threading.Thread):
      def run(self):
         TRIG1=23                            #Associate pin 23 to TRIG
         ECHO1=24                            #Associate pin 24 to ECHO
         GPIO.setup(TRIG1,GPIO.OUT)          #Set pin as GPIO out
         GPIO.setup(ECHO1,GPIO.IN)           #Set pin as GPIO in
         U_1=[]
         start=[]
         while True:
            d=ultrasonic(TRIG1,ECHO1)
            U_1.append(d)
            start.append(str(time.time()))
            x=pd.DataFrame({'1st':U_1,  'Time Stamp':start})
            export_csv = x.to_csv (r'/home/pi/q.csv', index = None,
            header=True)

 class vfThread(threading.Thread):
       def run(self):
       ret, frame=video.read()
       if ret == True:
          cv2.imwrite(str(time.time()) + '.jpg',frame)

U1=u1Thread()
VF=vfThread()

U1.run()
VF.run()
</code>```

I was expecting both threads to be executed but only first is being executed.

答:
Use U1.start() and VF.start() instead of run.

run executes the code without starting a new thread, thus, the program get stuck in the while loop.

start starts a thread and execute run inside it. Both threads runs at the same time.

Body:
I am a beginner in python. I learnt and applied Multi-threading in program but only one thread is being executed.

The program is about calling function which returns the distance value using Ultrasonic sensor and saving the frames of video from webcam with time stamps. I have tried the code without threading and it works fine but the number of frames are reduced due to time taken in distance measurement so I thought to execute them in parallel using Multi-threading in python.

import threading
import thread
video = cv2.VideoCapture(0)
class u1Thread(threading.Thread):
      def run(self):
         TRIG1=23                            #Associate pin 23 to TRIG
         ECHO1=24                            #Associate pin 24 to ECHO
         GPIO.setup(TRIG1,GPIO.OUT)          #Set pin as GPIO out
         GPIO.setup(ECHO1,GPIO.IN)           #Set pin as GPIO in
         U_1=[]
         start=[]
         while True:
            d=ultrasonic(TRIG1,ECHO1)
            U_1.append(d)
            start.append(str(time.time()))
            x=pd.DataFrame({'1st':U_1,  'Time Stamp':start})
            export_csv = x.to_csv (r'/home/pi/q.csv', index = None,
            header=True)

 class vfThread(threading.Thread):
       def run(self):
       ret, frame=video.read()
       if ret == True:
          cv2.imwrite(str(time.time()) + '.jpg',frame)

U1=u1Thread()
VF=vfThread()

U1.run()
VF.run()

I was expecting both threads to be executed but only first is being executed.


问:
Filter keys of map1 based on filtering criteria in map 2 and filtering info for each item in map 3 using java8 streams
I have 3 maps and they are setup as follows:-

```<code>  //Map1
  Map<CatalogCd, Set<ItemUID>> availableItems
  //Map2
  Map<CatalogCd, FilteringPreferences> filteringPrefs
  //Map3
  Map<ItemUID, ItemInformation> itemDetailInformation
</code>```

What I am trying to do is ,

go through the availableItems, and then see if the ItemInformation for a given ItemUID, matches with the preferences ( by basically doing some kind of predicate check).

As you can see the first two maps have the same keys, the filteringPrefs for the same key apply to the entire set of that catalogcd key, any object that does not qualify as per the predicates setup in Preferences , should be removed from the resulting set of itemuids.

I am interested in doing the java 8 stream, map, filter way of making this look better rather than traditional for loop over one map and then manually removing or adding items to a new result map.

This is the traditional for-loop non-java-8 style of code I got.

```<code>public Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,  Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation)
{
    Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap = new HashMap<>();
    for(Map.Entry<CatalogCd,FilteringPreferences> catalogCdEntry : filteringPrefs.entrySet()){
    CatalogCd catalogCdInRequest = catalogCdEntry.getKey();
    EnumSet<PrefA> prefA = catalogCdEntry.getValue().getSupportedPrefAs();

    //get set of items for this catalogcd, loop over each itemuid, check from itemDetailInformation map
    //to see if that itemuid's enumset has intersection with the enumset in request's preference.
    Set<ItemUID> itemsForThisCatalogCd = availableItems.get(catalogCdInRequest);
    for(ItemUID item:itemsForThisCatalogCd){
        EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
        enumSetFromItemInfo.retainAll(prefA);
        if(!enumSetFromItemInfo.isEmpty()){
            if(resultingFilteredItemsMap.get(catalogCdInRequest)!=null){
                Set<ItemUID> items = resultingFilteredItemsMap.get(catalogCdInRequest);
                items.add(item);
                resultingFilteredItemsMap.put(catalogCdInRequest, items);
            }else{
                resultingFilteredItemsMap.put(catalogCdInRequest, Sets.newHashSet(item));
              }
           }
        }
    }
   return resultingFilteredItemsMap;
}
</code>```

What I have tried so far is this:-

```<code>availableItems
    .entrySet()
    .stream()
    .filter(x- >predicateFilterFactory.createPredicateFilter(filteringPref.get(x.getKey())))
    .collect(Collectors.toMap(x->x.getKey(),x->x.getValue));
</code>```

but this says Predicate cannot be converted to boolean Also, I dont know how to rope-in the actual content map into this.
Any help would be great.
Thanks

答:
Here you go:</p>

```<code>public Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,
        Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation) {
    Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap = new HashMap<>();
    filteringPrefs.forEach((key, value) -> giveSuitableName(availableItems, itemDetailInformation,
            resultingFilteredItemsMap, key, value));
    return resultingFilteredItemsMap;
}

private void giveSuitableName(Map<CatalogCd, Set<ItemUID>> availableItems,
        Map<ItemUID, ItemInformation> itemDetailInformation, Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap,
        CatalogCd catalogCdInRequest, FilteringPreferences filteringPreferences) {
    EnumSet<PrefA> prefA = filteringPreferences.getSupportedPrefAs();

    // get set of items for this catalogcd, loop over each itemuid, check from
    // itemDetailInformation map
    // to see if that itemuid's enumset has intersection with the enumset in
    // request's preference.
    availableItems.get(catalogCdInRequest).stream()
            .map(ai -> collectAndAddItems(itemDetailInformation, resultingFilteredItemsMap, catalogCdInRequest,
                    prefA, ai))
            .filter(s -> !s.isEmpty()).forEach(fs -> resultingFilteredItemsMap.put(catalogCdInRequest, fs));
}

private Set<ItemUID> collectAndAddItems(Map<ItemUID, ItemInformation> itemDetailInformation,
        Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap, CatalogCd catalogCdInRequest, EnumSet<PrefA> prefA,
        ItemUID item) {
    EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
    enumSetFromItemInfo.retainAll(prefA);
    Set<ItemUID> items = new HashSet<>();
    if (!enumSetFromItemInfo.isEmpty()) {
        if (resultingFilteredItemsMap.get(catalogCdInRequest) != null) {
            items = resultingFilteredItemsMap.get(catalogCdInRequest);
            items.add(item);
        } else {
            items = new HashSet<>(Arrays.asList(item));
        }
    }
    return items;
}
</code>```

Body:
I have 3 maps and they are setup as follows:-

  //Map1
  Map<CatalogCd, Set<ItemUID>> availableItems
  //Map2
  Map<CatalogCd, FilteringPreferences> filteringPrefs
  //Map3
  Map<ItemUID, ItemInformation> itemDetailInformation

What I am trying to do is ,

go through the availableItems, and then see if the ItemInformation for a given ItemUID, matches with the preferences ( by basically doing some kind of predicate check).

As you can see the first two maps have the same keys, the filteringPrefs for the same key apply to the entire set of that catalogcd key, any object that does not qualify as per the predicates setup in Preferences , should be removed from the resulting set of itemuids.

I am interested in doing the java 8 stream, map, filter way of making this look better rather than traditional for loop over one map and then manually removing or adding items to a new result map.

This is the traditional for-loop non-java-8 style of code I got.

public Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,  Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation)
{
    Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap = new HashMap<>();
    for(Map.Entry<CatalogCd,FilteringPreferences> catalogCdEntry : filteringPrefs.entrySet()){
    CatalogCd catalogCdInRequest = catalogCdEntry.getKey();
    EnumSet<PrefA> prefA = catalogCdEntry.getValue().getSupportedPrefAs();

    //get set of items for this catalogcd, loop over each itemuid, check from itemDetailInformation map
    //to see if that itemuid's enumset has intersection with the enumset in request's preference.
    Set<ItemUID> itemsForThisCatalogCd = availableItems.get(catalogCdInRequest);
    for(ItemUID item:itemsForThisCatalogCd){
        EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
        enumSetFromItemInfo.retainAll(prefA);
        if(!enumSetFromItemInfo.isEmpty()){
            if(resultingFilteredItemsMap.get(catalogCdInRequest)!=null){
                Set<ItemUID> items = resultingFilteredItemsMap.get(catalogCdInRequest);
                items.add(item);
                resultingFilteredItemsMap.put(catalogCdInRequest, items);
            }else{
                resultingFilteredItemsMap.put(catalogCdInRequest, Sets.newHashSet(item));
              }
           }
        }
    }
   return resultingFilteredItemsMap;
}

What I have tried so far is this:-

availableItems
    .entrySet()
    .stream()
    .filter(x- >predicateFilterFactory.createPredicateFilter(filteringPref.get(x.getKey())))
    .collect(Collectors.toMap(x->x.getKey(),x->x.getValue));

but this says Predicate cannot be converted to boolean Also, I dont know how to rope-in the actual content map into this.
Any help would be great.
Thanks

Body:
Here you go:

public Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,
        Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation) {
    Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap = new HashMap<>();
    filteringPrefs.forEach((key, value) -> giveSuitableName(availableItems, itemDetailInformation,
            resultingFilteredItemsMap, key, value));
    return resultingFilteredItemsMap;
}

private void giveSuitableName(Map<CatalogCd, Set<ItemUID>> availableItems,
        Map<ItemUID, ItemInformation> itemDetailInformation, Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap,
        CatalogCd catalogCdInRequest, FilteringPreferences filteringPreferences) {
    EnumSet<PrefA> prefA = filteringPreferences.getSupportedPrefAs();

    // get set of items for this catalogcd, loop over each itemuid, check from
    // itemDetailInformation map
    // to see if that itemuid's enumset has intersection with the enumset in
    // request's preference.
    availableItems.get(catalogCdInRequest).stream()
            .map(ai -> collectAndAddItems(itemDetailInformation, resultingFilteredItemsMap, catalogCdInRequest,
                    prefA, ai))
            .filter(s -> !s.isEmpty()).forEach(fs -> resultingFilteredItemsMap.put(catalogCdInRequest, fs));
}

private Set<ItemUID> collectAndAddItems(Map<ItemUID, ItemInformation> itemDetailInformation,
        Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap, CatalogCd catalogCdInRequest, EnumSet<PrefA> prefA,
        ItemUID item) {
    EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
    enumSetFromItemInfo.retainAll(prefA);
    Set<ItemUID> items = new HashSet<>();
    if (!enumSetFromItemInfo.isEmpty()) {
        if (resultingFilteredItemsMap.get(catalogCdInRequest) != null) {
            items = resultingFilteredItemsMap.get(catalogCdInRequest);
            items.add(item);
        } else {
            items = new HashSet<>(Arrays.asList(item));
        }
    }
    return items;
}


问:
How to redirect from php function to set,cookie, triggered by ajax?
I'm trying to set a cookie on my web page.
After the cookie's set i would like to redirect him on page instant of doing nothing and wait the user to refresh the page to actualise the cookie.

I am using php jQuery 3.4 to do so.
I tried to refresh the page after the function in JQuery but it don't seems to be triggered.
I tried to use header('Location: /index.php') after the cookie set, but it didn't work either. Guess because the cookie set in the HTTP request or from the header(Content-Type :application/json)

Here is my javascript function

//get value from a search bar
var option = $(".search-text").val();
        //use ajax to sent it to my php file
        jQuery.ajax({
            type: "POST",
            url: 'script_php/cookie.php',
            dataType: 'json',
            data:{functionname: 'cookie', arguments: option},

            success: function (obj, textstatus){
                if( !('error' in obj) ) {
                  yourVariable = obj.result;
              }
              else {
                  console.log(obj.error);
              }
            }
        });
```

<p>Here is the php triggered</p>

<pre class="lang-php prettyprint-override"><code><?php
        //get the infos from the js file
    header('Content-Type: application/json');

    $Result = array();

        //stock them inside an array
    $Result['succes'] = cookie($_POST['arguments']);

    function cookie($name){
        setcookie("user", $name, time() + (86400 * 365.25), "/");
                header('Location: /index.php');
    }

    $Result = array();

?>
</code>```

I would like the cookie to be set and then to return the page index.php

The actual output is the cookie being set but the page to stand still

答:
I'm having some trouble understanding what you're trying to do, but I think I see multiple problems.

In your PHP snippet, you are overwriting $Result with an empty array. Not sure you want to do that.

You define a function cookie($name), but you don't call the function anywhere, so it's not executed..

Your PHP script, if it is being run at all, is not outputting any data to the client, other than the http header.

As noted in the comment above, if you want the browser to go somewhere else, you can do it client-side and in this case I think you have to. So upon success, i.e., in your callback:

```<code>document.location = "/index.php"
</code>```

If you're not already using a debugging tool like the Firefox console, you should. Then you can see what's happening in your xhr requests and responses.

Body:
I'm trying to set a cookie on my web page.
After the cookie's set i would like to redirect him on page instant of doing nothing and wait the user to refresh the page to actualise the cookie.

I am using php jQuery 3.4 to do so.
I tried to refresh the page after the function in JQuery but it don't seems to be triggered.
I tried to use header('Location: /index.php') after the cookie set, but it didn't work either. Guess because the cookie set in the HTTP request or from the header(Content-Type :application/json)

Here is my javascript function

//get value from a search bar
var option = $(".search-text").val();
        //use ajax to sent it to my php file
        jQuery.ajax({
            type: "POST",
            url: 'script_php/cookie.php',
            dataType: 'json',
            data:{functionname: 'cookie', arguments: option},

            success: function (obj, textstatus){
                if( !('error' in obj) ) {
                  yourVariable = obj.result;
              }
              else {
                  console.log(obj.error);
              }
            }
        });

Here is the php triggered

<?php
        //get the infos from the js file
    header('Content-Type: application/json');

    $Result = array();

        //stock them inside an array
    $Result['succes'] = cookie($_POST['arguments']);

    function cookie($name){
        setcookie("user", $name, time() + (86400 * 365.25), "/");
                header('Location: /index.php');
    }

    $Result = array();

?>

I would like the cookie to be set and then to return the page index.php

The actual output is the cookie being set but the page to stand still

Body:
I'm having some trouble understanding what you're trying to do, but I think I see multiple problems.

In your PHP snippet, you are overwriting $Result with an empty array. Not sure you want to do that.

You define a function cookie($name), but you don't call the function anywhere, so it's not executed..

Your PHP script, if it is being run at all, is not outputting any data to the client, other than the http header.

As noted in the comment above, if you want the browser to go somewhere else, you can do it client-side and in this case I think you have to. So upon success, i.e., in your callback:

document.location = "/index.php"

If you're not already using a debugging tool like the Firefox console, you should. Then you can see what's happening in your xhr requests and responses.


问:
React Native: How do I completely remove Instabug?
I recently removed Instabug from my React Native 0.53.3 project, but when I run react-native run-ios I get a build failure:

```<code>ld: framework not found Instabug
clang: error: linker command failed with exit code 1 (use -v to see invocation)

** BUILD FAILED **

The following build commands failed:

    Ld /Users/danale/Library/Developer/Xcode/DerivedData/build/Build/Products/Debug-iphonesimulator/NFIBEngage.app/NFIBEngage normal x86_64
(1 failure)

Installing build/Build/Products/Debug-iphonesimulator/NFIBEngage.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/NFIBEngage.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
</code>```

How can I completely remove Instabug from my project so it's not looking for it on iOS build?

So far I have completely removed it from App.js file, but it's still being referenced in build.gradle, MainActivity.java, MainApplication.java, settings.gradle, project.pbxproj and yarn.lock file. I don't even use yarn by the way.

How do I completely clean this up?

答:
If react-native unlink instabug-reactnative didn't work try removing all react-native link changes manually.

You may refer these pages to remove all references

Instabug rn link checklist

Instabug Documentation

Clean the project once every reference is removed.(Deleting Xcode derived data may be needed sometimes)

Body:
I recently removed Instabug from my React Native 0.53.3 project, but when I run react-native run-ios I get a build failure:

ld: framework not found Instabug
clang: error: linker command failed with exit code 1 (use -v to see invocation)

** BUILD FAILED **

The following build commands failed:

    Ld /Users/danale/Library/Developer/Xcode/DerivedData/build/Build/Products/Debug-iphonesimulator/NFIBEngage.app/NFIBEngage normal x86_64
(1 failure)

Installing build/Build/Products/Debug-iphonesimulator/NFIBEngage.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/NFIBEngage.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

How can I completely remove Instabug from my project so it's not looking for it on iOS build?

So far I have completely removed it from App.js file, but it's still being referenced in build.gradle, MainActivity.java, MainApplication.java, settings.gradle, project.pbxproj and yarn.lock file. I don't even use yarn by the way.

How do I completely clean this up?


问:
Nullable int not working as expected in LINQ (C#)
The following works as expected (LINQ to Entities):

```<code>var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == null select new { t.Title, t.Id }).ToList();
</code>```

However, the following returns nothing:

```<code>int? parent = null;
var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == parent select new { t.Title, t.Id }).ToList();
</code>```

Topic.ParentId is a nullable int. It's easy to work around, but this puzzles me. Can anyone shed any light?

答:
You are definately not the first person to observe this... interesting... behavior.

http://connect.microsoft.com/data/feedback/details/607404/entity-framework-and-linq-to-sql-incorrectly-handling-nullable-variables

In short, it's difficult to handle different ways of expressing null.

ContentLicense: CC BY-SA 3.0

Body:
The following works as expected (LINQ to Entities):

var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == null select new { t.Title, t.Id }).ToList();

However, the following returns nothing:

int? parent = null;
var topics = (from t in ctx.Topics where t.SubjectId == subjectId && t.ParentId == parent select new { t.Title, t.Id }).ToList();

Topic.ParentId is a nullable int. It's easy to work around, but this puzzles me. Can anyone shed any light?


问:
Checkbox required
I have this code for a newsletter block in my site, a specific CMS:

{if $tpl_settings.type == 'responsive_42'}{strip}

    <input placeholder="{$lang.massmailer_newsletter_your_name}" type="text" id="newsletter_name" maxlength="50" />
    <input placeholder="{$lang.massmailer_newsletter_your_e_mail}" type="text" id="newsletter_email" maxlength="100" />

    <input type="checkbox" id="newsletter_privacy" /> Privacy Policy.

    <input class="low" onclick="xajax_subscribe('subscribe', $('#newsletter_name').val(), $('#newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_subscribe}" />

{$lang.massmailer_newsletter_unsubscribe}

    <input placeholder="{$lang.massmailer_newsletter_your_e_mail}" type="text" id="un_newsletter_email" maxlength="50" />
    <input class="low" onclick="xajax_subscribe('unsubscribe', '', $('#un_newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_unsubscribe}" />

{$lang.massmailer_newsletter_subscribe}

{/strip}{else}

  {$lang.massmailer_newsletter_your_name}

<input type="text" id="newsletter_name" maxlength="150" style="width: 80%;" />

  {$lang.massmailer_newsletter_your_e_mail}

<input type="text" id="newsletter_email" maxlength="100" style="width: 80%" />

    <input onclick="xajax_subscribe('subscribe', $('#newsletter_name').val(), $('#newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_subscribe}" />

    {$lang.massmailer_newsletter_unsubscribe}

  {$lang.massmailer_newsletter_your_e_mail}

<input type="text" id="un_newsletter_email" maxlength="150" style="width: 80%" />

    <input onclick="xajax_subscribe('unsubscribe', '', $('#un_newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_unsubscribe}" />

    {$lang.massmailer_newsletter_subscribe}

{/if}

```

I can't enforce the "required" checkbox via JavaScript/Ajax, can you please help me to change the code correctly?

I'm not managing to make it work because the "form" tag is missing like any normal form.

Thanks!

答:
You only need to check the entered value before the ajax request is started:

```<code>function xajax_subscribe(subscribe,name,email) {

    if(email = '') {
        alert('Please enter an E-Mail Address')
    } else {
        // your ajax request
    }

}
</code>```

Be aware that you have to check again when request started respectively the entered values posted to your php file, learn how to check validate email and so on...

Title: Checkbox required

Body:
I have this code for a newsletter block in my site, a specific CMS:

{if $tpl_settings.type == 'responsive_42'}{strip}

    <input placeholder="{$lang.massmailer_newsletter_your_name}" type="text" id="newsletter_name" maxlength="50" />
    <input placeholder="{$lang.massmailer_newsletter_your_e_mail}" type="text" id="newsletter_email" maxlength="100" />

    <input type="checkbox" id="newsletter_privacy" /> Privacy Policy.

    <input class="low" onclick="xajax_subscribe('subscribe', $('#newsletter_name').val(), $('#newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_subscribe}" />

{$lang.massmailer_newsletter_unsubscribe}

    <input placeholder="{$lang.massmailer_newsletter_your_e_mail}" type="text" id="un_newsletter_email" maxlength="50" />
    <input class="low" onclick="xajax_subscribe('unsubscribe', '', $('#un_newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_unsubscribe}" />

{$lang.massmailer_newsletter_subscribe}

{/strip}{else}

  {$lang.massmailer_newsletter_your_name}

<input type="text" id="newsletter_name" maxlength="150" style="width: 80%;" />

  {$lang.massmailer_newsletter_your_e_mail}

<input type="text" id="newsletter_email" maxlength="100" style="width: 80%" />

    <input onclick="xajax_subscribe('subscribe', $('#newsletter_name').val(), $('#newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_subscribe}" />

    {$lang.massmailer_newsletter_unsubscribe}

  {$lang.massmailer_newsletter_your_e_mail}

<input type="text" id="un_newsletter_email" maxlength="150" style="width: 80%" />

    <input onclick="xajax_subscribe('unsubscribe', '', $('#un_newsletter_email').val());$(this).val('{$lang.loading}');" type="button" value="{$lang.massmailer_newsletter_unsubscribe}" />

    {$lang.massmailer_newsletter_subscribe}

{/if}

I can't enforce the "required" checkbox via JavaScript/Ajax, can you please help me to change the code correctly?

I'm not managing to make it work because the "form" tag is missing like any normal form.

Thanks!

Body:
You only need to check the entered value before the ajax request is started:

function xajax_subscribe(subscribe,name,email) {

    if(email = '') {
        alert('Please enter an E-Mail Address')
    } else {
        // your ajax request
    }

}

Be aware that you have to check again when request started respectively the entered values posted to your php file, learn how to check validate email and so on...


问:
Get a subset of items using .WHERE and then REMOVEALL by condition using Lambda Expressions
I have a list of items, these items have a property called vog_code, it is an int, this list have a variety of items with 4 different types of vog_code, 1,10,14,16.

Now, I want to remove the items on that list that doesnt abide to a certain date, but for items with vog_codes equals 14 and 16 the condition will be different.

This is the expression I have now:

```<code>transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => x.vog_code == 14 || x.vog_code == 16 && x.fecha_recepcion >= fechaOriginal);
</code>```

Which is incorrect since it will eliminate all the items with vog_code 14 and 16 and doesnt abide the AND operator.

Is there any way to ask "for these elements that are vog_code 14 and 16 I then, will check if the dates are greater or equal".

I tried with a .Where and then .RemoveAll but that is not possible.

I dont want to use more an auxiliary list unless it is the only way to do it.

答:
If I correctly understand your goal, this should be what you need.

The key difference is the use of () to group the 2 vog_code conditions.

This will remove all items where BOTH of the following are true

vog_code is either 14 or 16

fecha_recepcion >= fechaOriginal

transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => (x.vog_code == 14 || x.vog_code == 16) && x.fecha_recepcion >= fechaOriginal);
```

<h3>Another way</h3>

<p>Another approach to this is to switch your conditions around a bit like this:</p>

<pre class="lang-cs prettyprint-override"><code>transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => x.fecha_recepcion >= fechaOriginal && x.vog_code == 14 || x.vog_code == 16);
</code>```

Body:
I have a list of items, these items have a property called vog_code, it is an int, this list have a variety of items with 4 different types of vog_code, 1,10,14,16.

Now, I want to remove the items on that list that doesnt abide to a certain date, but for items with vog_codes equals 14 and 16 the condition will be different.

This is the expression I have now:

transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => x.vog_code == 14 || x.vog_code == 16 && x.fecha_recepcion >= fechaOriginal);

Which is incorrect since it will eliminate all the items with vog_code 14 and 16 and doesnt abide the AND operator.

Is there any way to ask "for these elements that are vog_code 14 and 16 I then, will check if the dates are greater or equal".

I tried with a .Where and then .RemoveAll but that is not possible.

I dont want to use more an auxiliary list unless it is the only way to do it.

Body:
If I correctly understand your goal, this should be what you need.

The key difference is the use of () to group the 2 vog_code conditions.

This will remove all items where BOTH of the following are true

vog_code is either 14 or 16

fecha_recepcion >= fechaOriginal

transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => (x.vog_code == 14 || x.vog_code == 16) && x.fecha_recepcion >= fechaOriginal);

Another way

Another approach to this is to switch your conditions around a bit like this:

transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => x.fecha_recepcion >= fechaOriginal && x.vog_code == 14 || x.vog_code == 16);


问:
Conditional aggregation in SQL Server based on a column value
My data is something like:

```
IdType     Date        ActualEst      Value     PriceType
  1        01-06         A            1          Settle
  1        02-06         A            2          Settle
  1        02-06         F            3          Settle
  1        03-06         A            4          Settle
  2        01-06         A            5          Settle
  2        02-06         A            6          Settle
  2        03-06         F            7          Settle
```

I want to do a average on "Value" column, grouping on "IdType" and "PriceType" columns such that if for a particular Date (column), ActualEst has records for both 'A' and 'F', I choose 'A' over 'F', otherwise any of them if only one of them exists for a Date.

So, for above data I should be picking these records for averaging Value:

```
IdType      Date           ActualEst       Value     PriceType
  1          01-06           A              1          Settle
  1          02-06           A              2          Settle
  1          03-06           A              4          Settle
```

as for date of 02-06 both 'A' and 'F' records exist and I give priority to 'A' if both types of records exist for a date.

second group..

```
IdType      Date           ActualEst       Value     PriceType
  2          01-06           A              5          Settle
  2          02-06           A              6          Settle
  2          03-06           F              7          Settle
```

and so on...

答:
With UNION ALL you get the rows on which you will group:

```<code>select * from tablename where ActualEst = 'A'
union all
select t.* from tablename t where ActualEst = 'F'
and not exists (
  select 1 from tablename
  where IdType = t.IdType and Date = t.Date and ActualEst = 'A'
)
</code>```

Then use it like this:

```<code>select
  t.IdType, t.Date, avg(value) averagevalue
from (
    select * from tablename where ActualEst = 'A'
    union all
    select t.* from tablename t where ActualEst = 'F'
    and not exists (
      select 1 from tablename
      where IdType = t.IdType and Date = t.Date and ActualEst = 'A'
    )
) t
group by t.IdType, t.Date
</code>```

Body:
My data is something like:

IdType     Date        ActualEst      Value     PriceType
  1        01-06         A            1          Settle
  1        02-06         A            2          Settle
  1        02-06         F            3          Settle
  1        03-06         A            4          Settle
  2        01-06         A            5          Settle
  2        02-06         A            6          Settle
  2        03-06         F            7          Settle

I want to do a average on "Value" column, grouping on "IdType" and "PriceType" columns such that if for a particular Date (column), ActualEst has records for both 'A' and 'F', I choose 'A' over 'F', otherwise any of them if only one of them exists for a Date.

So, for above data I should be picking these records for averaging Value:

IdType      Date           ActualEst       Value     PriceType
  1          01-06           A              1          Settle
  1          02-06           A              2          Settle
  1          03-06           A              4          Settle

as for date of 02-06 both 'A' and 'F' records exist and I give priority to 'A' if both types of records exist for a date.

second group..

IdType      Date           ActualEst       Value     PriceType
  2          01-06           A              5          Settle
  2          02-06           A              6          Settle
  2          03-06           F              7          Settle

and so on...

Body:
With UNION ALL you get the rows on which you will group:

select * from tablename where ActualEst = 'A'
union all
select t.* from tablename t where ActualEst = 'F'
and not exists (
  select 1 from tablename
  where IdType = t.IdType and Date = t.Date and ActualEst = 'A'
)

Then use it like this:

select
  t.IdType, t.Date, avg(value) averagevalue
from (
    select * from tablename where ActualEst = 'A'
    union all
    select t.* from tablename t where ActualEst = 'F'
    and not exists (
      select 1 from tablename
      where IdType = t.IdType and Date = t.Date and ActualEst = 'A'
    )
) t
group by t.IdType, t.Date


问:
MYSQL, ignore whitespace, punctuation, substitute accents in query
I need a way to use my dictionary with province abbreviations, full names and territories without having to add an entry for every possible misspelling of Ontario.
Table is as such:

```<code>state       |name     | territory
===================================
AB           Alberta   West
</code>```

Data is as such:

```<code>"Ontario,"
"ON,"
"ON"
"On"
" Ontario"
"Ontario "
" Ontario "

Quebec
Québec
QU
QB
Quebec,
</code>```

答:
not a real answer for you immediate problem, but this is what normalization is for.  make another table for provinces, and then link that to the original table instead of allowing freeform text.

alterantely, add a trigger tot he input to enforce some consistency to the data collected. (at least trim the spaces, make it all UPPER, maybe check for valid entries.. etc.)

Body:
I need a way to use my dictionary with province abbreviations, full names and territories without having to add an entry for every possible misspelling of Ontario.
Table is as such:

state       |name     | territory
===================================
AB           Alberta   West

Data is as such:

"Ontario,"
"ON,"
"ON"
"On"
" Ontario"
"Ontario "
" Ontario "

Quebec
Québec
QU
QB
Quebec,


问:
How to encode from PCM to AAC Format within a .mpg container?
I am trying to encode a file which has PCM audio to AAC format within a .mpg container.

This file has 1 Audio stream with 8 Channels. When I tried to encode with below code I am getting silence audio.

Tried audio manipulation like amerge split but no luck.

ffmpeg8 -ss 00:00:00.000 -t 00:00:18.000 -i input1 -ss 00:00:18.001 -t 00:00:35.000 -i input2 -filter_complex "[0:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part1crop]; [1:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part2crop]; [part1crop][0:a:0][part2crop][1:a:0]concat=n=2:v=1:a=1[vconcat][aconcat]" -map '[vconcat]' -codec:v libx264 -profile:v High -level 4.1 -coder 0 -pix_fmt yuv420p -video_track_timescale 25 -r 25 -s:v 1024x576 -aspect 16:9  -x264-params "cabac=0:ref=3:weightp=2:keyint=50:keyint_min=5:bframes=0:b-adapt=0:subq=6:subme=7:nal-hrd=cbr:cbv_maxrate=22500:cbv-bufsize=30000" -map '[aconcat]' -codec:a libfdk_aac  -ar 48000 -ac 2 -b:a 192K -write_tmcd off /output.mpg

Tried with mp2 codec it works perfectly. This problem occurs only when I use AAC codec.

Input Audio properties:

```<code>Audio
ID                                       : 3
Format                                   : PCM
Format settings, wrapping mode           : Frame (D-10)
Codec ID                                 : 0D01030102010101
Duration                                 : 35 s 0 ms
Bit rate mode                            : Constant
Bit rate                                 : 9 216 kb/s
Encoded bit rate                         : 12.3 Mb/s
Channel(s)                               : 8 channels
Channel positions                        : Front: L C R, Side: L R, Back: L R, LFE
Sampling rate                            : 48.0 kHz
Frame rate                               : 25.000 FPS (1920 SPF)
Bit depth                                : 24 bits
Stream size                              : 38.5 MiB (15%)
Encoded stream size                      : 51.3 MiB (20%)
Title                                    : A1
Locked                                   : Yes
</code>```

答:
Unsupported audio codec for mpeg. Must be:

mp1

mp2

mp3

16-bit pcm_dvd

pcm_s16be

ac3

dts

pcm_dvd and pcm_s16be will be the only two that support 8 channel layout.

Or use a different output container format such as .ts.

Body:
I am trying to encode a file which has PCM audio to AAC format within a .mpg container.

This file has 1 Audio stream with 8 Channels. When I tried to encode with below code I am getting silence audio.

Tried audio manipulation like amerge split but no luck.

ffmpeg8 -ss 00:00:00.000 -t 00:00:18.000 -i input1 -ss 00:00:18.001 -t 00:00:35.000 -i input2 -filter_complex "[0:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part1crop]; [1:v:0]crop=out_h=576:y=32,yadif=1:-1:0[part2crop]; [part1crop][0:a:0][part2crop][1:a:0]concat=n=2:v=1:a=1[vconcat][aconcat]" -map '[vconcat]' -codec:v libx264 -profile:v High -level 4.1 -coder 0 -pix_fmt yuv420p -video_track_timescale 25 -r 25 -s:v 1024x576 -aspect 16:9  -x264-params "cabac=0:ref=3:weightp=2:keyint=50:keyint_min=5:bframes=0:b-adapt=0:subq=6:subme=7:nal-hrd=cbr:cbv_maxrate=22500:cbv-bufsize=30000" -map '[aconcat]' -codec:a libfdk_aac  -ar 48000 -ac 2 -b:a 192K -write_tmcd off /output.mpg

Tried with mp2 codec it works perfectly. This problem occurs only when I use AAC codec.

Input Audio properties:

Audio
ID                                       : 3
Format                                   : PCM
Format settings, wrapping mode           : Frame (D-10)
Codec ID                                 : 0D01030102010101
Duration                                 : 35 s 0 ms
Bit rate mode                            : Constant
Bit rate                                 : 9 216 kb/s
Encoded bit rate                         : 12.3 Mb/s
Channel(s)                               : 8 channels
Channel positions                        : Front: L C R, Side: L R, Back: L R, LFE
Sampling rate                            : 48.0 kHz
Frame rate                               : 25.000 FPS (1920 SPF)
Bit depth                                : 24 bits
Stream size                              : 38.5 MiB (15%)
Encoded stream size                      : 51.3 MiB (20%)
Title                                    : A1
Locked                                   : Yes


问:
How can I install Python's pip3 on my Mac?
I'm trying to install pip3, but I'm not having any luck. Also, I tried sudo install and it did not work. How could I install pip3 on my Mac?

sudo easy_install pip3
Password:
Searching for pip3
Reading https://pypi.python.org/simple/pip3/
Couldn't find index page for 'pip3' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/

No local packages or download links found for pip3
error: Could not find suitable distribution for Requirement.parse('pip3')
```

答:
I also encountered the same problem but brew install python3 does not work properly to install pip3.

brre will throw the warning The post-install step did not complete successfully.

It has to do with homebrew does not have permission to /usr/local

Create the directory if not exist

```<code>sudo mkdir lib
sudo mkdir Frameworks
</code>```

Give the permissions inside /usr/local to homebrew so it can access them:

```<code>sudo chown -R $(whoami) $(brew --prefix)/*
</code>```

Now ostinstall python3

```<code>brew postinstall python3
</code>```

This will give you a successful installation

Body:
I also encountered the same problem but brew install python3 does not work properly to install pip3.

brre will throw the warning The post-install step did not complete successfully.

It has to do with homebrew does not have permission to /usr/local

Create the directory if not exist

sudo mkdir lib
sudo mkdir Frameworks

Give the permissions inside /usr/local to homebrew so it can access them:

sudo chown -R $(whoami) $(brew --prefix)/*

Now ostinstall python3

brew postinstall python3

This will give you a successful installation


问:
How can I improve my code for generating a dynamic UI element?
I have a dynamic Shiny UI element, where the user is prompted to select a number (1-4) from a dropdown. Shiny then responds by generating the corresponding number of numericInput() elements that will be used by my program.

The following code works, but it's very long-winded and I imagine there are methods to improve the code to (1) make it more concise, and (2) avoid using if/else statements.

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("num", label = h3("Select box"),
                  choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3,
                                 "Choice 4" = 4),
                  selected = 1),
      uiOutput("input_ui")
    ),
    mainPanel(
      tableOutput("table")
    )
  )
)

server <- function(input, output) {

  output$input_ui <- renderUI({
    num <- as.integer(input$num)
    if (num == 1) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)))
    } else if (num == 2) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)),
        column(6, numericInput("max", h5("Max"), value = 15))
      )
    } else if (num == 3) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)),
        column(6, numericInput("max", h5("Max"), value = 15)),
        column(6, numericInput("max", h5("Max"), value = 20))
      )
    } else if (num == 4) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)),
        column(6, numericInput("max", h5("Max"), value = 15)),
        column(6, numericInput("max", h5("Max"), value = 20)),
        column(6, numericInput("max", h5("Max"), value = 25))
      )
    }
  })
}

shinyApp(ui = ui, server = server)
```

Is there a better way to write this?

Note that in the above, the values and labels are arbitrary.

答:
You can use lapply() to create multiple (similar) UI elements based on choices by the user.

Replace your server with this:

```<code>server <- function(input, output) {

  output$input_ui <- renderUI({
    req(input$num)
    if (as.numeric(input$num) > 1) {
    lapply(1:(as.numeric(input$num)-1), function(i) {
      numericInput(paste0("max",i),
                   label=paste0("Max", i),
                   value = (i+2)*5)
    })
    }
  })
}
</code>```

Body:
I have a dynamic Shiny UI element, where the user is prompted to select a number (1-4) from a dropdown. Shiny then responds by generating the corresponding number of numericInput() elements that will be used by my program.

The following code works, but it's very long-winded and I imagine there are methods to improve the code to (1) make it more concise, and (2) avoid using if/else statements.

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("num", label = h3("Select box"),
                  choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3,
                                 "Choice 4" = 4),
                  selected = 1),
      uiOutput("input_ui")
    ),
    mainPanel(
      tableOutput("table")
    )
  )
)

server <- function(input, output) {

  output$input_ui <- renderUI({
    num <- as.integer(input$num)
    if (num == 1) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)))
    } else if (num == 2) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)),
        column(6, numericInput("max", h5("Max"), value = 15))
      )
    } else if (num == 3) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)),
        column(6, numericInput("max", h5("Max"), value = 15)),
        column(6, numericInput("max", h5("Max"), value = 20))
      )
    } else if (num == 4) {
      fluidRow(
        column(6, numericInput("min", h5("Min"), value = 10)),
        column(6, numericInput("max", h5("Max"), value = 15)),
        column(6, numericInput("max", h5("Max"), value = 20)),
        column(6, numericInput("max", h5("Max"), value = 25))
      )
    }
  })
}

shinyApp(ui = ui, server = server)

Is there a better way to write this?

Note that in the above, the values and labels are arbitrary.

Body:
You can use lapply() to create multiple (similar) UI elements based on choices by the user.

Replace your server with this:

server <- function(input, output) {

  output$input_ui <- renderUI({
    req(input$num)
    if (as.numeric(input$num) > 1) {
    lapply(1:(as.numeric(input$num)-1), function(i) {
      numericInput(paste0("max",i),
                   label=paste0("Max", i),
                   value = (i+2)*5)
    })
    }
  })
}


问:
Terraform Azure Extension Issue
Receiving this error when running Terraform apply on a module that I created to spin up an Azure Windows VM.

```<code>Error: Error applying plan:

1 error occurred:
        * module.vm-windows.azurerm_virtual_machine_extension.test: 1 error occurred:
        * azurerm_virtual_machine_extension.test: Code="VMExtensionProvisioningError" Message="VM has reported a failure when processing extension 'hostname'. Error message: \"Finished executing command\"."
</code>```

Here is my code for VM creation and extension

```<code>resource "azurerm_virtual_machine" "vm" {
  count                            = "${length(var.vm_name_suffix)}"
  name                             = "${var.vm_name_prefix}${element(var.vm_name_suffix, count.index)}"
  location                         = "${var.location}"
  resource_group_name              = "${var.rg_name}"
  network_interface_ids            = ["${element(azurerm_network_interface.nic.*.id, count.index)}"]
  vm_size                          = "${var.vm_size}"
  delete_os_disk_on_termination    = "true"
  delete_data_disks_on_termination = "true"
  license_type                     = "Windows_Server"
  zones                            = ["${element(local.azs, count.index)}"]

  storage_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "${var.win_os[var.os_name]}"
    version   = "latest"
  }

  storage_os_disk {
    name              = "${var.vm_name_prefix}${element(var.vm_name_suffix, count.index)}-OSDisk"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "${var.os_disk_type}"
  }

  os_profile {
    computer_name  = "${var.vm_name_prefix}${element(var.vm_name_suffix, count.index)}"
    admin_username = "admin"
    admin_password = "${random_string.adminpassword.result}"
  }

  os_profile_windows_config {
    provision_vm_agent = true
  }
}

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "hostname"
  location             = "${var.location}"
  resource_group_name  = "${var.rg_name}"
  virtual_machine_name = "${azurerm_virtual_machine.vm.name}"
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  settings = <<SETTINGS
    {
        "commandToExecute": "powershell -ExecutionPolicy Unrestricted -File C:\\FOLDER\\WinFirewall.ps1\""
    }
  SETTINGS

  depends_on = ["azurerm_virtual_machine.vm"]
}
</code>```

It looks like it is trying to run the extension before the machine has been created, which is why I added the depends on.  Not sure though as the error doesn't tell me much.  Any help would be greatly appreciated.

EDIT: Here are the logs from VM

Command Execution Log

```<code>[05/31/2019 20:09:24.31] Executing: C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\enable.cmd
[05/31/2019 20:09:24.34] Execution Complete.
######
Execution Output:
C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3>if not exist RuntimeSettings\*.settings exit /b -2
C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3>start cmd /C bin\CustomScriptHandler.exe "enable"

Execution Error:

######
 Number of Tries:
 1Command C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\enable.cmd of Microsoft.Compute.CustomScriptExtension has exited with Exit code: 0
Plugin (name: Microsoft.Compute.CustomScriptExtension, version: 1.9.3) completed successfully.
</code>```

Custom Script Handler Log

```<code>[2140+00000001] [05/31/2019 19:15:06.60] [INFO] Starting IaaS ScriptHandler Extension v1
[2140+00000001] [05/31/2019 19:15:06.63] [INFO] HandlerEnvironment = Version: 1, HandlerEnvironment: [LogFolder: "C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3", ConfigFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\RuntimeSettings", StatusFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status", HeartbeatFile: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status\HeartBeat.Json"]
[2140+00000001] [05/31/2019 19:15:06.63] [INFO] Installing Handler
[2140+00000001] [05/31/2019 19:15:06.63] [INFO] Handler successfully installed
[2140+00000001] [05/31/2019 19:15:06.64] [INFO] Removing user-level access rules for 2 directories
[2140+00000001] [05/31/2019 19:15:06.64] [INFO] Removing Users access rules from directory 'C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3'
[2140+00000001] [05/31/2019 19:15:06.67] [INFO] Removing Users access rules from directory 'C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3'
[2140+00000001] [05/31/2019 19:15:06.69] [INFO] Finished removing user-level access rules
[588+00000001] [05/31/2019 19:15:10.19] [INFO] Starting IaaS ScriptHandler Extension v1
[588+00000001] [05/31/2019 19:15:10.21] [INFO] HandlerEnvironment = Version: 1, HandlerEnvironment: [LogFolder: "C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3", ConfigFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\RuntimeSettings", StatusFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status", HeartbeatFile: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status\HeartBeat.Json"]
[588+00000001] [05/31/2019 19:15:10.21] [INFO] Enabling Handler
[588+00000001] [05/31/2019 19:15:10.22] [INFO] Successfully enabled TLS.
[588+00000001] [05/31/2019 19:15:10.22] [INFO] Handler successfully enabled
[588+00000001] [05/31/2019 19:15:10.24] [INFO] Loading configuration for sequence number 0
[588+00000001] [05/31/2019 19:15:10.27] [INFO] HandlerSettings = ProtectedSettingsCertThumbprint: , ProtectedSettings: {}, PublicSettings: {FileUris: [], CommandToExecute: powershell -ExecutionPolicy Unrestricted -File C:\FOLDER\WinFirewall.ps1"}
[588+00000001] [05/31/2019 19:15:10.27] [INFO] Downloading files specified in configuration...
[588+00000001] [05/31/2019 19:15:10.35] [INFO] No files to download.
[588+00000001] [05/31/2019 19:15:10.36] [INFO] Files downloaded. Asynchronously executing command: 'powershell -ExecutionPolicy Unrestricted -File C:\FOLDER\WinFirewall.ps1"'
[588+00000001] [05/31/2019 19:15:10.38] [INFO] Command execution task started. Awaiting completion...
[588+00000001] [05/31/2019 19:15:13.55] [ERROR] Command execution finished. Command exited with code: -196608
[1944+00000001] [05/31/2019 20:09:24.64] [INFO] Starting IaaS ScriptHandler Extension v1
[1944+00000001] [05/31/2019 20:09:24.65] [INFO] HandlerEnvironment = Version: 1, HandlerEnvironment: [LogFolder: "C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3", ConfigFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\RuntimeSettings", StatusFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status", HeartbeatFile: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status\HeartBeat.Json"]
[1944+00000001] [05/31/2019 20:09:24.65] [INFO] Enabling Handler
[1944+00000001] [05/31/2019 20:09:24.67] [INFO] Successfully enabled TLS.
[1944+00000001] [05/31/2019 20:09:24.67] [INFO] Handler successfully enabled
[1944+00000001] [05/31/2019 20:09:24.69] [INFO] Loading configuration for sequence number 0
[1944+00000001] [05/31/2019 20:09:24.70] [INFO] HandlerSettings = ProtectedSettingsCertThumbprint: , ProtectedSettings: {}, PublicSettings: {FileUris: [], CommandToExecute: powershell -ExecutionPolicy Unrestricted -File C:\WS\CloudTemplates\Terraform\Azure\Deployments\_Testing\ANSIBLE_TEST\Module\WinFirewall.ps1"}
[1944+00000001] [05/31/2019 20:09:24.70] [WARN] Current sequence number, 0, is not greater than the sequence number of the most recently executed configuration. Exiting...
</code>```

答:
why do you think ordering is the problem. when you are using "${azurerm_virtual_machine.vm.name}" you are creating an implicit dependency, so extension runs after the vm is created. also, the error suggests that the extension failed to execute the script (or rather it was executed by returned an error or something like this).

To figure out whats going on - check extension logs on the vm

https://learn.hashicorp.com/terraform/azure/dependencies_az

Title: Terraform Azure Extension Issue

Body:
Receiving this error when running Terraform apply on a module that I created to spin up an Azure Windows VM.

Error: Error applying plan:

1 error occurred:
        * module.vm-windows.azurerm_virtual_machine_extension.test: 1 error occurred:
        * azurerm_virtual_machine_extension.test: Code="VMExtensionProvisioningError" Message="VM has reported a failure when processing extension 'hostname'. Error message: \"Finished executing command\"."

Here is my code for VM creation and extension

resource "azurerm_virtual_machine" "vm" {
  count                            = "${length(var.vm_name_suffix)}"
  name                             = "${var.vm_name_prefix}${element(var.vm_name_suffix, count.index)}"
  location                         = "${var.location}"
  resource_group_name              = "${var.rg_name}"
  network_interface_ids            = ["${element(azurerm_network_interface.nic.*.id, count.index)}"]
  vm_size                          = "${var.vm_size}"
  delete_os_disk_on_termination    = "true"
  delete_data_disks_on_termination = "true"
  license_type                     = "Windows_Server"
  zones                            = ["${element(local.azs, count.index)}"]

  storage_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "${var.win_os[var.os_name]}"
    version   = "latest"
  }

  storage_os_disk {
    name              = "${var.vm_name_prefix}${element(var.vm_name_suffix, count.index)}-OSDisk"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "${var.os_disk_type}"
  }

  os_profile {
    computer_name  = "${var.vm_name_prefix}${element(var.vm_name_suffix, count.index)}"
    admin_username = "admin"
    admin_password = "${random_string.adminpassword.result}"
  }

  os_profile_windows_config {
    provision_vm_agent = true
  }
}

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "hostname"
  location             = "${var.location}"
  resource_group_name  = "${var.rg_name}"
  virtual_machine_name = "${azurerm_virtual_machine.vm.name}"
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  settings = <<SETTINGS
    {
        "commandToExecute": "powershell -ExecutionPolicy Unrestricted -File C:\\FOLDER\\WinFirewall.ps1\""
    }
  SETTINGS

  depends_on = ["azurerm_virtual_machine.vm"]
}

It looks like it is trying to run the extension before the machine has been created, which is why I added the depends on.  Not sure though as the error doesn't tell me much.  Any help would be greatly appreciated.

EDIT: Here are the logs from VM

Command Execution Log

[05/31/2019 20:09:24.31] Executing: C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\enable.cmd
[05/31/2019 20:09:24.34] Execution Complete.
######
Execution Output:
C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3>if not exist RuntimeSettings\*.settings exit /b -2
C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3>start cmd /C bin\CustomScriptHandler.exe "enable"

Execution Error:

######
 Number of Tries:
 1Command C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\enable.cmd of Microsoft.Compute.CustomScriptExtension has exited with Exit code: 0
Plugin (name: Microsoft.Compute.CustomScriptExtension, version: 1.9.3) completed successfully.

Custom Script Handler Log

[2140+00000001] [05/31/2019 19:15:06.60] [INFO] Starting IaaS ScriptHandler Extension v1
[2140+00000001] [05/31/2019 19:15:06.63] [INFO] HandlerEnvironment = Version: 1, HandlerEnvironment: [LogFolder: "C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3", ConfigFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\RuntimeSettings", StatusFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status", HeartbeatFile: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status\HeartBeat.Json"]
[2140+00000001] [05/31/2019 19:15:06.63] [INFO] Installing Handler
[2140+00000001] [05/31/2019 19:15:06.63] [INFO] Handler successfully installed
[2140+00000001] [05/31/2019 19:15:06.64] [INFO] Removing user-level access rules for 2 directories
[2140+00000001] [05/31/2019 19:15:06.64] [INFO] Removing Users access rules from directory 'C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3'
[2140+00000001] [05/31/2019 19:15:06.67] [INFO] Removing Users access rules from directory 'C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3'
[2140+00000001] [05/31/2019 19:15:06.69] [INFO] Finished removing user-level access rules
[588+00000001] [05/31/2019 19:15:10.19] [INFO] Starting IaaS ScriptHandler Extension v1
[588+00000001] [05/31/2019 19:15:10.21] [INFO] HandlerEnvironment = Version: 1, HandlerEnvironment: [LogFolder: "C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3", ConfigFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\RuntimeSettings", StatusFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status", HeartbeatFile: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status\HeartBeat.Json"]
[588+00000001] [05/31/2019 19:15:10.21] [INFO] Enabling Handler
[588+00000001] [05/31/2019 19:15:10.22] [INFO] Successfully enabled TLS.
[588+00000001] [05/31/2019 19:15:10.22] [INFO] Handler successfully enabled
[588+00000001] [05/31/2019 19:15:10.24] [INFO] Loading configuration for sequence number 0
[588+00000001] [05/31/2019 19:15:10.27] [INFO] HandlerSettings = ProtectedSettingsCertThumbprint: , ProtectedSettings: {}, PublicSettings: {FileUris: [], CommandToExecute: powershell -ExecutionPolicy Unrestricted -File C:\FOLDER\WinFirewall.ps1"}
[588+00000001] [05/31/2019 19:15:10.27] [INFO] Downloading files specified in configuration...
[588+00000001] [05/31/2019 19:15:10.35] [INFO] No files to download.
[588+00000001] [05/31/2019 19:15:10.36] [INFO] Files downloaded. Asynchronously executing command: 'powershell -ExecutionPolicy Unrestricted -File C:\FOLDER\WinFirewall.ps1"'
[588+00000001] [05/31/2019 19:15:10.38] [INFO] Command execution task started. Awaiting completion...
[588+00000001] [05/31/2019 19:15:13.55] [ERROR] Command execution finished. Command exited with code: -196608
[1944+00000001] [05/31/2019 20:09:24.64] [INFO] Starting IaaS ScriptHandler Extension v1
[1944+00000001] [05/31/2019 20:09:24.65] [INFO] HandlerEnvironment = Version: 1, HandlerEnvironment: [LogFolder: "C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3", ConfigFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\RuntimeSettings", StatusFolder: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status", HeartbeatFile: "C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.9.3\Status\HeartBeat.Json"]
[1944+00000001] [05/31/2019 20:09:24.65] [INFO] Enabling Handler
[1944+00000001] [05/31/2019 20:09:24.67] [INFO] Successfully enabled TLS.
[1944+00000001] [05/31/2019 20:09:24.67] [INFO] Handler successfully enabled
[1944+00000001] [05/31/2019 20:09:24.69] [INFO] Loading configuration for sequence number 0
[1944+00000001] [05/31/2019 20:09:24.70] [INFO] HandlerSettings = ProtectedSettingsCertThumbprint: , ProtectedSettings: {}, PublicSettings: {FileUris: [], CommandToExecute: powershell -ExecutionPolicy Unrestricted -File C:\WS\CloudTemplates\Terraform\Azure\Deployments\_Testing\ANSIBLE_TEST\Module\WinFirewall.ps1"}
[1944+00000001] [05/31/2019 20:09:24.70] [WARN] Current sequence number, 0, is not greater than the sequence number of the most recently executed configuration. Exiting...


问:
How can I get the win ratio of a value in sql?
I have 2 tables on my database: one called 'LEAGUES' and another called 'MATCHES'. I want to obtain the winrate of each league depending on the favorable result of the matches related to those leagues.

The structure of the tables:

```<code>#######################  ###########################
#   TABLE LEAGUES     #  #       TABLE MATCHES     #
#######################  ###########################
+----------+----------+  +-------------------------+
|    ID    |   name   |  |ID|match|League_id|Result|
+----------+----------+  +--+-----+---------+------+
|     1    |   aaa    |  |1 |xxxxx|    1    |  W   |
|     2    |   bbb    |  |2 |xxxxx|    1    |  L   |
|     3    |   ccc    |  |3 |xxxxx|    2    |  W   |
|     4    |   ddd    |  |4 |xxxxx|    3    |  W   |
+----------+----------+  |5 |xxxxx|    3    |  L   |
                         |6 |xxxxx|    3    |  W   |
                         +--+-----+---------+------+
</code>```

The result i want:

```<code>#######################
#       RESULT        #
#######################
+----------+----------+
|league.id | Winrate  |
+----------+----------+
|     1    |   50%    |
|     2    |   100%   |
|     3    |   66%    |
+----------+----------+
</code>```

I tried the following code but it is not working because the subquery returns more than one value:

```<code>SELECT leagues.id, COUNT(leagues.id)*100/(SELECT COUNT(leagues.id)
                              FROM leagues,matches WHERE
                              leagues.id=matches.League_id
                              GROUP BY leagues.id) as winrate
FROM leagues,matches
WHERE leagues.id=matches.League_id and matches.result like 'W'
GROUP BY leagues.id
</code>```

Is there another way to obtain these results? Thanks in advance.

答:
You seem to want:

```<code>SELECT m.League_id,
       AVG( m.result = 'W' ) as winrate
FROM matches m
GROUP BY m.League_id;
</code>```

Notes:

You don't need the leagues table, because the field you need is in matches.

Learn proper, explicit, standard JOIN syntax (although it is not necessary for this query).

MySQL treats booleans as numbers in a numeric context, with 1 for true and 0 for false, so AVG( <boolean expression> ) returns the ratio of true values.  Pretty nifty.

Although they do pretty much the same thing, = is more commonly used for equality comparisons as opposed to like.

Body:
I have 2 tables on my database: one called 'LEAGUES' and another called 'MATCHES'. I want to obtain the winrate of each league depending on the favorable result of the matches related to those leagues.

The structure of the tables:

#######################  ###########################
#   TABLE LEAGUES     #  #       TABLE MATCHES     #
#######################  ###########################
+----------+----------+  +-------------------------+
|    ID    |   name   |  |ID|match|League_id|Result|
+----------+----------+  +--+-----+---------+------+
|     1    |   aaa    |  |1 |xxxxx|    1    |  W   |
|     2    |   bbb    |  |2 |xxxxx|    1    |  L   |
|     3    |   ccc    |  |3 |xxxxx|    2    |  W   |
|     4    |   ddd    |  |4 |xxxxx|    3    |  W   |
+----------+----------+  |5 |xxxxx|    3    |  L   |
                         |6 |xxxxx|    3    |  W   |
                         +--+-----+---------+------+

The result i want:

#######################
#       RESULT        #
#######################
+----------+----------+
|league.id | Winrate  |
+----------+----------+
|     1    |   50%    |
|     2    |   100%   |
|     3    |   66%    |
+----------+----------+

I tried the following code but it is not working because the subquery returns more than one value:

SELECT leagues.id, COUNT(leagues.id)*100/(SELECT COUNT(leagues.id)
                              FROM leagues,matches WHERE
                              leagues.id=matches.League_id
                              GROUP BY leagues.id) as winrate
FROM leagues,matches
WHERE leagues.id=matches.League_id and matches.result like 'W'
GROUP BY leagues.id

Is there another way to obtain these results? Thanks in advance.

Body:
You seem to want:

SELECT m.League_id,
       AVG( m.result = 'W' ) as winrate
FROM matches m
GROUP BY m.League_id;

Notes:

You don't need the leagues table, because the field you need is in matches.

Learn proper, explicit, standard JOIN syntax (although it is not necessary for this query).

MySQL treats booleans as numbers in a numeric context, with 1 for true and 0 for false, so AVG( <boolean expression> ) returns the ratio of true values.  Pretty nifty.

Although they do pretty much the same thing, = is more commonly used for equality comparisons as opposed to like.