问:
List with arrays into seperate arrays
I have a constructor which uses a List parameter. Inside that list I have three items which are 3 integer arrays.

```<code>public HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)
</code>```

Now I want to initialize three new integer arrays with the arrays inside that list. But when I try this code, the index of my new arrays stay 0.

```<code>for (int i = 0; i < histogramXValues.Length; i++)
{
     rArray = separateRGB.Select(obj => obj.Item1[i]).ToArray();
     gArray = separateRGB.Select(obj => obj.Item2[i]).ToArray();
     bArray = separateRGB.Select(obj => obj.Item3[i]).ToArray();
}
</code>```

Anyone got any suggestions on how to fix this?

答:
Like they sad in comments you did reassign local member in each loop.
You could use something like this.

```<code>public HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)
{
    List<int> rList = new List<int>();
    List<int> gList = new List<int>();
    List<int> bList = new List<int>();

    separateRGB.ForEach((Tuple<int[], int[], int[]> tpl) =>
    {
        rList.AddRange(tpl.Item1);
        gList.AddRange(tpl.Item1);
        bList.AddRange(tpl.Item1);

    });

    rArray = rList.ToArray();
    gArray = gList.ToArray();
    bArray = bList.ToArray();

}
</code>```

If you wish to not use temp List object you should know final count of elements in tuple, create local array member to desired size. and fill it. List are more suitable for adding and expanding elements. Maybe you could use one Linq Statement but if I understand goal is to get one int[] array per color. If you take

```<code>separateRGB.AsQueryable().Select(m => m.Item1).ToArray();
</code>```

as a result you get int[][] result instead of simple int array;

Title: List with arrays into seperate arrays

Body:
I have a constructor which uses a List parameter. Inside that list I have three items which are 3 integer arrays.

public HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)

Now I want to initialize three new integer arrays with the arrays inside that list. But when I try this code, the index of my new arrays stay 0.

for (int i = 0; i < histogramXValues.Length; i++)
{
     rArray = separateRGB.Select(obj => obj.Item1[i]).ToArray();
     gArray = separateRGB.Select(obj => obj.Item2[i]).ToArray();
     bArray = separateRGB.Select(obj => obj.Item3[i]).ToArray();
}

Anyone got any suggestions on how to fix this?

Body:
Like they sad in comments you did reassign local member in each loop.
You could use something like this.

public HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)
{
    List<int> rList = new List<int>();
    List<int> gList = new List<int>();
    List<int> bList = new List<int>();

    separateRGB.ForEach((Tuple<int[], int[], int[]> tpl) =>
    {
        rList.AddRange(tpl.Item1);
        gList.AddRange(tpl.Item1);
        bList.AddRange(tpl.Item1);

    });

    rArray = rList.ToArray();
    gArray = gList.ToArray();
    bArray = bList.ToArray();

}

If you wish to not use temp List object you should know final count of elements in tuple, create local array member to desired size. and fill it. List are more suitable for adding and expanding elements. Maybe you could use one Linq Statement but if I understand goal is to get one int[] array per color. If you take

separateRGB.AsQueryable().Select(m => m.Item1).ToArray();

as a result you get int[][] result instead of simple int array;


来源: stackexchange

问:
font-awesome icons not showing up in Chrome 61
I've downloaded font-awesome icons in my project and imported font-awesome.min.css as

```<code><link rel="stylesheet" href="resources/font-awesome/css/font-awesome.min.css">
</code>```

And used them simply like

```<code><i class="fa fa-user-o" aria-hidden="true"></i>
</code>```

The stylesheet was loaded so there was no problem with the path.

The icons worked fine in Firefox, but didn't show up in Chrome 61 at all,  neither in Win 10 nor Linux, so I guess it has nothing to do with OS.

I don't have any plugin in Chrome that would be conflicting.

I've also tried <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> but nothing changed.

Does anyone know what might cause this problem? Thanks!

答: I'm having this exact same issue. I tried re-downloading the fonts and the css, rewriting my css into a new file, removing some of the scripts and tags in the head tag and nothing works. It seems to be related to Chrome 61. I was going to report this to the FA's github, but it looks like someone already did. </p>

ContentLicense: CC BY-SA 3.0

Body:
I've downloaded font-awesome icons in my project and imported font-awesome.min.css as

<link rel="stylesheet" href="resources/font-awesome/css/font-awesome.min.css">

And used them simply like

The stylesheet was loaded so there was no problem with the path.

The icons worked fine in Firefox, but didn't show up in Chrome 61 at all,  neither in Win 10 nor Linux, so I guess it has nothing to do with OS.

I don't have any plugin in Chrome that would be conflicting.

I've also tried <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> but nothing changed.

Does anyone know what might cause this problem? Thanks!


问:
mySQL and html form
I've made a form with the help of bootstrap studio and I've already created a database and established a connection using php.
Here's just the html(no css)

```<code><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/fonts/ionicons.min.css">
    <link rel="stylesheet" href="assets/css/Login-Form-Dark.css">
    <link rel="stylesheet" href="assets/css/Registration-Form-with-Photo.css">
    <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body>
    <div class="login-dark" style="background-image:url("assets/img/login-background.jpg");background-color:rgb(255,255,255);">
        <form action="login.php" method="POST">
            <h2 class="sr-only">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group">
    <input class="form-control" type="text" name="username" placeholder="Username">
</div>

            <div class="form-group">
    <input class="form-control" type="password" name="password" placeholder="Password">
</div>
            <div class="form-group">
                <button class="btn btn-primary btn-block" type="submit">Log In</button>
            </div><a href="#" class="forgot">Forgot your email or password?</a></form>
    </div>
</body>
</html>
</code>```

Here's the php:

```<code><?php
include('includes/DB.php');
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    echo submitted;
    //Runs query to see if username exists
    if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
        //Runs query to search for password
        $passwordDB = DB::query('SELECT password FROM users where username=:username', array(':username'=>$username))[0]['password'];
        //Checks if password already exists
        if($password==$passwordDB) {
            echo 'Logged in!';
            header('Location: main-page');
            //Create cookiee  for user to be logged in
            $cstrong = True;

     $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
            $user_id = DB::query("SELECT id FROM users WHERE username=:username", array('username'=>$username))[0]['id'];
            //store token in database
            //sha1 will hash the token
            DB::query("INSERT INTO login_tokens VALUES ('', :token, :user_id)",array(':token'=>sha1($token), ':user_id'=>$user_id));

            //cookie to log the user in
            //cookie will be valid for 1 week (time()+60*60*24*7)
            setcookie("SNID",$token, time()+60*60*24*7, '/', NULL,NULL,TRUE);
            setcookie("SNID_",1,time()+60*60*24*3, '/', NULL,NULL,TRUE);
            header('Location: main-page.php');
        } else {
            echo 'Incorrect Password!';
        }
    }
    else {
        echo 'User not registered!';
    }
};
?>
</code>```

