问:
with tensorflow and keras how to find the "category" of a given string
Hello ML/AI newbie here,

I'm asking this question because I've no idea about machine learning, ai, e.t.c and I've no idea how to continue, what questions to ask. Even if I accidentally find the solution i wouldn't know.

Ok, I followed this tutorial about "Text Classification" and it went pretty well, no problems up to here.
https://www.youtube.com/watch?v=6g4O5UOH304&list=WL&index=8&t=0s

It classifies IMDB comments and checks if a review is "Positive" or "Negative", "0" or "1"

My question is

Let say I've my own dataset, similar to IMDB but instead of "0" and "1" I have several categories as numbers like "1,2,3,4,5,6,7,8,9,10,11,12,...." for each string. So I need it to return one of these numbers (since it's learning let say two of them if it can't decide)

What should I do?
A link to a tutorial related to what I need would be great too.

```<code>import tensorflow as tf
from tensorflow import keras
import numpy as np

data = keras.datasets.imdb

(train_data, train_labels), (test_data, test_labels) = data.load_data(num_words=3000)

word_index = data.get_word_index()

word_index = {k:(v+3) for k, v in word_index.items()}
word_index["<PAD>"] = 0;
word_index["<START>"] = 1;
word_index["<UNK>"] = 2;
word_index["<UNUSED>"] = 3;

reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])

train_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index["<PAD>"], padding="post", maxlen=250)
test_data = keras.preprocessing.sequence.pad_sequences(test_data, value=word_index["<PAD>"], padding="post", maxlen=250)

def decode_review(text):
    return " ".join([reverse_word_index.get(i, "?") for i in text])

model = keras.Sequential()

model.add(keras.layers.Embedding(10000, 6))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation="relu"))
model.add(keras.layers.Dense(1, activation="sigmoid"))

#model.summary()

model.compile(optimizer="adam", loss="binary_crossentropy", metrics="accuracy")

x_val = train_data[:10000]
x_train = train_data[10000:]

y_val = train_labels[:10000]
y_train = train_labels[10000:]

fitModel = model.fit(x_train, y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1)

results = model.evaluate(test_data, test_labels)

print(results)

for index in range(20):
    test_review = test_data[index]
    predict = model.predict([test_review])
    if predict[0] > 0.8:
        print(decode_review(test_data[index]))
        print(str(predict[0]))
        print(str(test_labels[index]))
</code>```

答:
your task is a multiclass classification problem and for this reason, you have to modify your output layer. you have two possibilities.

if you have 1D integer encoded target you can use sparse_categorical_crossentropy as loss function, softmax as the last activation and the dimension of the last dense output equal to the number of class to predict

```<code>X = np.random.randint(0,10, (1000,100))
y = np.random.randint(0,3, 1000)

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
</code>```

Otherwise, if you have one-hot encoded your target you can use categorical_crossentropy, softmax as the last activation and the dimension of the last dense output equal to the number of class to predict

```<code>X = np.random.randint(0,10, (1000,100))
y = pd.get_dummies(np.random.randint(0,3, 1000)).values

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
</code>```

the usage of softmax enables to interpret the output as probability scores which sum to 1

when you compute the final prediction, to obtain the predicted class you can simply to in this way np.argmax(model.predict(X), axis=1)

these are some basic tutorials for multiclass text classification:

https://towardsdatascience.com/multi-class-text-classification-with-lstm-using-tensorflow-2-0-d88627c10a35

https://towardsdatascience.com/multi-class-text-classification-with-lstm-1590bee1bd17

Body:
Hello ML/AI newbie here,

I'm asking this question because I've no idea about machine learning, ai, e.t.c and I've no idea how to continue, what questions to ask. Even if I accidentally find the solution i wouldn't know.

Ok, I followed this tutorial about "Text Classification" and it went pretty well, no problems up to here.
https://www.youtube.com/watch?v=6g4O5UOH304&list=WL&index=8&t=0s

It classifies IMDB comments and checks if a review is "Positive" or "Negative", "0" or "1"

My question is

Let say I've my own dataset, similar to IMDB but instead of "0" and "1" I have several categories as numbers like "1,2,3,4,5,6,7,8,9,10,11,12,...." for each string. So I need it to return one of these numbers (since it's learning let say two of them if it can't decide)

What should I do?
A link to a tutorial related to what I need would be great too.

import tensorflow as tf
from tensorflow import keras
import numpy as np

data = keras.datasets.imdb

(train_data, train_labels), (test_data, test_labels) = data.load_data(num_words=3000)

word_index = data.get_word_index()

word_index = {k:(v+3) for k, v in word_index.items()}
word_index["<PAD>"] = 0;
word_index["<START>"] = 1;
word_index["<UNK>"] = 2;
word_index["<UNUSED>"] = 3;

reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])

train_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index["<PAD>"], padding="post", maxlen=250)
test_data = keras.preprocessing.sequence.pad_sequences(test_data, value=word_index["<PAD>"], padding="post", maxlen=250)

def decode_review(text):
    return " ".join([reverse_word_index.get(i, "?") for i in text])

model = keras.Sequential()

model.add(keras.layers.Embedding(10000, 6))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation="relu"))
model.add(keras.layers.Dense(1, activation="sigmoid"))

#model.summary()

model.compile(optimizer="adam", loss="binary_crossentropy", metrics="accuracy")

x_val = train_data[:10000]
x_train = train_data[10000:]

y_val = train_labels[:10000]
y_train = train_labels[10000:]

fitModel = model.fit(x_train, y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1)

results = model.evaluate(test_data, test_labels)

print(results)

for index in range(20):
    test_review = test_data[index]
    predict = model.predict([test_review])
    if predict[0] > 0.8:
        print(decode_review(test_data[index]))
        print(str(predict[0]))
        print(str(test_labels[index]))

Body:
your task is a multiclass classification problem and for this reason, you have to modify your output layer. you have two possibilities.

if you have 1D integer encoded target you can use sparse_categorical_crossentropy as loss function, softmax as the last activation and the dimension of the last dense output equal to the number of class to predict

X = np.random.randint(0,10, (1000,100))
y = np.random.randint(0,3, 1000)

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)

Otherwise, if you have one-hot encoded your target you can use categorical_crossentropy, softmax as the last activation and the dimension of the last dense output equal to the number of class to predict

X = np.random.randint(0,10, (1000,100))
y = pd.get_dummies(np.random.randint(0,3, 1000)).values

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)

the usage of softmax enables to interpret the output as probability scores which sum to 1

when you compute the final prediction, to obtain the predicted class you can simply to in this way np.argmax(model.predict(X), axis=1)

these are some basic tutorials for multiclass text classification:

https://towardsdatascience.com/multi-class-text-classification-with-lstm-using-tensorflow-2-0-d88627c10a35

https://towardsdatascience.com/multi-class-text-classification-with-lstm-1590bee1bd17


来源: stackexchange

问:
How to dismiss pushed ViewController after logout?
I spent so many hours with this issue, so I can't find any solution.

I open SettingsViewController from my TopBar on tap in avatar with pushViewController method (here is problem) and from menu (not modal).

I want to dismiss this pushed ViewController when I tap on logout button.

Below is a function that I use in some VC's and works very well.

```<code>func goToSettingsView() {
    let vc = SettingsViewController(nibName: "SettingsViewController", bundle: nil)
    vc.modalPresentationStyle = .fullScreen
    self.navigationController!.pushViewController(vc, animated: true)
    for constraint in vc.view.constraints {
        if constraint.identifier == "alignTopHeader" {
           constraint.constant = 0
        }
    }
}
</code>```

When I clicked logout button isn't working and when I login from (LoginViewController) this SettingsViewController is still showing, but I would go to Main Screen without any modals.

I did some ideas but not good working yet.

First idea was:

Below is my logout IBaction in my SettingsViewController:

```<code>- (void)logout {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[UserManager shared] logoutUserWithSuccessBlock:^{
        [self presentLoginViewController];
    }];
}
</code>```

LoginViewController is dismiss, but self is targeted for SettingsViewController?

Second idea:

I added a function declared in AppDelegate "backToRoot" in LoginViewController and call from viewWillDisappear.

```<code>[appDelegate backToRoot];
</code>```

function in AppDelegate.m file

```<code>-(void)backToRoot {
   [self.navigationController dismissViewControllerAnimated:YES completion:nil];
   PresentationsPickerViewController *mainvc = [[PresentationsPickerViewController alloc] init];
   [self setCenterPanelWithViewController:mainvc];
}
</code>```

But still not working with modal, it's work fine when SettingsViewController isn't modal.

Do you have any ideas how to hide/dismiss pushed SettingsViewController in logout action?

答:
You can simple dismiss all view controllers above the root view controller.

