问:
Trying to iterate through list of objects in node js
I'd like to send list of objects through postman tool and receive it on my server side code,
This is the json code i'm sending through postman tool and receiving it throught post method

```<code>{
    "user1" : {
        "name" : "grijan",
        "prof" : "student"
    },
    "user2" : {
        "name" : "vijay",
        "prof" : "teacher"
    }
}
</code>```

My server side code

```<code>var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/saveUser',function(req,res){
    var  obj= req.body;
    console.log(obj);
    //code for iteration ????
})

var server = app.listen(8008,function(){});
</code>```

I need to iterate through the objects and the fields in the objects!
FYI i'm new to node this is my 2nd day :)

答:
You are not sending a list, but an object. If you want to send a list you should send something like this:

```<code>[
    {
        "name" : "grijan",
        "prof" : "student"
    },
    {
        "name" : "vijay",
        "prof" : "teacher"
    }
]
</code>```

And them in the node side:

```<code>var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

var methodToSaveInDB = function(name, prof) {
    // save it here into DB
}

app.post('/saveUser',function(req,res){
    var usersList = req.body;
    for(var user of usersList) {
        methodToSaveInDB(user.name, user.prof);
    }
})

var server = app.listen(8008,function(){});
</code>```

If you need to send it like an object and not as a list, you could loop through object properties:

```<code>for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
        console.log(obj[property].name);
        console.log(obj[property].prof);
    }
}
</code>```

Body:
I'd like to send list of objects through postman tool and receive it on my server side code,
This is the json code i'm sending through postman tool and receiving it throught post method

{
    "user1" : {
        "name" : "grijan",
        "prof" : "student"
    },
    "user2" : {
        "name" : "vijay",
        "prof" : "teacher"
    }
}

My server side code

var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/saveUser',function(req,res){
    var  obj= req.body;
    console.log(obj);
    //code for iteration ????
})

var server = app.listen(8008,function(){});

I need to iterate through the objects and the fields in the objects!
FYI i'm new to node this is my 2nd day :)

Body:
You are not sending a list, but an object. If you want to send a list you should send something like this:

[
    {
        "name" : "grijan",
        "prof" : "student"
    },
    {
        "name" : "vijay",
        "prof" : "teacher"
    }
]

And them in the node side:

var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

var methodToSaveInDB = function(name, prof) {
    // save it here into DB
}

app.post('/saveUser',function(req,res){
    var usersList = req.body;
    for(var user of usersList) {
        methodToSaveInDB(user.name, user.prof);
    }
})

var server = app.listen(8008,function(){});

If you need to send it like an object and not as a list, you could loop through object properties:

for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
        console.log(obj[property].name);
        console.log(obj[property].prof);
    }
}


来源: stackexchange

问:
HTTP Error 404.17 - Not Found, on window server 2012 with 2.0 application pool
I have a 2.0 .Net framework application which I moved to windows server 2012 with the same application pool setting of v2.0 and integrated mode. For some reason it throws HTTP Error 404.17 - Not Found error. I have followed https://support.microsoft.com/en-us/kb/2019689 and it does not work yet.

Also see my web.config as per the above page setting:

Any help would be great.

答:
I had the same problem (with a .net 4 webapp).
In the past you could resolve this with a aspnet_regiis command.
In Windows server you can resolve this by uninstalling asp.net [your version]. and the re-installing the same version.

This will reregister the correct IIS mappings

You can access these settings in the Server Manager

ContentLicense: CC BY-SA 3.0


问:
Image crop function not working in Wordpress
I have used this following function in my localhost which is working fine

// Image cropping

```<code>function cropImage($sourcePath, $thumbSize, $destination = null) {

      $parts = explode('.', $sourcePath);
      $ext = $parts[count($parts) - 1];
      if ($ext == 'jpg' || $ext == 'jpeg') {
        $format = 'jpg';
      } else {
        $format = 'png';
      }
      if ($format == 'jpg') {
        $sourceImage = imagecreatefromjpeg($sourcePath);
      }
      if ($format == 'png') {
        $sourceImage = imagecreatefrompng($sourcePath);
      }

      list($srcWidth, $srcHeight) = getimagesize($sourcePath);

      // calculating the part of the image to use for thumbnail
      if ($srcWidth > $srcHeight) {
        $y = 0;
        $x = ($srcWidth - $srcHeight) / 2;
        $smallestSide = $srcHeight;
      } else {
        $x = 0;
        $y = ($srcHeight - $srcWidth) / 2;
        $smallestSide = $srcWidth;
      }

      $destinationImage = imagecreatetruecolor($thumbSize, $thumbSize);
      imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

      if ($destination == null) {
        header('Content-Type: image/jpeg');
        if ($format == 'jpg') {
          imagejpeg($destinationImage, null, 100);
        }
        if ($format == 'png') {
          imagejpeg($destinationImage);
        }
        if ($destination = null) {
        }
      } else {
        if ($format == 'jpg') {
          imagejpeg($destinationImage, $destination, 100);
        }
        if ($format == 'png') {
          imagepng($destinationImage, $destination);
        }
      }
    }
</code>```

But i am using this in my wordpress theme and it is showing some errors

����JFIF����?I��^��l�i�����76����6m�0ib�~���X��KR����J��W�9��.�7wK~��J��)�J��)�.�������A�_�]�pw��@��'��{1M{���5���7�#X��|�w�#9W^�t�]������t}ms�l���%���W{���G��1T+8�2s���0a��3�XX� �yL��FrU��@�Y٦'���r���{g��簪�;c�[�0r0q�q���N9��G��{?�c�w�K�ӯE�|ެ�Td2���F�?!#�G�z>ЀP�����u۝�ᓒ����d��A8��9't��=���b���'#'ג}O��\����P�S�]���o�h�Zy$|�Ns�q��Y��t8f+�O�

I have used this code for showing the image

```<code>                                    $docimg = $doctor_img['url'];

                                    if ($docimg):
                                        ?>
                                        <?php cropImage( $docimg, 200, null); ?>
</code>```

Is there anything to change in this code. So that i can get the image src instead of wired characters

答:
here is the working example </p>

```<code>$parts = explode('.', $docimg);
                                                    $ext = $parts[count($parts) - 1];
                                                    if ($ext == 'jpg' || $ext == 'jpeg') {
                                                        $format = 'jpg';
                                                        } else {
                                                        $format = 'png';
                                                    }
                                                    ob_start();
                                                     header( "Content-type: image/".$format );
                                                     cropImage( $docimg, 200, null);
</code>```

Body:
I have used this following function in my localhost which is working fine

// Image cropping

function cropImage($sourcePath, $thumbSize, $destination = null) {

      $parts = explode('.', $sourcePath);
      $ext = $parts[count($parts) - 1];
      if ($ext == 'jpg' || $ext == 'jpeg') {
        $format = 'jpg';
      } else {
        $format = 'png';
      }
      if ($format == 'jpg') {
        $sourceImage = imagecreatefromjpeg($sourcePath);
      }
      if ($format == 'png') {
        $sourceImage = imagecreatefrompng($sourcePath);
      }

      list($srcWidth, $srcHeight) = getimagesize($sourcePath);

      // calculating the part of the image to use for thumbnail
      if ($srcWidth > $srcHeight) {
        $y = 0;
        $x = ($srcWidth - $srcHeight) / 2;
        $smallestSide = $srcHeight;
      } else {
        $x = 0;
        $y = ($srcHeight - $srcWidth) / 2;
        $smallestSide = $srcWidth;
      }

      $destinationImage = imagecreatetruecolor($thumbSize, $thumbSize);
      imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

      if ($destination == null) {
        header('Content-Type: image/jpeg');
        if ($format == 'jpg') {
          imagejpeg($destinationImage, null, 100);
        }
        if ($format == 'png') {
          imagejpeg($destinationImage);
        }
        if ($destination = null) {
        }
      } else {
        if ($format == 'jpg') {
          imagejpeg($destinationImage, $destination, 100);
        }
        if ($format == 'png') {
          imagepng($destinationImage, $destination);
        }
      }
    }

But i am using this in my wordpress theme and it is showing some errors

����JFIF����?I��^��l�i�����76����6m�0ib�~���X��KR����J��W�9��.�7wK~��J��)�J��)�.�������A�_�]�pw��@��'��{1M{���5���7�#X��|�w�#9W^�t�]������t}ms�l���%���W{���G��1T+8�2s���0a��3�XX� �yL��FrU��@�Y٦'���r���{g��簪�;c�[�0r0q�q���N9��G��{?�c�w�K�ӯE�|ެ�Td2���F�?!#�G�z>ЀP�����u۝�ᓒ����d��A8��9't��=���b���'#'ג}O��\����P�S�]���o�h�Zy$|�Ns�q��Y��t8f+�O�

I have used this code for showing the image

                                    $docimg = $doctor_img['url'];

                                    if ($docimg):
                                        ?>
                                        <?php cropImage( $docimg, 200, null); ?>

Is there anything to change in this code. So that i can get the image src instead of wired characters

Body:
here is the working example

$parts = explode('.', $docimg);
                                                    $ext = $parts[count($parts) - 1];
                                                    if ($ext == 'jpg' || $ext == 'jpeg') {
                                                        $format = 'jpg';
                                                        } else {
                                                        $format = 'png';
                                                    }
                                                    ob_start();
                                                     header( "Content-type: image/".$format );
                                                     cropImage( $docimg, 200, null);


问:
How to extract last X digits from fixed Y digit number using RegEx?
How to extract last X digits from fixed Y digit number using RegEx?

input : 1234567890123456

((?=\d{16}$)\d{10}|)  gives 1234567890

But

((?=\d{16}$)\d{10}$|) does not give 7890123456

basically, I want last 10 digits if it is compulsory 16 digit no else nothing.

答:
You can see from regex101 that the regex ^\d{6}(\d{10})$ will check if there is 16digit from start to end of the String (so check the length) and capture the last 10.

^ : start of the String

\d{6} : first 6 digit

(\d{10}) : capture 10 digit

$ : end of the String

So you can use it in Java with

```<code>String s = "1234567890123456";
Pattern p = Pattern.compile("^\\d{6}(\\d{10})$");
Matcher m = p.matcher(s);
if(m.matches()){
    System.out.println(m.group(1));
}
</code>```

This can be checked on this ideone

You just have to add an else clause to print that the String is not valid.

Body:
You can see from regex101 that the regex ^\d{6}(\d{10})$ will check if there is 16digit from start to end of the String (so check the length) and capture the last 10.

^ : start of the String

\d{6} : first 6 digit

(\d{10}) : capture 10 digit

$ : end of the String

So you can use it in Java with

String s = "1234567890123456";
Pattern p = Pattern.compile("^\\d{6}(\\d{10})$");
Matcher m = p.matcher(s);
if(m.matches()){
    System.out.println(m.group(1));
}

This can be checked on this ideone

You just have to add an else clause to print that the String is not valid.


答:
Looks like you're not using Java and cannot use capture groups.

For your tibco tool you can use this regex with validation of 16 digits to grab last 10 digits:

```<code>(?<=^\d{6})\d{10}$
</code>```

RegEx Demo

RegEx Breakup:

(?<=^\d{6}) is a positive lookbehind to assert that we have 6 digits from start to previous position

\d{10}$ matched 10 digits at the end of string

Body:
How to extract last X digits from fixed Y digit number using RegEx?

input : 1234567890123456

((?=\d{16}$)\d{10}|)  gives 1234567890

But

((?=\d{16}$)\d{10}$|) does not give 7890123456

basically, I want last 10 digits if it is compulsory 16 digit no else nothing.

Body:
Looks like you're not using Java and cannot use capture groups.

For your tibco tool you can use this regex with validation of 16 digits to grab last 10 digits:

(?<=^\d{6})\d{10}$

RegEx Demo

RegEx Breakup:

(?<=^\d{6}) is a positive lookbehind to assert that we have 6 digits from start to previous position

\d{10}$ matched 10 digits at the end of string


问:
jquery clone and add event
I'm trying to clone a "div" and all inside it but one of the events disappear in the cloned div (I'm pretty new to web developing so ... I "cloned" a code found on SO).

The missing event is added with the following javascript:

```<code>var MyClass = document.querySelectorAll(".BtnOptList");
for (var ii = 0; ii < MyClass.length; ii++) {
    MyClass[ii].addEventListener('click', H_S_Btns_Func, false);
}
</code>```

Then, to clone the div, I use the following function:

```<code>$('#btnAddFlds').click(function () {
    //Count "cloned divs" we currently have
    //This will be also used as numeric ID of the new input(s) field(s) (1st have no number)
    var DivNum = $('.SDetails').length;
    // clone() element and update its id(s)
    var newElem2 = $('.SDetails:first').clone().attr('id', function( i, val ) {
                                                            return val + DivNum;
                                                            });
    // manipulate the id values of the input inside the new element
    newElem2.find('input,.BtnOptList,.HideIt').each(function(){
                                        $(this).attr('id', function( i, val ) {
                                                            return val + '_' + DivNum;
                                                            });
                                        });
    //Try to add function (DOESN'T WORK)
    newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);

    //I omitted other stuff
});
</code>```

I've already tried clone(true,true) but doesn't worked

答:
According to the documentation using clone with true means

A Boolean indicating whether event handlers and data should be copied along with the elements. (v1.4 onwards)

Hence, use

```<code>.clone(true)
</code>```

instead of

```<code>.clone()
</code>```

Ref: http://api.jquery.com/clone/

Title: jquery clone and add event

Body:
I'm trying to clone a "div" and all inside it but one of the events disappear in the cloned div (I'm pretty new to web developing so ... I "cloned" a code found on SO).

The missing event is added with the following javascript:

var MyClass = document.querySelectorAll(".BtnOptList");
for (var ii = 0; ii < MyClass.length; ii++) {
    MyClass[ii].addEventListener('click', H_S_Btns_Func, false);
}

Then, to clone the div, I use the following function:

$('#btnAddFlds').click(function () {
    //Count "cloned divs" we currently have
    //This will be also used as numeric ID of the new input(s) field(s) (1st have no number)
    var DivNum = $('.SDetails').length;
    // clone() element and update its id(s)
    var newElem2 = $('.SDetails:first').clone().attr('id', function( i, val ) {
                                                            return val + DivNum;
                                                            });
    // manipulate the id values of the input inside the new element
    newElem2.find('input,.BtnOptList,.HideIt').each(function(){
                                        $(this).attr('id', function( i, val ) {
                                                            return val + '_' + DivNum;
                                                            });
                                        });
    //Try to add function (DOESN'T WORK)
    newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);

    //I omitted other stuff
});

