问:
WooCommerce hide all products of a certain category if not loggedin
I have been searching everywhere to find this answer and have even downloaded multiple plugins, all of which haven't worked.

Is there a way to achieve this using PHP?

I have this code:

```<code> <?php if( !is_user_logged_in() && get_field('___unit_price') ): ?>
 <p>Unit Price: $<?php the_field('___unit_price'); ?></p>
 <?php endif; ?>
</code>```

Which seems to work for specific products but does not work for an entire category, any help would be much appeciated

答:
Please use the following in function.php of your child-theme:

```<code>/* hide YOURCATEGORY category for not loggedin user
===================================================*/

    if ( !is_user_logged_in()) {
        function custom_pre_get_posts_q( $q ) {

            $tax_query = (array) $q->get( 'tax_query' );

            $tax_query[] = array(
                   'taxonomy' => 'product_cat',
                   'field' => 'slug',
                   'terms' => array( 'YOURCATEGORY' ), // Don't display products in the composite category on the shop page.
                   'operator' => 'NOT IN'
            );

            $q->set( 'tax_query', $tax_query );

        }
        add_action( 'woocommerce_product_query', 'custom_pre_get_posts_q' );
    }
</code>```

Do not forget to replace 'YOURCATEGORY' by the slug of the category you want to hide.

Cheers

Body:
I have been searching everywhere to find this answer and have even downloaded multiple plugins, all of which haven't worked.

Is there a way to achieve this using PHP?

I have this code:

 <?php if( !is_user_logged_in() && get_field('___unit_price') ): ?>

Unit Price: $<?php the_field('___unit_price'); ?>

 <?php endif; ?>

Which seems to work for specific products but does not work for an entire category, any help would be much appeciated

Body:
Please use the following in function.php of your child-theme:

/* hide YOURCATEGORY category for not loggedin user
===================================================*/

    if ( !is_user_logged_in()) {
        function custom_pre_get_posts_q( $q ) {

            $tax_query = (array) $q->get( 'tax_query' );

            $tax_query[] = array(
                   'taxonomy' => 'product_cat',
                   'field' => 'slug',
                   'terms' => array( 'YOURCATEGORY' ), // Don't display products in the composite category on the shop page.
                   'operator' => 'NOT IN'
            );

            $q->set( 'tax_query', $tax_query );

        }
        add_action( 'woocommerce_product_query', 'custom_pre_get_posts_q' );
    }

Do not forget to replace 'YOURCATEGORY' by the slug of the category you want to hide.

Cheers


来源: stackexchange

问:
State machine Modelling Query regarding transitions originating from any state
I have query regarding state machine modeling.My state machine looks like this:
States: a,b,c,d,e
Transitions/events: E1,E2,E3,E4,E5
a--E1-->b---E2-->c--E5--> e

Some transitions E3 and E4 can occur from any state(i.e. both b & c) and terminate the state machine i.e. moves the state machine to terminal state

How to model transitions E3 & E4 in this scenario?
I am using Spring state machine for implementation.How to model these transitions using spring state machine?

答:
Generally speaking hierarchical states are used to prevent state explosion where you create more and more similar type of transitions from multiple states into some other state.

There are no wildcard transitions but if you create parent state p and create b and c as its child states, you can draw transition from state p.

ContentLicense: CC BY-SA 3.0


问:
How to read an input value from atmega32 pin?
I'm trying to read a value from an avr pin but it doesn't work.

I'm trying to read a value that is coming from a push button and this button is connected to 5V DC cell.

When I press the button the 5V should go to the atmega32 and reads it as 1, then the if statement becomes true and the led goes on.

However, when the value becomes true the led will turn on but its not.

bit 1 is the button
bit 0 is the led

Code

```<code>#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

int main(void) {
   DDRA |= 0b00000001;         // pin 0 output

    while (1) {
        if ((PINA&0b00000010) == 1) {  // button pressed
            PORTA |= 0b00000001;   // turn led on
        }
    }
}
</code>```

答:
You should change your hardware setup, and make your button active low, which means that pushing the button connects your GPIO pin to ground.  Instead of connecting your button to positive side of the 5V cell, connected it to the negative side.  That will let you take advantage of the internal pull resistor that you can active on your GPIO.  Once you do that, your code should be changed to look something like this:

```<code>#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

#define LED_BIT 0
#define BTN_BIT 1

int main(void)
{
    DDRA  = (1 << LED_BIT); // PA0 output
    PORTA = (1 << BTN_BIT); // enable internal pull up on PA1

    while (1) {
        if (!(PINA & (1 << BTN_BIT))) {  // button pressed
            PORTA |= (1 << LED_BIT);   // turn led on
        }
    }
}
</code>```

Notice that the if statement now checks to see if the PA1 is a 0 because the button is set up to connect to ground when it is pushed.  Also notice that there is a new line in there that enables an internal pull-up, which makes PA1 read a 1 while the button is not pressed.  If you don't change your button an active low configuration, you will have to use an external pull-down resistor in order for your code to work correctly.

Body:
I'm trying to read a value from an avr pin but it doesn't work.

I'm trying to read a value that is coming from a push button and this button is connected to 5V DC cell.

When I press the button the 5V should go to the atmega32 and reads it as 1, then the if statement becomes true and the led goes on.

However, when the value becomes true the led will turn on but its not.

bit 1 is the button
bit 0 is the led

Code

#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

int main(void) {
   DDRA |= 0b00000001;         // pin 0 output

    while (1) {
        if ((PINA&0b00000010) == 1) {  // button pressed
            PORTA |= 0b00000001;   // turn led on
        }
    }
}

Body:
You should change your hardware setup, and make your button active low, which means that pushing the button connects your GPIO pin to ground.  Instead of connecting your button to positive side of the 5V cell, connected it to the negative side.  That will let you take advantage of the internal pull resistor that you can active on your GPIO.  Once you do that, your code should be changed to look something like this:

#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

#define LED_BIT 0
#define BTN_BIT 1

int main(void)
{
    DDRA  = (1 << LED_BIT); // PA0 output
    PORTA = (1 << BTN_BIT); // enable internal pull up on PA1

    while (1) {
        if (!(PINA & (1 << BTN_BIT))) {  // button pressed
            PORTA |= (1 << LED_BIT);   // turn led on
        }
    }
}

Notice that the if statement now checks to see if the PA1 is a 0 because the button is set up to connect to ground when it is pushed.  Also notice that there is a new line in there that enables an internal pull-up, which makes PA1 read a 1 while the button is not pressed.  If you don't change your button an active low configuration, you will have to use an external pull-down resistor in order for your code to work correctly.


问:
Curl Post with File
I have data phone in phone.txt

+6285712341234

  +6285712341235

  +6285712341236

  +6285712341237

  +6285712341238

but I don't know how to use this data to curl, here's what I tried:

curl -X POST "https://rest-api.moceansms.com/rest/1/sms" -d "mocean-api-key={api_key}&mocean-api-secret={api_secret}&mocean-from={name}&mocean-to={phone.txt}&mocean-text=Hello"