```<code>func logout() {
  self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)
}
</code>```

Hope it will help. Thanks.

ContentLicense: CC BY-SA 4.0

Body:
I spent so many hours with this issue, so I can't find any solution.

I open SettingsViewController from my TopBar on tap in avatar with pushViewController method (here is problem) and from menu (not modal).

I want to dismiss this pushed ViewController when I tap on logout button.

Below is a function that I use in some VC's and works very well.

func goToSettingsView() {
    let vc = SettingsViewController(nibName: "SettingsViewController", bundle: nil)
    vc.modalPresentationStyle = .fullScreen
    self.navigationController!.pushViewController(vc, animated: true)
    for constraint in vc.view.constraints {
        if constraint.identifier == "alignTopHeader" {
           constraint.constant = 0
        }
    }
}

When I clicked logout button isn't working and when I login from (LoginViewController) this SettingsViewController is still showing, but I would go to Main Screen without any modals.

I did some ideas but not good working yet.

First idea was:

Below is my logout IBaction in my SettingsViewController:

- (void)logout {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[UserManager shared] logoutUserWithSuccessBlock:^{
        [self presentLoginViewController];
    }];
}

LoginViewController is dismiss, but self is targeted for SettingsViewController?

Second idea:

I added a function declared in AppDelegate "backToRoot" in LoginViewController and call from viewWillDisappear.

[appDelegate backToRoot];

function in AppDelegate.m file

-(void)backToRoot {
   [self.navigationController dismissViewControllerAnimated:YES completion:nil];
   PresentationsPickerViewController *mainvc = [[PresentationsPickerViewController alloc] init];
   [self setCenterPanelWithViewController:mainvc];
}

But still not working with modal, it's work fine when SettingsViewController isn't modal.

Do you have any ideas how to hide/dismiss pushed SettingsViewController in logout action?

Body:
You can simple dismiss all view controllers above the root view controller.

func logout() {
  self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)
}

Hope it will help. Thanks.


问:
Java. groupingBy throw to classes
I cant write a collector that calculates the total sum of transactions (long type, not integer) by each account (i.e. by account number). The collector will be applied to a stream of transactions.
How to use groupingBy for this chain Transaction -> Account -> Number ?

```<code>class TransactionCollector {

public static Map<String, Long> getAccount2TransSum(List<Transaction> trans) {
    return trans.stream().collect(  // place code here
            }

static class Transaction {

    private final String uuid;
    private final Long sum;
    private final Account account;

    public Transaction(String uuid, Long sum, Account account) {
        this.uuid = uuid;
        this.sum = sum;
        this.account = account;
    }

    public String getUuid() {
        return uuid;
    }

    public Long getSum() {
        return sum;
    }

    public Account getAccount() {
        return account;
    }

    @Override
    public String toString() {
        return "Transaction{" +
                "uuid='" + uuid + '\'' +
                ", sum=" + sum +
                '}';
    }
}

static class Account {
    private final String number;
    private final Long balance;

    public Account(String number, Long balance) {
        this.number = number;
        this.balance = balance;
    }

    public String getNumber() {
        return number;
    }

    public Long getBalance() {
        return balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "number='" + number + '\'' +
                ", balance=" + balance +
                '}';
    }
}
</code>```

}

答:
You can use groupingBy with the summingLong collector to group the transactions and calculate their sums.

```<code>trans.stream()
    .collect(Collectors.groupingBy(
        transaction -> transaction.getAccount().getNumber(),
        Collectors.summingLong(Transaction::getSum)))
</code>```

As a result you will have a Map<String, Long> where the key is the account number and the value is the sum of all transactions of accounts with that number.

Title: Java. groupingBy throw to classes

Body:
I cant write a collector that calculates the total sum of transactions (long type, not integer) by each account (i.e. by account number). The collector will be applied to a stream of transactions.
How to use groupingBy for this chain Transaction -> Account -> Number ?