I've already tried clone(true,true) but doesn't worked

Body:
According to the documentation using clone with true means

A Boolean indicating whether event handlers and data should be copied along with the elements. (v1.4 onwards)

Hence, use

.clone(true)

instead of

.clone()

Ref: http://api.jquery.com/clone/

ContentLicense: CC BY-SA 4.0


问:
is Apache Kylin good alternative for SSRS(SQL Server Reporting Services)?
We have framework for analysis data with the help of cube design for OLAP and warehouse that has ETL connections, all of them are in sqlServer structure and SSRS(SQL Server Reporting Services).
Some of our reports take a lot of time to come to a conclusion, we decided to migrate to Hadoop ecosystem. is Apache Kylin  a good alternative for this framework ?</p>

答: Based on my limited experience, most traditional OLAP products have limitations on scalability, and could not work together with Hadoop ecosystem very well. Apache Kylin follows the standard OLAP modeling methodology, and provides sub-second performance on Big Data architecture directly. So it's also the only open source OLAP on Hadoop solution. It worths a try. </p>


问:
How Can I Copy Data From an Access Table to An array In VBA?
I'm working on a program that can take data from one field in a table and put that whole column into an array or even just read from the table itself. The code seems to use a form or something else I would like to use an array.</p>

答:
Albert's solution above will work, but you would need to move the recordset to the end and then back again to fill the array fully, otherwise you will only get the first row. Use MoveLast and MoveFirst for this.

```<code>Dim rstData    As DAO.Recordset
Dim v          As Variant

Set rstData = CurrentDb.OpenRecordset("select FirstName from FaxBook3")
rstData.MoveLast
rstData.MoveFirst
v = rstData.GetRows(rstData.RecordCount)
</code>```

Body:
Albert's solution above will work, but you would need to move the recordset to the end and then back again to fill the array fully, otherwise you will only get the first row. Use MoveLast and MoveFirst for this.

Dim rstData    As DAO.Recordset
Dim v          As Variant

Set rstData = CurrentDb.OpenRecordset("select FirstName from FaxBook3")
rstData.MoveLast
rstData.MoveFirst
v = rstData.GetRows(rstData.RecordCount)


问:
router link attribute within the button tag doesnt work
I am unable to navigate with router link attribute that is placed within the button tag. Here is my code,</p>

```<code><button mat-raised-button color="primary"><a routerLink="/message-inbox">Inbox</a></button>
    <button mat-raised-button color="accent"><a routerLink="/sent">Sent</a></button>
    <a routerLink="/message-compose"><button color="warn">Compose</button></a>
</code>```

答:
What if you try something like this:

```<code><button mat-raised-button color="primary">
<a [routerLink]="['/message-inbox']">Inbox</a>
</button>
    <button mat-raised-button color="accent">
<a [routerLink]="['/sent']">Sent</a>
</button>
    <a [routerLink]="['/message-compose']"><button color="warn">Compose</button></a>
</code>```

Hope i helps you!!

Body:
I am unable to navigate with router link attribute that is placed within the button tag. Here is my code,

<button mat-raised-button color="primary">Inbox</button>
    <button mat-raised-button color="accent">Sent</button>
    <button color="warn">Compose</button>

Body:
What if you try something like this:

<button mat-raised-button color="primary">
<a [routerLink]="['/message-inbox']">Inbox</a>
</button>
    <button mat-raised-button color="accent">
<a [routerLink]="['/sent']">Sent</a>
</button>
    <a [routerLink]="['/message-compose']"><button color="warn">Compose</button></a>

Hope i helps you!!


答:
You can apply routerLink to the button directly. It doesn't have to be an <a element

```<code><button mat-raised-button color="primary" routerLink="/message-inbox">Inbox</button>
</code>```

Title: router link attribute within the button tag doesnt work

Body:
You can apply routerLink to the button directly. It doesn't have to be an <a element

<button mat-raised-button color="primary" routerLink="/message-inbox">Inbox</button>


问:
Optimize sql Query which take too long to execute
The following sql query is taking to much to return a result

```<code>SELECT count(*)
FROM List_declarations
WHERE  Id_antenne IN (
   SELECT id
   FROM Service
   WHERE id_direction IN (
      SELECT id_dr
      FROM affectation_service_dr
      WHERE id_service = 15
   )
)
</code>```

How I can do better  ?

答:
if Read Uncommitted data are not a concern here.If it concern then still you can try removing with (nolock)

```<code>SELECT count(*)
FROM List_declarations LD WITH (NOLOCK)
WHERE  exists (
   SELECT id
   FROM [Service] S WITH (NOLOCK)
   inner join affectation_service_dr dr WITH (NOLOCK)
   on s.id_direction=dr.id_dr
    WHERE ld.Id_antenne=s.id and dr.id_service = 15
   )
</code>```

Body:
The following sql query is taking to much to return a result

SELECT count(*)
FROM List_declarations
WHERE  Id_antenne IN (
   SELECT id
   FROM Service
   WHERE id_direction IN (
      SELECT id_dr
      FROM affectation_service_dr
      WHERE id_service = 15
   )
)

How I can do better  ?

Body:
if Read Uncommitted data are not a concern here.If it concern then still you can try removing with (nolock)

SELECT count(*)
FROM List_declarations LD WITH (NOLOCK)
WHERE  exists (
   SELECT id
   FROM [Service] S WITH (NOLOCK)
   inner join affectation_service_dr dr WITH (NOLOCK)
   on s.id_direction=dr.id_dr
    WHERE ld.Id_antenne=s.id and dr.id_service = 15
   )


问:
How do I check if an array includes a value in JavaScript?
What is the most concise and efficient way to find out if a JavaScript array contains a value?

This is the only way I know to do it:

```<code>function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}
</code>```

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

答:
It has one parameter: an array numbers of objects. Each object in the array has two integer properties denoted by x and y. The function must return a count of all such objects in the array that satisfy numbers.x == numbers.y

var numbers = [ { x: 1, y: 1 },
                { x: 2, y: 3 },
                { x: 3, y: 3 },
                { x: 3, y: 4 },
                { x: 4, y: 5 } ];
var count = 0;
var n = numbers.length;
for (var i =0;i<n;i++)
{
  if(numbers[i].x==numbers[i].y)
    {count+=1;}
}

alert(count);```

OwnerDisplayName: brad

Body:
What is the most concise and efficient way to find out if a JavaScript array contains a value?

This is the only way I know to do it:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

LastEditorDisplayName: brad


问:
Detect what form autocomplete value was selected
In HTML we can say to a form to show browser autocomplete. But is it possible to detect if some of the autocomplete values was selected?

答:
The browser fires an autocompletechange event. You can do something like this:

```<code>$(document).ready(function () {
    $('EnterElementHere').on('autocompletechange change', function () {
      $('EnterElementHere').html('You selected: ' + this.value);
    }).change();
});
</code>```

Read here

Body:
The browser fires an autocompletechange event. You can do something like this:

$(document).ready(function () {
    $('EnterElementHere').on('autocompletechange change', function () {
      $('EnterElementHere').html('You selected: ' + this.value);
    }).change();
});

Read here


问:
Why is this string not declared in the scope?
I'm experimenting with classes and I'm wondering why I'm getting an error saying "calvin" is not defined in the scope. Thanks.</p>

```<code>#include <iostream>
#include <string>
using namespace std;

class people
    {
    public:
        string name;
        int age;
    };