However, when I log in, nothing happens. It's supposed to echo out logged in and then redirect me to another page
(I'm using XAMPP with phpmyadmin if that helps)

I've tried to add

```<code>include("login.html");
</code>```

on top of the php file, however it makes no difference.

Before I used bootstrap studio I created a simple plain html form and it worked, as soon as I used bootsrap studio to make the form look nicer, I got this problem.
Fairly new to php and mySQL, how could I fix it?

答:
Try this and let me know what is displayed.

html file:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/fonts/ionicons.min.css">
    <link rel="stylesheet" href="assets/css/Login-Form-Dark.css">
    <link rel="stylesheet" href="assets/css/Registration-Form-with-Photo.css">
    <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body>
    <div class="login-dark" style="background-image:url("assets/img/login-background.jpg");background-color:rgb(255,255,255);">
        <form action="login.php" method="POST">
            <h2 class="sr-only">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group">
    <input class="form-control" type="text" name="username" placeholder="Username">
</div>

            <div class="form-group">
    <input class="form-control" type="password" name="password" placeholder="Password">
</div>
            <div class="form-group">
                <button class="btn btn-primary btn-block" type="submit" name="login">Log In</button>
            </div><a href="#" class="forgot">Forgot your email or password?</a></form>
    </div>
</body>
</html>
</code>```

Php

```<code><?php
include('includes/DB.php');
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    echo "username: ";
    echo $username;
    echo "<br>";
    echo "password: ";
    echo $password;

    //Runs query to see if username exists
    if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
        //Runs query to search for password
        $passwordDB = DB::query('SELECT password FROM users where username=:username', array(':username'=>$username))[0]['password'];
        //Checks if password already exists
        if($password==$passwordDB) {
            echo 'Logged in!';
            //Create cookiee  for user to be logged in
            $cstrong = True;

     $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
            $user_id = DB::query("SELECT id FROM users WHERE username=:username", array('username'=>$username))[0]['id'];
            //store token in database
            //sha1 will hash the token
            DB::query("INSERT INTO login_tokens VALUES ('', :token, :user_id)",array(':token'=>sha1($token), ':user_id'=>$user_id));

            //cookie to log the user in
            //cookie will be valid for 1 week (time()+60*60*24*7)
            setcookie("SNID",$token, time()+60*60*24*7, '/', NULL,NULL,TRUE);
            setcookie("SNID_",1,time()+60*60*24*3, '/', NULL,NULL,TRUE);

            die();
            header('Location: main-page.php');
        } else {
            echo 'Incorrect Password!';
            die();
        }
    }
    else {
        echo 'User not registered!';
        die();
    }
};
?>
</code>```

Title: mySQL and html form

Body:
I've made a form with the help of bootstrap studio and I've already created a database and established a connection using php.
Here's just the html(no css)

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/fonts/ionicons.min.css">
    <link rel="stylesheet" href="assets/css/Login-Form-Dark.css">
    <link rel="stylesheet" href="assets/css/Registration-Form-with-Photo.css">
    <link rel="stylesheet" href="assets/css/styles.css">

        <form action="login.php" method="POST">

Login Form

    <input class="form-control" type="text" name="username" placeholder="Username">

    <input class="form-control" type="password" name="password" placeholder="Password">

                <button class="btn btn-primary btn-block" type="submit">Log In</button>

Forgot your email or password?</form>

Here's the php:

<?php
include('includes/DB.php');
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    echo submitted;
    //Runs query to see if username exists
    if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
        //Runs query to search for password
        $passwordDB = DB::query('SELECT password FROM users where username=:username', array(':username'=>$username))[0]['password'];
        //Checks if password already exists
        if($password==$passwordDB) {
            echo 'Logged in!';
            header('Location: main-page');
            //Create cookiee  for user to be logged in
            $cstrong = True;

     $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
            $user_id = DB::query("SELECT id FROM users WHERE username=:username", array('username'=>$username))[0]['id'];
            //store token in database
            //sha1 will hash the token
            DB::query("INSERT INTO login_tokens VALUES ('', :token, :user_id)",array(':token'=>sha1($token), ':user_id'=>$user_id));

            //cookie to log the user in
            //cookie will be valid for 1 week (time()+60*60*24*7)
            setcookie("SNID",$token, time()+60*60*24*7, '/', NULL,NULL,TRUE);
            setcookie("SNID_",1,time()+60*60*24*3, '/', NULL,NULL,TRUE);
            header('Location: main-page.php');
        } else {
            echo 'Incorrect Password!';
        }
    }
    else {
        echo 'User not registered!';
    }
};
?>

However, when I log in, nothing happens. It's supposed to echo out logged in and then redirect me to another page
(I'm using XAMPP with phpmyadmin if that helps)

I've tried to add

include("login.html");

on top of the php file, however it makes no difference.

Before I used bootstrap studio I created a simple plain html form and it worked, as soon as I used bootsrap studio to make the form look nicer, I got this problem.
Fairly new to php and mySQL, how could I fix it?

Body:
Try this and let me know what is displayed.

html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/fonts/ionicons.min.css">
    <link rel="stylesheet" href="assets/css/Login-Form-Dark.css">
    <link rel="stylesheet" href="assets/css/Registration-Form-with-Photo.css">
    <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body>
    <div class="login-dark" style="background-image:url(&quot;assets/img/login-background.jpg&quot;);background-color:rgb(255,255,255);">
        <form action="login.php" method="POST">
            <h2 class="sr-only">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group">
    <input class="form-control" type="text" name="username" placeholder="Username">
</div>

            <div class="form-group">
    <input class="form-control" type="password" name="password" placeholder="Password">
</div>
            <div class="form-group">
                <button class="btn btn-primary btn-block" type="submit" name="login">Log In</button>
            </div><a href="#" class="forgot">Forgot your email or password?</a></form>
    </div>
</body>
</html>

Php

<?php
include('includes/DB.php');
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    echo "username: ";
    echo $username;
    echo "<br>";
    echo "password: ";
    echo $password;

    //Runs query to see if username exists
    if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
        //Runs query to search for password
        $passwordDB = DB::query('SELECT password FROM users where username=:username', array(':username'=>$username))[0]['password'];
        //Checks if password already exists
        if($password==$passwordDB) {
            echo 'Logged in!';
            //Create cookiee  for user to be logged in
            $cstrong = True;

     $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
            $user_id = DB::query("SELECT id FROM users WHERE username=:username", array('username'=>$username))[0]['id'];
            //store token in database
            //sha1 will hash the token
            DB::query("INSERT INTO login_tokens VALUES ('', :token, :user_id)",array(':token'=>sha1($token), ':user_id'=>$user_id));

            //cookie to log the user in
            //cookie will be valid for 1 week (time()+60*60*24*7)
            setcookie("SNID",$token, time()+60*60*24*7, '/', NULL,NULL,TRUE);
            setcookie("SNID_",1,time()+60*60*24*3, '/', NULL,NULL,TRUE);

            die();
            header('Location: main-page.php');
        } else {
            echo 'Incorrect Password!';
            die();
        }
    }
    else {
        echo 'User not registered!';
        die();
    }
};
?>


问:
Storing values from child to parent class
I want to know how to store values from child to parent class.

```<code>public class Question {

private HashMap<String,ArrayList<String>> mcqHashMap = new HashMap<String,ArrayList<String>>(); //storing question and options of MCQ
public ArrayList<String> rankingquestion = new ArrayList<String>();
public Scanner scan = new Scanner(System.in);
public ArrayList<String> correctMCQAnswer = new ArrayList<String>(); // will keeps the correct answer of each question
HashMap<String,ArrayList<String>> newmcqHashMap;

public HashMap<String, ArrayList<String>> getMCQQuestionAnswer() {
    System.out.println("NEW:" + mcqHashMap);
    return this.newmcqHashMap;

}

public void setMCQQuestionAnswer(HashMap<String, ArrayList<String>> mcqQuestionAnswer) {
    this.mcqHashMap = mcqQuestionAnswer;
    System.out.println("After setting" + this.mcqHashMap);
    newmcqHashMap = this.mcqHashMap;
}

}