class TransactionCollector {

public static Map<String, Long> getAccount2TransSum(List<Transaction> trans) {
    return trans.stream().collect(  // place code here
            }

static class Transaction {

    private final String uuid;
    private final Long sum;
    private final Account account;

    public Transaction(String uuid, Long sum, Account account) {
        this.uuid = uuid;
        this.sum = sum;
        this.account = account;
    }

    public String getUuid() {
        return uuid;
    }

    public Long getSum() {
        return sum;
    }

    public Account getAccount() {
        return account;
    }

    @Override
    public String toString() {
        return "Transaction{" +
                "uuid='" + uuid + '\'' +
                ", sum=" + sum +
                '}';
    }
}

static class Account {
    private final String number;
    private final Long balance;

    public Account(String number, Long balance) {
        this.number = number;
        this.balance = balance;
    }

    public String getNumber() {
        return number;
    }

    public Long getBalance() {
        return balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "number='" + number + '\'' +
                ", balance=" + balance +
                '}';
    }
}

}

Body:
You can use groupingBy with the summingLong collector to group the transactions and calculate their sums.

trans.stream()
    .collect(Collectors.groupingBy(
        transaction -> transaction.getAccount().getNumber(),
        Collectors.summingLong(Transaction::getSum)))

As a result you will have a Map<String, Long> where the key is the account number and the value is the sum of all transactions of accounts with that number.


问:
MLFlow Projects can't find conda executable
I am following the tutorial on MLFlow website. I was able to run the train.py and mlflow ui worked fine. Packaging the project tries to use env variable  MLFLOW_CONDA_HOME but can't find conda.
I have tried setting the variable to the path of anaconda3/condabin but it doesn't seem to find my executable. This is the error I get:
 ERROR mlflow.cli: === Could not find Conda executable at /anaconda3/condabin\bin/conda. Ensure Conda is installed as per the inst
ructions at https://conda.io/docs/user-guide/install/index.html. You can also configure MLflow to look for a specific Conda executable by setting the MLFLOW_CONDA_HOME environment variable
 to the path of the Conda executable ===

Adding \bin/conda at the end of my path seems to be the problem, I am not sure why mlflow is doing it. I even tried setting it to my python.exe in my conda env, but no luck. I can't find bin/conda folder in my Anaconda folder anywhere.

答: I resolved this by running it from Anaconda Prompt. Make sure mlflow is installed in anaconda first as well, nothing else. But the problem then is that it's not well compatible on windows, you would need to split into two steps, activate the conda environment and then run with --no-conda as mentioned here https://github.com/mlflow/mlflow/issues/2674</p>


问:
How I can set a temporary title on batch script?
Is there a way to set a title in a batch script that will desappear when the program exits?

In my case, I want to set 'JCC' as a title, but using title JCC, the title will remain when the program exits.

Thanks for your help.

答:
I was searching and I found a solution:

```<code>@echo off
if "%~1" equ ":SET-TITLE" goto %1
cmd /c "%~f0" :SET-TITLE %*
pause
exit /b

:SET-TITLE
shift /1
title JCC
</code>```

This will work. It's recommended to delete the fourth line to make it usable and leave the SET-TITLE paragraph at the bottom of the file. Also remember that you must put an exit /b before the SET-TITLE paragraph.

Body:
I was searching and I found a solution:

@echo off
if "%~1" equ ":SET-TITLE" goto %1
cmd /c "%~f0" :SET-TITLE %*
pause
exit /b

:SET-TITLE
shift /1
title JCC

This will work. It's recommended to delete the fourth line to make it usable and leave the SET-TITLE paragraph at the bottom of the file. Also remember that you must put an exit /b before the SET-TITLE paragraph.


问:
WiX ingores a running program when running uninstall for non-default path
WiX installer uses regular dialogs for specifying the target path:

```<code><UIRef Id="WixUI_Common" />
<UIRef Id="WixUI_InstallDir" />
<Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR" />
</code>```

When the user just clicks through the installation wizard the default path is used. The user then runs the program (SomeExecutable.exe) and leaves it running. He then goes to list of programs and asks Windows to uninstall the program. The wizard properly displays a message saying that SomeExecutable.exe is running, so a restart would be needed. That's the expected behavior.

However if the user changes the target to something like c:\UserSpecificedFolder then installation works just fine but when an uninstall is attempted while SomeExecutable.exe is running then unistall finishes without any messages and files are not removed. The program continues running. That's not the expected behavior.

It looks like some extra step is needed to inform the installer that install path was changed and so it should treat the new path as install path when uninstall is being run.

Why would it not work?

答:
What does the Windows Installer uninstall log say?  I'm not completely convinced this is a problem even though it seems obvious.   WiX only creates MSI databases.  It doesn't do the uninstall, MSI does.  MSI only prompts file in use / reboot interactions when it isn't able to do an operation.  If there is no file lock it may be completely normal to not see it.

My follow up question would be is the file uninstalled at the end without rebooting?

Body:
WiX installer uses regular dialogs for specifying the target path:

<UIRef Id="WixUI_Common" />
<UIRef Id="WixUI_InstallDir" />
<Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR" />

When the user just clicks through the installation wizard the default path is used. The user then runs the program (SomeExecutable.exe) and leaves it running. He then goes to list of programs and asks Windows to uninstall the program. The wizard properly displays a message saying that SomeExecutable.exe is running, so a restart would be needed. That's the expected behavior.

However if the user changes the target to something like c:\UserSpecificedFolder then installation works just fine but when an uninstall is attempted while SomeExecutable.exe is running then unistall finishes without any messages and files are not removed. The program continues running. That's not the expected behavior.

It looks like some extra step is needed to inform the installer that install path was changed and so it should treat the new path as install path when uninstall is being run.

Why would it not work?


问:
store user input in an array and display on screen
Storing info in an array(firstName, lastName, accNumber, etc). I already have some data in array. I want to ask user input and push that input in array and save it as well as display it on screen(not in console). Also new info is not saving in the array. I use prompt as well as form . from is not working.</p>

```<code>/* creatting array  */
        var customer = [
            {fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
            {fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
            {fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
        ];
        console.log(customer.length);
        console.log(customer[1].fname);
        console.log(customer[2].lname);
        var newName = prompt("what is your lnamename?");
        customer.push(newName);
        console.log(customer);

    /*function to add data in array*/
    function addInArray() {
        var  addName = document.getElementById("#nameInput");
        customer.push(addName.value);
        addName.value = "";
        console.log(customer);

    }
     /* display array*/
    function displayArray(){
        for(var i=0; i < customer.lenght; i++){
            document.write("customer" + i + customer[i] + "</br>");
            document.getElementById("#showName").innerHTML = customer[i];
        }
    }
    </script>

    <form>
        <input id="nameInput" type="text"/ placeholder="yourInfo">
        <button type="button" id="add" onclick="addInArray();">Add </button>
        <button type="button" id="myList" onclick="displayArray();">Display</button>
    </form>
        <div id="box"></div>
        <div id="showName"> </div>
    </body>
</code>```

答:
You shouldn't write # while you are using getElementById

/* creatting array  */
var customer = [
    {fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
    {fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
    {fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
];

displayMyAcc()
function displayMyAcc(){
var myAccNo = prompt("what is your acc number?");
document.getElementById("showName").innerHTML=JSON.stringify(customer.filter(x=>x.accNo==myAccNo)[0]);
}

/*function to add data in array*/
function addInArray() {
  var  addName = document.getElementById("nameInput");
  customer.push(addName.value);
  addName.value = "";

}
/* display array*/
function displayArray(){
  for(var i=0; i < customer.length; i++){
      document.getElementById("showName").innerHTML += JSON.stringify(customer[i]);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <input id="nameInput" type="text"/ placeholder="yourInfo">
    <button type="button" id="add" onclick="addInArray();">Add </button>
    <button type="button" id="myList" onclick="displayArray();">Display</button>
</form>
<div id="box"></div>
<div id="showName"> </div></code>```

Body:
Storing info in an array(firstName, lastName, accNumber, etc). I already have some data in array. I want to ask user input and push that input in array and save it as well as display it on screen(not in console). Also new info is not saving in the array. I use prompt as well as form . from is not working.

/* creatting array  */
        var customer = [
            {fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
            {fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
            {fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
        ];
        console.log(customer.length);
        console.log(customer[1].fname);
        console.log(customer[2].lname);
        var newName = prompt("what is your lnamename?");
        customer.push(newName);
        console.log(customer);

    /*function to add data in array*/
    function addInArray() {
        var  addName = document.getElementById("#nameInput");
        customer.push(addName.value);
        addName.value = "";
        console.log(customer);

    }
     /* display array*/
    function displayArray(){
        for(var i=0; i < customer.lenght; i++){
            document.write("customer" + i + customer[i] + "
");
            document.getElementById("#showName").innerHTML = customer[i];
        }
    }
    </script>

    <form>
        <input id="nameInput" type="text"/ placeholder="yourInfo">
        <button type="button" id="add" onclick="addInArray();">Add </button>
        <button type="button" id="myList" onclick="displayArray();">Display</button>
    </form>

Body:
You shouldn't write # while you are using getElementById

/* creatting array  */
var customer = [
    {fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
    {fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
    {fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
];

displayMyAcc()
function displayMyAcc(){
var myAccNo = prompt("what is your acc number?");
document.getElementById("showName").innerHTML=JSON.stringify(customer.filter(x=>x.accNo==myAccNo)[0]);
}

/*function to add data in array*/
function addInArray() {
  var  addName = document.getElementById("nameInput");
  customer.push(addName.value);
  addName.value = "";

}
/* display array*/
function displayArray(){
  for(var i=0; i < customer.length; i++){
      document.getElementById("showName").innerHTML += JSON.stringify(customer[i]);
  }
}

<form>
    <input id="nameInput" type="text"/ placeholder="yourInfo">
    <button type="button" id="add" onclick="addInArray();">Add </button>
    <button type="button" id="myList" onclick="displayArray();">Display</button>
</form>
<div id="box"></div>
<div id="showName"> </div>


问:
Cancel a push notification sound while it is playing
Tried to find this already but can't find any questions which are asking quite the same thing.

Basically I have set up my push notifications, everything works fine and they are received both when the app is open and closed. However, the push noise we are using is quite long and I'm not sure if it's possible to cancel the sound once they press the "ok" button on the alert.

I have tried to utilise the mute toggle switch, but this only seems to come into play at the moment that sound starts to play, if it's off the sound plays, if it's on then it doesn't. If I toggle the switch mid-sound it has no effect. However, if I just play a regular sound clip in my app (not a push notification sound) and use the toggle switch then the sound stops/starts as you would expect.

Is there a way to cancel the sound? Or is it treated differently as a system sound of some kind?

Edit: I've been trying to work this out myself for the last few days, and I'm coming to the conclusion that there is no way to cancel the push alert sound mid-sound. Can anyone confirm that this is definitely the case?

Edit2: For some reason the xcode tag has been removed - with the reason being that it is nothing to do with xcode. I feel maybe my issue was not clear - I AM using xcode to build the app, and I am looking for a way to programatically control whether the push notification sound is heard or not. Thanks.

答:
As of iOS 10, you can remove all notifications from Notification Center by calling

```<code>UNUserNotificationCenter.current().removeAllDeliveredNotifications()
</code>```

The audio stops playing and all the notifications are removed from Notification Center.

Alternatively, to stop the sound for only a specific notification, you can use:

```<code>UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String])
</code>```

This stops the audio for only the given notifications, and removes them from Notification Center.

To get the ids for all the delivered notifications, use

```<code>UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
  let ids = notifications.map { $0.request.identifier }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As of iOS 10, you can remove all notifications from Notification Center by calling

UNUserNotificationCenter.current().removeAllDeliveredNotifications()

The audio stops playing and all the notifications are removed from Notification Center.

Alternatively, to stop the sound for only a specific notification, you can use:

UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String])

This stops the audio for only the given notifications, and removes them from Notification Center.

To get the ids for all the delivered notifications, use

UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
  let ids = notifications.map { $0.request.identifier }
}


问:
How to upload the public url for an image uploaded to the Firebase Cloud Storage to the Realtime Database
After uploading an image to the Firebase Cloud Storage, I want to add its public download URL to a child node in my realtime database.

My File Upload Code

```<code>    private void uploadFile() {

        if (imageUri != null) {

            StorageReference fileRef = storageReference.child(UID + "/pic" + ".png");

            UploadTask uploadTask =  fileRef.putFile(imageUri);
            uploadTask.addOnSuccessListener(OrderPickupActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            imageURL = uri.toString();
                        }
                    });
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(OrderPickupActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                }
            });

        } else {
            Toast.makeText(this, "Choose an image!", Toast.LENGTH_SHORT).show();
        }

    }
</code>```

Uploading to the realtime database

```<code>uploadFile();

                    PickupDetails newPickup = new PickupDetails(
                            date,
                            time,
                            name,
                            email,
                            address,
                            pinCode,
                            UID,
                            phoneNumber,
                            imageURL
                    );

                    FirebaseDatabase.getInstance().getReference("Pending-Requests")
                            .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                            .setValue(newPickup)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    //Toast.makeText(OrderPickupActivity.this, "Success!", Toast.LENGTH_LONG).show();
                                    progressBar.setVisibility(View.GONE);
                                    startActivity(new Intent(OrderPickupActivity.this, MainActivity.class));
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(OrderPickupActivity.this, "Error, " + e, Toast.LENGTH_LONG).show();
                                    progressBar.setVisibility(View.GONE);
                                }
                            });
</code>```

Pickup Details class

```<code>public class PickupDetails {

    public String date, time, userName, userEmail, userAddress, pinCode, userUID, phoneNumber, image;

    public PickupDetails(String date, String time, String userName, String userEmail, String userAddress, String pinCode, String userUID, String phoneNumber, String image) {
        this.date = date;
        this.time = time;
        this.userName = userName;
        this.userEmail = userEmail;
        this.userAddress = userAddress;
        this.pinCode = pinCode;
        this.userUID = userUID;
        this.phoneNumber = phoneNumber;
        this.image = image;
    }
}
</code>```

I have used the answers from similar questions on StackOverflow, but none of them seems to help me. When I log the result, I am able to get the value, but it does not reach the database.

答: As mentioned by Doug, firebase APIs are asynchronous, which means, they will work in the background while letting the rest of your logic work. The trick was to submit to the database after the task was done. All I had to do was to move my adding to database logic in the onSuccessListener.

Body:
After uploading an image to the Firebase Cloud Storage, I want to add its public download URL to a child node in my realtime database.

My File Upload Code