int main()
{
    people peeps[10];

    peeps[1].name = calvin;
    peeps[1].age = 21;

    cout << peeps[1].name << peeps[1].age;
}
</code>```

答:
firstly i would suggest if you had made and age private class members and also create get name/age and set name/age member functions to protect your data and finally </p>

```<code>peeps[1].name = calvin;
//calvin is an undefined variable
</code>```

<p>you should have used string literals for example </p>

```<code>peeps[1].name = "calvin";
</code>```

Body:
I'm experimenting with classes and I'm wondering why I'm getting an error saying "calvin" is not defined in the scope. Thanks.

#include <iostream>
#include <string>
using namespace std;

class people
    {
    public:
        string name;
        int age;
    };

int main()
{
    people peeps[10];

    peeps[1].name = calvin;
    peeps[1].age = 21;

    cout << peeps[1].name << peeps[1].age;
}

Body:
firstly i would suggest if you had made and age private class members and also create get name/age and set name/age member functions to protect your data and finally

peeps[1].name = calvin;
//calvin is an undefined variable

you should have used string literals for example

peeps[1].name = "calvin";


问:
How to reference ArrayList into a HashMap

I have an ArrayList of getCourses and a HashMap for a ComboBox below:

```<code>public class QueryCourses {
public static ArrayList<Courses> getCourses() throws ClassNotFoundException, SQLException {
    String queryCourses = "SELECT course_id, course_title FROM tblcourses";
    Connection conn = DbConnection.ConnectDB();
    Statement stmt = conn.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(queryCourses);
    ArrayList<Courses> courseList = new ArrayList<>();
    while (rs.next()) {
        Courses crse = new Courses(rs.getInt("course_id"), rs.getString("course_title"));
        courseList.add(crse);
    }
    return courseList;
}

public HashMap<String, Integer> hashMap(){
    HashMap<String, Integer> map = new HashMap<>();
    final ComboBox<Courses> cmbCourse = new ComboBox(courseList.getItems());
    Connection conn = DbConnection.ConnectDB();

    try {
        Statement stmt = conn.createStatement();
        String qry = "SELECT `course_id`, `course_title` FROM `tblcourses`";
        ResultSet rs = stmt.executeQuery(qry);
        Courses crse;

        while (rs.next()) {
            crse = new Courses(rs.getInt(1), rs.getString(2));
            cmbCourse.addItem(crse);
        }
    } catch (SQLException ex) {
        Logger.getLogger(NewStudentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return map;
}
</code>```

}

I would like to reference the ArrayList onto the HashMap of a ComboBox in which has the id of a course and its title but I do not know which to reference the getCourses or the courseList.  Either of which gives me an error, am I missing something or what? This will then output onto the ComboBox the title and can return the key for database insertion.

答:
ArrayList cannot be referenced to HashMap. You need to iterate through the arraylist (from getCourses() ) and individually set each element to the map.

Something like :

```<code>for(Course crse : getCourses()){
  map.put(crse.getId(),crse.getTitle() );
}
</code>```

Body:
I have an ArrayList of getCourses and a HashMap for a ComboBox below:

public class QueryCourses {
public static ArrayList<Courses> getCourses() throws ClassNotFoundException, SQLException {
    String queryCourses = "SELECT course_id, course_title FROM tblcourses";
    Connection conn = DbConnection.ConnectDB();
    Statement stmt = conn.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(queryCourses);
    ArrayList<Courses> courseList = new ArrayList<>();
    while (rs.next()) {
        Courses crse = new Courses(rs.getInt("course_id"), rs.getString("course_title"));
        courseList.add(crse);
    }
    return courseList;
}

public HashMap<String, Integer> hashMap(){
    HashMap<String, Integer> map = new HashMap<>();
    final ComboBox<Courses> cmbCourse = new ComboBox(courseList.getItems());
    Connection conn = DbConnection.ConnectDB();

    try {
        Statement stmt = conn.createStatement();
        String qry = "SELECT `course_id`, `course_title` FROM `tblcourses`";
        ResultSet rs = stmt.executeQuery(qry);
        Courses crse;

        while (rs.next()) {
            crse = new Courses(rs.getInt(1), rs.getString(2));
            cmbCourse.addItem(crse);
        }
    } catch (SQLException ex) {
        Logger.getLogger(NewStudentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return map;
}

}

I would like to reference the ArrayList onto the HashMap of a ComboBox in which has the id of a course and its title but I do not know which to reference the getCourses or the courseList.  Either of which gives me an error, am I missing something or what? This will then output onto the ComboBox the title and can return the key for database insertion.

Body:
ArrayList cannot be referenced to HashMap. You need to iterate through the arraylist (from getCourses() ) and individually set each element to the map.

Something like :

for(Course crse : getCourses()){
  map.put(crse.getId(),crse.getTitle() );
}


问:
Comapring Objects of TreeSet and HashSet
```<code>List<String> list = Arrays.asList("Snehal", "Masne", "Anything", "Else");

HashSet<String> hashSet = new HashSet<String>(list);
TreeSet<String> treeSet = new TreeSet<String>(list);

System.out.println("Equality  = " + hashSet.equals(treeSet));  // returns True
</code>```

How the equals() is evaluating the result by comparing diff structures? How come its true? Is just Hashcode being compared? If so, how come its same?

答:
Underneath AbstractSet#equals calls containsAll. For every single element this method checks it's presence in the other Set:

```<code>public boolean containsAll(Collection<?> c) {
    for (Object e : c)
        if (!contains(e))
            return false;
    return true;
}
</code>```

This will call HashSet#contains that looks like this:

```<code>public boolean contains(Object o) {
    return map.containsKey(o);
}
</code>```

Notice that since HashSet is nothing more then a HashMap with a dummy value - hashCode does gets called, but only to find the bucket of where it might be - the comparison is still using equals

Body:
List<String> list = Arrays.asList("Snehal", "Masne", "Anything", "Else");

HashSet<String> hashSet = new HashSet<String>(list);
TreeSet<String> treeSet = new TreeSet<String>(list);

System.out.println("Equality  = " + hashSet.equals(treeSet));  // returns True

How the equals() is evaluating the result by comparing diff structures? How come its true? Is just Hashcode being compared? If so, how come its same?

Body:
Underneath AbstractSet#equals calls containsAll. For every single element this method checks it's presence in the other Set:

public boolean containsAll(Collection<?> c) {
    for (Object e : c)
        if (!contains(e))
            return false;
    return true;
}

This will call HashSet#contains that looks like this:

public boolean contains(Object o) {
    return map.containsKey(o);
}

Notice that since HashSet is nothing more then a HashMap with a dummy value - hashCode does gets called, but only to find the bucket of where it might be - the comparison is still using equals


问:
int max = ~0; What does it mean?
int max = ~0;

What does it mean?

答:
~ means bitwise not, it inverts all the bits in the given integer. In a signed int this will give you -1 (since all the bits in the int will be flipped from 0 to 1.) Look up two's complement for more information on this one.

In an unsigned int (uint) this would give you the maximum value of an integer (since the most significant bit in an unsigned int doesn't determine the sign.)

ContentLicense: CC BY-SA 2.5

Title: int max = ~0; What does it mean?

Body:
int max = ~0;

What does it mean?


问:
Wordpress Walker — how to add number of post to category menu items?
I wanted to add number of posts for menu items that are categories.
For example:

Category 1 (5)

Category 2 (8)

Category 3 (2)

etc...

I edit walker:

get number:

```<code>$item_count = $depth == 0 ? get_posts( array(
  'post_type' => 'post',
  'numberposts' => -1,
  'orderby' => 'category',
  'order' => 'ASC'
) ) : false;
</code>```

output:

```<code>$item_output .= $item_count ? ' <span>(' . count( $item_count ) . ')</span>' : '';
</code>```

The result is a postscript to each menu item the number of all posts.
How to modify?

答:
If you are using some custom post taxonomie you can change the code for this one :

```<code>if ($item->type == 'taxonomy'){
    $term = get_term($item->object_id);
    $item_output .= '<div class="meni-item-badge"> '.$term->count .'</div>';
}
</code>```

Hope this help someone !!
Regards Mario

Body:
I wanted to add number of posts for menu items that are categories.
For example:

Category 1 (5)

Category 2 (8)

Category 3 (2)

etc...

I edit walker:

get number:

$item_count = $depth == 0 ? get_posts( array(
  'post_type' => 'post',
  'numberposts' => -1,
  'orderby' => 'category',
  'order' => 'ASC'
) ) : false;

output:

$item_output .= $item_count ? ' (' . count( $item_count ) . ')' : '';

The result is a postscript to each menu item the number of all posts.
How to modify?

Body:
If you are using some custom post taxonomie you can change the code for this one :

if ($item->type == 'taxonomy'){
    $term = get_term($item->object_id);
    $item_output .= '<div class="meni-item-badge"> '.$term->count .'</div>';
}

Hope this help someone !!
Regards Mario


问:
How can we use TFIDF vectors with multinomial naive bayes?
Say we have used the TFIDF transform to encode documents into continuous-valued features.

How would we now use this as input to a Naive Bayes classifier?

Bernoulli naive-bayes is out, because our features aren't binary anymore.

Seems like we can't use Multinomial naive-bayes either, because the values are continuous rather than categorical.

As an alternative, would it be appropriate to use gaussian naive bayes instead? Are TFIDF vectors likely to hold up well under the gaussian-distribution assumption?

The sci-kit learn documentation for MultionomialNB suggests the following:

The multinomial Naive Bayes classifier is suitable for classification
  with discrete features (e.g., word counts for text classification).
  The multinomial distribution normally requires integer feature counts.
  However, in practice, fractional counts such as tf-idf may also work.

Isn't it fundamentally impossible to use fractional values for MultinomialNB?

As I understand it, the likelihood function itself assumes that we are dealing with discrete-counts (since it deals with counting/factorials)

How would TFIDF values even work with this formula?

答:
Technically, you are right. The (traditional) Multinomial N.B. model considers a document D as a vocabulary-sized feature vector x, where each element xi is the count of term i i document D. By definition, this vector x then follows a multinomial distribution, leading to the characteristic classification function of MNB.

When using TF-IDF weights instead of term counts, our feature vectors are (most likely) not following a multinomial distribution anymore, so the classification function is not theoretically well-founded anymore. However, it does turn out that tf-idf weights instead of counts work (much) better.

How would TFIDF values even work with this formula?

In the exact same way, except that the feature vector x is now a vector of tf-idf weights and not counts.

You can also check out the Sublinear tf-idf weighting scheme, implemented in sklearn tfidf-vectorizer. In my own research I found this one performing even better: it uses a logarithmic version of the term frequency. The idea is that when a query term occurs 20 times in doc. a and 1 time in doc. b, doc. a should (probably) not be considered 20 times as important but more likely log(20) times as important.


问:
How to integrate instantpay in php
One of my client want a functionality that recharge online through this third party [https://www.instantpay.in], I do not have any idea about this, how to use it or integration in PHP.

If someone have any idea about it please share me.

答:
Instantpay does not have any official php library but you can use this 3rd party libarary instantpay

How to use

Clients

```<code>use Instantpay\BusClient;

$ipay = new BusClient(["IPAY_TOKEN"=>"YOUR_TOCKEN_HERE"]);
</code>```

Cities

```<code>$source_list = $ipay->cities->sources();

echo '```';
print_r($source_list);

$destination_list = $ipay->cities->destinations([
            "request"=>[
                "source"=>1492
            ]
]);

echo '```';
print_r($destination_list);
</code>```

For more reference :
https://docs.instantpay.in/

Title: How to integrate instantpay in php

Body:
Instantpay does not have any official php library but you can use this 3rd party libarary instantpay

How to use

Clients

use Instantpay\BusClient;

$ipay = new BusClient(["IPAY_TOKEN"=>"YOUR_TOCKEN_HERE"]);

Cities

$source_list = $ipay->cities->sources();

echo '<pre>';
print_r($source_list);

$destination_list = $ipay->cities->destinations([
            "request"=>[
                "source"=>1492
            ]
]);

echo '<pre>';
print_r($destination_list);

For more reference :
https://docs.instantpay.in/


问:
How to push public GitHub repo to private repo using PhpStorm?
I'm using PhpStorm to create a custom WordPress plugin.  I cloned the CMB2 repo from GitHub into my plugin directory and saved the directory as CMB2.  The files and directory are saved on my local machine without issue, and the WordPress local instance has no problem finding files required from the CMB2 directory.

I then committed my custom plugin to a private GitHub repo that I host.  The CMB2 directory was part of the commit.  However, the private repo only shows the directory name without any files contained therein.  As such, when I install the plugin to a production WordPress instance, all required files in the CMB2 directory fail because CMB2 is empty.

I did git status on the CMB2 folder and shows that it was committed.  What other steps should be taken to ensure the contents of CMB2 are properly committed?

答: In addition to creating commits, you must git push your commits to the remote repository before your changes will be reflected.


问:
Ionic: background-image not applying correctly
I have a (long) page with ion-list and many ion-scroll in ion-grid. I'm trying to apply a background image to this page in particular. It's working perfectly on another page (with less html)

sample.html:

```<code><ion-content no-padding overflow-scroll="true" class="test">
 <ion-refresher (ionRefresh)="refreshHome($event)">
   <ion-refresher-content></ion-refresher-content>
 </ion-refresher>
 <img [src]="banner.png"/>
 <ion-list class="category_list" *ngIf="tags_home && tags_home[0]">
   <div *ngFor='let tag_selected of tags_home' class="category">
    <ion-grid no-padding align-items: center>
      <ion-row>
        <ion-col>title
        </ion-col>
        <ion-col col-auto>
          <button>button</button>
        </ion-col>
      </ion-row>
    </ion-grid>
    <ion-scroll scrollX="true" direction="x">
      <img *ngFor="let item of tag_selected.slide" [src]="item.img"/>
    </ion-scroll>
</code>```

sample.css:

```<code>  ion-content {
   .category_list {
     bottom: 0;
     height: 62vh;
     .category { ... }
    }
  }
</code>```

I tried adding background-image under ion-content (and ion-list) but nothing is showing up (working on other pages without any problem). Adding the background under .category_list only show it for about 30% of the page (it stop before even scrolling).

Inspecting the css in Chrome inspector, I added a scroll-content class with background-image. The whole page showed the background but every ion-scroll had its own background as well...

I tried using the :not() but failed (either no background at all, no result or lost the background-size on the 'real' background)

<s>I'm pretty sure the ion-scrolls are messing with my background because they are not present on the other page.</s>

Edit: It wasn't in my sample to avoid cluttering but I have an ion-refresh before my banner... This ion-refresh does have the background when it is placed under ion-content. Deleting it correctly show the background on the whole page. But I need this ion-refresh...

答:
Try setting your background for <ion-content> like this,

```<code><ion-content padding style="background-image:url('your-img-path/url');background-position: center;background-repeat: no-repeat; background-size: cover;">
</code>```

Body:
I have a (long) page with ion-list and many ion-scroll in ion-grid. I'm trying to apply a background image to this page in particular. It's working perfectly on another page (with less html)

sample.html:

<ion-content no-padding overflow-scroll="true" class="test">
 <ion-refresher (ionRefresh)="refreshHome($event)">
   <ion-refresher-content></ion-refresher-content>
 </ion-refresher>

 <ion-list class="category_list" *ngIf="tags_home && tags_home[0]">

    <ion-grid no-padding align-items: center>
      <ion-row>
        <ion-col>title
        </ion-col>
        <ion-col col-auto>
          <button>button</button>
        </ion-col>
      </ion-row>
    </ion-grid>
    <ion-scroll scrollX="true" direction="x">

    </ion-scroll>

sample.css:

  ion-content {
   .category_list {
     bottom: 0;
     height: 62vh;
     .category { ... }
    }
  }

I tried adding background-image under ion-content (and ion-list) but nothing is showing up (working on other pages without any problem). Adding the background under .category_list only show it for about 30% of the page (it stop before even scrolling).

Inspecting the css in Chrome inspector, I added a scroll-content class with background-image. The whole page showed the background but every ion-scroll had its own background as well...

I tried using the :not() but failed (either no background at all, no result or lost the background-size on the 'real' background)

<s>I'm pretty sure the ion-scrolls are messing with my background because they are not present on the other page.</s>

Edit: It wasn't in my sample to avoid cluttering but I have an ion-refresh before my banner... This ion-refresh does have the background when it is placed under ion-content. Deleting it correctly show the background on the whole page. But I need this ion-refresh...

Body:
Try setting your background for <ion-content> like this,

<ion-content padding style="background-image:url('your-img-path/url');background-position: center;background-repeat: no-repeat; background-size: cover;">


问:
Where is mod_jk.dll in tomcat-connectors-1.2.42-src ?
I have downloaded the Tomcat Connector from http://tomcat.apache.org/download-connectors.cgi. The document said I should have the mod_jk.dll or mod_jk.so but I couldn't find it anywhere. I need it to install the Tomcat Connector said the document. </p>

答: The Tomcat community no longer produces mod_jk binaries for httpd for any OS. They are available from other sources such as Apache Lounge but you can use mod_proxy_ajp instead for nearly all use cases.</p>


问:
How to loop output in python, pandas?

I want to randomly select data on a quarterly basis and set the output in different csv files, and make this loop for several years. The following is an example of data.

Event number	Month	Year	Unauthorised activity	Theft and fraud (internal)	Theft and fraud (external)

72	1	2015	0	1	1

73	2	2015	0	0	0

74	3	2015	0	0	1

75	4	2015	0	0	0

76	5	2015	0	0	0

80	6	2015	0	0	0

81	7	2015	0	0	1

83	8	2015	0	1	0

84	9	2015	0	0	0

87	10	2015	0	0	1

90	11	2015	0	0	0

103	12	2015	1	0	0

```
</div>
</div>
</p>

<p>
Here is my current code:</p>

```df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

df2015q1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == 2015)]

df2015q1_random = df2015q1.sample(n=200)
df2015q1_random.sort_index(inplace=True)
df2015q1_random = df2015q1_random.drop(['Month', 'Year'], axis = 1)
df2015q1_random = df2015q1_random.drop_duplicates()

df2015q1_random.to_csv('2015Q1.csv')
```

The expected output for 2015 quarter 1 is 2015Q1.csv，for quarter 2 is 2015Q2.csv etc.

Currently, my output for a single stage is right, but I do not know how to write a loop for this. How can I do this for several years, say 2010 to 2016, and write the output in different files? Thanks.

答:
Let's create a function and use a list as inputs to make this happen. I haven't tested the code so you'll have to do that yourself. This is more to give you an idea how it can be done. Basically, you create a function for re-usability and afterwards you loop over a list of years to get a set of results.</p>

```<code># create a function that will report on a specific year
def save_file(df, year):
    dfq1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == year)]
    dfq1_random = dfq1.sample(n=200)
    dfq1_random.sort_index(inplace=True)
    dfq1_random = dfq1_random.drop(['Month', 'Year'], axis = 1)
    dfq1_random = dfq1_random.drop_duplicates()

    dfq1_random.to_csv(str(year) + 'Q1.csv')

# load the data and call your function for each year you want reported on
df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

list_years = [2015, 2016]
for year in list_years:
    save_file(df, year)
</code>```

Title: How to loop output in python, pandas?

Body:
I want to randomly select data on a quarterly basis and set the output in different csv files, and make this loop for several years. The following is an example of data.

Event number	Month	Year	Unauthorised activity	Theft and fraud (internal)	Theft and fraud (external)

72	1	2015	0	1	1

73	2	2015	0	0	0

74	3	2015	0	0	1

75	4	2015	0	0	0

76	5	2015	0	0	0

80	6	2015	0	0	0

81	7	2015	0	0	1

83	8	2015	0	1	0

84	9	2015	0	0	0

87	10	2015	0	0	1

90	11	2015	0	0	0

103	12	2015	1	0	0

Here is my current code:

df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

df2015q1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == 2015)]

df2015q1_random = df2015q1.sample(n=200)
df2015q1_random.sort_index(inplace=True)
df2015q1_random = df2015q1_random.drop(['Month', 'Year'], axis = 1)
df2015q1_random = df2015q1_random.drop_duplicates()

df2015q1_random.to_csv('2015Q1.csv')

The expected output for 2015 quarter 1 is 2015Q1.csv，for quarter 2 is 2015Q2.csv etc.

Currently, my output for a single stage is right, but I do not know how to write a loop for this. How can I do this for several years, say 2010 to 2016, and write the output in different files? Thanks.

Body:
Let's create a function and use a list as inputs to make this happen. I haven't tested the code so you'll have to do that yourself. This is more to give you an idea how it can be done. Basically, you create a function for re-usability and afterwards you loop over a list of years to get a set of results.

# create a function that will report on a specific year
def save_file(df, year):
    dfq1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == year)]
    dfq1_random = dfq1.sample(n=200)
    dfq1_random.sort_index(inplace=True)
    dfq1_random = dfq1_random.drop(['Month', 'Year'], axis = 1)
    dfq1_random = dfq1_random.drop_duplicates()

    dfq1_random.to_csv(str(year) + 'Q1.csv')