I should use phone data to send SMS to everyone; I googled for a solution, but with no luck (I don't even know whether the keywords I used to look for a solution where correct or not).

答:
You should use --data flag:

Check:

https://curl.haxx.se/mail/archive-2007-03/0097.html

https://curl.haxx.se/docs/manpage.html#-d

Here the entire explanation from man:

-d, --data

(HTTP) Sends the specified data in a POST request to the HTTP server,
  in the same way that a browser does when a user has filled in an HTML
  form and presses the submit button. This will cause curl to pass the
  data to the server using the content-type
  application/x-www-form-urlencoded. Compare to -F, --form.

--data-raw is almost the same but does not have a special interpretation of the @ character. To post data purely binary, you
  should instead use the --data-binary option. To URL-encode the value
  of a form field you may use --data-urlencode.

If any of these options is used more than once on the same command
  line, the data pieces specified will be merged together with a
  separating &-symbol. Thus, using '-d name=daniel -d skill=lousy' would
  generate a post chunk that looks like 'name=daniel&skill=lousy'.

If you start the data with the letter @, the rest should be a file
  name to read the data from, or - if you want curl to read the data
  from stdin. Multiple files can also be specified. Posting data from a
  file named 'foobar' would thus be done with -d, --data @foobar. When
  --data is told to read from a file like that, carriage returns and newlines will be stripped out. If you don't want the @ character to
  have a special interpretation use --data-raw instead.

See also --data-binary and --data-urlencode and --data-raw. This
  option overrides -F, --form and -I, --head and --upload.

Title: Curl Post with File


问:
Compile native library that relies on other native libraries to run using Android NDK?
I have a large library of C files that relies on OpenSSL and I'm very new to working with native libraries, and especially new to working with android. I've managed to implement this library on iOS with no problems.

I've been looking around online for tutorials / information on how to do this, but so far I haven't found anything I can understand. It's all very confusing to me.

Essentially I'm trying to figure out how to compile the library of C files into a native lib using NDK and use the compiled library with imy android application.

From what I understand, I need a custom cmake file for android itself, but I don't know where to start with that and the documentation I've found has been incredibly difficult to follow.

So, I need some help understanding what the process would be of compiling the library in the following manor:

Compile the library, linking it with openssl and libcrypto, using Gradle and CMakeLists.txt and link the final library with my Android Studio project.

Be able to make calls to the native functions within these libraries from my Java code. (I understand that this requires a JNI Java Wrapper)

(I've already managed to build libssl and libcrypto for all archs that android requires, but I'm not sure what to do with the .a/.so files.)

Any help on this matter would be incredibly appreciated.

Thanks

EDIT:

I managed to generate some library files with the following.

File Structure:

```<code>.idea
app
build
gradle
jni    <--- I made this folder specifically fo this.
    Android.mk <-- This is the important file.
    include
        openssl
            <openssl header files>
    libs
        arm64-v8a
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        armeabi
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        armeabi--v7a
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        mips
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        mips64
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        x86
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        x86_64
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
    src <--- These are example files that i used to build this with.
        myc_files.c
        myother_c_files.c
        myc_heades.h
        myother_c_headers.h
</code>```

I then used the following in the Android.mk to generate some libraries by running ndk-build.

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Select from arm64-v8a armeabi armeabi-v7a mips mips64 x86 x86_64
ARCH := armeabi

APP_UNIFIED_HEADERS := true

#APP_ABI := $(ARCH)
# TARGET_ARCH := $(ARCH)
TARGET_PLATFORM := android-14

SRC_DIR := $(LOCAL_PATH)/src
HDR_DIR := $(LOCAL_PATH)/include
LIB_DIR := $(LOCAL_PATH)/libs

LOCAL_C_INCLUDES := $(HDR_DIR)
LOCAL_MODULE := myclib
LOCAL_SRC_FILES := $(SRC_DIR)/myc_files.c $(SRC_DIR)/myother_c_files.c
LOCAL_LDLIBS += -L$(LIB_DIR)/$(ARCH) -lssl -lcrypto

include $(BUILD_STATIC_LIBRARY)
</code>```

The libraries were put into PROJECT/obj/local and I have no idea where to go from here, or if that Android.mk file actually properly built the libraries.

答:
There are thousands of operations you can do with native development (I mean C/C++). These languages are so light and you can carry some heavy operations from Java to C/C++. For example, Camera hardware is one of the heaviest and baddest hardware in Android devices. So, it really sucks, when you try to handle this and add your own operations. When it comes to native development, this operations working on CPU and don't need translating via Dalvik or something else. That's why you need all CPU architecture of android devices. Because, each arch has its own calculation speed or technology. If there is any Co-Processors, you should take into consideration this also. This was a short overview about NDK.

For building or rebuilding native libraries you have two ways, CMake and NDK build. There are not lots of differences between these two building system, so i'd like to explain my answer with NDK building.

For native development, you should have main/jni folder which is you should put your libraries and native sources inside it and build them in this folder. Before you should create two files, Android.mk and Application.mk.
Android.mk is for building native libs (modules), adding flags and etc. You can build static and shared libraries in Android.mk. When you build your C sources, it creates static library (.a). But these libraries not for using in Java side. You can only use them for creating shared libraries (.so). For this, you should build your C++ sources, and if you want, you can add your static libraries to this.

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

ifneq (,$(filter $(TARGET_ARCH_ABI), armeabi-v7a x86 arm64-v8a x86_64))

LOCAL_MODULE := myLibrary

LOCAL_SHARED_LIBRARIES := cpufeatures opencv_imgproc opencv_core

LOCAL_C_INCLUDES := $(LOCAL_PATH)/c-files

LOCAL_SRC_FILES := $(LOCAL_PATH)/myJni.cpp

include $(BUILD_SHARED_LIBRARY)
</code>```

--- 1st line returns main/jni path.

--- 2nd line clear all old LOCAL_*** variables.

--- 3th line build modules for each arch's which are declared there.

--- 4th line shows module name, when you build it, NDK automatically add lib and .so extensions to it (libmyLibrary.so).

--- 5th line adds other shared libraries, which you need their sources in your native sources.

--- 6th line adds C files to your module.

--- 7th line shows your C++ sources which you try to build.

--- 8th line is building command.

In Application.mk you can give commands something like, your project in release mode or debug mode. And you should give arch's in this file. For example APP_ABI := armeabi-v7a x86 arm64-v8a x86_64  and etc.

When you try to build libraries and use them in java side, you should do some operations.

Check your ndk path in local.properties file in project folder. It shows ndk-bundle path for building makefiles.

ndk.dir=/Users/../Library/Android/sdk/ndk-bundle

Check build scripts in gradle file. This script shows where shared libs should be located:

```<code>sourceSets.main {
    jni.srcDirs = []
    jniLibs.srcDir 'src/main/libs'
}
</code>```

And show your makefile path to gradle.

```<code>externalNativeBuild {
   ndkBuild {
      path 'src/main/jni/Android.mk'
   }
}
</code>```

I think my answer will help you for understanding some details. For addition, you can take a look these answers also.

For calling native methods: Enter

For linking shared libraries: Enter

Enjoy!

Body:
I have a large library of C files that relies on OpenSSL and I'm very new to working with native libraries, and especially new to working with android. I've managed to implement this library on iOS with no problems.

I've been looking around online for tutorials / information on how to do this, but so far I haven't found anything I can understand. It's all very confusing to me.

Essentially I'm trying to figure out how to compile the library of C files into a native lib using NDK and use the compiled library with imy android application.

From what I understand, I need a custom cmake file for android itself, but I don't know where to start with that and the documentation I've found has been incredibly difficult to follow.

So, I need some help understanding what the process would be of compiling the library in the following manor:

Compile the library, linking it with openssl and libcrypto, using Gradle and CMakeLists.txt and link the final library with my Android Studio project.

Be able to make calls to the native functions within these libraries from my Java code. (I understand that this requires a JNI Java Wrapper)

(I've already managed to build libssl and libcrypto for all archs that android requires, but I'm not sure what to do with the .a/.so files.)

Any help on this matter would be incredibly appreciated.

Thanks

EDIT:

I managed to generate some library files with the following.

File Structure:

.idea
app
build
gradle
jni    <--- I made this folder specifically fo this.
    Android.mk <-- This is the important file.
    include
        openssl
            <openssl header files>
    libs
        arm64-v8a
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        armeabi
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        armeabi--v7a
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        mips
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        mips64
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        x86
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
        x86_64
            libcrypto.a
            libcrypto.so
            libssl.a
            libssl.so
    src <--- These are example files that i used to build this with.
        myc_files.c
        myother_c_files.c
        myc_heades.h
        myother_c_headers.h

I then used the following in the Android.mk to generate some libraries by running ndk-build.

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Select from arm64-v8a armeabi armeabi-v7a mips mips64 x86 x86_64
ARCH := armeabi

APP_UNIFIED_HEADERS := true

#APP_ABI := $(ARCH)
# TARGET_ARCH := $(ARCH)
TARGET_PLATFORM := android-14

SRC_DIR := $(LOCAL_PATH)/src
HDR_DIR := $(LOCAL_PATH)/include
LIB_DIR := $(LOCAL_PATH)/libs

LOCAL_C_INCLUDES := $(HDR_DIR)
LOCAL_MODULE := myclib
LOCAL_SRC_FILES := $(SRC_DIR)/myc_files.c $(SRC_DIR)/myother_c_files.c
LOCAL_LDLIBS += -L$(LIB_DIR)/$(ARCH) -lssl -lcrypto

include $(BUILD_STATIC_LIBRARY)

The libraries were put into PROJECT/obj/local and I have no idea where to go from here, or if that Android.mk file actually properly built the libraries.

Body:
There are thousands of operations you can do with native development (I mean C/C++). These languages are so light and you can carry some heavy operations from Java to C/C++. For example, Camera hardware is one of the heaviest and baddest hardware in Android devices. So, it really sucks, when you try to handle this and add your own operations. When it comes to native development, this operations working on CPU and don't need translating via Dalvik or something else. That's why you need all CPU architecture of android devices. Because, each arch has its own calculation speed or technology. If there is any Co-Processors, you should take into consideration this also. This was a short overview about NDK.

For building or rebuilding native libraries you have two ways, CMake and NDK build. There are not lots of differences between these two building system, so i'd like to explain my answer with NDK building.

For native development, you should have main/jni folder which is you should put your libraries and native sources inside it and build them in this folder. Before you should create two files, Android.mk and Application.mk.
Android.mk is for building native libs (modules), adding flags and etc. You can build static and shared libraries in Android.mk. When you build your C sources, it creates static library (.a). But these libraries not for using in Java side. You can only use them for creating shared libraries (.so). For this, you should build your C++ sources, and if you want, you can add your static libraries to this.

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

ifneq (,$(filter $(TARGET_ARCH_ABI), armeabi-v7a x86 arm64-v8a x86_64))

LOCAL_MODULE := myLibrary

LOCAL_SHARED_LIBRARIES := cpufeatures opencv_imgproc opencv_core

LOCAL_C_INCLUDES := $(LOCAL_PATH)/c-files

LOCAL_SRC_FILES := $(LOCAL_PATH)/myJni.cpp

include $(BUILD_SHARED_LIBRARY)

--- 1st line returns main/jni path.

--- 2nd line clear all old LOCAL_*** variables.

--- 3th line build modules for each arch's which are declared there.

--- 4th line shows module name, when you build it, NDK automatically add lib and .so extensions to it (libmyLibrary.so).

--- 5th line adds other shared libraries, which you need their sources in your native sources.

--- 6th line adds C files to your module.

--- 7th line shows your C++ sources which you try to build.

--- 8th line is building command.

In Application.mk you can give commands something like, your project in release mode or debug mode. And you should give arch's in this file. For example APP_ABI := armeabi-v7a x86 arm64-v8a x86_64  and etc.

When you try to build libraries and use them in java side, you should do some operations.

Check your ndk path in local.properties file in project folder. It shows ndk-bundle path for building makefiles.

ndk.dir=/Users/../Library/Android/sdk/ndk-bundle

Check build scripts in gradle file. This script shows where shared libs should be located:

sourceSets.main {
    jni.srcDirs = []
    jniLibs.srcDir 'src/main/libs'
}

And show your makefile path to gradle.

externalNativeBuild {
   ndkBuild {
      path 'src/main/jni/Android.mk'
   }
}

I think my answer will help you for understanding some details. For addition, you can take a look these answers also.

For calling native methods: Enter

For linking shared libraries: Enter

Enjoy!


问:
Can't append child to clicked element
I'm trying to attach div to an element when it is clicked however when I use .appendChild(div), the element I'm trying to attach to is undefined. I'm pretty confused because it's clearly in the DOM as I'm able to detect the click on it, I just can't append to it.</p>

```<code>var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function () {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       pcells[i].appendChild(div);
  };
}
</code>```

答:
You have a scoping issue. You need to pass in the event details into your handler and use the target property to identify which cell was clicked.

```<code>var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function (e) {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       e.target.appendChild(div);
  };
}
</code>```

(JSFiddle: https://jsfiddle.net/z3nhprzp/)

Title: Can't append child to clicked element

Body:
I'm trying to attach div to an element when it is clicked however when I use .appendChild(div), the element I'm trying to attach to is undefined. I'm pretty confused because it's clearly in the DOM as I'm able to detect the click on it, I just can't append to it.

var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function () {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       pcells[i].appendChild(div);
  };
}

Body:
You have a scoping issue. You need to pass in the event details into your handler and use the target property to identify which cell was clicked.

var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function (e) {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       e.target.appendChild(div);
  };
}