    private void uploadFile() {

        if (imageUri != null) {

            StorageReference fileRef = storageReference.child(UID + "/pic" + ".png");

            UploadTask uploadTask =  fileRef.putFile(imageUri);
            uploadTask.addOnSuccessListener(OrderPickupActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            imageURL = uri.toString();
                        }
                    });
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(OrderPickupActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                }
            });

        } else {
            Toast.makeText(this, "Choose an image!", Toast.LENGTH_SHORT).show();
        }

    }

Uploading to the realtime database

uploadFile();

                    PickupDetails newPickup = new PickupDetails(
                            date,
                            time,
                            name,
                            email,
                            address,
                            pinCode,
                            UID,
                            phoneNumber,
                            imageURL
                    );

                    FirebaseDatabase.getInstance().getReference("Pending-Requests")
                            .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                            .setValue(newPickup)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    //Toast.makeText(OrderPickupActivity.this, "Success!", Toast.LENGTH_LONG).show();
                                    progressBar.setVisibility(View.GONE);
                                    startActivity(new Intent(OrderPickupActivity.this, MainActivity.class));
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(OrderPickupActivity.this, "Error, " + e, Toast.LENGTH_LONG).show();
                                    progressBar.setVisibility(View.GONE);
                                }
                            });

Pickup Details class

public class PickupDetails {

    public String date, time, userName, userEmail, userAddress, pinCode, userUID, phoneNumber, image;

    public PickupDetails(String date, String time, String userName, String userEmail, String userAddress, String pinCode, String userUID, String phoneNumber, String image) {
        this.date = date;
        this.time = time;
        this.userName = userName;
        this.userEmail = userEmail;
        this.userAddress = userAddress;
        this.pinCode = pinCode;
        this.userUID = userUID;
        this.phoneNumber = phoneNumber;
        this.image = image;
    }
}

I have used the answers from similar questions on StackOverflow, but none of them seems to help me. When I log the result, I am able to get the value, but it does not reach the database.


问:
Import packages latex from directory
Is it possibile in latex to import a package like IEEEtran which I don't have installed but I have inside a directory named IEEETran_dir?

For instance I would like to do something like

```<code>\usepackage{./IEEEtran_dir/IEEEtran}

\documentclass[10pt, conference, letterpaper]{IEEEtran}

\begin{document}
\end{document}
</code>```

答:
Basically like it was suggested in the comment the proper way to do so was to import the relative path of the package directly in the \documentclass statement.

```<code>\documentclass[10pt, conference, letterpaper]{./IEEEtran_dir/IEEEtran}
\begin{document}
\end{document}
</code>```

Of course it's just a workaround for those cases where you cannot install it, but the correct way should be to install the package.

Title: Import packages latex from directory

Body:
Is it possibile in latex to import a package like IEEEtran which I don't have installed but I have inside a directory named IEEETran_dir?

For instance I would like to do something like

\usepackage{./IEEEtran_dir/IEEEtran}

\documentclass[10pt, conference, letterpaper]{IEEEtran}

\begin{document}
\end{document}

Body:
Basically like it was suggested in the comment the proper way to do so was to import the relative path of the package directly in the \documentclass statement.

\documentclass[10pt, conference, letterpaper]{./IEEEtran_dir/IEEEtran}
\begin{document}
\end{document}

Of course it's just a workaround for those cases where you cannot install it, but the correct way should be to install the package.


问:
get response.status in .then in Java Script
I tried to check if the status of my request is 200 (OK), but I do not know how to do these things together because the first and second .then, are not "like each other":

function f(path) {
    await fetch(path)
            .then(response => {
                // console.log(response.status);
                if (response.status != 200) {
                    throw response.status;
                } else {
                    // do something
                }
            })
            .then(response => response.json())
            .then(...method for the response.json()...)
            .catch(error => {
                // print some error message
            }
}
```

The second then failed and returned error.

I have a problem when I throw that.

It prints to the error to the console (when I check by changing the path to wrong path and I want to see if I treat errors).

what can I do?

答:
The number of browsers that support fetch but don't support async/await is now very small, so you may be better off using this simpler syntax first, and then transpiling for legacy browsers along with your shims for fetch.

Your function becomes:

try {
    const response = await fetch(path);

    // console.log(response.status);
    if (response.status != 200) {
        throw response.status;
    } else {
        // do something
    }

    const parsed =  await response.json();

    // do something with parsed
}
catch(error) {
    // print some error message
}
```

<p>This new syntax makes it much easier to deal with errors in the different <code>then</code> actions:</p>

<pre class="lang-js prettyprint-override"><code>const response = await fetch(path);

// console.log(response.status);
if (response.status != 200) {
    throw response.status;
} else {
    // do something
}

let parsed; // Will hold the parsed JSON
try {
    parsed =  await response.json();
}
catch(error) {
    // Deal with parsing errors
}

try {
    // do something with parsed
}
catch(error) {
    // Deal with errors using the parsed result
}
</code>```

Body:
I tried to check if the status of my request is 200 (OK), but I do not know how to do these things together because the first and second .then, are not "like each other":

function f(path) {
    await fetch(path)
            .then(response => {
                // console.log(response.status);
                if (response.status != 200) {
                    throw response.status;
                } else {
                    // do something
                }
            })
            .then(response => response.json())
            .then(...method for the response.json()...)
            .catch(error => {
                // print some error message
            }
}

The second then failed and returned error.

I have a problem when I throw that.

It prints to the error to the console (when I check by changing the path to wrong path and I want to see if I treat errors).

what can I do?

Body:
The number of browsers that support fetch but don't support async/await is now very small, so you may be better off using this simpler syntax first, and then transpiling for legacy browsers along with your shims for fetch.

Your function becomes:

try {
    const response = await fetch(path);

    // console.log(response.status);
    if (response.status != 200) {
        throw response.status;
    } else {
        // do something
    }

    const parsed =  await response.json();

    // do something with parsed
}
catch(error) {
    // print some error message
}

This new syntax makes it much easier to deal with errors in the different then actions:

const response = await fetch(path);

// console.log(response.status);
if (response.status != 200) {
    throw response.status;
} else {
    // do something
}

let parsed; // Will hold the parsed JSON
try {
    parsed =  await response.json();
}
catch(error) {
    // Deal with parsing errors
}

try {
    // do something with parsed
}
catch(error) {
    // Deal with errors using the parsed result
}


问:
Dynamic HTML Form Generation
I need to generate HTML forms in Java. I don't know in advance what fields are needed, those will probably be delivered in XML (i have some say over this). I could use the same input file to handle the form submission.

Are there libs, techniques that deal with this problem? I can't imagine that there aren't, but i can't find a suitable solution.
I looked at XForms, but it seems that there's not enough adoption from browsers.

Any ideas? Much obliged.

( Context: JSR-286 compliant portlet (using Liferay atm) )

答:
XSLTForms is an XSLT-based XForms engine for browsers. Of course, it can also be used on server-side. It's an opensource project.

The corresponding "compiler" will soon be available with technical documentation. It will permit you to customize it and add your own specific behavior.

OwnerDisplayName: Jeroen Dierckx

ContentLicense: CC BY-SA 2.5

Title: Dynamic HTML Form Generation

OwnerDisplayName: Alain COUTHURES

LastEditorDisplayName: Alain COUTHURES


问:
html button in asp.net
i am using html in asp page where i have to use html button. but the problem is i want to do the coding on html button in c#. but by using html button i cant do that.. is there any other way to do so..i am using html button as:

```<code> <button id="MyButton" runat="server" onserverclick="MyButton_ServerClick" >
   </button>
</code>```

if i double-click on the html button from .aspx page it generates the code as function under script as:

```<code> function MyButton_onclick() {

        }
</code>```

what can i do for this..

答:
You could use jQuery to call a .net WebService to do stuff on the server deepending on what you want to achieve.

Here an example.

Title: html button in asp.net

Body:
i am using html in asp page where i have to use html button. but the problem is i want to do the coding on html button in c#. but by using html button i cant do that.. is there any other way to do so..i am using html button as:

 <button id="MyButton" runat="server" onserverclick="MyButton_ServerClick" >
   </button>

if i double-click on the html button from .aspx page it generates the code as function under script as:

 function MyButton_onclick() {

        }

what can i do for this..


问:
Angular cli for existing github project
I'm new to Angular 2 CLI. As per tutorial, there is command provided called ng create <project_name>. My scenario is creating project in existing directory.

It throws error like below:

Directory 'angular-basic' already exists.

答:
try this command:</p>

```<code>ng new appName --directory ./
</code>```

Title: Angular cli for existing github project

Body:
try this command:

ng new appName --directory ./


问:
ComboBox.SelectedValue returns ToString() instead of the Name property
I am trying to make a ComboBox where the drop-down list shows the name and description of the campaign elements (properties NombreCampana and Descripcion of class Campana) and when you select one value it shows the Name (NombreCampana). I have done this with an ObservableCollection so the changes affect the ComboBox without reloading.

In the MainMenu window (menuPrincipal), I have this XAML for the ComboBox:

```<code><ComboBox Style="{DynamicResource comboBoxCampaign}"
            x:Name="campaignComboBox"
            Text="{DynamicResource CampaignList}"
            ItemsSource="{Binding Path=Nombres}"
            SelectedValue="{Binding Path=NombreCampana, Mode=TwoWay}"
            SelectedValuePath="Value"
            SelectionChanged="CampaigneComboBox_SelectionChanged">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0}
{1}">
                        <Binding Path="NombreCampana"/>
                        <Binding Path="Descripcion"/>
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