# load the data and call your function for each year you want reported on
df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

list_years = [2015, 2016]
for year in list_years:
    save_file(df, year)


问:
Set inherited Binding source for UserControl element
Simple syntax question really but I'm getting nowhere:

(Psuedo code)

MainWindow.xaml:

```<code><grid>
  <control:MyUserControl DataContext="{StaticResource MyDataSource}" />
</grid>
</code>```

MyUserControl.xaml

```<code><grid>
  <stackpanel DataContext="{StaticResource MyOtherDataSource}" IsEnabled="{Binding Path=CanUseMe, Source={StaticResource MyDataSource}" />
</grid>
</code>```

The problem is {StaticResource MyDataSource} in the stackpanel, since the user control doesn't have this resource.

How do I set the source binding to be the 'global' datasource passed into the usercontrol when I've already set the DataContext for the stackpanel?

Thanks!

答:
The UserControl's DataContext will be MyDataSource, so you can use RelativeSource in the Binding like this

```<code><grid>
    <stackpanel DataContext="{StaticResource MyOtherDataSource}"
                IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
                                    Path=DataContext.CanUseMe}"/>
</grid>
</code>```

Body:
Simple syntax question really but I'm getting nowhere:

(Psuedo code)

MainWindow.xaml:

<grid>
  <control:MyUserControl DataContext="{StaticResource MyDataSource}" />
</grid>

MyUserControl.xaml

<grid>
  <stackpanel DataContext="{StaticResource MyOtherDataSource}" IsEnabled="{Binding Path=CanUseMe, Source={StaticResource MyDataSource}" />
</grid>

The problem is {StaticResource MyDataSource} in the stackpanel, since the user control doesn't have this resource.

How do I set the source binding to be the 'global' datasource passed into the usercontrol when I've already set the DataContext for the stackpanel?

Thanks!

Body:
The UserControl's DataContext will be MyDataSource, so you can use RelativeSource in the Binding like this

<grid>
    <stackpanel DataContext="{StaticResource MyOtherDataSource}"
                IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
                                    Path=DataContext.CanUseMe}"/>
</grid>


问:
How can i use different wow animation
How can I use different wow animation within two div tags, I tried this code, but both animation happen at the same time. I need the animations to happen sequentially.</p>

```<code> <div class="game-box wow slideInUp">
      <div class="play wow swing"></div>
 </div>
</code>```

答:
If your animation is done using CSS, then you could define a rule for tags having wow class inside another tag having a wow class:

```<code>.wow .wow {
    -webkit-animation-delay: 2s; /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}
</code>```

where 2s is assumed to be the length of the animation.

Read more here: https://www.w3schools.com/cssref/css3_pr_animation-delay.asp

Title: How can i use different wow animation

Body:
If your animation is done using CSS, then you could define a rule for tags having wow class inside another tag having a wow class:

.wow .wow {
    -webkit-animation-delay: 2s; /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}

where 2s is assumed to be the length of the animation.

Read more here: https://www.w3schools.com/cssref/css3_pr_animation-delay.asp


问:
User Input to Array and then compare it to a random number?
I'm trying to make a classic lottery style code, where the objective is for the user to choose ten numbers to play with, and then those numbers are compared to a randomly generated number.