(JSFiddle: https://jsfiddle.net/z3nhprzp/)


问:
Swift : alamofire post with json body
I'm using alarmofire to implement POST request.

The goal is to post as :

```<code>curl -X POST --header 'Content-Type: application/json'
     --header 'Accept: application/json' -d '{"dest":"Place","reason":"Reason","carId":1,"starttime":1496975475840,"departmentId":3,"distance":0.0,"driverId":1}'
     'http://localhost:8080/serviceCar/v1_0/placeOrder?access_token=25621648-1da5-438e-a52c-f927e2c59de4'
</code>```

The URL is http://localhost:8080/serviceCar/v1_0/placeOrder

And I have an order class, how can I post the object as request body and also send token as form data?

答:
Here is writen this case which you want.

In the event that the provided ParameterEncoding types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom JSONStringArrayEncoding type to encode a JSON string array onto a Request.

```<code>struct JSONStringArrayEncoding: ParameterEncoding {
    private let array: [String]

    init(array: [String]) {
        self.array = array
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        let data = try JSONSerialization.data(withJSONObject: array, options: [])

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = data

        return urlRequest
    }
}
</code>```

This is example of setting header of request[from doc]:

```<code>let user = "user"
let password = "password"

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}

Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers)
    .responseJSON { response in
        debugPrint(response)
    }
</code>```

Title: Swift : alamofire post with json body

Body:
I'm using alarmofire to implement POST request.

The goal is to post as :

curl -X POST --header 'Content-Type: application/json'
     --header 'Accept: application/json' -d '{"dest":"Place","reason":"Reason","carId":1,"starttime":1496975475840,"departmentId":3,"distance":0.0,"driverId":1}'
     'http://localhost:8080/serviceCar/v1_0/placeOrder?access_token=25621648-1da5-438e-a52c-f927e2c59de4'

The URL is http://localhost:8080/serviceCar/v1_0/placeOrder

And I have an order class, how can I post the object as request body and also send token as form data?

Body:
Here is writen this case which you want.

In the event that the provided ParameterEncoding types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom JSONStringArrayEncoding type to encode a JSON string array onto a Request.

struct JSONStringArrayEncoding: ParameterEncoding {
    private let array: [String]

    init(array: [String]) {
        self.array = array
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        let data = try JSONSerialization.data(withJSONObject: array, options: [])

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = data

        return urlRequest
    }
}

This is example of setting header of request[from doc]:

let user = "user"
let password = "password"

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}

Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers)
    .responseJSON { response in
        debugPrint(response)
    }


问:
Phalcon Volt, how to print translation with a variable
I'm using Phalcon with Volt for my multilanguage application.

I've setup a translation file which contains the following variables:

```<code>'numbervalidation-field' => '%field% is a number',
'Teams' => 'Teams',
</code>```

And this is how I print 'Teams is a number' correctly

```<code><?php echo $t->_("numbervalidation-field", array("field" => $t->_('Teams'))); ?>
</code>```

I just want to be able to print the same using volt, I've tried several things but nothing works, this was my latest attempt:

```<code>{{t['numbervalidation-field', ['field': t['Teams']]]}}
</code>```

Help please, I couldn't find how to do this.

答:
You can use a filter for ease of use, assuming your Translation service is $di->t, that would read:

```<code>$volt->getCompiler()->addFilter('trans', function ($resolvedArgs, $exprArgs) {
    return sprintf('$this->t->query(%s)', $resolvedArgs);
});
</code>```

Then, in the volt template, you can do:

```<code>{{ 'name'|trans }}
</code>```

In your case, you'll have two translations, so it could read:

```<code>{{ 'numbervalidation-field'|trans({'field': ('Teams'|trans)}) }}
</code>```

Body:
I'm using Phalcon with Volt for my multilanguage application.

I've setup a translation file which contains the following variables:

'numbervalidation-field' => '%field% is a number',
'Teams' => 'Teams',

And this is how I print 'Teams is a number' correctly

<?php echo $t->_("numbervalidation-field", array("field" => $t->_('Teams'))); ?>

I just want to be able to print the same using volt, I've tried several things but nothing works, this was my latest attempt:

{{t['numbervalidation-field', ['field': t['Teams']]]}}

Help please, I couldn't find how to do this.

Body:
You can use a filter for ease of use, assuming your Translation service is $di->t, that would read:

$volt->getCompiler()->addFilter('trans', function ($resolvedArgs, $exprArgs) {
    return sprintf('$this->t->query(%s)', $resolvedArgs);
});

Then, in the volt template, you can do:

{{ 'name'|trans }}

In your case, you'll have two translations, so it could read:

{{ 'numbervalidation-field'|trans({'field': ('Teams'|trans)}) }}


问:
What am I doing wrong with boost::interprocess::message_queue?
I've created a boost::message_queue by the following way:

```<code>namespace bipc = boost::interprocess;

...

try {
    bipc::message_queue::remove("EDBA90AC-289D-4825-98D9-F85185041676");

    // The below throws exception, no matter what's the name of the queue...

    boost::shared_ptr<bipc::message_queue> mq(new bipc::message_queue(bipc::create_only, "EDBA90AC-289D-4825-98D9-F85185041676", 32767, 256));

    ...
} catch (std::exception &e) {
    std::cout << "exception: " << e.what() << std::endl;
}
</code>```

Now, I cannot get it to work, since the mq-creation throws every time the following exception

```exception: invalid string position```

This used to work fine with Boost version prior to 1.42, but not anymore. The documentation of Boost's message_queue hasn't changed, so no help from there. What am I doing wrong here?

答:
You cannot name an interprocess mechanism with '-' inside. It's written in the documentation:</p>

```<code>* Starts with a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples: Sharedmemory, sharedmemory, sHaReDmEmOrY...
* Can include letters, underscore, or digits. Examples: shm1, shm2and3, ShM3plus4...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've created a boost::message_queue by the following way:

namespace bipc = boost::interprocess;

...

try {
    bipc::message_queue::remove("EDBA90AC-289D-4825-98D9-F85185041676");

    // The below throws exception, no matter what's the name of the queue...

    boost::shared_ptr<bipc::message_queue> mq(new bipc::message_queue(bipc::create_only, "EDBA90AC-289D-4825-98D9-F85185041676", 32767, 256));

    ...
} catch (std::exception &e) {
    std::cout << "exception: " << e.what() << std::endl;
}

Now, I cannot get it to work, since the mq-creation throws every time the following exception

exception: invalid string position

This used to work fine with Boost version prior to 1.42, but not anymore. The documentation of Boost's message_queue hasn't changed, so no help from there. What am I doing wrong here?

Body:
You cannot name an interprocess mechanism with '-' inside. It's written in the documentation:

* Starts with a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples: Sharedmemory, sharedmemory, sHaReDmEmOrY...
* Can include letters, underscore, or digits. Examples: shm1, shm2and3, ShM3plus4...


问:
How to combine stdin and file for formatted output in sed or awk?
I need to find a single line of code, I think SED or AWK would be the best tools, to take two inputs (one stdin, one file) and combine them to output one formatted line to stdout.

stdin data: 20170607233000 wind0 180 1 2 3

file data: 270

output needed: 270 1 2 3
(replace the 180 with 270 from file, drop the timestamp and wind0 "name")

I have this line of code:

```<code>awk ‘ { printf "%d %d %d %d", $7, $4, $5, $6 }’ - heading.txt
</code>```

but it processes stdin and heading.txt and independent inputs and provides two outputs.

I also found this example of code, and it gets close to what I want but I don't understand how to format/reorder the output:

```<code>awk ’FNR==NR { a[FNR""] = $0; next } { print a[FNR""], $0 }'
</code>```

Here's the context in case you care: This is for a weather station sitting on a (large) boat. The wind direction always reports relative to the boat, typically reporting North, but that's not accurate. The boat pivots on a single anchor point and always faces in to the wind. I have a magnetometer (compass) hooked to the RaspberryPi that is the weather station and reads the heading the boat is facing and writes it to a file via cron. This makes the boat in to a giant wind vane. I need to take the heading data from the file and replace the wind direction with the "real" value. The weather station code is nice enough to allow me to create a "virtual" gauge based on other gauges and insert code via a cgi script. The limitation is that the code has to be a single line that can be executed in the linux shell and return data via stdout.

答:
You can't read from stdin and file unless you refer to stdin as - or /dev/stdin so first read in the value from the file and store it to a var. Then read the data from stdin and output:

```<code>$ echo 20170607233000 wind0 180 1 2 3 | awk 'NR==FNR{b=$1;next}{print b, $4,$5,$6}' file -
270 1 2 3
</code>```

Body:
I need to find a single line of code, I think SED or AWK would be the best tools, to take two inputs (one stdin, one file) and combine them to output one formatted line to stdout.

stdin data: 20170607233000 wind0 180 1 2 3

file data: 270

output needed: 270 1 2 3
(replace the 180 with 270 from file, drop the timestamp and wind0 "name")

I have this line of code:

awk ‘ { printf "%d %d %d %d", $7, $4, $5, $6 }’ - heading.txt

but it processes stdin and heading.txt and independent inputs and provides two outputs.

I also found this example of code, and it gets close to what I want but I don't understand how to format/reorder the output:

awk ’FNR==NR { a[FNR""] = $0; next } { print a[FNR""], $0 }'

Here's the context in case you care: This is for a weather station sitting on a (large) boat. The wind direction always reports relative to the boat, typically reporting North, but that's not accurate. The boat pivots on a single anchor point and always faces in to the wind. I have a magnetometer (compass) hooked to the RaspberryPi that is the weather station and reads the heading the boat is facing and writes it to a file via cron. This makes the boat in to a giant wind vane. I need to take the heading data from the file and replace the wind direction with the "real" value. The weather station code is nice enough to allow me to create a "virtual" gauge based on other gauges and insert code via a cgi script. The limitation is that the code has to be a single line that can be executed in the linux shell and return data via stdout.

Body:
You can't read from stdin and file unless you refer to stdin as - or /dev/stdin so first read in the value from the file and store it to a var. Then read the data from stdin and output:

$ echo 20170607233000 wind0 180 1 2 3 | awk 'NR==FNR{b=$1;next}{print b, $4,$5,$6}' file -
270 1 2 3


问:
c# Unit Testing errors
im trying to get familiar with unit testing , but I keep getting this annoying error and I have no idea why. I made a class that just divides 2 numbers.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DivideNum
{
    class Program
    {
        public static int doStuff(int num1, int num2)
        {
            int result = num1 / num2;
            return result;

        }
        static void Main(string[] args)
        {

        }
    }
}
</code>```