The ComboBox, is linked to an ObservableCollection in the code-behind:

```<code>        private List<Campana> listacampana = new List<Campana>();
        private ObservableCollection<Campana> nombres = new ObservableCollection<Campana>();

        public ObservableCollection<Campana> Nombres
        {
            get { return nombres; }
            set { nombres = value; }
        }

        public List<Campana> ListaCampanas
        {
            get { return listacampana; }
            set { listacampana = value; }
        }

        public menuPrincipal()
        {
            InitializeComponent();
            ConfiguracionPagina.DefinirIdioma(this, "MainMenu");

            this.listacampana.AddRange(MainWindow.DatosUsuario.ListCampaigns);

            foreach (Campana item in this.listacampana)
            {
                this.nombres.Add(item);
            }

            campaignComboBox.ItemsSource = this.nombres;

        }
</code>```

That code defines the language, changes the texts, adds the user list to the property list, and after that adds to the all the items Campana (campaign) to the ObservableCollection.

After that I set the ItemSource of the ComboBox to Nombres (the ObservableCollection).

The class Campana is:

```<code>public class Campana
{
    private string nombre;
    private string descripcion;
    private string imagen;
    private List<RecursosCampana> listarecursos = new List<RecursosCampana>();

    public string DireccionImagen
    {
        get { return imagen; }
        set { imagen = value; }
    }

    public List<RecursosCampana> RecursosCampana
    {
        get { return listarecursos; }
        set { listarecursos = value; }
    }

    public string Descripcion
    {
        get { return descripcion; }
        set { descripcion = value; }
    }

    public string NombreCampana
    {
        get { return nombre; }
        set { nombre = value; }
    }
}
</code>```

When I run the application, the DataTemplate works fine and shows the items with the description.

But when I select one item I get this:

I have tried everything that I founded by searching Google, but I don't get what is happening. Also, if I don't define the ItemSource in the code, the XAML ItemSource doesn't work. This is what happens if I comment out campaignComboBox.ItemsSource = this.nombres;:

Edit: answering the comments, i have solved thanks to @Keith Stein, a part of the problem, this was the style

```<code><Style x:Key="comboBoxCampaign" TargetType="ComboBox">
        <Setter Property="Margin" Value="10"/>
        <Setter Property="BorderThickness" Value="2"/>
        <Setter Property="IsEditable" Value="True"/>
        <Setter Property="IsReadOnly" Value="True"/>
        <Setter Property="Focusable" Value="True"/>
        <Setter Property="FontSize" Value="15"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="Height" Value="Auto"/>
    </Style>
</code>```

I used that to have a "placeholder" text, an initial text which is going to dissapears once you click in the combobox, when i delete "IsEditable" i lost the initial title the combobox just have the V to press, but now when i select an item, i get the name + description.

Is not exactly what i want, i just want to show the name, but is more close to that.

Edit2: The problem with the databinding was that i didnt use the DataContext = this; now i can get the bind from xaml but still i cant show just the name.

Lastly answering to the last comment, what i am trying to do is:
- I'm doing an application to prepare roleplaying adventures or scenarios, in this section the user select the campaign that he is going to use, so i want that when he press the combobox, he can see the name of the campaign and the description because he could have 2 similar campaigns or based in the same system, and once he choose one, just show the name that is more elegant specially if he writes a big description

答:
Finally i get the answer in this post Can I use a different Template for the selected item in a WPF ComboBox than for the items in the dropdown part?

Simple swapping between two templates if the item is selected or not.

Body:
I am trying to make a ComboBox where the drop-down list shows the name and description of the campaign elements (properties NombreCampana and Descripcion of class Campana) and when you select one value it shows the Name (NombreCampana). I have done this with an ObservableCollection so the changes affect the ComboBox without reloading.

In the MainMenu window (menuPrincipal), I have this XAML for the ComboBox:

<ComboBox Style="{DynamicResource comboBoxCampaign}"
            x:Name="campaignComboBox"
            Text="{DynamicResource CampaignList}"
            ItemsSource="{Binding Path=Nombres}"
            SelectedValue="{Binding Path=NombreCampana, Mode=TwoWay}"
            SelectedValuePath="Value"
            SelectionChanged="CampaigneComboBox_SelectionChanged">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0}
{1}">
                        <Binding Path="NombreCampana"/>
                        <Binding Path="Descripcion"/>
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

The ComboBox, is linked to an ObservableCollection in the code-behind:

        private List<Campana> listacampana = new List<Campana>();
        private ObservableCollection<Campana> nombres = new ObservableCollection<Campana>();

        public ObservableCollection<Campana> Nombres
        {
            get { return nombres; }
            set { nombres = value; }
        }

        public List<Campana> ListaCampanas
        {
            get { return listacampana; }
            set { listacampana = value; }
        }

        public menuPrincipal()
        {
            InitializeComponent();
            ConfiguracionPagina.DefinirIdioma(this, "MainMenu");

            this.listacampana.AddRange(MainWindow.DatosUsuario.ListCampaigns);

            foreach (Campana item in this.listacampana)
            {
                this.nombres.Add(item);
            }

            campaignComboBox.ItemsSource = this.nombres;

        }

That code defines the language, changes the texts, adds the user list to the property list, and after that adds to the all the items Campana (campaign) to the ObservableCollection.

After that I set the ItemSource of the ComboBox to Nombres (the ObservableCollection).

The class Campana is:

public class Campana
{
    private string nombre;
    private string descripcion;
    private string imagen;
    private List<RecursosCampana> listarecursos = new List<RecursosCampana>();

    public string DireccionImagen
    {
        get { return imagen; }
        set { imagen = value; }
    }

    public List<RecursosCampana> RecursosCampana
    {
        get { return listarecursos; }
        set { listarecursos = value; }
    }

    public string Descripcion
    {
        get { return descripcion; }
        set { descripcion = value; }
    }

    public string NombreCampana
    {
        get { return nombre; }
        set { nombre = value; }
    }
}

When I run the application, the DataTemplate works fine and shows the items with the description.

But when I select one item I get this:

I have tried everything that I founded by searching Google, but I don't get what is happening. Also, if I don't define the ItemSource in the code, the XAML ItemSource doesn't work. This is what happens if I comment out campaignComboBox.ItemsSource = this.nombres;:

Edit: answering the comments, i have solved thanks to @Keith Stein, a part of the problem, this was the style

I used that to have a "placeholder" text, an initial text which is going to dissapears once you click in the combobox, when i delete "IsEditable" i lost the initial title the combobox just have the V to press, but now when i select an item, i get the name + description.

Is not exactly what i want, i just want to show the name, but is more close to that.

Edit2: The problem with the databinding was that i didnt use the DataContext = this; now i can get the bind from xaml but still i cant show just the name.