public class MultipleChoiceQuestion extends Question {

String storeMultipleChoiceQuestion;
ArrayList<String> answersMCQ = new ArrayList<String>();
HashMap<String, ArrayList<String>> mcqQuestionAnswer = new HashMap<String, ArrayList<String>>();

//returns MCQQuestion
public String storeMultipleChoiceQuestion() {
    System.out.println("Enter the Multiple question: ");
    String MultipleChoiceQuestion = scan.nextLine();
    while(MultipleChoiceQuestion.isEmpty()) {
        System.out.println("Null in invalid");
        MultipleChoiceQuestion = scan.nextLine();

    }
    return MultipleChoiceQuestion;
}

//creates MCQ Questions with mcq options
public void create() {
    String value = storeMultipleChoiceQuestion();
    try {
        System.out.println("Enter the number of choices for your multiple choice question:");
        int numberOfChoices = scan.nextInt();
        scan.nextLine();
        if(numberOfChoices <= 0) {
            System.out.println("Must be greater than 0");
        }
        else {
            for(int i=1; i <= numberOfChoices; i++){
                System.out.println("Enter prompt " + i);
                String Option = scan.nextLine();
                answersMCQ.add(Option);
                while(Option.isEmpty()) {
                    System.out.println("Null in invalid");
                     Option = scan.nextLine();
                }
                mcqQuestionAnswer.put(value, answersMCQ);
                super.setMCQQuestionAnswer(mcqQuestionAnswer);
                //this.mcqHashMap.put(value, answersMCQ);
            }
        }
        }catch (Exception e) {
        System.out.println("Exception thrown! Use integer greater than 0.");
        }
        }
</code>```

upto here its fine...

Now, when I try to access from another child class Survey.

```<code>public class Survey extends Question implements Serializable {

MultipleChoiceQuestion mcq = new MultipleChoiceQuestion();
public void Display() {

    System.out.println("THis is from get " + this.getMCQQuestionAnswer());
    System.out.println("THis is from get mcqhash" + this.newmcqHashMap);

}
</code>```

`
Doesn't print anything...

I'm sure I am doing wrong somewhere. I also used getter setter in parent class but still no luck. So basically, question will store into mcqHashMap and I want to use the stored mcqHashMap for displaying purpose from Survey class.

Help is appreciated. Thanks

答:
Nevermind guys, I figured it out. Thanks! I made protected static instead of protected hashmap. Bad practice but works!

Thanks for the help.

Body:
I want to know how to store values from child to parent class.

public class Question {

private HashMap<String,ArrayList<String>> mcqHashMap = new HashMap<String,ArrayList<String>>(); //storing question and options of MCQ
public ArrayList<String> rankingquestion = new ArrayList<String>();
public Scanner scan = new Scanner(System.in);
public ArrayList<String> correctMCQAnswer = new ArrayList<String>(); // will keeps the correct answer of each question
HashMap<String,ArrayList<String>> newmcqHashMap;

public HashMap<String, ArrayList<String>> getMCQQuestionAnswer() {
    System.out.println("NEW:" + mcqHashMap);
    return this.newmcqHashMap;

}

public void setMCQQuestionAnswer(HashMap<String, ArrayList<String>> mcqQuestionAnswer) {
    this.mcqHashMap = mcqQuestionAnswer;
    System.out.println("After setting" + this.mcqHashMap);
    newmcqHashMap = this.mcqHashMap;
}

}

public class MultipleChoiceQuestion extends Question {

String storeMultipleChoiceQuestion;
ArrayList<String> answersMCQ = new ArrayList<String>();
HashMap<String, ArrayList<String>> mcqQuestionAnswer = new HashMap<String, ArrayList<String>>();

//returns MCQQuestion
public String storeMultipleChoiceQuestion() {
    System.out.println("Enter the Multiple question: ");
    String MultipleChoiceQuestion = scan.nextLine();
    while(MultipleChoiceQuestion.isEmpty()) {
        System.out.println("Null in invalid");
        MultipleChoiceQuestion = scan.nextLine();

    }
    return MultipleChoiceQuestion;
}

//creates MCQ Questions with mcq options
public void create() {
    String value = storeMultipleChoiceQuestion();
    try {
        System.out.println("Enter the number of choices for your multiple choice question:");
        int numberOfChoices = scan.nextInt();
        scan.nextLine();
        if(numberOfChoices <= 0) {
            System.out.println("Must be greater than 0");
        }
        else {
            for(int i=1; i <= numberOfChoices; i++){
                System.out.println("Enter prompt " + i);
                String Option = scan.nextLine();
                answersMCQ.add(Option);
                while(Option.isEmpty()) {
                    System.out.println("Null in invalid");
                     Option = scan.nextLine();
                }
                mcqQuestionAnswer.put(value, answersMCQ);
                super.setMCQQuestionAnswer(mcqQuestionAnswer);
                //this.mcqHashMap.put(value, answersMCQ);
            }
        }
        }catch (Exception e) {
        System.out.println("Exception thrown! Use integer greater than 0.");
        }
        }

upto here its fine...

Now, when I try to access from another child class Survey.

public class Survey extends Question implements Serializable {

MultipleChoiceQuestion mcq = new MultipleChoiceQuestion();
public void Display() {

    System.out.println("THis is from get " + this.getMCQQuestionAnswer());
    System.out.println("THis is from get mcqhash" + this.newmcqHashMap);

}

`
Doesn't print anything...

I'm sure I am doing wrong somewhere. I also used getter setter in parent class but still no luck. So basically, question will store into mcqHashMap and I want to use the stored mcqHashMap for displaying purpose from Survey class.

Help is appreciated. Thanks


问:
group array object by multiple properties
I'm trying to group the following array with objects base on the siteId:

```<code>var Details = [
   {
       "addressId": "399906",
       "extAddressId": null,
       "addressType": "ORDER_FULFILLMENT",
       "siteId": 101,
       "bankAccount": [
              {"bankAccountId": "409539","extBankAccountId":null,"primary": true},
              {"bankAccountId": "409537","extBankAccountId": null, "primary": false},
              {"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
       ],
       "contactId": ["399908"],
       "extContactId": null,
       "emailForPurchaseOrders": "test@test.com",
       "emailForRemittance": "example@example.com",
       "emailLanguage": "English"
   },
   {
       "addressId": "399906",
       "extAddressId": null,
       "addressType": "LEGAL",
       "siteId": 101,
       "bankAccount": [
             {"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
             {"bankAccountId": "409540","extBankAccountId":null,"primary": true},
       ],
       "contactId": [],
       "extContactId": null,
       "emailForPurchaseOrders": "example@example.com",
       "emailForRemittance": "test@test.com",
       "emailLanguage": "English"
   }
]
</code>```

To something like this:

```<code>{
   "addressId": ["399906"],
   "addressType": ["ORDER_FULFILLMENT", "LEGAL"],
   "siteId": 101,
   "bankAccount": [
        {
           "bankAccountId": "409539",
           "extBankAccountId": null,
           "primary": true
        },
        {
           "bankAccountId": "409537",
           "extBankAccountId": null,
           "primary": false
        },
        {
           "bankAccountId": "399907",
           "extBankAccountId": null,
           "primary": false
        },
        {
            "bankAccountId":"409540",
            "extBankAccountId":null,
            "primary": true
        },
    ],
    "contactId": ["399908"],
    "emailForPurchaseOrders": ["test@test.com", "example@example.com"],
    "emailForRemittance": ["example@example.com","test@test.com"],
    "emailLanguage": "English"
},
</code>```

Right now I'm trying to group it but could not get the above structure to meet my needs. so far this is what i am trying to do to achieve it. Any help be highly appreciated.

```<code>       var group_to_values = subscriptionDetail.reduce(function (obj, item) {
            obj[item.siteId] = obj[item.siteId] || [];
            obj[item.siteId].push(item);
            return obj;
        }, {});
        console.log(group_to_values);
        var groups = Object.keys(group_to_values).map(function (key) {
            return {siteId: key, details: group_to_values[key]};
        });
</code>```

I know I'm missing something but can't figure it out. Any suggestion?

答:
`

```<code> var Details = [
    {
        "addressId": "399906",
        "extAddressId": null,
        "addressType": "ORDER_FULFILLMENT",
        "siteId": 101,
        "bankAccount": [
                {"bankAccountId": "409539","extBankAccountId":null,"primary": true},
                {"bankAccountId": "409537","extBankAccountId": null, "primary": false},
                {"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
        ],
        "contactId": ["399908"],
        "extContactId": null,
        "emailForPurchaseOrders": "test@test.com",
        "emailForRemittance": "example@example.com",
        "emailLanguage": "English"
    }
    ]

    let detailTwo = Details.map(item => {
    let keys = Object.keys(item);
    let copy = Object.assign({}, item);
    keys.forEach( val => {
        if(Array.isArray(copy[val]) && val !== 'bankAccount') {
            copy[val] = copy[val][0];
        }
        if(copy[val] === null) {
            delete copy[val];
        }
    });
return copy;
});

console.log(detailTwo);
</code>```

`

Body:
I'm trying to group the following array with objects base on the siteId:

var Details = [
   {
       "addressId": "399906",
       "extAddressId": null,
       "addressType": "ORDER_FULFILLMENT",
       "siteId": 101,
       "bankAccount": [
              {"bankAccountId": "409539","extBankAccountId":null,"primary": true},
              {"bankAccountId": "409537","extBankAccountId": null, "primary": false},
              {"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
       ],
       "contactId": ["399908"],
       "extContactId": null,
       "emailForPurchaseOrders": "test@test.com",
       "emailForRemittance": "example@example.com",
       "emailLanguage": "English"
   },
   {
       "addressId": "399906",
       "extAddressId": null,
       "addressType": "LEGAL",
       "siteId": 101,
       "bankAccount": [
             {"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
             {"bankAccountId": "409540","extBankAccountId":null,"primary": true},
       ],
       "contactId": [],
       "extContactId": null,
       "emailForPurchaseOrders": "example@example.com",
       "emailForRemittance": "test@test.com",
       "emailLanguage": "English"
   }
]

To something like this:

{
   "addressId": ["399906"],
   "addressType": ["ORDER_FULFILLMENT", "LEGAL"],
   "siteId": 101,
   "bankAccount": [
        {
           "bankAccountId": "409539",
           "extBankAccountId": null,
           "primary": true
        },
        {
           "bankAccountId": "409537",
           "extBankAccountId": null,
           "primary": false
        },
        {
           "bankAccountId": "399907",
           "extBankAccountId": null,
           "primary": false
        },
        {
            "bankAccountId":"409540",
            "extBankAccountId":null,
            "primary": true
        },
    ],
    "contactId": ["399908"],
    "emailForPurchaseOrders": ["test@test.com", "example@example.com"],
    "emailForRemittance": ["example@example.com","test@test.com"],
    "emailLanguage": "English"
},

Right now I'm trying to group it but could not get the above structure to meet my needs. so far this is what i am trying to do to achieve it. Any help be highly appreciated.

       var group_to_values = subscriptionDetail.reduce(function (obj, item) {
            obj[item.siteId] = obj[item.siteId] || [];
            obj[item.siteId].push(item);
            return obj;
        }, {});
        console.log(group_to_values);
        var groups = Object.keys(group_to_values).map(function (key) {
            return {siteId: key, details: group_to_values[key]};
        });

I know I'm missing something but can't figure it out. Any suggestion?

Body:
`

 var Details = [
    {
        "addressId": "399906",
        "extAddressId": null,
        "addressType": "ORDER_FULFILLMENT",
        "siteId": 101,
        "bankAccount": [
                {"bankAccountId": "409539","extBankAccountId":null,"primary": true},
                {"bankAccountId": "409537","extBankAccountId": null, "primary": false},
                {"bankAccountId": "399907", "extBankAccountId": null, "primary": false}
        ],
        "contactId": ["399908"],
        "extContactId": null,
        "emailForPurchaseOrders": "test@test.com",
        "emailForRemittance": "example@example.com",
        "emailLanguage": "English"
    }
    ]

    let detailTwo = Details.map(item => {
    let keys = Object.keys(item);
    let copy = Object.assign({}, item);
    keys.forEach( val => {
        if(Array.isArray(copy[val]) && val !== 'bankAccount') {
            copy[val] = copy[val][0];
        }
        if(copy[val] === null) {
            delete copy[val];
        }
    });
return copy;
});

console.log(detailTwo);

`


问:
Heroku Rails - 500 Internal Server Error
When I post something in my Rails app (locally), it works perfectly. However, when I deploy it on Herokuapp, it breaks. Here is what I have:

```<code>#Gemfile

# Use sqlite3 as the database for Active Record
gem 'sqlite3', group: :development
gem 'pg', '0.18.1', group: :production
gem 'rails_12factor', group: :production

#database.yml

production:
<<: *default
adapter: postgresql
database: db/production.sqlite3
</code>```

I then proceeded to deploy my app to Heroku like this:

```<code>git add .
git commit -m "comment"
git push heroku master
heroku run rake db:migrate
heroku run rake db:seed
</code>```

I've checked my version using the following:

```<code>heroku run rake db:version
>> Current version: 20171103035018
rake db:version
>> Current version: 20171103035018
</code>```

Finally, here is my controller where I perform a create action:

```<code>#suggestions_controller.rb

def create
    @suggestion = Suggestion.new(suggestion_params)

    if @suggestion.save
        flash[:notice] = "Suggestion successfully posted!"
        redirect_to root_path
    else
        flash[:error] = "Suggestion failed to post!"
        redirect_to root_path
    end
end

private
    def suggestion_params
        params.require(:suggestion).permit(:suggester, :ip, :suggestion_type, :title, :body)
    end
</code>```

I tried this on my localhost and it creates just fine, but when I deploy it on Heroku, it displays this error:

I'm pretty certain I did everything correctly and I have no idea what's breaking here.

Thanks for any help.

Edit: I just got a lead to the problem. It says that my created_at is null.

ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint

I'm researching on the web now to see how I can fix this problem.

答:
Well, you should take a look at your logs. Heroku documented their logging here: https://devcenter.heroku.com/articles/logging
From your description, it may be something about your database setup, e.g. wrong database.yml.
If the logs don't help you, please fix the indentation of your database.yml posted above.</p>

Body:
When I post something in my Rails app (locally), it works perfectly. However, when I deploy it on Herokuapp, it breaks. Here is what I have:

#Gemfile

# Use sqlite3 as the database for Active Record
gem 'sqlite3', group: :development
gem 'pg', '0.18.1', group: :production
gem 'rails_12factor', group: :production

#database.yml

production:
<<: *default
adapter: postgresql
database: db/production.sqlite3

I then proceeded to deploy my app to Heroku like this:

git add .
git commit -m "comment"
git push heroku master
heroku run rake db:migrate
heroku run rake db:seed

I've checked my version using the following:

heroku run rake db:version
>> Current version: 20171103035018
rake db:version
>> Current version: 20171103035018

Finally, here is my controller where I perform a create action:

#suggestions_controller.rb

def create
    @suggestion = Suggestion.new(suggestion_params)

    if @suggestion.save
        flash[:notice] = "Suggestion successfully posted!"
        redirect_to root_path
    else
        flash[:error] = "Suggestion failed to post!"
        redirect_to root_path
    end
end

private
    def suggestion_params
        params.require(:suggestion).permit(:suggester, :ip, :suggestion_type, :title, :body)
    end

I tried this on my localhost and it creates just fine, but when I deploy it on Heroku, it displays this error:

I'm pretty certain I did everything correctly and I have no idea what's breaking here.

Thanks for any help.

Edit: I just got a lead to the problem. It says that my created_at is null.

ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint

I'm researching on the web now to see how I can fix this problem.


问:
help with rewriterule
Why wont http://mysite.com/threads/add go to post.php? instead it only show main.php no matter what i write after threads/

```<code> RewriteRule threads/? /forum/main.php
 RewriteRule threads/add$ /forum/post.php
</code>```

答:
When a request to anything with "/threads" comes in, it's being Rewritten to "/forum/main.php". Since "/forum/main.php" doesn't match your second RewriteRule it gets skipped.

To do what you're expecting, you should A) order your RewriteRules in order of precedence, and B) anchor your matches, like so:

```<code>RewriteRule ^/threads/?$ /forum/main.php
RewriteRule ^/threads/add$ /forum/post.php
</code>```

And honestly, those could be cleaned up and made more flexible too.

ContentLicense: CC BY-SA 2.5

Title: help with rewriterule

Body:
Why wont http://mysite.com/threads/add go to post.php? instead it only show main.php no matter what i write after threads/

 RewriteRule threads/? /forum/main.php
 RewriteRule threads/add$ /forum/post.php

Body:
When a request to anything with "/threads" comes in, it's being Rewritten to "/forum/main.php". Since "/forum/main.php" doesn't match your second RewriteRule it gets skipped.

To do what you're expecting, you should A) order your RewriteRules in order of precedence, and B) anchor your matches, like so:

RewriteRule ^/threads/?$ /forum/main.php
RewriteRule ^/threads/add$ /forum/post.php

And honestly, those could be cleaned up and made more flexible too.


问:
External powershell scripts only run once when action called
I am trying to call an outside ps script to run every time files are created. The monitoring and logging of files work well, but the Invoke-Expression of running the external script only runs one time even if more files are created. How do I run the external script with every time a new file is created.

```<code>### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "c:\mypath"
    $watcher.Filter = "*.txt*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "C:\mypath\log.txt" -value $logline
                Invoke-Expression (start powershell ("C:\MyOtherScript.ps1")) ###### This only runs one time even if file is changes and logged
              }

### DECIDE WHICH EVENTS SHOULD BE WATCHED

    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 5}
</code>```

EDIT: This got it working incase anyone find themselves here looking to solve the porblem

```<code>### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "c:\mypath"
    $watcher.Filter = "*.txt*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "C:\mypath\log.txt" -value $logline
                Start-Process powershell -argument "C:\MyOtherScript.ps1"
              }

### DECIDE WHICH EVENTS SHOULD BE WATCHED

    Register-ObjectEvent $watcher "Created" -Action $action
    #while ($true) {sleep 5}
</code>```

答:
Invoke-Expression is not recommend over using & due to security concerns.  In your example, however, I'd suggest Start-Process:

```<code>Start-Process -FilePath 'powershell' -ArgumentList @('-File','"C:\MyOtherScript.ps1"')
</code>```

Body:
I am trying to call an outside ps script to run every time files are created. The monitoring and logging of files work well, but the Invoke-Expression of running the external script only runs one time even if more files are created. How do I run the external script with every time a new file is created.

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "c:\mypath"
    $watcher.Filter = "*.txt*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "C:\mypath\log.txt" -value $logline
                Invoke-Expression (start powershell ("C:\MyOtherScript.ps1")) ###### This only runs one time even if file is changes and logged
              }

### DECIDE WHICH EVENTS SHOULD BE WATCHED

    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 5}

EDIT: This got it working incase anyone find themselves here looking to solve the porblem

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "c:\mypath"
    $watcher.Filter = "*.txt*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "C:\mypath\log.txt" -value $logline
                Start-Process powershell -argument "C:\MyOtherScript.ps1"
              }

### DECIDE WHICH EVENTS SHOULD BE WATCHED

    Register-ObjectEvent $watcher "Created" -Action $action
    #while ($true) {sleep 5}

Body:
Invoke-Expression is not recommend over using & due to security concerns.  In your example, however, I'd suggest Start-Process:

Start-Process -FilePath 'powershell' -ArgumentList @('-File','"C:\MyOtherScript.ps1"')


问:
Azure continuous webjob fails in some cases
I have a continuous webjob that is running on azure that after a larger deployment 8 hours ago gets the status never finished in some cases and in other cases completed the job.
I have enabled all logging I could find and have been spending quite a few hours trying to figure out what the problem is.

The only log error information I seem to be able to find is from the job_log which states:

[11/15/2017 14:46:23 > e553e5: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (404) Not Found. ---> System.Net.WebException: The remote server returned an error: (404) Not Found.
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase1 cmd, Exception ex) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Shared\Protocol\HttpResponseParsers.Common.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.<DeleteBlobImpl>b__33(RESTCommand1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 3349
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 299
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of inner exception stack trace ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.EndDelete(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 1729
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass4.b__3(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 114
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Protocols.PersistentQueueWriter1.<DeleteAsync>d__6.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Loggers.CompositeFunctionInstanceLogger.<DeleteLogFunctionStartedAsync>d__e.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.<TryExecuteAsync>d__1.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.TriggeredFunctionExecutor1.d__0.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Timers.BackgroundExceptionDispatcher.<>c__DisplayClass1.b__0()
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart()

Can anyone give me some ideas on how to debug this, because I am out of ideas.

My webjobs main looks like this:

```<code> static void Main()
    {
         var host = new JobHost();

        var config = new JobHostConfiguration();
        config.Queues.MaxPollingInterval = new TimeSpan(0,0,0,30);
        config.Queues.MaxDequeueCount = 3;
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }
</code>```

and the processqueuemessage looks like:

```<code> public static void ProcessQueueMessage([QueueTrigger("importqueue")] string msg)
    {
        try
        {
            WorkerWebJobCore wwjc = new WorkerWebJobCore();
            wwjc.RunCore(msg, TableStorageAccessResources.ImportQueue,
                TableStorageAccessResources.TableStorageDataOneId,
                TableStorageAccessResources.TableStorageDataOnePassword);
        }
        catch (Exception e)
        {
            CommunicatorLog.Log.LogError("WebJobWorker","WebJobWorker","Error in processing queue message","ERRWJWF01");
        }
    }
</code>```

So I have a catch around everything, therefore I don't get how it can fail?

Thanks in advance.

答:
Apparently running versions below 2.0.0 of the Microsoft.Azure.Webjob makes it impossible to get a useful answer.
When I finally got around to try and install that version, it pointed me to the issues with useful error messages.

Issues were related to wrong versions of dlls in regards to what the webjob core works with

Body:
I have a continuous webjob that is running on azure that after a larger deployment 8 hours ago gets the status never finished in some cases and in other cases completed the job.
I have enabled all logging I could find and have been spending quite a few hours trying to figure out what the problem is.

The only log error information I seem to be able to find is from the job_log which states:

[11/15/2017 14:46:23 > e553e5: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (404) Not Found. ---> System.Net.WebException: The remote server returned an error: (404) Not Found.
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase1 cmd, Exception ex) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Shared\Protocol\HttpResponseParsers.Common.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.<DeleteBlobImpl>b__33(RESTCommand1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 3349
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 299
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of inner exception stack trace ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.EndDelete(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 1729
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass4.b__3(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 114
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Protocols.PersistentQueueWriter1.<DeleteAsync>d__6.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Loggers.CompositeFunctionInstanceLogger.<DeleteLogFunctionStartedAsync>d__e.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.<TryExecuteAsync>d__1.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.TriggeredFunctionExecutor1.d__0.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Timers.BackgroundExceptionDispatcher.<>c__DisplayClass1.b__0()
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart()

Can anyone give me some ideas on how to debug this, because I am out of ideas.

My webjobs main looks like this:

 static void Main()
    {
         var host = new JobHost();

        var config = new JobHostConfiguration();
        config.Queues.MaxPollingInterval = new TimeSpan(0,0,0,30);
        config.Queues.MaxDequeueCount = 3;
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }

and the processqueuemessage looks like:

 public static void ProcessQueueMessage([QueueTrigger("importqueue")] string msg)
    {
        try
        {
            WorkerWebJobCore wwjc = new WorkerWebJobCore();
            wwjc.RunCore(msg, TableStorageAccessResources.ImportQueue,
                TableStorageAccessResources.TableStorageDataOneId,
                TableStorageAccessResources.TableStorageDataOnePassword);
        }
        catch (Exception e)
        {
            CommunicatorLog.Log.LogError("WebJobWorker","WebJobWorker","Error in processing queue message","ERRWJWF01");
        }
    }

So I have a catch around everything, therefore I don't get how it can fail?

Thanks in advance.


问:
How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?
```<code>    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x)

    print(check)
</code>```

I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :

output of "check.remove(y)"

I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.

How the list 'check' looks like

How can I compare the tuples with each other in the same list and remove the second one that contains the same values?

答:
Use in and not ==

```<code>for x in check:
    this = sorted(x) #the first tuple
    for y in check:
        that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
        if this in that:
            check.remove(x)
     # alternatively you might need to loop through this if its a tuple of tuples
     # for t in this:
     #     if t in that:
     #         check.remove(x)

print(check)
</code>```

Body:
    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x)

    print(check)

I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :

output of "check.remove(y)"

I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.

How the list 'check' looks like

How can I compare the tuples with each other in the same list and remove the second one that contains the same values?

Body:
Use in and not ==

for x in check:
    this = sorted(x) #the first tuple
    for y in check:
        that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
        if this in that:
            check.remove(x)
     # alternatively you might need to loop through this if its a tuple of tuples
     # for t in this:
     #     if t in that:
     #         check.remove(x)

print(check)


问:
how to make the html table header fixed + Content above the table to be fixed
please help, I have a html table , without changing the layout and responsive behavior - i want to make table header fixed - please suggest

https://codepen.io/shaswat/pen/EbwPNK

here want to implement table header and responsiveness of the table both together . which is not working

while scrolling down -- 3 headers and the table head should get fixed .

.rg-container {
  font-family: 'Lato', Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 1.4;
  margin: 0;
  padding: 1em 0.5em;
  color: #222;
}

.rg-header {
  margin-bottom: 1em;
  text-align: left;
}

.rg-header>* {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Some more Header information</h1>
<h2>Some more Header information</h2>
<h3>Header
  <div>
    <div class='rg-container'>
      <div class='rg-content'>
        <table class='rg-table'>
          <thead>
            <tr>
              <th class='text '>id</th>
              <th class='text '>somcol</th>
              <th class='text '>biggger id</th>
              <th class='text '>another id</th>
              <th class='text '>med col</th>
              <th class='text '>med col</th>
            </tr>
          </thead>
          <tbody>

            <tr class=''>
              <td class='text ' data-title='id'>id</td>
              <td class='text ' data-title='somcol'>somcol</td>
              <td class='text ' data-title='biggger id'>biggger id</td>
              <td class='text ' data-title='another id'>another id</td>
              <td class='text ' data-title='med col'>med col</td>
              <td class='text ' data-title='med col'>med col</td>
              <td class='text ' data-title='sheet'>sheet</td>
              <td class='text ' data-title='sheet'>sheet</td>
              <td class='text ' data-title='anotherbigcoloumn'>another big coloumn</td>
              <td class='text ' data-title='small'>small</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div></code>```

答:
In that case, you would need to set the header height, and put all content under the header.

The CSS:

```<code>.headers {
  position: fixed;
  height: 100px; /* However long you want the header background */
  top: 0;
  width: 100%;
}

/* Then, for the tables, you would set the **margin-top** to whatever the
headers height is. */

.content {
  margin-top: 100px;
}
</code>```

Next, just set the div id's:

The HTML:

```<code><div id="headers">
/* Your headers */
</div>
<div id="content">
/* Your HTML content */
</div>
</code>```

Body:
please help, I have a html table , without changing the layout and responsive behavior - i want to make table header fixed - please suggest

https://codepen.io/shaswat/pen/EbwPNK

here want to implement table header and responsiveness of the table both together . which is not working

while scrolling down -- 3 headers and the table head should get fixed .

.rg-container {
  font-family: 'Lato', Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 1.4;
  margin: 0;
  padding: 1em 0.5em;
  color: #222;
}

.rg-header {
  margin-bottom: 1em;
  text-align: left;
}

.rg-header>* {
  display: block;
}

Some more Header information

Some more Header information

Header

              id
              somcol
              biggger id
              another id
              med col
              med col

              id
              somcol
              biggger id
              another id
              med col
              med col
              sheet
              sheet
              another big coloumn
              small

Body:
In that case, you would need to set the header height, and put all content under the header.

The CSS:

.headers {
  position: fixed;
  height: 100px; /* However long you want the header background */
  top: 0;
  width: 100%;
}

/* Then, for the tables, you would set the **margin-top** to whatever the
headers height is. */

.content {
  margin-top: 100px;
}

Next, just set the div id's:

The HTML:

<div id="headers">
/* Your headers */
</div>
<div id="content">
/* Your HTML content */
</div>


问:
Download files via batch with custom header
Im trying to download tons of isochrones from an opentripplanner server.
Restriction is: no external tools or installations possible. Client is Windows 7. To create the .bat file i use a selfmade excel tool.

Default response is .json file format. This works just fine with bitsadmin:

```<code>bitsadmin /Transfer Download_Isochrone_1 /download /priority normal http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.059,-0.880^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_1.json
bitsadmin /Transfer Download_Isochrone_2 /download /priority normal http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.089,-0.881^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_2.json
bitsadmin /Transfer Download_Isochrone_3 /download /priority normal http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.159,-0.882^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_3.json
</code>```

But .shp (.zip) is possible by using a custom header. ("Accept: application/x-zip-compressed"). Already done this via Browser-Plugin for a single isochrone.
So i tried

```<code>bitsadmin /Create /Download Download_Isochrones
bitsadmin /SetCustomHeader Download_Isochrones "Accept: application/x-zip-compressed"
bitsadmin /Addfile Download_Isochrones http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.059,-0.880^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_1.txt
bitsadmin /Addfile Download_Isochrones http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.089,-0.881^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_2.txt
bitsadmin /Addfile Download_Isochrones http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.159,-0.882^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_3.txt
bitsadmin /Resume Download_Isochrones
bitsadmin /Complete Download_Isochrones
</code>```

But it doesnt work. Actually "/Addfile" seems to not work at all for this purpose. (using .txt extension for testing purposes)
Is it somehow possible to to combine /transfer with /setcustomheader or did i just do a mistake in the code above? Or is there any other possibilty to do this without win7-external tools?
In case of interest, heres the OpenTripPlanner doc: http://dev.opentripplanner.org/apidoc/1.0.0/resource_LIsochrone.html

答:
Try with winhttpjs.bat:

```<code>call winhttpjs.bat "https://requestb.in/vp4p0gvp"  -headers-file headers.txt  -saveTo file.gzip
</code>```

You'll need a headers.txt file in the same directory looking like:

```<code>#compression header
Accept: application/x-zip-compressed
</code>```

To check the result I've created a a test link on the https://requestb.in site.

Body:
Im trying to download tons of isochrones from an opentripplanner server.
Restriction is: no external tools or installations possible. Client is Windows 7. To create the .bat file i use a selfmade excel tool.

Default response is .json file format. This works just fine with bitsadmin:

bitsadmin /Transfer Download_Isochrone_1 /download /priority normal http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.059,-0.880^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_1.json
bitsadmin /Transfer Download_Isochrone_2 /download /priority normal http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.089,-0.881^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_2.json
bitsadmin /Transfer Download_Isochrone_3 /download /priority normal http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.159,-0.882^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_3.json

But .shp (.zip) is possible by using a custom header. ("Accept: application/x-zip-compressed"). Already done this via Browser-Plugin for a single isochrone.
So i tried

bitsadmin /Create /Download Download_Isochrones
bitsadmin /SetCustomHeader Download_Isochrones "Accept: application/x-zip-compressed"
bitsadmin /Addfile Download_Isochrones http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.059,-0.880^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_1.txt
bitsadmin /Addfile Download_Isochrones http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.089,-0.881^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_2.txt
bitsadmin /Addfile Download_Isochrones http://exampleserver.com/otp-rest-servlet/ws/isochrone?routerId=bordeaux^&algorithm=accSampling^&fromPlace=47.159,-0.882^&date=2013/10/01^&time=12:00:00^&maxWalkDistance=1000^&mode=WALK,TRANSIT^&cutoffSec=1800^&cutoffSec=3600 c:\username\downloads\Isochrone_3.txt
bitsadmin /Resume Download_Isochrones
bitsadmin /Complete Download_Isochrones

But it doesnt work. Actually "/Addfile" seems to not work at all for this purpose. (using .txt extension for testing purposes)
Is it somehow possible to to combine /transfer with /setcustomheader or did i just do a mistake in the code above? Or is there any other possibilty to do this without win7-external tools?
In case of interest, heres the OpenTripPlanner doc: http://dev.opentripplanner.org/apidoc/1.0.0/resource_LIsochrone.html

Body:
Try with winhttpjs.bat:

call winhttpjs.bat "https://requestb.in/vp4p0gvp"  -headers-file headers.txt  -saveTo file.gzip

You'll need a headers.txt file in the same directory looking like:

#compression header
Accept: application/x-zip-compressed

To check the result I've created a a test link on the https://requestb.in site.


问:
Image Not Shown In IIS7
I faced some problems after hosting my web project in IIS 7 / Windows 2008. Images are not shown when I run the project on my browser.

I copied my project folder (webtest) to c:\inetpub\wwwroot\. To be sure, I chose image from webtest\image\sample.jpg again. It works properly when I run it. However, after putting up for hosting and I call it from browser it doesn't show the image.

What are the possible causes of the problem?

答: Possible solution is to add .jpg/.jpeg mime type in IIS Manager if it doesn't exists.

Title: Image Not Shown In IIS7


问:
Directly delete selected record in gird from database
I want delete selected row directly from database. I wrote this code but it doesn't work correctly.

Here is my code but it doesn't delete record from my SQL server local db;

```<code>MyDataSet.Tables["ProductTable"].Rows[gridView1.GetFocusedDataSourceRowIndex()].Delete();
</code>```

答:
Double click on DataGridView; you get an event named CellContentClick.

```<code>try
{
    int x = int.Parse(datagridview.Rows[e.RowIndex].Cells[UserID.Index].Value.ToString());
    string query = "delete from productable where UserID=" + x;
    // now delete execute procedure
    MessageBox.Show("Deleted Successfully");
    // write code to bring record again.
}
catch(Exception ex)
{
    MessageBox.Show(ex.StackTrace);
}
</code>```

Body:
I want delete selected row directly from database. I wrote this code but it doesn't work correctly.

Here is my code but it doesn't delete record from my SQL server local db;

MyDataSet.Tables["ProductTable"].Rows[gridView1.GetFocusedDataSourceRowIndex()].Delete();

Body:
Double click on DataGridView; you get an event named CellContentClick.

try
{
    int x = int.Parse(datagridview.Rows[e.RowIndex].Cells[UserID.Index].Value.ToString());
    string query = "delete from productable where UserID=" + x;
    // now delete execute procedure
    MessageBox.Show("Deleted Successfully");
    // write code to bring record again.
}
catch(Exception ex)
{
    MessageBox.Show(ex.StackTrace);
}


问:
Loading an xlsx or csv file from Sharepoint into Spotfire using IronPython script
if I try to load the data using below script, the html code is being loaded instead of proper data. The given link leads to the direct source of xlsx or csv file (if you run that link in the browser, the xlsx or csv file will start downloading automatically). I would be glad to hear why this kind of situation happens and how to love this problem.</p>

```<code>import clr
clr.AddReference('System.Net')
from System.Net import HttpWebRequest, NetworkCredential
from Spotfire.Dxp.Data.Import import TextFileDataSource, TextDataReaderSettings

readerSettings = TextDataReaderSettings()
readerSettings.Separator = ";"
readerSettings.CultureName = "en-GB"

req = HttpWebRequest.Create("some link to xlsx file")

user_agent = 'individual user-agent'
req.UserAgent = user_agent
req.Method = "GET"

req.UseDefaultCredentials = True
#req.PreAuthenticate = True
user = Document.Properties["Username"]
password = Document.Properties["Password"]

req.Credentials = NetworkCredential(user, password)

rsp = req.GetResponse()
dSource = TextFileDataSource(rsp.GetResponseStream(),readerSettings)
rsp.Close()

dataManager = Document.Data
dataTable = dataManager.Tables[document.Name]
dataTable.ReplaceData(dSource)
</code>```

答:
the important part of the HTML returned isn't "Javascript is disabled", it's "We can't sign you in because Javascript is disabled." based on this it sounds like your issue is that you haven't properly authenticated your session.

I would try to validate by loading this code into the Python IDE of your choice and try it independent of Spotfire.

the correct way to access Sharepoint, most likely, is through the Sharepoint API. I don't have experience with this but I'm sure some googling could turn up a solution. once you have a (third-party library free!) solution working in Python, you can adapt it to Spotfire without too much trouble.

Body:
if I try to load the data using below script, the html code is being loaded instead of proper data. The given link leads to the direct source of xlsx or csv file (if you run that link in the browser, the xlsx or csv file will start downloading automatically). I would be glad to hear why this kind of situation happens and how to love this problem.

import clr
clr.AddReference('System.Net')
from System.Net import HttpWebRequest, NetworkCredential
from Spotfire.Dxp.Data.Import import TextFileDataSource, TextDataReaderSettings

readerSettings = TextDataReaderSettings()
readerSettings.Separator = ";"
readerSettings.CultureName = "en-GB"

req = HttpWebRequest.Create("some link to xlsx file")

user_agent = 'individual user-agent'
req.UserAgent = user_agent
req.Method = "GET"

req.UseDefaultCredentials = True
#req.PreAuthenticate = True
user = Document.Properties["Username"]
password = Document.Properties["Password"]

req.Credentials = NetworkCredential(user, password)

rsp = req.GetResponse()
dSource = TextFileDataSource(rsp.GetResponseStream(),readerSettings)
rsp.Close()

dataManager = Document.Data
dataTable = dataManager.Tables[document.Name]
dataTable.ReplaceData(dSource)


问:
Raise an NSDecimalNumber to a negative power
I need an equivalent to C's pow() function that will work with NSDecimalNumbers. With pow you can use negative numbers e.g. pow(1514,-1234), with NSDecimal's decimalNumberByRaisingToPower: method, you are forced to use an NSUInteger which seems to require a positive value.

I'd like to be able to do something like this:

```<code>[decimalNumber decimalNumberByRaisingToPower:-217.089218];
</code>```

or

```<code>[decimalNumber decimalNumberByMultiplyingByPowerOf10:-217];
</code>```

without crashing from overflow or underflow exceptions.

答:
Incidentally, you appear to be correct about decimalNumberByRaisingToPower, but, from the Apple docs:

(NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power

That's not unsigned.

Body:
I need an equivalent to C's pow() function that will work with NSDecimalNumbers. With pow you can use negative numbers e.g. pow(1514,-1234), with NSDecimal's decimalNumberByRaisingToPower: method, you are forced to use an NSUInteger which seems to require a positive value.

I'd like to be able to do something like this:

[decimalNumber decimalNumberByRaisingToPower:-217.089218];

or

[decimalNumber decimalNumberByMultiplyingByPowerOf10:-217];

without crashing from overflow or underflow exceptions.


问:
Unable to understand the pointer to pointer output : 15 15
Could someone please help to understand on how the output of the following code is 15 15?

```<code>#include <stdio.h>
void foo(int **p1);
int main()
{
    int i = 10;
    int *p = &i;
    foo(&p);  //address of constant pointer p passed to function
    printf("%d\n", *p);

}
void foo(int **p1)
{
    int j = 15;
    *p1 = &j; //I don't get this line
    printf("%d\n", **p1);
}
</code>```

Let's assume that addr(i)=ff2, addr(pointer p)=ff4, addr(j)=ff6

i=10, j=15

p= address(i), so p= ff2

p1=address(p), so p1= ff4

答:
The program has undefined behavior.

To understand what is wrong in the program let's introduce a typedef for the pointer type.

Here is a demonstrative program.

```<code>#include <stdio.h>

typedef int * T;

int main(void)
{
    int i = 10;
    const T p = &i;

    printf( "%d\n", *p );

    return 0;
}
</code>```

The program output is

```<code>10
</code>```

As it is seen the variable p is declared with the qualifier const.

Now let's try to add the function foo.

```<code>#include <stdio.h>

typedef int * T;

void foo( T *pp )
{

}

int main(void)
{
    int i = 10;
    const T p = &i;

    foo( &p );

    printf( "%d\n", *p );

    return 0;
}
</code>```

Oops, the compiler issued an error

```<code>prog.c:15:7: error: passing argument 1 of ‘foo’ discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]
  foo( &p );
       ^
prog.c:5:6: note: expected ‘int **’ but argument is of type ‘int * const*’
 void foo( T *pp )
</code>```

Indeed the variable p is declared with the qualifier const

```<code>    const T p = &i;
</code>```

So a pointer to the variable must have the type const T *.

```<code>#include <stdio.h>

typedef int * T;

void foo( const T *pp )
{

}

int main(void)
{
    int i = 10;
    const T p = &i;

    foo( &p );

    printf( "%d\n", *p );

    return 0;
}
</code>```

Now if to dereference the parameter pp within the function we get a constant object that may not be changed.

```<code>#include <stdio.h>

typedef int * T;

void foo( const T *pp )
{
    int j = 15;
    *pp = &j;
}

int main(void)
{
    int i = 10;
    const T p = &i;

    foo( &p );

    printf( "%d\n", *p );

    return 0;
}
</code>```

So the compiler again will issue an error

```<code>prog.c: In function ‘foo’:
prog.c:8:6: error: assignment of read-only location ‘*pp’
  *pp = &j;
      ^
</code>```

And moreover you are trying to assign the address of a local variable that after exiting the function will be invalid. So even if the pointer was not constant in any case the program had undefined behavior.

EDIT:
After you seriously changed your program (that is a bad idea) in the question removing the const qualifier from the declaration of the pointer p nevertheless as I already said the program has undefined behavior because the pointer is assigned with the value of a local variable. So the pointer will have invalid value because the variable is not alive any more after exiting the function though you can get an expected result.

```<code>void foo(int **p1)
{
    int j = 15;
    // Assigning the original variable p pointed to by the parameter p1
    // the address of the local variable j.
    *p1 = &j; //I don't get this line
    printf("%d\n", **p1);
}
</code>```

As for this statement

```<code>*p1 = &j;
</code>```

then the pointer p1 points to the original pointer p. So dereferencing the pointer p1 you get the original pointer p to which the address of the local variable j is assigned.

Body:
Could someone please help to understand on how the output of the following code is 15 15?

#include <stdio.h>
void foo(int **p1);
int main()
{
    int i = 10;
    int *p = &i;
    foo(&p);  //address of constant pointer p passed to function
    printf("%d\n", *p);

}
void foo(int **p1)
{
    int j = 15;
    *p1 = &j; //I don't get this line
    printf("%d\n", **p1);
}

Let's assume that addr(i)=ff2, addr(pointer p)=ff4, addr(j)=ff6

i=10, j=15

p= address(i), so p= ff2

p1=address(p), so p1= ff4

Body:
The program has undefined behavior.

To understand what is wrong in the program let's introduce a typedef for the pointer type.

Here is a demonstrative program.

#include <stdio.h>

typedef int * T;

int main(void)
{
    int i = 10;
    const T p = &i;

    printf( "%d\n", *p );

    return 0;
}

The program output is

10

As it is seen the variable p is declared with the qualifier const.

Now let's try to add the function foo.

#include <stdio.h>

typedef int * T;

void foo( T *pp )
{

}

int main(void)
{
    int i = 10;
    const T p = &i;

    foo( &p );

    printf( "%d\n", *p );

    return 0;
}

Oops, the compiler issued an error

prog.c:15:7: error: passing argument 1 of ‘foo’ discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]
  foo( &p );
       ^
prog.c:5:6: note: expected ‘int **’ but argument is of type ‘int * const*’
 void foo( T *pp )

Indeed the variable p is declared with the qualifier const

    const T p = &i;

So a pointer to the variable must have the type const T *.

#include <stdio.h>

typedef int * T;

void foo( const T *pp )
{

}

int main(void)
{
    int i = 10;
    const T p = &i;

    foo( &p );

    printf( "%d\n", *p );

    return 0;
}

Now if to dereference the parameter pp within the function we get a constant object that may not be changed.

#include <stdio.h>

typedef int * T;

void foo( const T *pp )
{
    int j = 15;
    *pp = &j;
}

int main(void)
{
    int i = 10;
    const T p = &i;

    foo( &p );

    printf( "%d\n", *p );

    return 0;
}

So the compiler again will issue an error

prog.c: In function ‘foo’:
prog.c:8:6: error: assignment of read-only location ‘*pp’
  *pp = &j;
      ^

And moreover you are trying to assign the address of a local variable that after exiting the function will be invalid. So even if the pointer was not constant in any case the program had undefined behavior.

EDIT:
After you seriously changed your program (that is a bad idea) in the question removing the const qualifier from the declaration of the pointer p nevertheless as I already said the program has undefined behavior because the pointer is assigned with the value of a local variable. So the pointer will have invalid value because the variable is not alive any more after exiting the function though you can get an expected result.

void foo(int **p1)
{
    int j = 15;
    // Assigning the original variable p pointed to by the parameter p1
    // the address of the local variable j.
    *p1 = &j; //I don't get this line
    printf("%d\n", **p1);
}

As for this statement

*p1 = &j;

then the pointer p1 points to the original pointer p. So dereferencing the pointer p1 you get the original pointer p to which the address of the local variable j is assigned.


问:
How determine if a string has been encoded programmatically in C#?
How determine if a string has been encoded programmatically in C#?

Lets for example string:

```<code><p>test</p>
</code>```

I would like have my logic understand that this value it has been encoded..
Any ideas? Thanks

答:
I'm doing .NET Core 2.0 development and I'm using System.Net.WebUtility.HtmlDecode, but I have a situation where strings being processed in a microservice might have an indeterminate number of encodings performed on some strings.  So I put together a little recursive method to handle this:

```<code>    public string HtmlDecodeText(string value, int decodingCount = 0)
    {
        // If decoded text equals the original text, then we know decoding is done;
        // Don't go past 4 levels of decoding to prevent possible stack overflow,
        // and because we don't have a valid use case for that level of multi-decoding.

        if (decodingCount < 0)
        {
            decodingCount = 1;
        }

        if (decodingCount >= 4)
        {
            return value;
        }

        var decodedText = WebUtility.HtmlDecode(value);

        if (decodedText.Equals(value, StringComparison.OrdinalIgnoreCase))
        {
            return value;
        }

        return HtmlDecodeText(decodedText, ++decodingCount);
    }
</code>```

And here I called the method on each item in a list where strings were encoded:

```<code>  result.FavoritesData.folderMap.ToList().ForEach(x => x.Name = HtmlDecodeText(x.Name));
</code>```

Body:
How determine if a string has been encoded programmatically in C#?

Lets for example string:

test

I would like have my logic understand that this value it has been encoded..
Any ideas? Thanks

Body:
I'm doing .NET Core 2.0 development and I'm using System.Net.WebUtility.HtmlDecode, but I have a situation where strings being processed in a microservice might have an indeterminate number of encodings performed on some strings.  So I put together a little recursive method to handle this:

    public string HtmlDecodeText(string value, int decodingCount = 0)
    {
        // If decoded text equals the original text, then we know decoding is done;
        // Don't go past 4 levels of decoding to prevent possible stack overflow,
        // and because we don't have a valid use case for that level of multi-decoding.

        if (decodingCount < 0)
        {
            decodingCount = 1;
        }

        if (decodingCount >= 4)
        {
            return value;
        }

        var decodedText = WebUtility.HtmlDecode(value);

        if (decodedText.Equals(value, StringComparison.OrdinalIgnoreCase))
        {
            return value;
        }

        return HtmlDecodeText(decodedText, ++decodingCount);
    }

And here I called the method on each item in a list where strings were encoded:

  result.FavoritesData.folderMap.ToList().ForEach(x => x.Name = HtmlDecodeText(x.Name));


问:
Is this the correct way to imitate the following POST request using python?
I need to imitate this request:

text part

```<code>POST /comeback_campaigns/entry HTTP/1.1
Host: ishin-global.aktsk.com
Accept: */*
X-Platform: android
X-Language: en
X-ClientVersion: 3.6.1
X-AssetVersion: 1510308536
X-DatabaseVersion: 1510542279
X-RequestVersion: 2
Content-Type: application/json
Authorization: MAC id="TVTYcxqDlO61l0yQYQnaKirWEVOPcVp2O4FCZOAb0pLrP++EEsKaqrlSho8VQRLFLV+4wvAV53DBwJyNuqUfqg==", nonce="1510773145:5a7b051af7f3e76e5b14f4e79753589f", ts="1510773145", mac="Eot1a1QPvyhecW3wNjWCW1JAENjuOjfjyxltmcguYqc="
Content-Length: 5
</code>```

JSON part

```<code>null
</code>```

I wrote it like this in my code, using the request function

```<code>url='http://ishin-global.aktsk.com/comeback_campaigns/entry'

myhead={'Accept':'*/*',
    'X-Platform':'android',
    'X-Language':'en',
    'X-ClientVersion':'3.6.1',
    'X-AssetVersion':'1510308536',
    'X-DatabaseVersion':'1510542279',
    'X-RequestVersion':'2',
    'Content-Type':'application/json',
    'Authorization':'MAC id='+mac_key +', nonce='+TS+':'+nonce+', ts='+ TS + ', mac='+mac_gen,
    'Content-Length':'5'
    }

payload='null'

r=requests.post(url, headers=myhead, json=payload)
</code>```

Is this the correct way to do it? Do I have to send in the auth part like, request.post(url, auth, header)? Do I have to convert the access token in the image into an OAuth2 thing before using it?

Right now im getting an error saying

oauth2_mac_rails/access_token_required

The access token is the MAC id right after authorization.

答:
Add quotes (") around the individual parts of the Authorization key:

```<code>'Authorization': 'MAC id="' + mac_key + '", nonce="' + TS + ':' + nonce + '", ts="' + TS + '", mac="' + mac_gen + '"'
</code>```

You are currently sending one long string without intermediate quotes:

```<code>'Authorization': 'MAC id=TVTxxx, nonce=151xxx:5a7xxx, ts=151xxx, mac=Eotxxx'
</code>```

while your reference POST looks like:

```<code>'Authorization': 'MAC id="TVTxxx", nonce="151xxx:5a7xxx", ts="151xxx", mac="Eot..."'
</code>```

Body:
I need to imitate this request:

text part

POST /comeback_campaigns/entry HTTP/1.1
Host: ishin-global.aktsk.com
Accept: */*
X-Platform: android
X-Language: en
X-ClientVersion: 3.6.1
X-AssetVersion: 1510308536
X-DatabaseVersion: 1510542279
X-RequestVersion: 2
Content-Type: application/json
Authorization: MAC id="TVTYcxqDlO61l0yQYQnaKirWEVOPcVp2O4FCZOAb0pLrP++EEsKaqrlSho8VQRLFLV+4wvAV53DBwJyNuqUfqg==", nonce="1510773145:5a7b051af7f3e76e5b14f4e79753589f", ts="1510773145", mac="Eot1a1QPvyhecW3wNjWCW1JAENjuOjfjyxltmcguYqc="
Content-Length: 5

JSON part

null

I wrote it like this in my code, using the request function

url='http://ishin-global.aktsk.com/comeback_campaigns/entry'

myhead={'Accept':'*/*',
    'X-Platform':'android',
    'X-Language':'en',
    'X-ClientVersion':'3.6.1',
    'X-AssetVersion':'1510308536',
    'X-DatabaseVersion':'1510542279',
    'X-RequestVersion':'2',
    'Content-Type':'application/json',
    'Authorization':'MAC id='+mac_key +', nonce='+TS+':'+nonce+', ts='+ TS + ', mac='+mac_gen,
    'Content-Length':'5'
    }

payload='null'

r=requests.post(url, headers=myhead, json=payload)

Is this the correct way to do it? Do I have to send in the auth part like, request.post(url, auth, header)? Do I have to convert the access token in the image into an OAuth2 thing before using it?

Right now im getting an error saying

oauth2_mac_rails/access_token_required

The access token is the MAC id right after authorization.

Body:
Add quotes (") around the individual parts of the Authorization key:

'Authorization': 'MAC id="' + mac_key + '", nonce="' + TS + ':' + nonce + '", ts="' + TS + '", mac="' + mac_gen + '"'

You are currently sending one long string without intermediate quotes:

'Authorization': 'MAC id=TVTxxx, nonce=151xxx:5a7xxx, ts=151xxx, mac=Eotxxx'

while your reference POST looks like:

'Authorization': 'MAC id="TVTxxx", nonce="151xxx:5a7xxx", ts="151xxx", mac="Eot..."'


问:
why the regression doesnt work? (MATLAB)
I have a accelerometer signal as below:

and I have a walking signal as below:

I tried to regress these two signal using regression. Here is the code:

```<code>regMat=zeros(size(walkVec,1),size(walkVec,2));
for i=1:size(data,1)
   b=regress(walkAcc', walkVec(i,:)');
    regMat(i,:)=walkVec(i,:)-repmat(b,1,length(walkAcc));
    regData(i,:)=[data(i,1:(ipt(1)-1)),regMat(i,:), data(i,
     (ipt(2)+1):size(data,2) ) ];
 end

 figure(1),hold on, plot(data(1,:),'r'), plot(regData(1,:)), title
('regressed (b) and raw(r) ')
legend('raw','regressed')
 xlabel('samples')
ylabel('Intensity')
</code>```

and here is the reslts:

as you can see the regression doesnt really work. Do you have any idea why and how I can fix it?

Thanks a lot and kind Regards

答: If what you are looking for is just a visual representation of regressions, and you don't need to store/process data, I suggest you to use the function plotregression (https://it.mathworks.com/help/nnet/ref/plotregression.html).

Body:
I have a accelerometer signal as below:

and I have a walking signal as below:

I tried to regress these two signal using regression. Here is the code:

regMat=zeros(size(walkVec,1),size(walkVec,2));
for i=1:size(data,1)
   b=regress(walkAcc', walkVec(i,:)');
    regMat(i,:)=walkVec(i,:)-repmat(b,1,length(walkAcc));
    regData(i,:)=[data(i,1:(ipt(1)-1)),regMat(i,:), data(i,
     (ipt(2)+1):size(data,2) ) ];
 end

 figure(1),hold on, plot(data(1,:),'r'), plot(regData(1,:)), title
('regressed (b) and raw(r) ')
legend('raw','regressed')
 xlabel('samples')
ylabel('Intensity')

and here is the reslts:

as you can see the regression doesnt really work. Do you have any idea why and how I can fix it?

Thanks a lot and kind Regards


问:
Responsive aspect ratios with pure css: how to fill container's height?
I have a div (the one with class container) with fixed height (which is supposed to be dynamic and not known in advance) which contains another div (the one with class fixed-aspect-ratio).

I would like the inner div to fill the container's height while keeping a fixed aspect ratio of 1:1.

The commonly used trick to achieve fixed aspect ratios is to exploit padding: in fact when declaring percentages instead of fixed values for padding, the percentage is calculated based on the WIDTH of the element in question, even if we are declaring a vertical value such as padding-top or padding-bottom.

This makes padding a great trick to exploit if you want to fill the container's WIDTH, but not if you want to fill the container's HEIGHT.

Is it possibile to achieve it using CSS only? No javascript thanks.

Ideally I would love to have CSS units complementary to the viewport ones, but relative to the container. Something like:

cw (container width)

ch (container height)

cmin (container min)

cmax (container max)

Would be freaking awesome.

<!DOCTYPE html>

Some text

```

https://www.w3schools.com/code/tryit.asp?filename=FLJBS4J2MTWS

答:
Set height to 100% and width to x%

<!DOCTYPE html>

Some text

```

Body:
I have a div (the one with class container) with fixed height (which is supposed to be dynamic and not known in advance) which contains another div (the one with class fixed-aspect-ratio).

I would like the inner div to fill the container's height while keeping a fixed aspect ratio of 1:1.

The commonly used trick to achieve fixed aspect ratios is to exploit padding: in fact when declaring percentages instead of fixed values for padding, the percentage is calculated based on the WIDTH of the element in question, even if we are declaring a vertical value such as padding-top or padding-bottom.

This makes padding a great trick to exploit if you want to fill the container's WIDTH, but not if you want to fill the container's HEIGHT.

Is it possibile to achieve it using CSS only? No javascript thanks.

Ideally I would love to have CSS units complementary to the viewport ones, but relative to the container. Something like:

cw (container width)

ch (container height)

cmin (container min)

cmax (container max)

Would be freaking awesome.

<!DOCTYPE html>

Some text

https://www.w3schools.com/code/tryit.asp?filename=FLJBS4J2MTWS

Body:
Set height to 100% and width to x%

<!DOCTYPE html>
<html>

<head>
  <style>
    .container {
      background-color: green;
      height: 30vh;
    }

    .fixed-aspect-ratio {
      background-color: red;
      height: 100%;
      width: 10%;
      /* 1:1 Aspect Ratio */
      position: relative;
      /* If you want text inside of it */
    }
    /* If you want text inside of the container */

    .text {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="fixed-aspect-ratio">
      <div class="text">Some text</div>
      <!-- If you want text inside the container -->
    </div>
  </div>
</body>

</html>


问:
Find duplicates in two columns in a table
I just browse this post and tried all the scripts but still i am not getting what i am expecting.

Here is my table

```<code>Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
Madison Taylor  Madison.Tyl@abc.com

SELECT Name
FROM Employee
GROUP BY Name
HAVING ( COUNT(Name > 1 )
</code>```

result

BRIAN MAT

```<code>SELECT email
FROM Employee
GROUP BY email
HAVING ( COUNT(email> 1 )
</code>```

Result

AMY.Lee@abc.Com

I was trying to group this two script but it shows blank

```<code>SELECT
    Name, email,COUNT(*)
FROM
    Employee
GROUP BY
    Name, email
HAVING
    COUNT(*) > 1
</code>```

Please correct me what i am missing in my script to acheive the result like below

```<code>Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
</code>```

答:
The least complicated. A quick and dirty solution.</p>

```<code>SELECT
    a.name,
    a.email, count(*)
FROM
    employee a

INNER JOIN
    employee b on b.name = a.name or b.email = a.email
GROUP BY a.name, a.email
HAVING COUNT(*) > 1
</code>```

Body:
I just browse this post and tried all the scripts but still i am not getting what i am expecting.

Here is my table

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
Madison Taylor  Madison.Tyl@abc.com

SELECT Name
FROM Employee
GROUP BY Name
HAVING ( COUNT(Name > 1 )

result

BRIAN MAT

SELECT email
FROM Employee
GROUP BY email
HAVING ( COUNT(email> 1 )

Result

AMY.Lee@abc.Com

I was trying to group this two script but it shows blank

SELECT
    Name, email,COUNT(*)
FROM
    Employee
GROUP BY
    Name, email
HAVING
    COUNT(*) > 1

Please correct me what i am missing in my script to acheive the result like below

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com

Body:
The least complicated. A quick and dirty solution.

SELECT
    a.name,
    a.email, count(*)
FROM
    employee a

INNER JOIN
    employee b on b.name = a.name or b.email = a.email
GROUP BY a.name, a.email
HAVING COUNT(*) > 1