I then made my unit test

```<code>using DivideNum;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {

            //arrange
            int a = 10;
            int b = 2;
            int result = 5;

            //act

        }
    }
}
</code>```

i added a reference to my DivideNum namespace and added using DivideNum , but i still cant get a reference to the DivideNum class in my testing class. It wont show up at all in my testing code. why cant i use my DivideNum class in my Test class?

答:
The Program class does not have an access type so by default it is internal. Changing it to public should fix the job.

```<code>public class Program
{
   // Do stuff
}
</code>```

Title: c# Unit Testing errors

Body:
im trying to get familiar with unit testing , but I keep getting this annoying error and I have no idea why. I made a class that just divides 2 numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DivideNum
{
    class Program
    {
        public static int doStuff(int num1, int num2)
        {
            int result = num1 / num2;
            return result;

        }
        static void Main(string[] args)
        {

        }
    }
}

I then made my unit test

using DivideNum;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {

            //arrange
            int a = 10;
            int b = 2;
            int result = 5;

            //act

        }
    }
}

i added a reference to my DivideNum namespace and added using DivideNum , but i still cant get a reference to the DivideNum class in my testing class. It wont show up at all in my testing code. why cant i use my DivideNum class in my Test class?

Body:
The Program class does not have an access type so by default it is internal. Changing it to public should fix the job.

public class Program
{
   // Do stuff
}


问:
scraping website with login page
I currently login to the time from website using the following script.

```<code>browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()
</code>```

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?

答:
You can use mechanize, it took me 3.22 seconds in my old notebook to login and parse the site.

```<code>from mechanize import Browser
import time    #just to check elapsed time and check performance
started_time = time.time()

browser = Browser()
url = 'https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F'
browser.open(url)
browser.select_form(nr = 0)
browser["EmailAddress"] = 'putyouremailhere'
browser["Password"] = 'p4ssw0rd'

logged = browser.submit()
redirected_url = logged.read()
print redirected_url

#you can delete this section:
elapsed_time = time.time() - started_time
print elapsed_time,' seconds'
</code>```

I hope it helps! :)

Title: scraping website with login page

Body:
I currently login to the time from website using the following script.

browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?

Body:
You can use mechanize, it took me 3.22 seconds in my old notebook to login and parse the site.

from mechanize import Browser
import time    #just to check elapsed time and check performance
started_time = time.time()

browser = Browser()
url = 'https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F'
browser.open(url)
browser.select_form(nr = 0)
browser["EmailAddress"] = 'putyouremailhere'
browser["Password"] = 'p4ssw0rd'

logged = browser.submit()
redirected_url = logged.read()
print redirected_url

#you can delete this section:
elapsed_time = time.time() - started_time
print elapsed_time,' seconds'

I hope it helps! :)


问:
What is the runtime complexity of a switch statement?
I'd like to know what the worst-case runtime complexity of a switch statement is, assuming you have n cases.

I always assumed it was O(n). I don't know if compilers do anything clever, though. If the answer is implementation-specific, I'd like to know for the following languages:

Java

C/C++

C#

PHP

Javascript

答:
The big-O complexity of a switch statement is not really the important point. Big-O notation refers to the performance as n increases towards infinity. If you have a switch statement big enough that the asymptotic performance is an issue then it is too big and should be refactored.

Apart from the readability issue, in Java and C# I think you would soon hit some internal limits for the maximum size of a single method.

For relatively small switch statements that are called often it would probably be more informative to measure the actual performance of the switch statement against other approaches that you could use instead. This measurement could be made by repeatedly performing the operation in a loop.

For larger switch statements I'd suggest refactoring to use a dictionary or similar data structure that has approximately O(1) performance even has n gets very large and it won't run into problems with the limited method size.


问:
Scripting for file management with a very large amount of files
I have a three OSX machine setup that was using syncthing to keep shared drives synchronized remotely.  Someone made some mistakes and a lot of files ended up getting renamed.

So all throughout this drive I have situations where there's a file of size 0KB named,for example, file.jpg and another file with real size named
file.sync-confilct201705-4528.jpg.  I need to search the entire drive recursively and while I find a file with the sync-conflict string in it, check to see if there is the same file without the 'sync-conflict' string along with a size of 0KB.  If there is, I need to rename the sync-conflict file to overwrite the 0KB file.

I have considered tackling this with a bash script or a Perl script.  Using bash I think just using the 'find' command with -regex would get me started but I don't really know how to process the results and run the next find test.  I am studying and working on it.

Same problem with Perl. I can get through the first step using File::Find:find and select what I need using regex to filter out the files, but there again I am stuck getting to the next step, which would be finding the original file in the same directory and performing the necessary file move function.

In both of these cases I am willing to put in the time to figure it out, but I wonder what the caveats will be?  Can both of these scenarios handle recursing a large number of files without exception?  Is there perhaps a better approach anyone can recommend?

答:
One good tool in Perl for this is File::Find::Rule.

Find all sync-conflict files, then test whether corresponding files exist and are zero size

```<code>use warnings;
use strict;
use FindBin qw($RealBin);
use File::Copy qw(move);
use File::Find::Rule;

my $dir = shift || '.';  # top of hierarchy to search (from command line, or ./)

my @conflict_files = File::Find::Rule
    ->file->name('*sync-conflict*.jpg')->in($dir);

foreach my $conflict (@conflict_files)
{
    my ($file) = $conflict =~ m|(.*)\.sync-conflict|;
    $file .= '.jpg';

    if (-z "$RealBin/$file") {
        print "Rename $conflict to $file\n"
        #move($conflict, $file) or warn "Can't move $conflict to $file: $!";
    }
 }
</code>```

This builds the file's name file for each file.sync-conflict file and applies -z file test (-X), which tests for both existence and zero size. Then it renames the file using the core File::Copy.

Note that file-test operators need the full path while File::Find::Rule returns the path relative to the $dir it searches. I use $RealBin provided by FindBin, which is the path to the directory where the script was started with all links resolved,  to build the full path for -z.

Uncomment the move line after sufficient testing (and with having made a backup first).

The code makes some assumptions about file names, please adjust as needed.
The $dir supplied on the command line is expected to be relative to the script's directory.

Body:
One good tool in Perl for this is File::Find::Rule.

Find all sync-conflict files, then test whether corresponding files exist and are zero size

use warnings;
use strict;
use FindBin qw($RealBin);
use File::Copy qw(move);
use File::Find::Rule;

my $dir = shift || '.';  # top of hierarchy to search (from command line, or ./)

my @conflict_files = File::Find::Rule
    ->file->name('*sync-conflict*.jpg')->in($dir);

foreach my $conflict (@conflict_files)
{
    my ($file) = $conflict =~ m|(.*)\.sync-conflict|;
    $file .= '.jpg';

    if (-z "$RealBin/$file") {
        print "Rename $conflict to $file\n"
        #move($conflict, $file) or warn "Can't move $conflict to $file: $!";
    }
 }

This builds the file's name file for each file.sync-conflict file and applies -z file test (-X), which tests for both existence and zero size. Then it renames the file using the core File::Copy.

Note that file-test operators need the full path while File::Find::Rule returns the path relative to the $dir it searches. I use $RealBin provided by FindBin, which is the path to the directory where the script was started with all links resolved,  to build the full path for -z.

Uncomment the move line after sufficient testing (and with having made a backup first).

The code makes some assumptions about file names, please adjust as needed.
The $dir supplied on the command line is expected to be relative to the script's directory.


问:
Is it possible to deploy an ASP.NET Web Forms website without building
Just wondering if it is possible to deploy an ASP.NET Web Forms website to AWS without building as I started maintaining a disordered project with too many errors and I'm almost new to ASP.NET.</p>

答: Yes you can do this by adding your website in IIS.</p>


问:
XML Fragment event bindings to controller not working
I have a Problem with my UI5 application and a simple form. As displayed in the examples of the explored app.

The scenario there is that pressing edit replaces the content of the page with the other SimpleForm of the fragment (codebehind in the controllers).

I do the same; the only difference is that I just replace the content of the SimpleForm with the Controls stored in the XML fragment.

Now I have a Button, which click event should be bound to the underlying controller. But when you do this in codebehind the events on the controller are not fired anymore. It worked when I was using the fragment in my xml view definition file, but now it does not.

```<code>controllerModelPropertyChanged(oEvent: sap.ui.base.Event) {
            let cdata = (oEvent.getSource() as any).getData() as agenttemplatesdetailcontroller;
            let p = this.byId("form") as sap.ui.layout.form.SimpleForm;
            for(let c of p.getContent())
                c.destroy();
            p.removeAllContent();
            let f = sap.ui.xmlfragment("ifm.datalink.linerecorder.ams.frontend.view.fragments.agentTemplates."+ (cdata.edit ? "AgentTemplateDetailsEdit" : "AgentTemplateDetailsDisplay")) as sap.ui.core.Control[];
            f.forEach((v) => { p.addContent(v); });
        }
</code>```

Are bound events to the controller not bound when adding the control? Do I have to bind them manually?

EDIT:

Display Fragment:

```<code><core:FragmentDefinition
        xmlns="sap.m"
        xmlns:core="sap.ui.core"
        xmlns:u="sap.ui.unified">
      <Label text="{i18n>templates.details.name}"/>
      <Text text="{template>/Name}" enabled="{form>/enabled}"/>
      <Label text="{i18n>templates.details.description}"/>
      <Text text="{template>/Description}" editable="{form>/enabled}"/>
      <List headerText="{i18n>templates.details.versionsTitle}" items="{template>/Versions}">
        <CustomListItem>
          <HBox>
            <Label text="{template>Version/Major}.{template>Version/Minor}.{template>Version/Build}"/>
            <Label text=" ({parts: [{path: 'template>CreationDate', type: 'sap.ui.model.odata.type.Date'}, {path: 'i18n>global.dateformat', type: 'sap.ui.model.type.String'}], formatter: '.odatadateformatter'})"/>
            <Label text="{ams>Guarantor/username}"/>
          </HBox>
          </CustomListItem>
      </List>
</core:FragmentDefinition>
</code>```

Edit Fragment:

```<code><core:FragmentDefinition
        xmlns="sap.m"
        xmlns:core="sap.ui.core"
        xmlns:u="sap.ui.unified">
      <Label text="Name"/>
      <Input value="{template>/Name}" enabled="{form>/enabled}"/>
      <Label text="Description"/>
      <TextArea value="{template>/Description}" editable="{form>/enabled}"/>
      <Label text="Upload new Version"/>
      <u:FileUploader id="fileUploader" name="MyFileUpload" uploadUrl="http://localhost:13917/api/fileupload/uploadfile" tooltip="Upload your file to the local server" uploadComplete="handleUploadComplete"/>
      <Button   text="Upload File" press="AddNewTemplateVersion"/>
      <List headerText="{i18n>templates.details.versionsTitle}" items="{template>/Versions}">
        <CustomListItem>
          <HBox>
            <Label text="{template>Version/Major}.{template>Version/Minor}.{template>Version/Build}"/>
            <Label text=" ({parts: [{path: 'template>CreationDate', type: 'sap.ui.model.odata.type.Date'}, {path: 'i18n>global.dateformat', type: 'sap.ui.model.type.String'}],
                            formatter: '.odatadateformatter'})"/>
            <!--<Label text="{ams>Guarantor/username}"/>-->
          </HBox>
          </CustomListItem>
      </List>
  </core:FragmentDefinition>
</code>```

View:

```<code><mvc:View
        controllerName="ifm.datalink.linerecorder.ams.frontend.controller.agentTemplates.AgentTemplatesDetail"
        xmlns="sap.m"
        xmlns:core="sap.ui.core"
        xmlns:commons="sap.ui.commons"
        xmlns:f="sap.ui.layout.form"
        xmlns:l="sap.ui.layout"
        xmlns:mvc="sap.ui.core.mvc">
  <f:SimpleForm
            class="lra5form"
            minWidth="500"
            maxContainerCols="2"
            layout="ResponsiveGridLayout"
            title="{i18n>templates.details.title}"
            editable="{controller>/edit}"
            labelSpanL="3"
            labelSpanM="3"
            emptySpanL="4"
            emptySpanM="4"
            columnsL="1"
            columnsM="1"
            id="form">
    <f:toolbar>
      <Toolbar>
        <Button text="{i18n>templates.details.edit}" icon="sap-icon://edit" enabled="{= !${controller>/edit}}" press="onEditPressed" />
        <Button text="{i18n>templates.details.delete}" icon="sap-icon://delete" press="onDelete" visible="{= !${controller>/edit}}" />
        <ToolbarSpacer/>
        <Button text="{i18n>global.accept}" icon="sap-icon://accept" press="onAcceptClicked" visible="{controller>/edit}" enabled="{controller>/changed}"/>
        <Button text="{i18n>global.cancel}" icon="sap-icon://cancel" press="onCancelClicked" visible="{controller>/edit}" />
      </Toolbar>
    </f:toolbar>
    <f:content>
      <core:Fragment fragmentName="ifm.datalink.linerecorder.ams.frontend.view.fragments.agentTemplates.AgentTemplateDetailsDisplay" type="XML"/>
    </f:content>
  </f:SimpleForm>
</mvc:View>
</code>```

答:
You should add a reference to the controller to handle the callback.

Example:

this._oDialog = sap.ui.xmlfragment("sap.ui.demo.wt.view.HelloDialog", this);

Here's a link to the fragment callback documentation: (https://help.sap.com/viewer/0ce0b8c56fa74dd897fffda8407e8272/7.5.5/en-US/354f98ed2b514ba9960556333428d35e.html)

Body:
I have a Problem with my UI5 application and a simple form. As displayed in the examples of the explored app.

The scenario there is that pressing edit replaces the content of the page with the other SimpleForm of the fragment (codebehind in the controllers).

I do the same; the only difference is that I just replace the content of the SimpleForm with the Controls stored in the XML fragment.

Now I have a Button, which click event should be bound to the underlying controller. But when you do this in codebehind the events on the controller are not fired anymore. It worked when I was using the fragment in my xml view definition file, but now it does not.

controllerModelPropertyChanged(oEvent: sap.ui.base.Event) {
            let cdata = (oEvent.getSource() as any).getData() as agenttemplatesdetailcontroller;
            let p = this.byId("form") as sap.ui.layout.form.SimpleForm;
            for(let c of p.getContent())
                c.destroy();
            p.removeAllContent();
            let f = sap.ui.xmlfragment("ifm.datalink.linerecorder.ams.frontend.view.fragments.agentTemplates."+ (cdata.edit ? "AgentTemplateDetailsEdit" : "AgentTemplateDetailsDisplay")) as sap.ui.core.Control[];
            f.forEach((v) => { p.addContent(v); });
        }

Are bound events to the controller not bound when adding the control? Do I have to bind them manually?

EDIT:

Display Fragment:

<core:FragmentDefinition
        xmlns="sap.m"
        xmlns:core="sap.ui.core"
        xmlns:u="sap.ui.unified">
      templates.details.name}"/>
      <Text text="{template>/Name}" enabled="{form>/enabled}"/>
      templates.details.description}"/>
      <Text text="{template>/Description}" editable="{form>/enabled}"/>
      <List headerText="{i18n>templates.details.versionsTitle}" items="{template>/Versions}">
        <CustomListItem>
          <HBox>
            Version/Major}.{template>Version/Minor}.{template>Version/Build}"/>
            CreationDate', type: 'sap.ui.model.odata.type.Date'}, {path: 'i18n>global.dateformat', type: 'sap.ui.model.type.String'}], formatter: '.odatadateformatter'})"/>
            Guarantor/username}"/>
          </HBox>
          </CustomListItem>
      </List>
</core:FragmentDefinition>

Edit Fragment:

<core:FragmentDefinition
        xmlns="sap.m"
        xmlns:core="sap.ui.core"
        xmlns:u="sap.ui.unified">

      <Input value="{template>/Name}" enabled="{form>/enabled}"/>

      <TextArea value="{template>/Description}" editable="{form>/enabled}"/>

      <Button   text="Upload File" press="AddNewTemplateVersion"/>
      <List headerText="{i18n>templates.details.versionsTitle}" items="{template>/Versions}">
        <CustomListItem>
          <HBox>
            Version/Major}.{template>Version/Minor}.{template>Version/Build}"/>
            CreationDate', type: 'sap.ui.model.odata.type.Date'}, {path: 'i18n>global.dateformat', type: 'sap.ui.model.type.String'}],
                            formatter: '.odatadateformatter'})"/>

          </HBox>
          </CustomListItem>
      </List>
  </core:FragmentDefinition>

View:

<mvc:View
        controllerName="ifm.datalink.linerecorder.ams.frontend.controller.agentTemplates.AgentTemplatesDetail"
        xmlns="sap.m"
        xmlns:core="sap.ui.core"
        xmlns:commons="sap.ui.commons"
        xmlns:f="sap.ui.layout.form"
        xmlns:l="sap.ui.layout"
        xmlns:mvc="sap.ui.core.mvc">
  <f:SimpleForm
            class="lra5form"
            minWidth="500"
            maxContainerCols="2"
            layout="ResponsiveGridLayout"
            title="{i18n>templates.details.title}"
            editable="{controller>/edit}"
            labelSpanL="3"
            labelSpanM="3"
            emptySpanL="4"
            emptySpanM="4"
            columnsL="1"
            columnsM="1"
            id="form">
    <f:toolbar>
      <Toolbar>
        <Button text="{i18n>templates.details.edit}" icon="sap-icon://edit" enabled="{= !${controller>/edit}}" press="onEditPressed" />
        <Button text="{i18n>templates.details.delete}" icon="sap-icon://delete" press="onDelete" visible="{= !${controller>/edit}}" />
        <ToolbarSpacer/>
        <Button text="{i18n>global.accept}" icon="sap-icon://accept" press="onAcceptClicked" visible="{controller>/edit}" enabled="{controller>/changed}"/>
        <Button text="{i18n>global.cancel}" icon="sap-icon://cancel" press="onCancelClicked" visible="{controller>/edit}" />
      </Toolbar>
    </f:toolbar>
    <f:content>
      <core:Fragment fragmentName="ifm.datalink.linerecorder.ams.frontend.view.fragments.agentTemplates.AgentTemplateDetailsDisplay" type="XML"/>
    </f:content>
  </f:SimpleForm>
</mvc:View>


问:
Firebase Reference Query on Root
I am working on a student-teacher private messenger application using Firebase and I can insert data inside the root like this:

The usernames are retrived from a MySQL database, so I just only need to make a query. I would like to get only the data inside a ListView where chatID equals to my generated ID. I've searched in a lot of places like here but can't make the DatabaseReference working. Here is my code:

```<code>private void displayStudentChatMessages() {
    listofMessages = (ListView) findViewById(R.id.list_msg);

    adapter = new FirebaseListAdapter<BubbleMessageStudent>(this, BubbleMessageStudent.class, R.layout.item_chat_right, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, BubbleMessageStudent model, int position) {
            TextView studentUsername = (TextView) v.findViewById(R.id.message_user_sender);
            TextView studentMessage = (TextView) v.findViewById(R.id.message_user);
            TextView studentSentDate = (TextView) v.findViewById(R.id.message_usertime);

            studentUsername.setText(model.getStudentUsername());
            studentMessage.setText(model.getStudentMessage());

            studentSentDate.setText(android.text.format.DateFormat.format("yyyy-MM-dd%n(HH:mm:ss)", model.getStudentMessageTime()));
        }
    };

    listofMessages.setAdapter(adapter);
    listofMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}
</code>```

答:
As @cricket_007 commented, you'll need a query to get the chat messages with the correct ID:

```<code>rootRef = FirebaseDatabase.getInstance().getReference();
chatQuery = rootRef.orderByChild("chatID").equalTo("teststudent-testteacher...");
adapter = new FirebaseListAdapter<BubbleMessageStudent>(
  this, BubbleMessageStudent.class, R.layout.item_chat_right, chatQuery)...
</code>```

With this code your adapter will only show the messages with the correct chatID.

But in general your data model seems suboptimal. You've essentially mapped a table from your MySQL database into a node in Firebase. It probably works for now, but there are better ways to do this mapping.

In Firebase (and many other NoSQL databases) you should model your data for what you show on the screen. So if your app shows a chat room, which is a list of messages with the same chatID, then you should model precisely that in the database: a list of messages with the same chat ID:

```<code>chatId1
  chat1Message1: ...
  chat1Message2: ...
  chat1Message3: ...
chatId2
  chat2Message1: ...
  chat2Message2: ...
  chat2Message3: ...
</code>```

With this structure you don't need a query to read the messages for a specific chat room. Instead you can directly access the node where they're under:

```<code>chatRoom = rootRef.child("teststudent-testteacher...");
adapter = new FirebaseListAdapter<BubbleMessageStudent>(
  this, BubbleMessageStudent.class, R.layout.item_chat_right, chatRoom)...
</code>```

This results in much better scalability.

I recommend reading NoSQL data modeling and watching Firebase for SQL developers.

Title: Firebase Reference Query on Root

Body:
I am working on a student-teacher private messenger application using Firebase and I can insert data inside the root like this:

The usernames are retrived from a MySQL database, so I just only need to make a query. I would like to get only the data inside a ListView where chatID equals to my generated ID. I've searched in a lot of places like here but can't make the DatabaseReference working. Here is my code:

private void displayStudentChatMessages() {
    listofMessages = (ListView) findViewById(R.id.list_msg);

    adapter = new FirebaseListAdapter<BubbleMessageStudent>(this, BubbleMessageStudent.class, R.layout.item_chat_right, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, BubbleMessageStudent model, int position) {
            TextView studentUsername = (TextView) v.findViewById(R.id.message_user_sender);
            TextView studentMessage = (TextView) v.findViewById(R.id.message_user);
            TextView studentSentDate = (TextView) v.findViewById(R.id.message_usertime);

            studentUsername.setText(model.getStudentUsername());
            studentMessage.setText(model.getStudentMessage());

            studentSentDate.setText(android.text.format.DateFormat.format("yyyy-MM-dd%n(HH:mm:ss)", model.getStudentMessageTime()));
        }
    };

    listofMessages.setAdapter(adapter);
    listofMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}

Body:
As @cricket_007 commented, you'll need a query to get the chat messages with the correct ID:

rootRef = FirebaseDatabase.getInstance().getReference();
chatQuery = rootRef.orderByChild("chatID").equalTo("teststudent-testteacher...");
adapter = new FirebaseListAdapter<BubbleMessageStudent>(
  this, BubbleMessageStudent.class, R.layout.item_chat_right, chatQuery)...

With this code your adapter will only show the messages with the correct chatID.

But in general your data model seems suboptimal. You've essentially mapped a table from your MySQL database into a node in Firebase. It probably works for now, but there are better ways to do this mapping.

In Firebase (and many other NoSQL databases) you should model your data for what you show on the screen. So if your app shows a chat room, which is a list of messages with the same chatID, then you should model precisely that in the database: a list of messages with the same chat ID:

chatId1
  chat1Message1: ...
  chat1Message2: ...
  chat1Message3: ...
chatId2
  chat2Message1: ...
  chat2Message2: ...
  chat2Message3: ...

With this structure you don't need a query to read the messages for a specific chat room. Instead you can directly access the node where they're under:

chatRoom = rootRef.child("teststudent-testteacher...");
adapter = new FirebaseListAdapter<BubbleMessageStudent>(
  this, BubbleMessageStudent.class, R.layout.item_chat_right, chatRoom)...

This results in much better scalability.

I recommend reading NoSQL data modeling and watching Firebase for SQL developers.


问:
Cant install Grandnode
when I try to install grandnode, it gives me this error.

A timeout occured after 30000ms selecting a server using
  CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{
  ReadPreference = { Mode : Primary } }, LatencyLimitingServerSelector{
  AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster
  state is { ClusterId : "1", ConnectionMode : "Automatic", Type :
  "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId
  : 1, EndPoint : "123.223.223.11:27111" }", EndPoint:
  "123.223.223.11:27111", State: "Disconnected", Type: "Unknown",
  HeartbeatException: "MongoDB.Driver.MongoConnectionException: An
  exception occurred while opening a connection to the server. --->
  MongoDB.Driver.MongoAuthenticationException: Unable to authenticate
  username 'testing' on database 'grandnodetest'. --->
  MongoDB.Driver.MongoCommandException: Command authenticate failed:
  auth fails. at
  MongoDB.Driver.Core.WireProtocol.CommandWireProtocol1.ProcessReply(ConnectionId
  connectionId, ReplyMessage1 reply) at
  MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.d__11.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at
  MongoDB.Driver.Core.Authentication.MongoDBCRAuthenticator.d__7.MoveNext()
  --- End of inner exception stack trace --- at MongoDB.Driver.Core.Authentication.MongoDBCRAuthenticator.d__7.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at
  MongoDB.Driver.Core.Authentication.AuthenticationHelper.d__1.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at
  MongoDB.Driver.Core.Connections.ConnectionInitializer.d__3.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at
  MongoDB.Driver.Core.Connections.BinaryConnection.d__48.MoveNext()
  --- End of inner exception stack trace --- at MongoDB.Driver.Core.Connections.BinaryConnection.d__48.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task
  task) at
  MongoDB.Driver.Core.Servers.ServerMonitor.d__27.MoveNext()"
  }] }

can anyone help me with this? I am running the project from local.

Please and Thank you.

答: You are using an older version of MongoDB than is supported by your application. Please use MongoDB version 3.0 or higher and try again. If the problem happens again, please reach out to me on our support. </p>

Title: Cant install Grandnode


问:
Trigger jquery tab active by data-tab
I've checked around in here, but not found my answer. I have my code below:

```<code><div class="gdlr-session-item gdlr-tab-session-item gdlr-item">
<div class="gdlr-session-item-head">
<div class="gdlr-session-item-head-info gdlr-active" data-tab="gdlr-tab-1">
<div class="gdlr-session-head-day">Day 1</div>
<div class="gdlr-session-head-date">23 May 2016</div>
</div>

<div class="gdlr-session-item-head-info" data-tab="gdlr-tab-2">
<div class="gdlr-session-head-day">Day 2</div>
<div class="gdlr-session-head-date">24 May 2016</div>
</div>

<div class="gdlr-session-item-tab-content gdlr-tab-1 gdlr-active" style="display: block;">
Content here
</div>
<div class="gdlr-session-item-tab-content gdlr-tab-2" style="display: none;">
Content here
</div>
</div>
</div>
</code>```

Jquery code:

```<code>// script for session tab item
    $('.gdlr-session-item-head-info').click(function(){
    if( $(this).hasClass('gdlr-active') ) return;
    $(this).siblings().removeClass('gdlr-active');
    $(this).addClass('gdlr-active');

    var selected_tab = $(this).attr('data-tab');
    $(this).parent('.gdlr-session-item-head').siblings('.gdlr-session-item-tab-content').hide();
    $(this).parent('.gdlr-session-item-head').siblings('.' + selected_tab).fadeIn();
});
</code>```

In the default, The day 1 will active and show the content from class: gdlr-tab-1.

I need help to active the day 2 instead day 1. Thank so much for all help!

Live demo: http://goodlayers.tienloc.net/keynote/.

答:
Check if below code helps.

You can hide all the content div first and then can show (fade in) the required div using the data attr, same applies to add and remove active class.

```<code>$('.gdlr-session-item-head-info').click(function(){
  if( $(this).hasClass('gdlr-active') ) return;
  $('.gdlr-active').removeClass('gdlr-active');
  $(this).addClass('gdlr-active');

  var selected_tab = $(this).attr('data-tab');
  $(".gdlr-session-item-tab-content").hide();
  $("."+selected_tab).addClass('gdlr-active');
  $("."+selected_tab).fadeIn();
});
</code>```

Title: Trigger jquery tab active by data-tab

Body:
I've checked around in here, but not found my answer. I have my code below:

Day 1

23 May 2016

Day 2

24 May 2016

Content here

Content here

Jquery code:

// script for session tab item
    $('.gdlr-session-item-head-info').click(function(){
    if( $(this).hasClass('gdlr-active') ) return;
    $(this).siblings().removeClass('gdlr-active');
    $(this).addClass('gdlr-active');

    var selected_tab = $(this).attr('data-tab');
    $(this).parent('.gdlr-session-item-head').siblings('.gdlr-session-item-tab-content').hide();
    $(this).parent('.gdlr-session-item-head').siblings('.' + selected_tab).fadeIn();
});

In the default, The day 1 will active and show the content from class: gdlr-tab-1.

I need help to active the day 2 instead day 1. Thank so much for all help!

Live demo: http://goodlayers.tienloc.net/keynote/.

Body:
Check if below code helps.

You can hide all the content div first and then can show (fade in) the required div using the data attr, same applies to add and remove active class.

$('.gdlr-session-item-head-info').click(function(){
  if( $(this).hasClass('gdlr-active') ) return;
  $('.gdlr-active').removeClass('gdlr-active');
  $(this).addClass('gdlr-active');

  var selected_tab = $(this).attr('data-tab');
  $(".gdlr-session-item-tab-content").hide();
  $("."+selected_tab).addClass('gdlr-active');
  $("."+selected_tab).fadeIn();
});


问:
How to properly position bootstrap html divs
I want to properly align the controls within bootstrap divs, so that they look like

Currently there is a lot of gap between the rows and margin-bottom or padding doesnot seem to work. Also, how do i expand the list box to completely cover the length of screen? It looks like this

HTML