Lastly answering to the last comment, what i am trying to do is:
- I'm doing an application to prepare roleplaying adventures or scenarios, in this section the user select the campaign that he is going to use, so i want that when he press the combobox, he can see the name of the campaign and the description because he could have 2 similar campaigns or based in the same system, and once he choose one, just show the name that is more elegant specially if he writes a big description


问:
Can using an object with true and false keys or the logical operators instead of a single if else reduce cyclomatic complexity?
So I'm currently learning JavaScript and the lecturer who taught the course I'm currently watching constantly talks about reducing cyclomatic complexity. He uses a few tricks for doing so which I cannot understand. I think I understand why a switch statement replaced by a map reduces the cyclomatic complexity - from many possible cases there is only one. However, he has been doing something like the following to reduce cyclomatic complexity:

```<code>if (condition) {
    arr.push(element);
} else {
    arr.pop();
}
</code>```

becomes:

```<code>const actionsMap = {true: "push", false: "pop"};
arr[actionsMap[condition]](element);
</code>```

I prefer the second one, but how does it reduce the cyclomatic complexity? There are still two cases which are now only called in another way. If that really reduces cyclomatic complexity, can every if be replaced with a map with true and false keys to reduce cyclomatic complexity? He also uses || and && to reduce the cyclomatic complexity, but I've seen them listed as part of the cyclomatic complexity. How does this reducing of cyclomatic complexity work? Isn't it just a different shape for the same condition?

Edit: I do realize there are switch statements which cannot be so easily replaced by a map. Thank you for pointing out the reduced maintainability, but my question is: How does the reduction of complexity work here? Why is the actionsMap better than the if. Is it not a condition? Also, how do the logical operators reduce complexity?

```<code>return (a>5 && a) || a-1;
</code>```

How is this better than the following in terms of cyclomatic complexity:

```<code>if (a>5) return a;
else return a-1;
</code>```

I know the examples are not of production quality code, but they illustrate my point pretty well.

答:
IMO, your priority as a developer should be to write code that:

works

is easy for others to understand.

If your project is full of code fragments like the second example, the next person who comes along to maintain it is going to have a much harder time. It's a nice demonstration of how to use an alternative pattern to achieve the same result, but to me it's overkill for replacing a simple if/else.

Body:
So I'm currently learning JavaScript and the lecturer who taught the course I'm currently watching constantly talks about reducing cyclomatic complexity. He uses a few tricks for doing so which I cannot understand. I think I understand why a switch statement replaced by a map reduces the cyclomatic complexity - from many possible cases there is only one. However, he has been doing something like the following to reduce cyclomatic complexity:

if (condition) {
    arr.push(element);
} else {
    arr.pop();
}

becomes:

const actionsMap = {true: "push", false: "pop"};
arr[actionsMap[condition]](element);

I prefer the second one, but how does it reduce the cyclomatic complexity? There are still two cases which are now only called in another way. If that really reduces cyclomatic complexity, can every if be replaced with a map with true and false keys to reduce cyclomatic complexity? He also uses || and && to reduce the cyclomatic complexity, but I've seen them listed as part of the cyclomatic complexity. How does this reducing of cyclomatic complexity work? Isn't it just a different shape for the same condition?

Edit: I do realize there are switch statements which cannot be so easily replaced by a map. Thank you for pointing out the reduced maintainability, but my question is: How does the reduction of complexity work here? Why is the actionsMap better than the if. Is it not a condition? Also, how do the logical operators reduce complexity?

return (a>5 && a) || a-1;

How is this better than the following in terms of cyclomatic complexity:

if (a>5) return a;
else return a-1;

I know the examples are not of production quality code, but they illustrate my point pretty well.


问:
Even or odd. If the number is equal to 0, the program must stop
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.

```<code>Input
1
2
3
0
Output
odd
even
odd
</code>```

My code:

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int num;
        for (; ; ) {
            Scanner reader = new Scanner(System.in);
            num = reader.nextInt();
            if (num % 2 == 0) {
                System.out.println("even");
            }
            else if(num == 0){
                break;
            }
            else{
                System.out.println("odd");
            }
        }
    }
}
</code>```

答:
You need to check if the value is zero before checking if the value is even.
For example:</p>

```<code>public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    int num;

    while(true) {
        num = reader.nextInt();

        if(num == 0) break;
        else if(num % 2 == 0) System.out.println("even");
        else System.out.println("odd");
    }
}
</code>```

Body:
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.

Input
1
2
3
0
Output
odd
even
odd

My code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int num;
        for (; ; ) {
            Scanner reader = new Scanner(System.in);
            num = reader.nextInt();
            if (num % 2 == 0) {
                System.out.println("even");
            }
            else if(num == 0){
                break;
            }
            else{
                System.out.println("odd");
            }
        }
    }
}

Body:
You need to check if the value is zero before checking if the value is even.
For example:

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    int num;

    while(true) {
        num = reader.nextInt();

        if(num == 0) break;
        else if(num % 2 == 0) System.out.println("even");
        else System.out.println("odd");
    }
}


问:
Debugging asynchronous ASP.NET WebAPI controller shows "No tasks to display" in Tasks window
I'm trying to debug some asynchronous code using the Tasks window (Debug -> Windows -> Tasks), but when I break on a line within an async method using a breakpoint the Tasks window shows "No tasks to display".

My project is a WebAPI project running in IIS Express on a Windows 8.1 machine in Visual Studio 2013.

I've seen this question which is very similar, but the answer given here is that it needs to run on a windows 8.1 machine rather than Windows 7... but I am running 8.1!

I've tried creating a basic console application, setup a very simple asynchronous app and debugging that, and it works perfectly ok there... so what am I doing wrong? Why doesn't it work in my WebAPI project?

答:
Using Visual Studio 2017 15.6 or above can solve this problem.

This problem was a known issue and it can be found here on Developer Community The status tag confirms that the issue was fixed in Visual Studio 2017 15.6 preview 1 and Visual Studio 2017 15.6. I was trying to find an official announcement for fixing this issue in the official release note and their official blog but found none.

Visual Studio Blog, Official Release Notes

With the latest version, this should be no longer an issue.


问:
Array of types?
I have several structs, and I want to create an array of them so that I can use its members as an argument for a template, something like types = {int, float}; multiply<types[i]>();. It can be done through overloading, but I have lots of functions so this is not a way. As far as I know, we can store types only as pointers (so I'll actually have to dereference it: multiply<*types[i]>();), but here I stop to understand because to create a pointer I have to know type of variable it's pointing to, and what is a type of a class (of a type)? I thought "screw it, I'll use auto", but then it seems to be that pointers to different classes are of different types, so that I have to erase their type to store them in a common array, and so on, I have this now:

```<code>auto types = {std::make_shared<void>(Student), std::make_shared<void>(Citizen)};
</code>```

And it says that Student and Citizen don't refer to a value.

答:
The convenient built-in array of types in C++ is std::tuple<Types...>.

To access the ith type in a std::tuple, use std::tuple_element_t.

For example:

using types = std::tuple<int, float>;
multiply<std::tuple_element_t>();
```

<p>Types are only "there" at compile time, thus all of your indices need to be at compile time, and you store them in the type information (here the variadic type in <code>std::tuple</code>), instead of in a variable.</p>

<p>You can use a helper type to make this less verbose:</p>

<pre class="lang-cpp prettyprint-override"><code>template<class... Types>
struct type_array {
    using as_tuple = std::tuple<Types...>;

    template<std::size_t I>
    using get = std::tuple_element_t<I, as_tuple>;

    static constexpr std::size_t size = sizeof...(Types);
};