So far I got this:

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
        Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
        Console.WriteLine("Go ahead and type them in.");

        int[] lotteri = new int[10]; //Array to catch ten numbers input.

        for (int i=0; i<lotteri.Length; i++)
            lotteri[i] = int.Parse(Console.ReadLine());

        Console.WriteLine("Very good! Now we'll see if you won anything!");

        Random randomNumber = new Random(1-100);

        Console.ReadKey();
    }
}
</code>```

That's as far as I got, I think the array is doing what it should (collecting the user input ten times before moving on).

The MAIN PROBLEM for me now is that I want the program to compare those numbers in the array to a randomly chosen number, and if either of those ten user input numbers match with the randomly generated number to tell the user that they've won (or if it doesn't, that they lost). I just can't seem to get it to work!

Secondary problem, but that I'm trying to learn is handling methods better, so if anyone got any tip on how to use the array in a method and then get it to main, that'd be very appreciated as well!

答:
Simply replace this line Random randomNumber = new Random(1-100); with this :

```<code>Random rnd = new Random();//Instanciate a Random object
int randomNumber = rnd.Next(1, 101);//Generate your Random number in range [[1,100]]
</code>```

Then

Empiric solution (explicit foreach)

```<code>foreach (var a in lotteri)
{
    if (a == randomNumber)
    {
        //Handle if the user got the number
        break;
    }
}
</code>```

Solution 2 (implicit foreach)

```<code>if (lotteri.Any(x => x == randomNumber))
    //Handle if the user got the number
</code>```

Solution 3 (using Contains)

```<code>if (lotteri.Contains(randomNumber))
    //Handle if the user got the number
</code>```

EDIT : Added the suggested solution and increased the range of Next()

Body:
I'm trying to make a classic lottery style code, where the objective is for the user to choose ten numbers to play with, and then those numbers are compared to a randomly generated number.

So far I got this:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
        Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
        Console.WriteLine("Go ahead and type them in.");

        int[] lotteri = new int[10]; //Array to catch ten numbers input.

        for (int i=0; i<lotteri.Length; i++)
            lotteri[i] = int.Parse(Console.ReadLine());

        Console.WriteLine("Very good! Now we'll see if you won anything!");

        Random randomNumber = new Random(1-100);

        Console.ReadKey();
    }
}

That's as far as I got, I think the array is doing what it should (collecting the user input ten times before moving on).

The MAIN PROBLEM for me now is that I want the program to compare those numbers in the array to a randomly chosen number, and if either of those ten user input numbers match with the randomly generated number to tell the user that they've won (or if it doesn't, that they lost). I just can't seem to get it to work!

Secondary problem, but that I'm trying to learn is handling methods better, so if anyone got any tip on how to use the array in a method and then get it to main, that'd be very appreciated as well!

Body:
Simply replace this line Random randomNumber = new Random(1-100); with this :

Random rnd = new Random();//Instanciate a Random object
int randomNumber = rnd.Next(1, 101);//Generate your Random number in range [[1,100]]

Then

Empiric solution (explicit foreach)

foreach (var a in lotteri)
{
    if (a == randomNumber)
    {
        //Handle if the user got the number
        break;
    }
}

Solution 2 (implicit foreach)

if (lotteri.Any(x => x == randomNumber))
    //Handle if the user got the number

Solution 3 (using Contains)

if (lotteri.Contains(randomNumber))
    //Handle if the user got the number

EDIT : Added the suggested solution and increased the range of Next()


问:
Trivial query with if statements
How to achieve this simple logic?

```<code>void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }
</code>```

Essentially, I want to check for the same CONDITION1 over two consecutive interrupts. For 1st interrupt, I want to update the variable value to 1 and exit the loop (precisely do not execute the following if condition).  As I see, I cannot use break condition with "if"! I am struck here for a while! Please help me!

答:
There is no loop in your code, just a bunch of selection statements using if condition.

In this case, seeing this as a function body, if you want execution not to continue to the rest part, you can always return ; from the function.

Title: Trivial query with if statements

Body:
How to achieve this simple logic?

void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }

Essentially, I want to check for the same CONDITION1 over two consecutive interrupts. For 1st interrupt, I want to update the variable value to 1 and exit the loop (precisely do not execute the following if condition).  As I see, I cannot use break condition with "if"! I am struck here for a while! Please help me!


答:
Is turned out, there were plenty garbage in the paths. After removing this trash, the map renders perfect. Here is my code:</p>

```<code>var svgMap = function(options){

    var vars = {
        svg  : null,
        width: 0,
        heigth: 0,
        strokeWidth: 10
    };

    /*
     * Can access this.method
     * inside other methods using
     * root.method()
     */
    var root = this;

    /*
     * Constructor
     */
    this.construct = function(options){
        $.extend(vars , options);

        vars.svg = $('#'+vars.svgId).get(0);

        draw(vars.svg, vars.states);
    };

    /*
     * Draws the paths from array
     */
    var draw = function(svg, states) {
        $.each(states, function( index, value ) {
            var path = document.createElementNS('http://www.w3.org/2000/svg',"path");
            path.setAttributeNS( null, "id", value.id);
            path.setAttributeNS( null, "d", value.d);
            path.setAttributeNS( null, "stroke", "black");
            path.setAttributeNS( null, "stroke-width", vars.strokeWidth);
            path.setAttributeNS( null, "opacity", 1);
            path.setAttributeNS( null, "fill", "none");
            svg.appendChild(path);
        });
        adaptViewBox(svg);
    };

    /*
     * Adapts dimension of SVG according it paths
     */
    var adaptViewBox = function(svg) {
        var bbox = svg.getBBox();
        svg.setAttribute('viewBox', '0 0 '+bbox.width+' '+bbox.height);
    };

    /*
     * Pass options when class instantiated
     */
    this.construct(options);

};