```<code>  <div class="row" style="margin-left: 5px; margin-right: 5px">
    <div class="table">
        <div class="row" style="margin-top:0px; padding-top:0px; border:dotted">
            <div style="float: left; margin-left:10px;">
                @Html.ListBoxFor(m => m.cM.CategoryList, new SelectList(Model.cM.CategoryList, "CategoryID", "Description"), new { @id = "listCommentCategory" })
            </div>
            <div style="margin-left:100px; margin-top:0px;">
                <div class="row" style="margin:0px; padding:0px; margin-bottom:0px; padding-bottom:0px; border:dashed">
                    <div class="col-md-1">
                        @Html.DropDownListFor(m => m.cM.HeaderList, new SelectList(Model.cM.HeaderList, "CommentID", "Comment"), new { @id = "ddlCommentHeaders" })
                    </div>
                    <div class="col-md-2" style="margin-left:10px">
                        Search:
                        @Html.TextBox("txtSearchHeader")
                        <button id="clear">X</button>
                    </div>
                    <div class="col-md-1" style="margin-left:10px">
                        <button id="refresh">Refresh</button>
                    </div>
                </div>
                <div class="row" style="margin-left:10px;  border:dashed">
                    Select or double-click on a comment to insert:
                </div>
                <div class="row" style="margin-left:10px;  border:dashed">
                    @Html.ListBoxFor(m => m.cM.CommentsList, new SelectList(Model.cM.CommentsList, "CommentID", "Comment"), "listComments")
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
The reason why the second column doesn't align is because using .col adds 15px padding on the left and right. Row on the other hand adds -15px margin on the left and right.

Because you used col-md-1 on the first row but no columns on the rest, there's a 15px left padding on the row where you have your dropdown.

Instead, it may be better to do the following:

```<code><div class="row">

  // First Column
  <div class="col-xs-2">
     <!-- select list -->
  <div>

  // Second Column
  <div class="col-xs-10">

      <div class="row">

          <!-- 4 to divide the grid into 3 equal parts -->
          <div class="col-xs-4">
          </div>

          <div class="col-xs-4">
          </div>

          <div class="col-xs-4">
          </div>

      </div>

      <div class="row">
         <div class="col-xs-12">
            <!-- Your text here -->
         </div>
      </div>

      <div class="row">
         <div class="col-xs-12">
            <!-- Your other list box here -->
         </div>
      </div>

  </div>
</div>
</code>```

Body:
I want to properly align the controls within bootstrap divs, so that they look like

Currently there is a lot of gap between the rows and margin-bottom or padding doesnot seem to work. Also, how do i expand the list box to completely cover the length of screen? It looks like this

HTML

                @Html.ListBoxFor(m => m.cM.CategoryList, new SelectList(Model.cM.CategoryList, "CategoryID", "Description"), new { @id = "listCommentCategory" })

                        @Html.DropDownListFor(m => m.cM.HeaderList, new SelectList(Model.cM.HeaderList, "CommentID", "Comment"), new { @id = "ddlCommentHeaders" })

                        Search:
                        @Html.TextBox("txtSearchHeader")
                        <button id="clear">X</button>

                        <button id="refresh">Refresh</button>

                    Select or double-click on a comment to insert:

                    @Html.ListBoxFor(m => m.cM.CommentsList, new SelectList(Model.cM.CommentsList, "CommentID", "Comment"), "listComments")

Body:
The reason why the second column doesn't align is because using .col adds 15px padding on the left and right. Row on the other hand adds -15px margin on the left and right.

Because you used col-md-1 on the first row but no columns on the rest, there's a 15px left padding on the row where you have your dropdown.

Instead, it may be better to do the following:

<div class="row">

  // First Column
  <div class="col-xs-2">
     <!-- select list -->
  <div>

  // Second Column
  <div class="col-xs-10">

      <div class="row">

          <!-- 4 to divide the grid into 3 equal parts -->
          <div class="col-xs-4">
          </div>

          <div class="col-xs-4">
          </div>

          <div class="col-xs-4">
          </div>

      </div>

      <div class="row">
         <div class="col-xs-12">
            <!-- Your text here -->
         </div>
      </div>

      <div class="row">
         <div class="col-xs-12">
            <!-- Your other list box here -->
         </div>
      </div>

  </div>
</div>


问:
VBA Excel Export Rows to Columns in .txt
Does anyone have an idea how to write VBA in Excel to export multiple rows to just one column. Additionally, I would like to add "enter" at the end of each "row". Ideally, this would be exported in .txt, but it would be already great even if it is converted inside the same document.

Thank you!

Edit: For example: I have rows which contain some text/value A1:A5, B1:B5, ... I would need all of These rows to get "moved" in a single column D for instance. So, A1 would go to D1,A2-D2, A3-D3 ... B1 to D7 and so on. After each end (A5, B5, C5,...) I would need an empty cell (when I convert this to .txt it means enter). I hope it is a bit clearer now.

答:
The code below will do what you describe. Use the constants in the beginning to set how many columns and rows that should be moved to one single column, specified by TargetColNo. An empty cell will be added after each scanned column.

If you prefer to save it to a textfile you can use this code and add a text file to add the result in instead of a column.

```<code>Sub Rows2OneColumn()
    Const StartColumnNo = 1 ' Start at column A
    Const EndColNo = 3      ' End at column C
    Const StartRowNo = 1    ' Start at row 1
    Const EndRowNo = 5      ' End at row 5

    Const TargetColNo = 5   ' Put result in column E

    Dim source_row As Integer
    Dim source_col As Integer
    Dim target_row As Integer

    target_row = 1

    For source_col = StartColumnNo To EndColNo
        For source_row = StartRowNo To EndRowNo
            Cells(target_row, TargetColNo).Value = Cells(source_row, source_col).Value
            target_row = target_row + 1
        Next
        target_row = target_row + 1 ' leave one cell empty
    Next
End Sub
</code>```

Body:
The code below will do what you describe. Use the constants in the beginning to set how many columns and rows that should be moved to one single column, specified by TargetColNo. An empty cell will be added after each scanned column.

If you prefer to save it to a textfile you can use this code and add a text file to add the result in instead of a column.

Sub Rows2OneColumn()
    Const StartColumnNo = 1 ' Start at column A
    Const EndColNo = 3      ' End at column C
    Const StartRowNo = 1    ' Start at row 1
    Const EndRowNo = 5      ' End at row 5

    Const TargetColNo = 5   ' Put result in column E

    Dim source_row As Integer
    Dim source_col As Integer
    Dim target_row As Integer

    target_row = 1

    For source_col = StartColumnNo To EndColNo
        For source_row = StartRowNo To EndRowNo
            Cells(target_row, TargetColNo).Value = Cells(source_row, source_col).Value
            target_row = target_row + 1
        Next
        target_row = target_row + 1 ' leave one cell empty
    Next
End Sub


问:
Reusing Tensorflow Variables
I want to have basically two different graphs based on whether I am training my network or actually running it. Basically, one piece uses some unsupervised techniques to learn the values of a given matrix and then I want to use the exact same matrix in a different graph.

I know how to get the value of the matrix using matrix_value = sess.run(my_matrix, {input=input_data}) but then is there a way to initialize a tf.Variable with a set value?

答:
You don't have to create two identical graphs, you could just use the same but run different nodes.

Let me explain what I mean. Let's look at this example:

```<code>W = tf.Variable(tf.truncated_normal([1, 1], stddev=0.1))
# Declare bias variable initialized to a constant 0.1
b = tf.Variable(tf.constant(0.1, shape=[1]))

y_pred = x_ph * W + b

# loss function
loss = tf.mul(tf.reduce_mean(tf.square(tf.sub(y_pred, y_ph))), 1. / 2)
</code>```

The first part calls the train_op.

```<code>train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
</code>```

This op will run a gradient descent step based on the loss op which will induce an update of the variables W and b.

```<code>with tf.Session() as sess:
    # initialize all the variables by running the initializer operator
    sess.run(init)
    for epoch in xrange(num_epoch):
        # Run sequentially the train_op and loss operators with
        # x_ph and y_ph placeholders fed by variables x and y
        _, loss_val = sess.run([train_op, loss], feed_dict={x_ph: x, y_ph: y})
        print('epoch %d: loss is %.4f' % (epoch, loss_val))
</code>```

But now if you just want to run it you can just run the y_pred op. It will pick up the current values of W and b and they won't be modified as you didn't call the train_op.

```<code>with tf.Session() as sess:
    # see what model do in the test set
    # by evaluating the y_pred operator using the x_test data
    test_val = sess.run(y_pred, feed_dict={x_ph: x_test})