using types = type_array<int, float>;
multiply<types::get<i>>();
</code>```

Title: Array of types?

Body:
I have several structs, and I want to create an array of them so that I can use its members as an argument for a template, something like types = {int, float}; multiply<types[i]>();. It can be done through overloading, but I have lots of functions so this is not a way. As far as I know, we can store types only as pointers (so I'll actually have to dereference it: multiply<*types[i]>();), but here I stop to understand because to create a pointer I have to know type of variable it's pointing to, and what is a type of a class (of a type)? I thought "screw it, I'll use auto", but then it seems to be that pointers to different classes are of different types, so that I have to erase their type to store them in a common array, and so on, I have this now:

auto types = {std::make_shared<void>(Student), std::make_shared<void>(Citizen)};

And it says that Student and Citizen don't refer to a value.

Body:
The convenient built-in array of types in C++ is std::tuple<Types...>.

To access the ith type in a std::tuple, use std::tuple_element_t<i, your_tuple>.

For example:

using types = std::tuple<int, float>;
multiply<std::tuple_element_t<i, types>>();

Types are only "there" at compile time, thus all of your indices need to be at compile time, and you store them in the type information (here the variadic type in std::tuple), instead of in a variable.

You can use a helper type to make this less verbose:

template<class... Types>
struct type_array {
    using as_tuple = std::tuple<Types...>;

    template<std::size_t I>
    using get = std::tuple_element_t<I, as_tuple>;

    static constexpr std::size_t size = sizeof...(Types);
};

using types = type_array<int, float>;
multiply<types::get<i>>();


问:
Compare XPATH attributes
Why does my code not work? I basically have to check if the person is mentioned in "abgebildet" (so i the compared emails but it does not work for some reason)

```<code>socialnetwork/personen/person[@email = person/photos/photo/abgebildet/@personemail]/@vorname
</code>```

XML:

```<code><socialnetwork>
<personen>
    <person email="H.Mueller@yahoo.com" vorname="Hannah" nachname="Müller" geburtsdatum="1991-02-02">
        <photos>
            <photo url="http://www.flickr.com/myphoto/H.Mueller/147.jpg" titel="Photo Number 147" beschreibung="This is a very nice picture taken by H.Mueller@yahoo.com">
                <abgebildet personemail="F.Kaiser@yahoo.com"/>
                <abgebildet personemail="Laura.Heinrich@gmail.com"/>
                <abgebildet personemail="Lucas.Bergmann@sms.at"/>
                <abgebildet personemail="M.Krause@sms.at"/>
                <abgebildet personemail="Neele.Schmitt@yahoo.com"/>
                <abgebildet personemail="P.Winkler@gmx.net"/>
                <abgebildet personemail="S.Hofmann@live.at"/>
                <abgebildet personemail="S.Sommer@gmx.net"/>
            </photo>
</code>```

答:
Update your XML to include a possible match, because as @JackFleeting comments, no @personemail matches @email.

Update your XML to include a @vorname, because it has no such attribute currently, or drop @vorname from your XPath.

Change your predicate from

```<code>person[@email = person/photos/photo/abgebildet/@personemail]
</code>```

to

```<code>person[@email = photos/photo/abgebildet/@personemail]
</code>```

because the current node is already a person element within the predicate.

Title: Compare XPATH attributes

Body:
Why does my code not work? I basically have to check if the person is mentioned in "abgebildet" (so i the compared emails but it does not work for some reason)

socialnetwork/personen/person[@email = person/photos/photo/abgebildet/@personemail]/@vorname

XML:

<socialnetwork>
<personen>
    <person email="H.Mueller@yahoo.com" vorname="Hannah" nachname="Müller" geburtsdatum="1991-02-02">
        <photos>
            <photo url="http://www.flickr.com/myphoto/H.Mueller/147.jpg" titel="Photo Number 147" beschreibung="This is a very nice picture taken by H.Mueller@yahoo.com">
                <abgebildet personemail="F.Kaiser@yahoo.com"/>
                <abgebildet personemail="Laura.Heinrich@gmail.com"/>
                <abgebildet personemail="Lucas.Bergmann@sms.at"/>
                <abgebildet personemail="M.Krause@sms.at"/>
                <abgebildet personemail="Neele.Schmitt@yahoo.com"/>
                <abgebildet personemail="P.Winkler@gmx.net"/>
                <abgebildet personemail="S.Hofmann@live.at"/>
                <abgebildet personemail="S.Sommer@gmx.net"/>
            </photo>

Body:
Update your XML to include a possible match, because as @JackFleeting comments, no @personemail matches @email.

Update your XML to include a @vorname, because it has no such attribute currently, or drop @vorname from your XPath.

Change your predicate from

person[@email = person/photos/photo/abgebildet/@personemail]

to

person[@email = photos/photo/abgebildet/@personemail]

because the current node is already a person element within the predicate.


问:
How can I put the names of dataframes that are stored in a list into the column names of each dataframe?
Objective: add the dataframe names as prefixes to some columns for a long list of dataframes

Problem: Using lapply or loops it seems like R doesn't pass the name of the dataframes to the method.

Data:

```<code>A<-data.frame(column_1=c(1,2,3),column_2=c(4,5,6),column_3=c(7,8,9),column_4=c(10,11,12))
B<-data.frame(column_1=c(13,14,15),column_2=c(16,17,18),column_3=c(19,20,21),column_4=c(22,23,24))
C<-data.frame(column_1=c(25,26,27),column_2=c(28,29,30),column_3=c(31,32,33),column_4=c(34,35,36))
list_of_dataframes<-list(A,B,C)
names(list_of_dataframes)<-c("A","B","C")
</code>```

This is just an example. Actually my list of dataframes is quite long. So, it comes unhandy to add names manually with 'comment' like it is done here.

Desired Solution:

```<code>$A
  A_column_1 A_column_2 A_column_3 column_4
1          1          4          7       10
2          2          5          8       11
3          3          6          9       12

$B
  B_column_1 B_column_2 B_column_3 column_4
1         13         16         19       22
2         14         17         20       23
3         15         18         21       24

$C
  C_column_1 C_column_2 C_column_3 column_4
1         25         28         31       34
2         26         29         32       35
3         27         30         33       36
</code>```

As you can see the dataframe names are in the column names, except for column 4 which I want to exclude from this operation.

My Try:

The desired solution was actually produced by some code:

```<code>comment(list_of_dataframes$A) <- "A"
comment(list_of_dataframes$B) <- "B"
comment(list_of_dataframes$C) <- "C"

list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-comment(dataframe)

  colnames(dataframe)[c(1,2,3)]<-paste(a, colnames(dataframe)[c(1,2,3)], sep = "_")

  return(dataframe)

}
)

list_of_dataframes
</code>```

The problem with this solution is that I actually have a very long list of dataframes and I have many of such lists. So, I need to do all of this in an automated fashion.
In the above code I use 'comment' where I separately type in the name of each dataframe. I need instead to automatically take the name of each dataframe. How can I do this?

I tried to use deparse(substitute(dataframe)) as here:

```<code>list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-deparse(substitute(dataframe))

  colnames(dataframe)<-paste(a, colnames(dataframe), sep = "_")

  return(dataframe)

}
)
</code>```

But, as you can see the names of the dataframe don't seem to be passed to lapply:

```<code>$A
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1               1               4               7              10
2               2               5               8              11
3               3               6               9              12

$B
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              13              16              19              22
2              14              17              20              23
3              15              18              21              24

$C
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              25              28              31              34
2              26              29              32              35
3              27              30              33              36
</code>```

Do you have any ideas how I can overcome this problem?

答:
We can also use str_c

```<code>library(dplyr)
library(purrr)
imap(list_of_dataframes, ~ {
            nm1 <- .y
            .x %>% rename_at(1:3, ~ str_c(nm1, ., sep="_"))
        })