var map = new svgMap({
    svgId : 'mapSVG',
    states: ruStates
});
</code>```

Title: Draw huge svg from an array and scale it within the parent element

Body:
I have grabbed the svg file (the map of Russia) and have got the array of paths. Here is the snippet:

var states = [
    {
        id: "1",
        d: [
            "m 6477.42,3306.03 -13.31,-25.82 -71.82,-40.46 -52.18,49.61 -52.21,5.21 -74.43,-48.3 -50.89,-62.66 -18.29,-63.95 -33.92,-10.44 -41.79,20.88 -40.45,-3.91 -20.89,-27.42 -18.28,15.67 -16.97,-18.29 -20.86,19.59 29.99,30.02 -70.47,5.23 -40.47,-35.25 22.19,-75.71 -40.47,-39.15 v 58.73 h -27.41 l -27.41,-24.8 -6.52,30.03 40.47,36.55 -43.09,-2.62 -127.92,-65.26 24.8,-30.02 -36.54,-35.25 14.35,-26.1 26.12,13.06 2.61,-37.87 31.32,-36.55 -48.31,-11.74 -14.35,-19.59 13.06,-31.31 -39.15,-6.54 -52.22,15.67 -15.66,-58.73 -88.78,15.66 v -130.53 l -62.64,10.43 -96.61,87.46 35.25,24.8 -58.72,87.46 -37.87,18.27 -57.43,-19.57 -63.95,24.79 -9.15,-99.2 -116.16,-49.6 -44.38,30.03 6.51,23.48 -118.77,1.31 -31.34,-41.77 -7.84,-27.42 -7.81,40.47 -22.21,19.59 -26.09,-27.42 -36.2,-18.09 -2,-24.87 16.91,-22.54 0.33,-0.46 0.12,-0.55 7.67,-40.21 55.94,-79.12 0.45,-0.64 v -0.75 -51.52 l 28.54,-34.24 1.6,-1.9 -1.94,-1.56 -65.19,-51.76 -3.76,-30.04 -0.09,-0.58 -0.31,-0.48 -15.27,-22.91 -11.52,-55.77 -0.47,-2.19 -2.19,0.27 -31.96,3.76 -51.6,-42.03 -0.19,-0.16 -0.23,-0.12 -17.33,-8.94 40.92,-62.56 0.34,-0.53 0.06,-0.61 13.89,-174.86 0.09,-1.01 -0.7,-0.8 -35.98,-39.78 23.73,-18.27 1.21,-0.92 -0.31,-1.49 -9.69,-46.47 21.04,-22.95 0.61,-0.68 v -0.95 -32.49 l 24.81,-17.16 1.54,-1.09 -0.64,-1.78 -11.95,-31.76 -0.13,-0.42 -0.26,-0.31 -37.29,-45.14 -3.59,-32.32 h 60.85 0.84 l 0.68,-0.54 26.43,-20.75 28.33,18.88 1.86,1.23 1.41,-1.74 15.89,-19.85 1.26,-1.63 -0.1,-0.12 20.81,-31.53 1.34,-2.06 -2.08,-1.34 -23.59,-15 v -27.92 l 26.12,-2.02 21.77,15.25 2.28,1.57 1.26,-2.44 26.99,-51.74 0.3,-0.55 -0.02,-0.66 -2.2,-61.47 34.69,-19.53 1.6,-0.89 -0.42,-1.8 -15.56,-64.4 19.47,-43.22 43.93,-13.17 2.57,-0.79 -1.06,-2.5 -33.56,-78.36 -6.66,-97.48 33.75,-35.87 36.52,27.92 0.58,0.45 0.8,0.03 54.85,2.18 19.57,34.84 1.57,2.77 2.28,-2.24 29.63,-29.63 38.56,44.96 60.58,130.15 0.53,1.15 1.26,0.22 40.51,6.75 0.68,0.11 0.61,-0.26 78.72,-31.48 1.05,-0.42 0.36,-1.07 17.13,-51.42 47.04,21.4 1.24,0.56 1.15,-0.78 29.24,-20.25 0.55,-0.39 0.29,-0.63 52.97,-120.12 68.83,-127.58 43.32,28.33 0.19,0.14 0.22,0.08 45,18.01 1.31,0.53 1.13,-0.89 34.37,-27.95 18.68,16.63 1.66,1.45 1.62,-1.48 27.53,-25.42 25.34,25.33 0.73,0.76 1.06,-0.03 62.97,-2.27 0.81,-0.03 0.63,-0.48 39.4,-30.64 77.45,28.76 1.33,0.47 1.07,-0.89 25.81,-21.52 106.58,48.85 0.73,0.36 0.78,-0.17 30.78,-6.6 33.46,12.53 -4.16,25.02 -0.31,1.74 1.57,0.82 82.46,42.88 -20.62,58.14 -0.5,1.37 1.01,1.08 27.7,29.68 -11.47,28.65 -52.74,34.49 -1.83,1.2 1.02,1.94 27.74,53.56 -51.62,35.72 -2.22,1.55 1.77,2.03 24.05,28.08 v 118.19 1.65 l 1.57,0.61 101.22,38.46 3.96,45.72 0.2,2.07 2.07,0.15 60.02,3.98 13.65,37.08 -2.02,38.5 -0.09,1.63 1.5,0.7 28.92,13.49 -21.8,77.25 -40.32,28.26 -1.43,0.98 0.47,1.66 26.46,93.69 -36.65,97.81 -0.48,1.27 0.81,1.05 20.53,26.7 1.07,1.39 1.63,-0.57 71.25,-24.41 45.47,9.88 15.9,27.81 0.59,1.02 1.18,0.17 53.87,7.99 9.61,34.55 -89.65,185.98 -0.34,0.74 0.14,0.78 9.09,45.47 0.21,0.94 0.78,0.57 60.1,42.42 -22.66,43.58 -0.85,1.63 1.35,1.26 58.19,54.56 0.6,0.57 0.81,0.08 51.82,5.36 29.74,33.25 5.27,58.01 -33.64,30.09 -0.75,0.69 -0.06,1.01 -1.78,37.5 -21.48,32.19 -1.12,1.72 1.52,1.41 25.59,23.88 -27.61,32.8 -1.52,1.77 1.71,1.57 67.29,61.83 0.31,0.3 0.42,0.15 30.26,12.46 22.44,32.81 -42.39,88.28 h -53.02 -0.51 l -0.48,0.2 -41.82,18.18 -0.92,0.42 -0.36,0.94 -21.83,56.38 -0.54,1.35 0.96,1.09 84.87,99.35 v 48.81 l -111.04,83.3 v 0",
            "m 4743.9,2834.2 30.11,-23.91 13.82,21.81 4.61,18.03 -16.74,10.48 -20.09,2.94 -11.71,-29.35 v 0",
            "m 5337.71,3240.7 6.6,-29.65 26.35,-30.76 16.48,6.59 -19.77,36.25 -29.66,17.57 v 0",
            "m 5426.68,3074.84 50.53,-6.58 2.19,-25.27 -19.77,-5.49 -23.05,14.29 -9.9,23.05 v 0",
            "m 5531.02,3332.96 23.09,-35.15 42.83,-8.79 1.09,49.44 -14.29,24.16 -50.52,3.28 -26.35,-18.66 -40.63,6.59 -3.3,-27.46 24.15,-25.26 -13.16,-15.39 -38.46,31.86 -46.14,-4.4 -3.28,-37.34 4.4,-38.44 20.84,-26.35 7.7,-29.66 42.83,-12.08 39.54,3.29 -3.28,41.74 28.57,-3.29 21.96,36.24 26.34,-5.49 17.58,19.76 -17.58,17.58 -38.42,10.98 -30.75,36.25 25.24,6.59 v 0",
            "m 5559.58,3158.32 8.79,-40.63 h 20.87 l 4.39,36.24 -20.87,17.57 -13.18,-13.18 v 0",
            "m 5605.7,3124.28 v -46.14 l 51.62,10.98 48.34,25.27 -16.46,37.35 -31.88,4.39 -24.15,5.49 -17.58,-26.37 -9.89,-10.97 v 0",
            "m 5622.19,3381.28 15.39,-32.95 98.83,-1.09 28.57,52.72 -18.69,40.64 -20.86,-23.08 -40.64,3.3 -10.98,-18.66 h -21.96 l -3.29,-21.97 -26.37,1.09 v 0",
            "m 5583.74,3546.04 -6.58,-24.16 19.78,-4.4 7.66,20.87 -20.86,7.69 v 0",
            "m 6315.25,3332.96 -6.6,-18.68 16.49,-10.98 18.64,10.98 -6.57,23.06 -21.96,-4.38 v 0"
        ]
    },
    {
        id: "2",
        d: [
            "m 7478.07,3285.08 -12.8,141.33 -39.16,22.18 92.68,63.97 -13.05,43.08 -172.31,14.36 -20.87,-27.42 -47.01,-3.91 -5.19,-36.55 -37.86,2.61 v 50.91 l 43.05,14.36 16.99,35.23 -9.16,92.68 -16.96,6.52 -20.9,-13.04 -1.29,33.93 -40.47,-15.65 -27.41,31.32 10.45,50.9 33.93,-30.01 19.57,15.66 28.73,-31.33 16.96,39.16 -3.9,46.99 31.31,26.11 54.83,-5.23 91.36,69.18 -22.18,26.12 45.69,-6.53 -1.29,44.38 -49.6,-9.14 -14.38,31.32 -66.57,13.06 26.13,32.63 -33.96,24.8 31.34,22.19 -39.18,50.92 -110.94,-65.28 -6.54,-53.51 -30.02,-39.16 74.42,-30.02 -40.46,-18.28 -120.1,32.63 -139.67,-92.67 -208.84,-113.56 -56.14,-91.38 5.22,-27.4 -37.86,-10.44 -53.5,-48.3 37.86,-47 33.92,10.44 50.92,-28.72 -5.22,-50.91 -46.98,-5.21 -31.35,-18.27 -66.56,41.76 v -84.84 l -67.89,-50.92 -26.2,-50.74 112.68,-84.51 0.99,-0.73 v -1.2 -50.92 -0.89 l -0.6,-0.69 -84.53,-98.93 20.95,-54.07 40.42,-17.57 h 54.06 1.51 l 0.68,-1.4 21.26,-44.28 35.1,-5.28 1.18,-0.17 0.57,-1.04 22.52,-39.85 47.07,22.65 0.87,0.42 0.93,-0.29 44.15,-14.12 33.5,29.98 0.63,0.57 0.84,0.06 51.81,3.57 38.48,40.24 -7.05,38.8 -0.39,2.09 2.05,0.66 38.76,12.33 10.56,36.94 0.45,1.58 1.63,0.17 33,3.48 10.42,31.25 0.42,1.29 1.31,0.3 60.81,14.31 15.84,28.16 0.65,1.15 1.32,0.09 90.93,5.46 1.8,0.1 0.63,-1.7 21.03,-57.85 63.27,19.33 0.37,0.12 0.39,-0.01 69.15,-1.78 55.81,160.18 0.92,2.66 2.5,-1.3 33.68,-17.73 43.08,13.06 v 0",
            "m 6609.14,3956.42 56.3,-66.71 12.31,12.31 15.36,76.96 18.43,35.92 -20.48,27.71 -51.2,-4.1 -30.72,-46.19 v -35.9 0"
        ]
    },
    {
        id: "3",
        d: [
            "m 6754.17,2018.43 34.94,23.04 23.5,19.59 32.64,7.83 -10.45,66.56 57.44,18.28 44.38,39.16 40.46,1.31 -30.01,-43.09 28.73,-24.8 41.75,47 10.45,74.4 37.83,14.36 30.02,39.16 -31.3,23.5 -27.42,-33.95 -28.71,27.42 -7.83,134.45 -24.79,79.62 7.8,58.75 48.31,69.18 27.41,1.29 13.06,39.16 56.11,-77.02 39.18,6.54 2.61,28.72 -9.15,58.74 -9.91,41.36 -37.7,21.26 -1.01,0.56 -0.19,1.1 -7.2,37.7 -24.27,22.54 -39.22,-3.56 -1.83,-0.17 -0.67,1.72 -23.34,61.07 -33.51,7.04 -0.96,0.21 -0.55,0.8 -53.73,78.07 -37.94,-39.66 -0.69,-0.7 -0.91,-0.06 -51.91,-3.58 -33.92,-30.35 -1.05,-0.93 -1.32,0.43 -44.54,14.25 -48.22,-23.23 -2.05,-0.98 -1.13,1.99 -23.05,40.77 -30.68,4.61 19.84,-41.33 0.61,-1.27 -0.79,-1.15 -23.64,-34.56 -0.42,-0.59 -0.67,-0.28 -30.51,-12.57 -65.27,-59.97 27.61,-32.77 1.49,-1.77 -1.68,-1.57 -25.79,-24.05 20.7,-31.02 0.37,-0.54 0.02,-0.69 1.78,-37.19 33.78,-30.23 0.92,-0.8 -0.1,-1.22 -5.48,-60.01 -0.06,-0.81 -0.53,-0.6 -30.93,-34.55 -0.61,-0.7 -0.93,-0.1 -51.93,-5.37 -56.25,-52.73 22.77,-43.83 0.99,-1.89 -1.74,-1.23 -61.04,-43.07 -8.73,-43.74 88.44,-183.53 40.81,27.19 0.98,0.66 1.12,-0.39 92.4,-30.8 1.35,-0.45 0.28,-1.37 10.26,-51.32 0.16,-0.86 -0.42,-0.78 -21.96,-39.97 16.6,-33.22 36.7,27.03 0.66,0.47 h 0.78 47.21 1.43 l 0.67,-1.22 23.29,-40.7 v 0"
        ]
    },
...

Now, I would like to generate svg element on the page based on this data.

// I put <svg id="mapSVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" /> tag on the page
$.each(states, function( index, value ) {
    var newpath = document.createElementNS('http://www.w3.org/2000/svg',"path");
    newpath.setAttributeNS( null, "id", value.id);
    newpath.setAttributeNS( null, "d", value.d);
    newpath.setAttributeNS( null, "stroke", "black");
    newpath.setAttributeNS( null, "stroke-width", 3);
    newpath.setAttributeNS( null, "opacity", 1);
    newpath.setAttributeNS( null, "fill", "none");
    document.getElementById('mapSVG').appendChild(newpath);
    console.log( index + ": " + value.d );
});

var svg = $("#mapSVG").get(0);
var w = svg.width.baseVal.value;
var h = svg.height.baseVal.value;
svg.setAttribute('viewBox', '0 0 '+w+' '+h);
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');
console.log('viewBox', '0 0 '+w+' '+h);

When I load the page, I see empty SVG element, but in DevTool I can find all the paths in proper place. The problem is that the SVG doesn't scale correctly! The paths are too far away from viewport.

Then I tried my own array of data and it renders quite well. I can see all the lines and they are fit to the viewport.

d: [
    "M 1,97.857143 C 19.285714,96.428571 24.016862,131.64801 90.714286,132.85714 140.78762,133.7649 202.79376,66.16041 202.79376,66.16041",
    "M 7500,167.857443 C 278.282714,920.428571 20.016862,110.64801 190.714286,12.85714 50.78762,13.7649 2.79376,6.16041 102.79376,56.16041"
]

My ultimate aim is to draw the map inside a parent element. Can somebody give me an advice how to do it properly?

Body:
Is turned out, there were plenty garbage in the paths. After removing this trash, the map renders perfect. Here is my code:

var svgMap = function(options){

    var vars = {
        svg  : null,
        width: 0,
        heigth: 0,
        strokeWidth: 10
    };

    /*
     * Can access this.method
     * inside other methods using
     * root.method()
     */
    var root = this;

    /*
     * Constructor
     */
    this.construct = function(options){
        $.extend(vars , options);

        vars.svg = $('#'+vars.svgId).get(0);

        draw(vars.svg, vars.states);
    };

    /*
     * Draws the paths from array
     */
    var draw = function(svg, states) {
        $.each(states, function( index, value ) {
            var path = document.createElementNS('http://www.w3.org/2000/svg',"path");
            path.setAttributeNS( null, "id", value.id);
            path.setAttributeNS( null, "d", value.d);
            path.setAttributeNS( null, "stroke", "black");
            path.setAttributeNS( null, "stroke-width", vars.strokeWidth);
            path.setAttributeNS( null, "opacity", 1);
            path.setAttributeNS( null, "fill", "none");
            svg.appendChild(path);
        });
        adaptViewBox(svg);
    };

    /*
     * Adapts dimension of SVG according it paths
     */
    var adaptViewBox = function(svg) {
        var bbox = svg.getBBox();
        svg.setAttribute('viewBox', '0 0 '+bbox.width+' '+bbox.height);
    };

    /*
     * Pass options when class instantiated
     */
    this.construct(options);

};

var map = new svgMap({
    svgId : 'mapSVG',
    states: ruStates
});


问:
Pass Key of Grid to Business Class via Object Data Source
In ASP.NET Webforms have an ASP.NET GridView connected to a C# class via an object data source

I have an ID set up as a DataKeyName in the grid. How do I pass this to the C# class when I update the grid?

答: Actually data key names are passed automatically by the datagrid to the object data source.</p>


问:
How to remove the existing file dropzone?
I have this sample:

link

CODE HTML:

```<code><div class="dropzone dz-clickable" id="myDrop">
     <div class="dz-default dz-message" data-dz-message="">
          <span>Upload or drag patient photo here</span>
     </div>
</div>
</code>```

CODE JS:

```<code> Dropzone.autoDiscover = false;
 var myDropzone = new Dropzone("div#myDrop", {
   addRemoveLinks: true,
   url: "#",
   maxFiles: 1,
   init: function() {

     this.on("maxfilesexceeded", function(file) {
       alert("You are not allowed to chose more than 1 file!");
       this.removeFile(file);

     });

     this.on("addedfile", function(file) {
       myDropzone.options.removefile.call(myDropzone, mockFile);
       //  I want to delete an existing element
     });

   }
 });

 var fileName = $('#profilePicture').val();
 var mockFile = {
   name: fileName,
   size: 12345
 };
 myDropzone.options.addedfile.call(myDropzone, mockFile);
 myDropzone.options.thumbnail.call(myDropzone, mockFile, "https://lh3.googleusercontent.com/-eubcS91wUNg/AAAAAAAAAAI/AAAAAAAAAL0/iE1Hduvbbqc/photo.jpg?sz=104");