</code>```

When you ask TensorFlow to run an op y_pred with new data x_test fed into x_ph, it will only compute y_pred = x_ph * W + b (taking W and b as constant) without modifying anything else.

Also, it is worth mentioning that when you're done with training you have the ability to override some variable values (e.g. in the case of a variable value learnt to be very close to 1, you could just set it to 1 directly as per the TensorFlow documentation.

We could improve this manually by reassigning the values of W and b to the perfect values of -1 and 1. A variable is initialized to the value provided to tf.Variable but can be changed using operations like tf.assign. For example, W=-1 and b=1 are the optimal parameters for our model. We can change W and b accordingly:

```<code>fixW = tf.assign(W, [-1., 1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print(sess.run(loss, {x_ph:x_test}))
</code>```

Title: Reusing Tensorflow Variables

Body:
You don't have to create two identical graphs, you could just use the same but run different nodes.

Let me explain what I mean. Let's look at this example:

W = tf.Variable(tf.truncated_normal([1, 1], stddev=0.1))
# Declare bias variable initialized to a constant 0.1
b = tf.Variable(tf.constant(0.1, shape=[1]))

y_pred = x_ph * W + b

# loss function
loss = tf.mul(tf.reduce_mean(tf.square(tf.sub(y_pred, y_ph))), 1. / 2)

The first part calls the train_op.

train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

This op will run a gradient descent step based on the loss op which will induce an update of the variables W and b.

with tf.Session() as sess:
    # initialize all the variables by running the initializer operator
    sess.run(init)
    for epoch in xrange(num_epoch):
        # Run sequentially the train_op and loss operators with
        # x_ph and y_ph placeholders fed by variables x and y
        _, loss_val = sess.run([train_op, loss], feed_dict={x_ph: x, y_ph: y})
        print('epoch %d: loss is %.4f' % (epoch, loss_val))

But now if you just want to run it you can just run the y_pred op. It will pick up the current values of W and b and they won't be modified as you didn't call the train_op.

with tf.Session() as sess:
    # see what model do in the test set
    # by evaluating the y_pred operator using the x_test data
    test_val = sess.run(y_pred, feed_dict={x_ph: x_test})

When you ask TensorFlow to run an op y_pred with new data x_test fed into x_ph, it will only compute y_pred = x_ph * W + b (taking W and b as constant) without modifying anything else.

Also, it is worth mentioning that when you're done with training you have the ability to override some variable values (e.g. in the case of a variable value learnt to be very close to 1, you could just set it to 1 directly as per the TensorFlow documentation.

We could improve this manually by reassigning the values of W and b to the perfect values of -1 and 1. A variable is initialized to the value provided to tf.Variable but can be changed using operations like tf.assign. For example, W=-1 and b=1 are the optimal parameters for our model. We can change W and b accordingly:

fixW = tf.assign(W, [-1., 1.])
fixb = tf.assign(b, [1.])
sess.run([fixW, fixb])
print(sess.run(loss, {x_ph:x_test}))


问:
Calculate coordinates from coordinates, distance and an angle
I want to calculate the coordinates of a new point given an original point, a distance and an angle.

```<code>Position calculateDestinationPoint(Position position, double distanceInMeter, double angle) {
    double startLatitude = Math.toRadians(position.getLatitude());
    double startLongitude = Math.toRadians(position.getLongitude());
    double bearing = Math.toRadians(angle);
    double earthRadius = 6371e3;

    double angularDistance = distanceInMeter / earthRadius;

    double destinationLatitudeRadians = Math.asin(Math.sin(startLatitude) * Math.cos(angularDistance) +
            Math.cos(startLatitude) * Math.sin(angularDistance) * Math.cos(bearing));

    double destinationLongitudeRadians = startLongitude + Math.atan2(Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(startLatitude),
            Math.cos(angularDistance) - Math.sin(startLatitude) * Math.sin(destinationLatitudeRadians));

    return new Position(Math.toDegrees(destinationLatitudeRadians), (Math.toDegrees(destinationLongitudeRadians) + 540) % 360 - 180);
}
</code>```

Unfortunately a test for that method is not passing

```<code>    @Test
public void test100km90Degree() throws Exception {
    Position position = new PointCalculator().calculateDestinationPoint(new Position(0.0, 0.0), 100_000, 90);
    Assert.assertEquals(new Position(0.0, 0.89944444), position);
}
</code>```

Log

```<code>java.lang.AssertionError:
Expected :Position(latitude=0.0, longitude=0.89944444)
Actual   :Position(latitude=5.506530518221826E-17, longitude=0.8993216059187716)
</code>```

I am not sure if the logic is correct or I missed something.

PS: I got inspired by this github repo

答: The latitude looks like a rounding error, but the longitude is off by 1.37e-4, which is quite big. Where did you get the correct result and the size of the Earth? If 6371e3 is off by 1e3 then you get an error of 1.6e-4. It is more likely to be an imprecise constant than a rounding error greater than 1e-4 on doubles.</p>

Body:
I want to calculate the coordinates of a new point given an original point, a distance and an angle.

Position calculateDestinationPoint(Position position, double distanceInMeter, double angle) {
    double startLatitude = Math.toRadians(position.getLatitude());
    double startLongitude = Math.toRadians(position.getLongitude());
    double bearing = Math.toRadians(angle);
    double earthRadius = 6371e3;

    double angularDistance = distanceInMeter / earthRadius;

    double destinationLatitudeRadians = Math.asin(Math.sin(startLatitude) * Math.cos(angularDistance) +
            Math.cos(startLatitude) * Math.sin(angularDistance) * Math.cos(bearing));

    double destinationLongitudeRadians = startLongitude + Math.atan2(Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(startLatitude),
            Math.cos(angularDistance) - Math.sin(startLatitude) * Math.sin(destinationLatitudeRadians));

    return new Position(Math.toDegrees(destinationLatitudeRadians), (Math.toDegrees(destinationLongitudeRadians) + 540) % 360 - 180);
}

Unfortunately a test for that method is not passing

    @Test
public void test100km90Degree() throws Exception {
    Position position = new PointCalculator().calculateDestinationPoint(new Position(0.0, 0.0), 100_000, 90);
    Assert.assertEquals(new Position(0.0, 0.89944444), position);
}

Log

java.lang.AssertionError:
Expected :Position(latitude=0.0, longitude=0.89944444)
Actual   :Position(latitude=5.506530518221826E-17, longitude=0.8993216059187716)

I am not sure if the logic is correct or I missed something.

PS: I got inspired by this github repo


问:
How to change build directory in Ionic 3 build process?
I'm developing a PWA using Ionic 3.

Normally the JavaScript files generated by the build to browser process of Ionic 3 are in www/build folder.

I wish to change this folder to www/build/v1 and, of course, keep the application working.

How could I change the build process of Ionic 3 to achieve this result?

答:
You may want to try the config option in the package.json file to provide custom build configuration.

To get started, add a config entry to the package.json file. From there, you can provide your own configuration file.

Here's an example of specifying a custom configuration:

```<code>"config": {
    ...
    "ionic_rollup": "./config/rollup.config.js",
    "ionic_cleancss": "./config/cleancss.config.js",
    ...
  },
</code>```

You may want to see this Ionic documentation for more information.

Body:
You may want to try the config option in the package.json file to provide custom build configuration.

To get started, add a config entry to the package.json file. From there, you can provide your own configuration file.

Here's an example of specifying a custom configuration:

"config": {
    ...
    "ionic_rollup": "./config/rollup.config.js",
    "ionic_cleancss": "./config/cleancss.config.js",
    ...
  },

You may want to see this Ionic documentation for more information.


问:
Why doesn't it work when I hover on the image?
I'm sure this is incredibly stupid once I get a hint, but I can't see why the hover doesn't work. I added the jQuery just to check whether or not it works with a click.

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover .popover {
  opacity: 1;
}</code>```

      Bla bla

```

答:
Change :

```<code>.figure:hover .popover {
  opacity: 1;
}
</code>```

To :

```<code>.figure:hover + .popover {
  opacity: 1;
}
</code>```

Body:
I'm sure this is incredibly stupid once I get a hint, but I can't see why the hover doesn't work. I added the jQuery just to check whether or not it works with a click.

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})

.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover .popover {
  opacity: 1;
}

      Bla bla

Body:
Change :

.figure:hover .popover {
  opacity: 1;
}

To :

.figure:hover + .popover {
  opacity: 1;
}


问:
Canvas client size in fabric js
In a usual canvas css width and client width could be not equal to each other, how to get this on Fabricjs? As an example: I want 640*360px canvas on a page with 1280*720px image inside.
I know I could scale image, but dataUrl will give me a smaller picture, isn't it?</p>

答:
There is a solution. You could init Fabric.js with CSS sizes and then setDimensions with backstoreOnly flag or init with desired client size and use setDimensions with cssOnly flag.
Example #1:

```<code>var canvas = new fabric.Canvas('c', {width: 640, height: 360});
canvas.setDimensions({width: 1280, height: 720}, {backstoreOnly: true});
</code>```

Example #2:

```<code>var canvas = new fabric.Canvas('c', {width: 1280, height: 720});
canvas.setDimensions({width: '640px', height: '360px'}, {cssOnly: true});
</code>```

Title: Canvas client size in fabric js

Body:
There is a solution. You could init Fabric.js with CSS sizes and then setDimensions with backstoreOnly flag or init with desired client size and use setDimensions with cssOnly flag.
Example #1:

var canvas = new fabric.Canvas('c', {width: 640, height: 360});
canvas.setDimensions({width: 1280, height: 720}, {backstoreOnly: true});

Example #2:

var canvas = new fabric.Canvas('c', {width: 1280, height: 720});
canvas.setDimensions({width: '640px', height: '360px'}, {cssOnly: true});

ContentLicense: CC BY-SA 4.0


问:
WooCommerce hide all products of a certain category if not loggedin
I have been searching everywhere to find this answer and have even downloaded multiple plugins, all of which haven't worked.

Is there a way to achieve this using PHP?

I have this code:

```<code> <?php if( !is_user_logged_in() && get_field('___unit_price') ): ?>
 <p>Unit Price: $<?php the_field('___unit_price'); ?></p>
 <?php endif; ?>
</code>```

Which seems to work for specific products but does not work for an entire category, any help would be much appeciated

答:
```<code>add_action('init', 'bbloomer_hide_price_add_cart_not_logged_in');

function bbloomer_hide_price_add_cart_not_logged_in() {
if ( !is_user_logged_in() ) {
 remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
 remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
 remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
 remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
 add_action( 'woocommerce_single_product_summary', 'bbloomer_print_login_to_see', 31 );
 add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_print_login_to_see', 11 );
}
}

function bbloomer_print_login_to_see() {
echo '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) . '">' . __('Login to see prices', 'theme_name') . '</a>';
}
</code>```

add this into your functions.php files for more check this link
https://businessbloomer.com/woocommerce-hide-price-add-cart-logged-users/

Body:
I have been searching everywhere to find this answer and have even downloaded multiple plugins, all of which haven't worked.

Is there a way to achieve this using PHP?

I have this code:

 <?php if( !is_user_logged_in() && get_field('___unit_price') ): ?>

Unit Price: $<?php the_field('___unit_price'); ?>

 <?php endif; ?>

Which seems to work for specific products but does not work for an entire category, any help would be much appeciated

Body:
add_action('init', 'bbloomer_hide_price_add_cart_not_logged_in');

function bbloomer_hide_price_add_cart_not_logged_in() {
if ( !is_user_logged_in() ) {
 remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
 remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
 remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
 remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
 add_action( 'woocommerce_single_product_summary', 'bbloomer_print_login_to_see', 31 );
 add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_print_login_to_see', 11 );
}
}

function bbloomer_print_login_to_see() {
echo '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) . '">' . __('Login to see prices', 'theme_name') . '</a>';
}

add this into your functions.php files for more check this link
https://businessbloomer.com/woocommerce-hide-price-add-cart-logged-users/


问:
How to run Heroku rails app locally without access to source code
My Heroku app is created and it also runs in my big commerce store but I want to run in locally.

Basically, I want to get all file in local machine from Heroku app.

Please help..

答:
Since you have access to git repository, you just need to clone it

```<code>git clone GIT_URL
</code>```

then move into the app root directory

```<code>cd my_app
</code>```

and then do

```<code>bundle install
</code>```

now start the server

```<code>rails server
</code>```

goto localhost:3000 from your browser..

Update

Since you have access to heroku, in the app dashboard goto settings near the bottom page you will find Heroku Git URL, clone that.

In a new empty folder just type this from cmd

```<code>git clone https://github.com/bigcommerce/hello-world-app-ruby-sinatra.git
</code>```

Body:
Since you have access to git repository, you just need to clone it

git clone GIT_URL

then move into the app root directory

cd my_app

and then do

bundle install

now start the server

rails server

goto localhost:3000 from your browser..

Update

Since you have access to heroku, in the app dashboard goto settings near the bottom page you will find Heroku Git URL, clone that.

In a new empty folder just type this from cmd

git clone https://github.com/bigcommerce/hello-world-app-ruby-sinatra.git