</code>```

Body:
Objective: add the dataframe names as prefixes to some columns for a long list of dataframes

Problem: Using lapply or loops it seems like R doesn't pass the name of the dataframes to the method.

Data:

A<-data.frame(column_1=c(1,2,3),column_2=c(4,5,6),column_3=c(7,8,9),column_4=c(10,11,12))
B<-data.frame(column_1=c(13,14,15),column_2=c(16,17,18),column_3=c(19,20,21),column_4=c(22,23,24))
C<-data.frame(column_1=c(25,26,27),column_2=c(28,29,30),column_3=c(31,32,33),column_4=c(34,35,36))
list_of_dataframes<-list(A,B,C)
names(list_of_dataframes)<-c("A","B","C")

This is just an example. Actually my list of dataframes is quite long. So, it comes unhandy to add names manually with 'comment' like it is done here.

Desired Solution:

$A
  A_column_1 A_column_2 A_column_3 column_4
1          1          4          7       10
2          2          5          8       11
3          3          6          9       12

$B
  B_column_1 B_column_2 B_column_3 column_4
1         13         16         19       22
2         14         17         20       23
3         15         18         21       24

$C
  C_column_1 C_column_2 C_column_3 column_4
1         25         28         31       34
2         26         29         32       35
3         27         30         33       36

As you can see the dataframe names are in the column names, except for column 4 which I want to exclude from this operation.

My Try:

The desired solution was actually produced by some code:

comment(list_of_dataframes$A) <- "A"
comment(list_of_dataframes$B) <- "B"
comment(list_of_dataframes$C) <- "C"

list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-comment(dataframe)

  colnames(dataframe)[c(1,2,3)]<-paste(a, colnames(dataframe)[c(1,2,3)], sep = "_")

  return(dataframe)

}
)

list_of_dataframes

The problem with this solution is that I actually have a very long list of dataframes and I have many of such lists. So, I need to do all of this in an automated fashion.
In the above code I use 'comment' where I separately type in the name of each dataframe. I need instead to automatically take the name of each dataframe. How can I do this?

I tried to use deparse(substitute(dataframe)) as here:

list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-deparse(substitute(dataframe))

  colnames(dataframe)<-paste(a, colnames(dataframe), sep = "_")

  return(dataframe)

}
)

But, as you can see the names of the dataframe don't seem to be passed to lapply:

$A
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1               1               4               7              10
2               2               5               8              11
3               3               6               9              12

$B
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              13              16              19              22
2              14              17              20              23
3              15              18              21              24

$C
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              25              28              31              34
2              26              29              32              35
3              27              30              33              36

Do you have any ideas how I can overcome this problem?

Body:
We can also use str_c

library(dplyr)
library(purrr)
imap(list_of_dataframes, ~ {
            nm1 <- .y
            .x %>% rename_at(1:3, ~ str_c(nm1, ., sep="_"))
        })


问:
Gin problem using GWT - GWT.create(someClass.class) return different instance every time is called
here is my problem. I m using Gin in a gwt project, i m using GWT.create(SomeClass.class) to get instance ,but the problem is that i want signleton instance and for that purpose i bind that class in the app module to be singleton. Every tome i execute GWT.create(TemplatePanel.class) it returns different instance..why??
Here is snippet of my code.
Module

```<code>public class AppClientModule extends AbstractGinModule
{
protected void configure()
{
  bind(MainPanel.class).in(Singleton.class);
  bind(TemplatePanel.class).in(Singleton.class);
}
}
</code>```

Injector

```<code>@GinModules(AppClientModule.class)
public interface AppInjector extends Ginjector
{
  MainPanel getMainForm();
  TemplatePanel getTemplateForm();
}
</code>```

TemplatePanel

```<code>public class TemplatePanel extends VerticalPanel
@Inject
public TemplatePanel()
{
  this.add(initHeader());
  this.add(initContent());
}
..
</code>```

MainPanel

```<code>public void onSuccess(List<MyUser> result)
    {
.......
  TemplatePanel temp = GWT.create(TemplatePanel.class);

.......
}
</code>```

And the entry point

```<code>private final AppInjector injector = GWT.create(AppInjector.class);
public void onModuleLoad()
{
  MainPanel mf = injector.getMainForm();
  TemplatePanel template = injector.getTemplateForm();
  template.setContent(mf);
  RootPanel.get().add(template);
}
</code>```

答:
GWT.create(..) does not work with GIN, it just creates an object in a normal GWT way. You should either:

Inject TemplatePanel in MainPanel, or

Instantiate injector (via static method maybe) and then get TemplatePanel.

I usually have a static reference to injector (since you only need one per app) so I can access it anywhere:

```<code>@GinModules(AppClientModule.class)
public interface AppInjector extends Ginjector
{
    AppInjector INSTANCE = GWT.create(AppInjector.class);

    MainPanel getMainForm();
    TemplatePanel getTemplateForm();
}
</code>```

(Note: constant interface fields are by definition public and static, so you can omit those.)

Then you'd use:

```<code>TemplatePanel temp = AppInjector.INSTANCE.getTemplateForm();
</code>```

Body:
here is my problem. I m using Gin in a gwt project, i m using GWT.create(SomeClass.class) to get instance ,but the problem is that i want signleton instance and for that purpose i bind that class in the app module to be singleton. Every tome i execute GWT.create(TemplatePanel.class) it returns different instance..why??
Here is snippet of my code.
Module

public class AppClientModule extends AbstractGinModule
{
protected void configure()
{
  bind(MainPanel.class).in(Singleton.class);
  bind(TemplatePanel.class).in(Singleton.class);
}
}

Injector

@GinModules(AppClientModule.class)
public interface AppInjector extends Ginjector
{
  MainPanel getMainForm();
  TemplatePanel getTemplateForm();
}

TemplatePanel

public class TemplatePanel extends VerticalPanel
@Inject
public TemplatePanel()
{
  this.add(initHeader());
  this.add(initContent());
}
..

MainPanel

public void onSuccess(List<MyUser> result)
    {
.......
  TemplatePanel temp = GWT.create(TemplatePanel.class);

.......
}

And the entry point

private final AppInjector injector = GWT.create(AppInjector.class);
public void onModuleLoad()
{
  MainPanel mf = injector.getMainForm();
  TemplatePanel template = injector.getTemplateForm();
  template.setContent(mf);
  RootPanel.get().add(template);
}

Body:
GWT.create(..) does not work with GIN, it just creates an object in a normal GWT way. You should either:

Inject TemplatePanel in MainPanel, or

Instantiate injector (via static method maybe) and then get TemplatePanel.

I usually have a static reference to injector (since you only need one per app) so I can access it anywhere:

@GinModules(AppClientModule.class)
public interface AppInjector extends Ginjector
{
    AppInjector INSTANCE = GWT.create(AppInjector.class);

    MainPanel getMainForm();
    TemplatePanel getTemplateForm();
}

(Note: constant interface fields are by definition public and static, so you can omit those.)

Then you'd use:

TemplatePanel temp = AppInjector.INSTANCE.getTemplateForm();


问:
cURL results in NULL although JSON is valid
I'm curling a url that drops a json result. The result of the curl is always NULL though.

main.php

```<code>function getUserSettings(){
...
$json = json_encode($userSettings);
header('Content-Type: application/json');
return $json;
}
</code>```

getusersettings.php

```<code>...
$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();

$result = $api->getUserSettings();
echo $result;
...
</code>```

settings.php

```<code><?php
session_start();

if(isset($_SESSION['uid'])) {
    //get the user settings
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, 'https://www.url.com/api/getstgs');
    $result = curl_exec($ch);
    curl_close($ch);

    $obj = json_decode($result, true);
    print_r($obj);die();
}
...
generate html
...
?>
</code>```

The json looks like this:

{"lcns":[{"product_name":"Addon: Addonname","license_key_decrypted":"XXXXXXXXXXXXXX","expires_at":"0000-00-00 00:00:00"}],"stgs":[{"Type":"1","Amount":"0"}]}

答:
Per the shown code, the cURL call is expected to 'fail'.

This is because cURL makes a new request which does not automatically include session information or cookies. Such behavior can be duplicated using cURL from the command-line or a browser tab in a new incognito window. (Checking the result of web requests from other tools can diagnose a number of issues much quicker than code changes.)

The following is expected to fail the request instead of returning the desired JSON unless the session "uid" value has previously been established this request. It does not matter if there is a session "uid" value in the request which invoked cURL: the request made by cURL is separate.

```<code>$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();
</code>```

Body:
I'm curling a url that drops a json result. The result of the curl is always NULL though.

main.php

function getUserSettings(){
...
$json = json_encode($userSettings);
header('Content-Type: application/json');
return $json;
}

getusersettings.php

...
$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();

$result = $api->getUserSettings();
echo $result;
...

settings.php

<?php
session_start();

if(isset($_SESSION['uid'])) {
    //get the user settings
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, 'https://www.url.com/api/getstgs');
    $result = curl_exec($ch);
    curl_close($ch);

    $obj = json_decode($result, true);
    print_r($obj);die();
}
...
generate html
...
?>

The json looks like this:

{"lcns":[{"product_name":"Addon: Addonname","license_key_decrypted":"XXXXXXXXXXXXXX","expires_at":"0000-00-00 00:00:00"}],"stgs":[{"Type":"1","Amount":"0"}]}

Body:
Per the shown code, the cURL call is expected to 'fail'.

This is because cURL makes a new request which does not automatically include session information or cookies. Such behavior can be duplicated using cURL from the command-line or a browser tab in a new incognito window. (Checking the result of web requests from other tools can diagnose a number of issues much quicker than code changes.)

The following is expected to fail the request instead of returning the desired JSON unless the session "uid" value has previously been established this request. It does not matter if there is a session "uid" value in the request which invoked cURL: the request made by cURL is separate.

$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();


问:
How to Create SMS API using Node.js
I need to send notifications and special messages to my app users as an SMS. so I want to make SMS API. how can I create it using node.js?

答:
You can use the nexmo communication API; Run

npm install nexmo

for the package

```<code>const Nexmo = require('nexmo')

const nexmo = new Nexmo({
    apiKey: '*****',
    apiSecret: '*****',
});
var to = 'numberTo';
var from = 'brandName';
var text = 'someText';
nexmo.message.sendSms(from, to, text);
</code>```

Title: How to Create SMS API using Node.js

Body:
You can use the nexmo communication API; Run

npm install nexmo

for the package

const Nexmo = require('nexmo')

const nexmo = new Nexmo({
    apiKey: '*****',
    apiSecret: '*****',
});
var to = 'numberTo';
var from = 'brandName';
var text = 'someText';
nexmo.message.sendSms(from, to, text);