</code>```

What I want to do is when the user uploads a file, then the existing one to be removed.

How can you do this correctly?

Thanks in advance!

答:
"Every your events" Like : success - error - sending - removedfile or addedfile and etc.

http://www.dropzonejs.com/#event-list

```<code>init : function () {
    self.on('Every your events', function (file, response) {
        this.removeFile(file);
    }
}
</code>```

for remove file from out of this function can do this :

```<code>Dropzone.forElement("div#myDrop").removeAllFiles(true);
</code>```

Body:
I have this sample:

link

CODE HTML:

          Upload or drag patient photo here

CODE JS:

 Dropzone.autoDiscover = false;
 var myDropzone = new Dropzone("div#myDrop", {
   addRemoveLinks: true,
   url: "#",
   maxFiles: 1,
   init: function() {

     this.on("maxfilesexceeded", function(file) {
       alert("You are not allowed to chose more than 1 file!");
       this.removeFile(file);

     });

     this.on("addedfile", function(file) {
       myDropzone.options.removefile.call(myDropzone, mockFile);
       //  I want to delete an existing element
     });

   }
 });

 var fileName = $('#profilePicture').val();
 var mockFile = {
   name: fileName,
   size: 12345
 };
 myDropzone.options.addedfile.call(myDropzone, mockFile);
 myDropzone.options.thumbnail.call(myDropzone, mockFile, "https://lh3.googleusercontent.com/-eubcS91wUNg/AAAAAAAAAAI/AAAAAAAAAL0/iE1Hduvbbqc/photo.jpg?sz=104");

What I want to do is when the user uploads a file, then the existing one to be removed.

How can you do this correctly?

Thanks in advance!

Body:
"Every your events" Like : success - error - sending - removedfile or addedfile and etc.

http://www.dropzonejs.com/#event-list

init : function () {
    self.on('Every your events', function (file, response) {
        this.removeFile(file);
    }
}

for remove file from out of this function can do this :

Dropzone.forElement("div#myDrop").removeAllFiles(true);


答:
```<code>if(update_variable == 0)
    {
        if(CONDITION1)
         {
            /* MORE CODE */
            update_variable = 1;
          }
         return;
    } /* Here i want to exit the loop */
</code>```

It's not a loop, so there's nothing to break from. Use return to exit the function.

In this case it's better to go for M.K's answer and use else but return is always an option to exit a function at any place in the code. It can be very useful if you want to exit from a lot of nested if statements.

Example:

```<code>if(cond1) {
   <code>
   if(cond2) {
      <code>
      if(cond3) {
         <code>
         if(cond4) {
             return;
         }
      <code>
      }
   <code>
   }
}
</code>```

Title: Trivial query with if statements

Body:
if(update_variable == 0)
    {
        if(CONDITION1)
         {
            /* MORE CODE */
            update_variable = 1;
          }
         return;
    } /* Here i want to exit the loop */

It's not a loop, so there's nothing to break from. Use return to exit the function.

In this case it's better to go for M.K's answer and use else but return is always an option to exit a function at any place in the code. It can be very useful if you want to exit from a lot of nested if statements.

Example:

if(cond1) {
   <code>
   if(cond2) {
      <code>
      if(cond3) {
         <code>
         if(cond4) {
             return;
         }
      <code>
      }
   <code>
   }
}


问:
iOS: ObjectMapper mapping an array of objects without root field
Suppose that I have a User object:

```<code>class User: Mappable {
    var username: String?
    var age: Int?
    var weight: Double!
    var array: [Any]?
    var dictionary: [String : Any] = [:]
    var bestFriend: User?                       // Nested User object
    var friends: [User]?                        // Array of Users
    var birthday: Date?

    required init?(map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        username    <- map["username"]
        age         <- map["age"]
        weight      <- map["weight"]
        array       <- map["arr"]
        dictionary  <- map["dict"]
        bestFriend  <- map["best_friend"]
        friends     <- map["friends"]
        birthday    <- (map["birthday"], DateTransform())
    }
}
</code>```

And my Json contains an array of that object: [User] How can I map this array even if it has not a specific field name? This is what I did:

```<code>class Users: Mappable {

var users: [User]?

required init?(map: Map) {

        }

// Mappable
        func mapping(map: Map) {
          //What have I to put here??
        }
</code>```

}

答:
It's quite simple you just have to use mapArray instead of map.

You just don't need to create new users class, only user class is enough to do this task

Use in this way

```<code>let arrUser = Mapper<User>().mapArray(JSONObject: JSONResponse.rawValue)
</code>```

Body:
Suppose that I have a User object:

class User: Mappable {
    var username: String?
    var age: Int?
    var weight: Double!
    var array: [Any]?
    var dictionary: [String : Any] = [:]
    var bestFriend: User?                       // Nested User object
    var friends: [User]?                        // Array of Users
    var birthday: Date?

    required init?(map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        username    <- map["username"]
        age         <- map["age"]
        weight      <- map["weight"]
        array       <- map["arr"]
        dictionary  <- map["dict"]
        bestFriend  <- map["best_friend"]
        friends     <- map["friends"]
        birthday    <- (map["birthday"], DateTransform())
    }
}

And my Json contains an array of that object: [User] How can I map this array even if it has not a specific field name? This is what I did:

class Users: Mappable {

var users: [User]?

required init?(map: Map) {

        }

// Mappable
        func mapping(map: Map) {
          //What have I to put here??
        }

}

Body:
It's quite simple you just have to use mapArray instead of map.

You just don't need to create new users class, only user class is enough to do this task

Use in this way

let arrUser = Mapper<User>().mapArray(JSONObject: JSONResponse.rawValue)


问:
Draw bonds PyMOL using R package Bio3d
Using the R package bio3d I would like to draw bonds between two atoms on a protein and parse the structure to PyMOL using the pymol().

```<code>library(bio3d)

# Import PDB file
pdb <- read.pdb( system.file("examples/1hel.pdb", package="bio3d") )

# Atom 1
sele.1 <- atom.select(pdb, "calpha", resno=43, verbose=TRUE)

# Atom 2
sele.2 <- atom.select(pdb, "calpha", resno=54, verbose=TRUE)
</code>```

In this example I would like to draw a bond/tangent/line between atoms sele.1 and sele.2 - a fairly trivial problem, is this possible?

答:
It is possible to parse a PyMOL script from R:

```<code># Return a string of commands to draw
pymol.bond.sele.command = function(atom1, atom2, nbond, chainID){

    # return PyMOL command to draw a bond between atoms 1 and 2
    return(paste(paste('distance ', paste('mydist', nbond, ', ', sep=''),
        'chain ', pymolchain, ' and ', atom1, '/CA, ', 'chain ', pymolchain, ' and ', atom2, '/CA', sep='')))
}

> pymol.bond.sele.command(43, 54, 1, A)

[1] distance mydist1, chain A and 43/CA, chain A and 54/CA
</code>```

Copy output of pymol.bond.sele.command() into the PyMOL terminal.

To remove the distance label:

```<code>pymol.bond.lab.rm.command = function(nbond, chainID){

    # return PyMOL command to remove the distance label drawn for distance element x
    return(paste('hide labels, mydist', nbond, sep=''))
}

> pymol.bond.lab.rm.command(1, A)
[1] hide labels, mydist1
</code>```

Copy output of pymol.bond.lab.rm.command() into the PyMOL terminal.

Title: Draw bonds PyMOL using R package Bio3d

Body:
Using the R package bio3d I would like to draw bonds between two atoms on a protein and parse the structure to PyMOL using the pymol().

library(bio3d)

# Import PDB file
pdb <- read.pdb( system.file("examples/1hel.pdb", package="bio3d") )

# Atom 1
sele.1 <- atom.select(pdb, "calpha", resno=43, verbose=TRUE)

# Atom 2
sele.2 <- atom.select(pdb, "calpha", resno=54, verbose=TRUE)

In this example I would like to draw a bond/tangent/line between atoms sele.1 and sele.2 - a fairly trivial problem, is this possible?

Body:
It is possible to parse a PyMOL script from R:

# Return a string of commands to draw
pymol.bond.sele.command = function(atom1, atom2, nbond, chainID){

    # return PyMOL command to draw a bond between atoms 1 and 2
    return(paste(paste('distance ', paste('mydist', nbond, ', ', sep=''),
        'chain ', pymolchain, ' and ', atom1, '/CA, ', 'chain ', pymolchain, ' and ', atom2, '/CA', sep='')))
}

> pymol.bond.sele.command(43, 54, 1, A)

[1] distance mydist1, chain A and 43/CA, chain A and 54/CA

Copy output of pymol.bond.sele.command() into the PyMOL terminal.

To remove the distance label:

pymol.bond.lab.rm.command = function(nbond, chainID){

    # return PyMOL command to remove the distance label drawn for distance element x
    return(paste('hide labels, mydist', nbond, sep=''))
}

> pymol.bond.lab.rm.command(1, A)
[1] hide labels, mydist1

Copy output of pymol.bond.lab.rm.command() into the PyMOL terminal.


问:
pg_query_params equivalent in mysql?
Is there a mysql equivalent of pg_query_params?</p>

答: Check mysqli_prepare() or PDOStatement(). Both are a bit different, but still use a prepared statement.</p>

Title: pg_query_params equivalent in mysql?


问:
C++ - Different concurrent behavious when using locals and globals
Given this program:

```<code>#include <thread>
#include <iostream>
#include <atomic>
template<typename T>
struct node
{
    T data;
    node* next;
    node(const T& data) : data(data), next(nullptr) {}
};

template<typename T>
class stack {
    std::atomic<node<T>*> head;
 public:
    void push(const T& data) {
      node<T>* new_node = new node<T>(data);
      new_node->next = head.load();
      while(!head.compare_exchange_weak(new_node->next, new_node));
    }
    node<T>* get_head() {
        return head;
    }
};

stack<int> x;
int main() {
    std::cout << "main() starts" << std::endl;
    const int MAKS_OP = 100;
    std::thread t1{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 1 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    std::thread t2{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 2 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    t1.join();
    t2.join();

    for (auto nod = x.get_head(); nod != nullptr; nod = nod->next) {
        std::cout << nod->data << "\n";
    }
    std::cout << "main() completes\n";
}
</code>```

The code is more or less appropriated from here.
In its current state it behaves exactly as expected, both threads push numbers to the stack in an unspecified order, and the stack is then printed in the correct order. It works whether or not I specify the default lambda capture for threads. However, when I move the declaration of stack x into main(), the program runs into a segfault when printing the contents of the stack. GDB tells me that it happens when accessing nod->data in the loop at the end, and running info locals crashes gdb. What is going on? Why does it even make a difference?

答:
Initialize the std::atomic*> head; in the stack constructor as follows, that should solve the issue,</p>

```<code>    template<typename T>
    class stack {
        std::atomic<node<T>*> head;
    public:
        stack()
        {
          head = 0;
        }
        void push(const T& data) {
          node<T>* new_node = new node<T>(data);
          new_node->next = head.load();
          while (!head.compare_exchange_weak(new_node->next, new_node));
        }
        node<T>* get_head() {
          return head;
        }
    };
</code>```

Body:
Given this program:

#include <thread>
#include <iostream>
#include <atomic>
template<typename T>
struct node
{
    T data;
    node* next;
    node(const T& data) : data(data), next(nullptr) {}
};

template<typename T>
class stack {
    std::atomic<node<T>*> head;
 public:
    void push(const T& data) {
      node<T>* new_node = new node<T>(data);
      new_node->next = head.load();
      while(!head.compare_exchange_weak(new_node->next, new_node));
    }
    node<T>* get_head() {
        return head;
    }
};

stack<int> x;
int main() {
    std::cout << "main() starts" << std::endl;
    const int MAKS_OP = 100;
    std::thread t1{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 1 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    std::thread t2{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 2 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    t1.join();
    t2.join();

    for (auto nod = x.get_head(); nod != nullptr; nod = nod->next) {
        std::cout << nod->data << "\n";
    }
    std::cout << "main() completes\n";
}

The code is more or less appropriated from here.
In its current state it behaves exactly as expected, both threads push numbers to the stack in an unspecified order, and the stack is then printed in the correct order. It works whether or not I specify the default lambda capture for threads. However, when I move the declaration of stack x into main(), the program runs into a segfault when printing the contents of the stack. GDB tells me that it happens when accessing nod->data in the loop at the end, and running info locals crashes gdb. What is going on? Why does it even make a difference?

Body:
Initialize the std::atomic*> head; in the stack constructor as follows, that should solve the issue,

    template<typename T>
    class stack {
        std::atomic<node<T>*> head;
    public:
        stack()
        {
          head = 0;
        }
        void push(const T& data) {
          node<T>* new_node = new node<T>(data);
          new_node->next = head.load();
          while (!head.compare_exchange_weak(new_node->next, new_node));
        }
        node<T>* get_head() {
          return head;
        }
    };


问:
Nested elements in custom view using xaml
I have custom StackLayout

```<code>public partial class CustomView : StackLayout
{
    public CustomView()
    {
        InitializeComponent();
    }
}
</code>```

And Xaml

```<code><?xml version="1.0" encoding="UTF-8"?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="XamlSample.CustomView"
    Orientation="Vertical"
    VerticalOptions="FillAndExpand">
    <StackLayout x:Name="FirstContainer"
        Orientation="Horizontal"
        HeightRequest="40"
        Spacing="0">
    </StackLayout>
    <StackLayout x:Name="SecondContainer"
        BackgroundColor="Red">
    </StackLayout>
</StackLayout>
</code>```

The idea is to use this layout in xaml with child elements like this

```<code><custom:CustomView>
        <StackLayout x:Name="FirstChild"
            VerticalOptions="FillAndExpand"
            BackgroundColor="Transparent">
        </StackLayout>
        <StackLayout x:Name="SecondChild"
            VerticalOptions="FillAndExpand"
            BackgroundColor="Green">
        </StackLayout>
    </custom:CustomView>
</code>```

But main thing that I need is that FirstChild should be child of FirstContainer and SecondChild should be child of SecondContainer. So that I can handle position of child elements in CustomView and use xaml.
I know how to make what I want using code behind it's pretty simple but in this case I need to migrate a lot of xaml elements to code behind.

答:
You can try this:

Xaml

```<code><?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MonRdvEnLigne.Common.Views.Xaml.CustomStackLayout">
  <ContentView.Content>
      <StackLayout>
          <StackLayout x:Name="FirstChild"
                       VerticalOptions="FillAndExpand"
                       BackgroundColor="Transparent">
          </StackLayout>
          <StackLayout x:Name="SecondChild"
                       VerticalOptions="FillAndExpand"
                       BackgroundColor="Green">
          </StackLayout>
        </StackLayout>
  </ContentView.Content>
</ContentView>
</code>```

And

```<code>[ContentProperty("Elements")]
public partial class CustomStackLayout : ContentView
{
    public CustomStackLayout()
    {
        InitializeComponent();
    }

    public IEnumerable<View> Elements { get; set; }
}
</code>```

Body:
I have custom StackLayout

public partial class CustomView : StackLayout
{
    public CustomView()
    {
        InitializeComponent();
    }
}

And Xaml

<?xml version="1.0" encoding="UTF-8"?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="XamlSample.CustomView"
    Orientation="Vertical"
    VerticalOptions="FillAndExpand">
    <StackLayout x:Name="FirstContainer"
        Orientation="Horizontal"
        HeightRequest="40"
        Spacing="0">
    </StackLayout>
    <StackLayout x:Name="SecondContainer"
        BackgroundColor="Red">
    </StackLayout>
</StackLayout>

The idea is to use this layout in xaml with child elements like this

<custom:CustomView>
        <StackLayout x:Name="FirstChild"
            VerticalOptions="FillAndExpand"
            BackgroundColor="Transparent">
        </StackLayout>
        <StackLayout x:Name="SecondChild"
            VerticalOptions="FillAndExpand"
            BackgroundColor="Green">
        </StackLayout>
    </custom:CustomView>

But main thing that I need is that FirstChild should be child of FirstContainer and SecondChild should be child of SecondContainer. So that I can handle position of child elements in CustomView and use xaml.
I know how to make what I want using code behind it's pretty simple but in this case I need to migrate a lot of xaml elements to code behind.

Body:
You can try this:

Xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MonRdvEnLigne.Common.Views.Xaml.CustomStackLayout">
  <ContentView.Content>
      <StackLayout>
          <StackLayout x:Name="FirstChild"
                       VerticalOptions="FillAndExpand"
                       BackgroundColor="Transparent">
          </StackLayout>
          <StackLayout x:Name="SecondChild"
                       VerticalOptions="FillAndExpand"
                       BackgroundColor="Green">
          </StackLayout>
        </StackLayout>
  </ContentView.Content>
</ContentView>

And

[ContentProperty("Elements")]
public partial class CustomStackLayout : ContentView
{
    public CustomStackLayout()
    {
        InitializeComponent();
    }

    public IEnumerable<View> Elements { get; set; }
}


问:
8086- why can't we move an immediate data into segment register?
In 8086 assembly programming, we can only load a data into a segment register by, first loading it into a general purpose register and then we have to move it from this general register to the segment register.

Why can't we load it directly? Is there any special reason for not being allowed?

What is the difference between mov ax,5000H and mov ax,[5000H]? Does [5000h] mean content in memory location 5000h?

答:
x86 machine code only has one opcode for move-to-Sreg.  That opcode is

8E /r mov Sreg, r/m16, and allows a register or memory source (but not immediate).

Contrary to some claims in other answers, mov ds, [5000h] runs just fine, assuming the 2 bytes at address 5000h hold a useful segment value for the mode you're in.  (Real mode where they're used directly as numbers vs. protected where Sreg values are selectors that index the LDT / GDT).

x86 always uses a different opcode for the immediate form of an instruction (with a constant encoded as part of the machine code) vs. the register/memory source version.  e.g. add eax, 123 assembles to a different opcode from add eax, ecx.  But add eax, [esi] is the same add r, r/m32 opcode as add eax, ecx, just a different ModR/M byte.

NASM listing, from nasm sreg.asm -l/dev/stdout, assembling a flat binary in 16-bit mode and producing a listing.

I edited by hand to separate the bytes into opcode modrm extra.  These are all one-byte opcodes (with no extra opcode bits borrowing space in the /r field of the ModRM byte), so just look at the first byte to see what opcode it is, and notice when two instructions share the same opcode.

```<code>   address    machine code         source           ;  comments
 1 00000000 BE 0050           mov si, 5000h     ; mov si, imm16
 2 00000003 A1 0050           mov ax, [5000h]   ; special encoding for AX, no modrm
 3 00000006 8B 36 0050        mov si, [5000h]   ; mov r16, r/m16 disp16
 4 0000000A 89 C6             mov si, ax        ; mov r/m16, r16
 5
 6 0000000C 8E 1E 0050        mov ds, [5000h]   ; mov Sreg, r/m16
 7 00000010 8E D8             mov ds, ax        ; mov Sreg, r/m16
 8
 9                            mov ds, 5000h
 9          ******************       error: invalid combination of opcode and operands
</code>```

Supporting a mov Sreg, imm16 encoding would need a separate opcode.  This would take extra transistors for 8086 to decode, and it would use up more opcode coding space leaving less room for future extensions.  I'm not sure which of these was considered more important by the architect(s) of the 8086 ISA.

Notice that 8086 has special mov AL/AX, moffs opcodes which save 1 byte when loading the accumulator from an absolute address.  But it couldn't spare an opcode for mov-immediate to Sreg?  This design decision makes good sense.  How often do you need to reload a segment register?  Very infrequently, and in real large programs it often wouldn't be with a constant (I think).  But in code using static data, you might be loading / storing the accumulator to a fixed address inside a loop.  (8086 had very weak code-fetch, so code-size = speed most of the time).

Also keep in mind that you can use mov Sreg, r/m16 for assemble-time constants with just one extra instruction (like mov ax, 4321h).  But if we'd only had mov Sreg, imm16, runtime variable segment values would have required self-modifying code.  (So obviously you wouldn't leave out the r/m16 source version.)  My point is if you're only going to have one, it's definitely going to be the register/memory source version.

Body:
x86 machine code only has one opcode for move-to-Sreg.  That opcode is

8E /r mov Sreg, r/m16, and allows a register or memory source (but not immediate).

Contrary to some claims in other answers, mov ds, [5000h] runs just fine, assuming the 2 bytes at address 5000h hold a useful segment value for the mode you're in.  (Real mode where they're used directly as numbers vs. protected where Sreg values are selectors that index the LDT / GDT).

x86 always uses a different opcode for the immediate form of an instruction (with a constant encoded as part of the machine code) vs. the register/memory source version.  e.g. add eax, 123 assembles to a different opcode from add eax, ecx.  But add eax, [esi] is the same add r, r/m32 opcode as add eax, ecx, just a different ModR/M byte.

NASM listing, from nasm sreg.asm -l/dev/stdout, assembling a flat binary in 16-bit mode and producing a listing.

I edited by hand to separate the bytes into opcode modrm extra.  These are all one-byte opcodes (with no extra opcode bits borrowing space in the /r field of the ModRM byte), so just look at the first byte to see what opcode it is, and notice when two instructions share the same opcode.

   address    machine code         source           ;  comments
 1 00000000 BE 0050           mov si, 5000h     ; mov si, imm16
 2 00000003 A1 0050           mov ax, [5000h]   ; special encoding for AX, no modrm
 3 00000006 8B 36 0050        mov si, [5000h]   ; mov r16, r/m16 disp16
 4 0000000A 89 C6             mov si, ax        ; mov r/m16, r16
 5
 6 0000000C 8E 1E 0050        mov ds, [5000h]   ; mov Sreg, r/m16
 7 00000010 8E D8             mov ds, ax        ; mov Sreg, r/m16
 8
 9                            mov ds, 5000h
 9          ******************       error: invalid combination of opcode and operands

Supporting a mov Sreg, imm16 encoding would need a separate opcode.  This would take extra transistors for 8086 to decode, and it would use up more opcode coding space leaving less room for future extensions.  I'm not sure which of these was considered more important by the architect(s) of the 8086 ISA.

Notice that 8086 has special mov AL/AX, moffs opcodes which save 1 byte when loading the accumulator from an absolute address.  But it couldn't spare an opcode for mov-immediate to Sreg?  This design decision makes good sense.  How often do you need to reload a segment register?  Very infrequently, and in real large programs it often wouldn't be with a constant (I think).  But in code using static data, you might be loading / storing the accumulator to a fixed address inside a loop.  (8086 had very weak code-fetch, so code-size = speed most of the time).

Also keep in mind that you can use mov Sreg, r/m16 for assemble-time constants with just one extra instruction (like mov ax, 4321h).  But if we'd only had mov Sreg, imm16, runtime variable segment values would have required self-modifying code.  (So obviously you wouldn't leave out the r/m16 source version.)  My point is if you're only going to have one, it's definitely going to be the register/memory source version.