问:
Fail to send data to server using device
I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.

While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so.
I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.

This is the doInbackground method in my BackgroundTask class:

```<code>@Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
    // the ip is default for localhost
    String reg_url = "http://**MyIP**/webapp/register.php";
    String login_url = "http://**MyIP**/webapp/login.php";
    String method = params[0];
    if (Objects.equals(method, "register")){
        String userName = params[1];
        String userPass = params[2];
        String gender = params[3];
        try {
            URL url = new URL(reg_url);
            // run the register php script.
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
            // applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
            // the info the user typed.
            String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
                    URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
                    URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
            // write the data to server
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Registration Successs";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
</code>```

答:
you want to do setting of the wampp server in your pc. i will give a URL for doing your work. please any query ask for it.

http://androidcss.com/android/test-android-app-php-localhost-wamp/

Body:
I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.

While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so.
I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.

This is the doInbackground method in my BackgroundTask class:

@Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
    // the ip is default for localhost
    String reg_url = "http://**MyIP**/webapp/register.php";
    String login_url = "http://**MyIP**/webapp/login.php";
    String method = params[0];
    if (Objects.equals(method, "register")){
        String userName = params[1];
        String userPass = params[2];
        String gender = params[3];
        try {
            URL url = new URL(reg_url);
            // run the register php script.
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
            // applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
            // the info the user typed.
            String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
                    URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
                    URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
            // write the data to server
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Registration Successs";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}


来源: stackexchange

问:
NullPointerException at mocked class method
I am currently writing a test for the method buy of the class Buy which should actually test if the correct request is going to the server and if it's handling the response correctly.

At the moment I always receive a java.lang.NullPointerException because execute(post) returns null instead of the CloseableHttpResponse.

CloseableHttpResponse response = httpClient.execute(post);

But I don't understand because in my test I tell mockito to return the mocked closeableHttpResponse.

The test

```<code>  @Test
    public void testBid() throws IOException {
        //given:
        HttpPost post = mock(HttpPost.class);
        HttpResponse httpResponse = mock(HttpResponse.class);

        StatusLine statusLine = mock(StatusLine.class);

        ObserverImp observer = mock(ObserverImp.class);

        CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
        HttpEntity httpEntity = mock(HttpEntity.class);
        BufferedInputStream inputStream = mock(BufferedInputStream.class);

        //and:
        when(statusLine.getStatusCode()).thenReturn(200);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);
        when(closeableHttpClient.execute(post)).thenReturn(closeableHttpResponse);
        when(closeableHttpResponse.getEntity()).thenReturn(httpEntity);
        when(httpEntity.getContent()).thenReturn(inputStream);
        when(inputStream.read()).thenReturn(1);
        when(observer.getKey()).thenReturn("##213");

        Buy buy = new Buy(observer, closeableHttpClient);
        buy.bid(14455);
    }
</code>```

And the related Implementation

```<code>public class Buy {
    private ObserverImp observer;
    private CloseableHttpClient httpClient;

    public Buy (ObserverImp observer, CloseableHttpClient httpClient) {
       this.observer = observer;
       this.httpClient = httpClient;
    }

    public void buy(double price) {
            String queryArgs = "command=order&amount=1" + "&price=" + String.valueOf(price); // generates query

            HttpPost post = new HttpPost("wwww.hm.edu/projectGroup1");
            post.addHeader("Key", observer.getKey());
            try {
                post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
            } catch (UnsupportedEncodingException e) {
                System.out.println("Exception in run");
            }
            List<NameValuePair> params = new ArrayList<>();

            params.add(new BasicNameValuePair("command", "order"));
            params.add(new BasicNameValuePair("amount", "1"));
            params.add(new BasicNameValuePair("price", String.valueOf(price)));
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
                CloseableHttpResponse response = httpClient.execute(post);
                HttpEntity entity = response.getEntity();
                Scanner in = new Scanner(entity.getContent());
                String orderNumber = "";
                while (in.hasNext()) {
                    orderNumber = in.nextLine();
                }
                String[] findOrderNumber = orderNumber.split(".");
                long lastOrderNumber = -1;
                try {
                    lastOrderNumber = Long.valueOf(findOrderNumber[3]);
                } catch (NumberFormatException exception) {
                    System.out.println("NumberFormatException");
                } finally {
                    if (lastOrderNumber != -1) {
                        observer.setOrderNumber(lastOrderNumber);
                    }
                }
                in.close();
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                System.out.println("Exception occured during process");
            }
        }
}
</code>```

Please help me to fix that issue. Thank you a lot.

答: You need to set the return type, by default null will be returned from the mock. Also in the implementation call createDefault http object. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am currently writing a test for the method buy of the class Buy which should actually test if the correct request is going to the server and if it's handling the response correctly.

At the moment I always receive a java.lang.NullPointerException because execute(post) returns null instead of the CloseableHttpResponse.

CloseableHttpResponse response = httpClient.execute(post);

But I don't understand because in my test I tell mockito to return the mocked closeableHttpResponse.

The test

  @Test
    public void testBid() throws IOException {
        //given:
        HttpPost post = mock(HttpPost.class);
        HttpResponse httpResponse = mock(HttpResponse.class);

        StatusLine statusLine = mock(StatusLine.class);

        ObserverImp observer = mock(ObserverImp.class);

        CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
        HttpEntity httpEntity = mock(HttpEntity.class);
        BufferedInputStream inputStream = mock(BufferedInputStream.class);

        //and:
        when(statusLine.getStatusCode()).thenReturn(200);
        when(httpResponse.getStatusLine()).thenReturn(statusLine);
        when(closeableHttpClient.execute(post)).thenReturn(closeableHttpResponse);
        when(closeableHttpResponse.getEntity()).thenReturn(httpEntity);
        when(httpEntity.getContent()).thenReturn(inputStream);
        when(inputStream.read()).thenReturn(1);
        when(observer.getKey()).thenReturn("##213");

        Buy buy = new Buy(observer, closeableHttpClient);
        buy.bid(14455);
    }

And the related Implementation

public class Buy {
    private ObserverImp observer;
    private CloseableHttpClient httpClient;

    public Buy (ObserverImp observer, CloseableHttpClient httpClient) {
       this.observer = observer;
       this.httpClient = httpClient;
    }

    public void buy(double price) {
            String queryArgs = "command=order&amount=1" + "&price=" + String.valueOf(price); // generates query

            HttpPost post = new HttpPost("wwww.hm.edu/projectGroup1");
            post.addHeader("Key", observer.getKey());
            try {
                post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
            } catch (UnsupportedEncodingException e) {
                System.out.println("Exception in run");
            }
            List<NameValuePair> params = new ArrayList<>();

            params.add(new BasicNameValuePair("command", "order"));
            params.add(new BasicNameValuePair("amount", "1"));
            params.add(new BasicNameValuePair("price", String.valueOf(price)));
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
                CloseableHttpResponse response = httpClient.execute(post);
                HttpEntity entity = response.getEntity();
                Scanner in = new Scanner(entity.getContent());
                String orderNumber = "";
                while (in.hasNext()) {
                    orderNumber = in.nextLine();
                }
                String[] findOrderNumber = orderNumber.split(".");
                long lastOrderNumber = -1;
                try {
                    lastOrderNumber = Long.valueOf(findOrderNumber[3]);
                } catch (NumberFormatException exception) {
                    System.out.println("NumberFormatException");
                } finally {
                    if (lastOrderNumber != -1) {
                        observer.setOrderNumber(lastOrderNumber);
                    }
                }
                in.close();
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                System.out.println("Exception occured during process");
            }
        }
}

Please help me to fix that issue. Thank you a lot.


问:
How to make only two div clickable among multiple divs and send their content to php file
I have this php  file which is fetch  data from my database and place it into divs. this div created by while loop I want tow div only to be select then send the content to php file using Ajax.
The code execute with no problem but there is no result!!
Any help advance and I completely lost of mind !!!

```<code>while($row=mysqli_fetch_array($result)){

    $so=$row[0];
    $s=$row[1];
    $m=$row[2];
    $a=$row[3];
    $b=$row[5];
    $c=$row[8];

?>
 <body>
 <div id="all"> //start all
 <div class="r"> //start r
  <div id="e"><?php echo"{$s}"; ?></div>
  <div id="b"><?php echo"{$m}"; ?></div>
  <div id="a"><?php echo"{$a}"; ?></div>
  <div id="b"><?php echo"{$b}"; ?></div>
 </div> //end r
 </div> //end all
  <?php
  } //end while
  ?>
  <div id="show"></div>
</code>```

script code

```<code>$(document).ready(function(){
         $(".r").click(function(){

          $data = $(this).text();
          alert($data); //it work well
               $.ajax({
               url: "view.php",
               type: "post",
               data: {
               you: $data
                     },
                     success:function(response){
                     $('#show').html(response);
                     }
               });

           });
       });
</code>```

view.php

```<code><?php
if(isset($_post['you'])){
printf("ok");   //just to check
}
?>
</code>```

答:
First of all

IDs on a page should be unique

Now coming to your code, maintain a global variable to have select count and call the below function to allow selection of maximum 2 divs

```<code>var selectCount = 0;
$('.r div').click(function() {
    if(!$(this).hasClass('active') && selectCount < 2) {
        $(this).addClass('active');
        selectCount++;
    }
    else if($(this).hasClass('active')) {
        $(this).removeClass('active');
        selectCount--;
    }
    else {
        alert("ony 2 allowed");
    }
});
</code>```

To send the data to your call you can

```<code>$('button').click(function() {
    var result = [];
    $('.active').each(function(val){
        result.push(val);
    });
});
</code>```

You may change the data format accordingly.

Body:
I have this php  file which is fetch  data from my database and place it into divs. this div created by while loop I want tow div only to be select then send the content to php file using Ajax.
The code execute with no problem but there is no result!!
Any help advance and I completely lost of mind !!!

while($row=mysqli_fetch_array($result)){

    $so=$row[0];
    $s=$row[1];
    $m=$row[2];
    $a=$row[3];
    $b=$row[5];
    $c=$row[8];

?>

 //start all

 //start r

<?php echo"{$s}"; ?>

<?php echo"{$m}"; ?>

<?php echo"{$a}"; ?>

<?php echo"{$b}"; ?>

 //end r

 //end all
  <?php
  } //end while
  ?>

script code

$(document).ready(function(){
         $(".r").click(function(){

          $data = $(this).text();
          alert($data); //it work well
               $.ajax({
               url: "view.php",
               type: "post",
               data: {
               you: $data
                     },
                     success:function(response){
                     $('#show').html(response);
                     }
               });

           });
       });

view.php

<?php
if(isset($_post['you'])){
printf("ok");   //just to check
}
?>

Body:
First of all

IDs on a page should be unique

Now coming to your code, maintain a global variable to have select count and call the below function to allow selection of maximum 2 divs

var selectCount = 0;
$('.r div').click(function() {
    if(!$(this).hasClass('active') && selectCount < 2) {
        $(this).addClass('active');
        selectCount++;
    }
    else if($(this).hasClass('active')) {
        $(this).removeClass('active');
        selectCount--;
    }
    else {
        alert("ony 2 allowed");
    }
});

To send the data to your call you can

$('button').click(function() {
    var result = [];
    $('.active').each(function(val){
        result.push(val);
    });
});

You may change the data format accordingly.


问:
Code migration from Swift 2.x to Swift 4
We have big enough project which is built up with Swift 2.x and now Apple has just released Swift 4 so to move forward for latest version of Swift which path we can choose...

Do we need to migrate our code to Swift 3 first? Or we can directly migrate our code to Swift 4 using Xcode 9?

答:
Yes, you must migrate your code in Swift 3 compatible version. Xcode 9 allows conversion/migration from swift 3.0 only.

Swift 3.2 is supported by Xcode 9 & Xcode 8 both.

Convert your source code from Swift 2.0 to 3.2 using Xcode 8 and then continue with Xcode 9 (Swift 3.2 or 4).

For easier migration of your code, follow these steps: (it will help you to covert into latest version of swift supported by your Xcode Tool)

(Xcode) Menus: Edit ► Covert ► To Current Swift Syntax


问:
How to find product of arithmetic progression?
I need to write a function to find a product of arithmetic progression elements (using recursion). I have only vague idea how to do it – something like this:

```<code>public static int product(int n)
{
   if (n == 0)
      return 0;
   else
      return <some code> * product(n-1);
}
</code>```

Could you at least give me a hint?

答:
you need to write a function which take 3 arguments first Term(f) , common difference(d) , and total number of term (n) in AP.</p>

```<code>     int fun(int f,int d,int n){
      if(n==0) return 1;
else (f+(n-1)*d) * fun(f,d,n--);
    }
</code>```

Body:
I need to write a function to find a product of arithmetic progression elements (using recursion). I have only vague idea how to do it – something like this:

public static int product(int n)
{
   if (n == 0)
      return 0;
   else
      return <some code> * product(n-1);
}

Could you at least give me a hint?

Body:
you need to write a function which take 3 arguments first Term(f) , common difference(d) , and total number of term (n) in AP.

     int fun(int f,int d,int n){
      if(n==0) return 1;
else (f+(n-1)*d) * fun(f,d,n--);
    }


问:
Newly upgraded Sonar not showing projects or users
Hi the problem i am having is after upgrading from 5.1.2 -> 5.6 -> 6.4. I believe i followed the upgrade path as documented.
The system worked fine on 5.1.2 & 5.6 but now on 6.4 the initial projects page that loads first thing is empty. It reads "Once you analyze some projects, they will show up here." Does this mean i need to analyse new projects? It does not pull the old analysis from the previous versions?

If i go into administration -> projects -> management i see all the projects in there.

Also if i go into administration -> security -> users all i see in the admin user. (i am not logged in as admin i am logged in as tbusby)
If i go to administration -> security -> groups i see groups and all the members e.g. sonar-users - 23users.

We use Crowd as our user repository and it seems to be authenticating fine just not displaying the users.

Just wondering if this behaviour is expected with the new UI and i am just reading things wrong or there is an actual issue.

Kind Regards
Tom Busby

答: I upgraded from 6.3.1 to 6.4 and are using Azure AD to authenticate. I saw the exact same behavior as Tom Busby. After deleting everything below /data/es as Bernard Dubreuil suggested it is working as expected again!</p>


问:
SQL Server refactor a column from varchar(50) to uniqueidentifier and surrounding issues
I have a table message in a database that has almost a million rows. It has a externalId column which is varchar(50). The values stored in it are guid but I want to update this column to be uniqueidentifier.

So I think I am going to add a new column which is uniqueidentifier. Copy all the values across to this column and then drop the original column. Then I will rename this column to externalId.

My problem is there are hundreds of stored procs etc and I need to make sure that I don't break anything. I also have to grep through all the code and make changes so that we expect a Guid and not a string. (I am using C#)

Does anyone have some tips or recommendations?

Would I be better do just duplicate this column and not touch the existing column and make any code that does a select on it use the guid column instead of the string (currently it sometimes times-out!). I would also have to update any code then that inserts into this table to also insert a guid...)

I love legacy crap .......................

答:
I would probably approach this like so:

work on a copy

add a new column externalIdGuid of type uniqueidentifier

try to convert all externalId into the new externalIdGuid

If that works, then all your externalId are valid GUID's - in that case you could just simply convert the column to type uniqueidentifier:

```<code>ALTER TABLE dbo.Message
  ALTER COLUMN externalID uniqueidentifier
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would probably approach this like so:

work on a copy

add a new column externalIdGuid of type uniqueidentifier

try to convert all externalId into the new externalIdGuid

If that works, then all your externalId are valid GUID's - in that case you could just simply convert the column to type uniqueidentifier:

ALTER TABLE dbo.Message
  ALTER COLUMN externalID uniqueidentifier


问:
My Woocommerce shop page doesn't show correctly. Products are not arranged in similar pattern?
My shop page look like this https://ibb.co/bBfEdF
It is showing like this here because some products have long product name & some have short. In the same way some products are having price mentioned and some are without price.
I have tried so many thing but couldn’t figure it out to set it automatically in same pattern, when I am making changes in the CSS files the changes are modifying other pages too, so I need to resolve this by without affecting other pages.
Can I set product names to be displayed always in one single line, weather the name is too short or long.
Either can I fix the box size for each row so that it look like similar for each product along with name.</p>

答: Its one of Woocommerce flaws. The fast solution is to give the product titles a similar word count</p>


问:
How to change waitSeconds timeout before config in requirejs
I am working on an application in which it is required to set waitSeconds to 0 before configuration(i.e. requirejs.config() ) gets loaded.

I don't want to set waitSeconds into requirejs library file.

Is there any way to achieve it ?

答:
RequireJS can be configured any number of times. You could have

```<code><script src="./path/to/require.js"></script>
<script>
  requirejs.config({ waitSeconds: 0 });
  requirejs(["main"]);
</script>
</code>```

It is fine if main contains another call to requirejs.config (or require.config).

Or you could have:

```<code><script>requirejs = { waitSeconds: 0 }</script>
<script src="./path/to/require.js" data-main="main"></script>
</code>```

If require or requirejs is defined and has for value something else than a function before your load the script for RequireJS, then RequireJS will take it as its configuration.

Body:
RequireJS can be configured any number of times. You could have

<script src="./path/to/require.js"></script>
<script>
  requirejs.config({ waitSeconds: 0 });
  requirejs(["main"]);
</script>

It is fine if main contains another call to requirejs.config (or require.config).

Or you could have:

<script>requirejs = { waitSeconds: 0 }</script>
<script src="./path/to/require.js" data-main="main"></script>

If require or requirejs is defined and has for value something else than a function before your load the script for RequireJS, then RequireJS will take it as its configuration.


问:
Zip -x is not behaving as expected
I'm trying to ignore a directory when creating a zip file. I am using this command:

```<code>zip -r  /home/username/Backups/HTML/$YEAR/$MONTH/$DAY.zip /home/username/public_html/ -x */home/username/public_html/wp-content/uploads/* -x *log -x *.git* -x *.zip* -x *.gz* -x *.tar*
</code>```

$YEAR, $MONTH and $DAY have all been defined earlier and function as expected.

I'm trying to ignore this directory and all its sub-directories and files:

```<code>/home/username/public_html/wp-content/uploads
</code>```

However, even though I have excluded it using -x flag, it is still backed up, as shown in the log:

```<code>adding: home/username/public_html/wp-content/uploads/2017/01/file.jpg
</code>```

How do I avoid doing this?

答:
You may use --exclude instead of -x. Typical command will look as follows. </p>

```<code>zip -r  /home/username/Backups/HTML/$YEAR/$MONTH/$DAY.zip /home/username/public_html/ --exclude=*/home/username/public_html/wp-content/uploads*
</code>```

Title: Zip -x is not behaving as expected

Body:
I'm trying to ignore a directory when creating a zip file. I am using this command:

zip -r  /home/username/Backups/HTML/$YEAR/$MONTH/$DAY.zip /home/username/public_html/ -x */home/username/public_html/wp-content/uploads/* -x *log -x *.git* -x *.zip* -x *.gz* -x *.tar*

$YEAR, $MONTH and $DAY have all been defined earlier and function as expected.

I'm trying to ignore this directory and all its sub-directories and files:

/home/username/public_html/wp-content/uploads

However, even though I have excluded it using -x flag, it is still backed up, as shown in the log:

adding: home/username/public_html/wp-content/uploads/2017/01/file.jpg

How do I avoid doing this?

Body:
You may use --exclude instead of -x. Typical command will look as follows.

zip -r  /home/username/Backups/HTML/$YEAR/$MONTH/$DAY.zip /home/username/public_html/ --exclude=*/home/username/public_html/wp-content/uploads*


问:
Reflect Laser off collider
I'm trying to accurately reflect a LaserBeam off a wall/collider.  The Laser Beam is fired from a LaserGun and is small, measuring around 2.

So I have currently set my LaserBeam as a 3D Capsule and coloured it red.  Its pretty ugly, but I'm not too concerned just now.

Whenever the LaserBeam collides with an Object/Wall it doesn't rebound as I would like.  I suppose it would have to be completely absorbed by the wall/collider so that the direction would be pointing the correct way.

The image in the website below should explain what I'm trying to achieve.
http://answers.unity3d.com/questions/631311/making-an-object-bounce-off-a-wall-the-same-way-li.html
(If the LaserBeam was an Arrow.  And the arrow is the InDirection and once the Arrow has collided with the wall, it would be in the direction of the Result).

I have set both the Drag and AngularDrag to 0.
In my Capsule material.  Dynamic and Static Friction is set to 0.  Bounciness is 1.  FrictionCombine is Min and BounceCombine is Max.

I'm wondering if I have to change the 3D Capsule to a LineRenderer?

Any help would be greatly appreciated.

答:
This script detects collisions solely using Raycasts. It first does a Raycast at its (the lasers) tip, testing if it collides with anything. If it does, it spawns a reflected version of itself. Also it does q Raycast at its end, to test if it completely penetrated a collider. If so, it destroys itself. The result is a pretty realistic laser beam that even "bends" on collision while keeping its total length.

The script assumes

that the laser beam has a CapsuleCollider which points in Y-direction and that's centered at (0, 0, 0)

that there is no Rigidbody attached to it

that you specified the Layers you want your laser to bounce off of in wallLayers

that the laser beam itself is in a Layer not included in wallLayers

that your walls are big enough to completely contain the laser beam (this is only relevant because otherwise it will look weird, but work nonetheless)

The script will

travel along its object's positive Y axis by speedOfLight units per second

reliably detect collisions even at very (!) high travel speeds

freely travel in 3D space, so if you want it to stick to a plain you'll have to add logic for that

Test it out, it's fun:

```<code>using UnityEngine;

[RequireComponent(typeof(CapsuleCollider))]
public class LaserBeam : MonoBehaviour
{
    public LayerMask wallLayers;
    public float speedOfLight = 1f;

    private Vector3 reflectionTestPointLocal, completeIntrusionTestPointLocal;
    private float beamLengthLocal;
    private bool didSpawnReflection;

    void Awake()
    {
        CapsuleCollider capsuleCollider = GetComponent<CapsuleCollider>();
        beamLengthLocal = capsuleCollider.height;
        reflectionTestPointLocal = Vector3.up * beamLengthLocal * .5f;
        completeIntrusionTestPointLocal = -Vector3.up * beamLengthLocal * .5f;
    }

    void Update()
    {
        float stepLength = speedOfLight * Time.deltaTime;

        Travel(stepLength);
    }

    private void Travel(float stepLength)
    {
        Vector3 step = transform.up * stepLength;

        if (!didSpawnReflection)
        {
            RaycastHit hit;
            if (Physics.Raycast(transform.TransformPoint(reflectionTestPointLocal), step, out hit, stepLength, wallLayers))
            {
                SpawnReflection(hit.point, hit.normal, stepLength - hit.distance);
                didSpawnReflection = true;
            }
        }
        if (didSpawnReflection)
        {
            RaycastHit hit;
            if (Physics.Raycast(transform.TransformPoint(completeIntrusionTestPointLocal), step, out hit, stepLength, wallLayers))
            {
                Destroy(gameObject);
            }
        }

        transform.position += step;
    }

    private void SpawnReflection(Vector3 pointOfReflection, Vector3 reflectionNormal, float intrusion)
    {
        float impactAngle = Vector3.Angle(-transform.up, reflectionNormal);
        Vector3 impactTangent = Vector3.Cross(-transform.up, reflectionNormal);

        Quaternion reflectedRotation = Quaternion.AngleAxis(180 + impactAngle * 2, impactTangent) * transform.rotation;

        LaserBeam reflectedBeam = Instantiate(this);
        reflectedBeam.gameObject.name = gameObject.name;
        reflectedBeam.transform.parent = transform.parent;
        reflectedBeam.transform.localScale = transform.localScale;
        reflectedBeam.transform.rotation = reflectedRotation;
        reflectedBeam.transform.position = pointOfReflection - reflectedBeam.transform.TransformVector(Vector3.up * beamLengthLocal * .5f);

        reflectedBeam.Travel(intrusion);
    }
}
</code>```

Title: Reflect Laser off collider

Body:
This script detects collisions solely using Raycasts. It first does a Raycast at its (the lasers) tip, testing if it collides with anything. If it does, it spawns a reflected version of itself. Also it does q Raycast at its end, to test if it completely penetrated a collider. If so, it destroys itself. The result is a pretty realistic laser beam that even "bends" on collision while keeping its total length.

The script assumes

that the laser beam has a CapsuleCollider which points in Y-direction and that's centered at (0, 0, 0)

that there is no Rigidbody attached to it

that you specified the Layers you want your laser to bounce off of in wallLayers

that the laser beam itself is in a Layer not included in wallLayers

that your walls are big enough to completely contain the laser beam (this is only relevant because otherwise it will look weird, but work nonetheless)

The script will

travel along its object's positive Y axis by speedOfLight units per second

reliably detect collisions even at very (!) high travel speeds

freely travel in 3D space, so if you want it to stick to a plain you'll have to add logic for that

Test it out, it's fun:

using UnityEngine;

[RequireComponent(typeof(CapsuleCollider))]
public class LaserBeam : MonoBehaviour
{
    public LayerMask wallLayers;
    public float speedOfLight = 1f;

    private Vector3 reflectionTestPointLocal, completeIntrusionTestPointLocal;
    private float beamLengthLocal;
    private bool didSpawnReflection;

    void Awake()
    {
        CapsuleCollider capsuleCollider = GetComponent<CapsuleCollider>();
        beamLengthLocal = capsuleCollider.height;
        reflectionTestPointLocal = Vector3.up * beamLengthLocal * .5f;
        completeIntrusionTestPointLocal = -Vector3.up * beamLengthLocal * .5f;
    }

    void Update()
    {
        float stepLength = speedOfLight * Time.deltaTime;

        Travel(stepLength);
    }

    private void Travel(float stepLength)
    {
        Vector3 step = transform.up * stepLength;

        if (!didSpawnReflection)
        {
            RaycastHit hit;
            if (Physics.Raycast(transform.TransformPoint(reflectionTestPointLocal), step, out hit, stepLength, wallLayers))
            {
                SpawnReflection(hit.point, hit.normal, stepLength - hit.distance);
                didSpawnReflection = true;
            }
        }
        if (didSpawnReflection)
        {
            RaycastHit hit;
            if (Physics.Raycast(transform.TransformPoint(completeIntrusionTestPointLocal), step, out hit, stepLength, wallLayers))
            {
                Destroy(gameObject);
            }
        }

        transform.position += step;
    }

    private void SpawnReflection(Vector3 pointOfReflection, Vector3 reflectionNormal, float intrusion)
    {
        float impactAngle = Vector3.Angle(-transform.up, reflectionNormal);
        Vector3 impactTangent = Vector3.Cross(-transform.up, reflectionNormal);

        Quaternion reflectedRotation = Quaternion.AngleAxis(180 + impactAngle * 2, impactTangent) * transform.rotation;

        LaserBeam reflectedBeam = Instantiate(this);
        reflectedBeam.gameObject.name = gameObject.name;
        reflectedBeam.transform.parent = transform.parent;
        reflectedBeam.transform.localScale = transform.localScale;
        reflectedBeam.transform.rotation = reflectedRotation;
        reflectedBeam.transform.position = pointOfReflection - reflectedBeam.transform.TransformVector(Vector3.up * beamLengthLocal * .5f);

        reflectedBeam.Travel(intrusion);
    }
}


问:
Form Dynamic JSON array in C#
For a web service, I need to create dynamic JSON array to be sent as response based on the data given by a stored procedure.

```<code>var t = new Dictionary<string, dynamic>();
for (int i = 0; i < reader.FieldCount; i++)
{
  columnName = reader.GetName(i);
  fieldValue = reader.GetValue(i).ToString();
  t[columnName] = fieldValue;
}
_response.data.Add(t);
</code>```

But the response received is data: [[{"key": "name", "value": "123"}, {"date": "01-Jun-2017"}],[{"key": "name", "value": "abc"}]]

whereas the response needed is : [{ "name": "abc", "date": "01-Jun-2017"},{ "name": "123"}]

Can anyone let me know what could the issue be?

Thanks in Advance.

答:
You should create a C# class similar to your JSON structure.

```<code>public class SomeClassName
{
    public string name { get; set; }
    public string date { get; set; }
}
</code>```

then instead of Dictionary, use List of the above class as follow:

```<code>List<SomeClassName> t = new List<SomeClassName>();
for (int i = 0; i < reader.FieldCount; i++)
{
    t.Add(new SomeClassName() { name = reader.GetName(i), date = reader.GetValue(i).ToString() });
}
_response.data.Add(t);
</code>```

Title: Form Dynamic JSON array in C#

Body:
For a web service, I need to create dynamic JSON array to be sent as response based on the data given by a stored procedure.

var t = new Dictionary<string, dynamic>();
for (int i = 0; i < reader.FieldCount; i++)
{
  columnName = reader.GetName(i);
  fieldValue = reader.GetValue(i).ToString();
  t[columnName] = fieldValue;
}
_response.data.Add(t);

But the response received is data: [[{"key": "name", "value": "123"}, {"date": "01-Jun-2017"}],[{"key": "name", "value": "abc"}]]

whereas the response needed is : [{ "name": "abc", "date": "01-Jun-2017"},{ "name": "123"}]

Can anyone let me know what could the issue be?

Thanks in Advance.

Body:
You should create a C# class similar to your JSON structure.

public class SomeClassName
{
    public string name { get; set; }
    public string date { get; set; }
}

then instead of Dictionary, use List of the above class as follow:

List<SomeClassName> t = new List<SomeClassName>();
for (int i = 0; i < reader.FieldCount; i++)
{
    t.Add(new SomeClassName() { name = reader.GetName(i), date = reader.GetValue(i).ToString() });
}
_response.data.Add(t);


问:
CUB segmented reduction not producing results
I'm trying to use CUB's segmented-reduction sum primitive, and I'm stuck on it.

Here is my code:

```<code>int main() {

     const int N = 7;
     const int num_segments  = 3;
     int d_offsets[]= {0,3,3,7};

    int *h_data       = (int *)malloc(N * sizeof(int));
    int *h_result = (int *)malloc(num_segments * sizeof(int));

    for (int i=0; i<N; i++) {
        h_data[i] = 3;

    }

    int *d_data;
    cudaMalloc((int**)&d_data, N * sizeof(int));
    cudaMemcpy(d_data, h_data, N * sizeof(int), cudaMemcpyHostToDevice);

    int           *d_result;
    cudaMalloc((int**)&d_result, num_segments * sizeof(int));

    void            *d_temp_storage = NULL;
    size_t          temp_storage_bytes = 0;

    cudaMalloc((void**)&d_temp_storage, temp_storage_bytes);

    cub::DeviceSegmentedReduce::Sum(d_temp_storage, temp_storage_bytes, d_data, d_result,
        num_segments, d_offsets, d_offsets + 1);

    cudaMemcpy(h_result, d_result, num_segments*sizeof(int), cudaMemcpyDeviceToHost);

    printf("Results:\n");

   for (int i=0; i<num_segments; i++) {
        printf("CUB: %d\n", h_result[i]);

    }

}
</code>```

But as a result I got this :

```<code>Results:
CUB: 0
CUB: 0
CUB: 0
</code>```

I can't figure out what is the problem exactly.
In the real example I have a very large array with segments equal to 400.
s can I optimize the code such that I don't need declare and allocate memory for d_offsets.

答:
You have really not seriously tried to debug your code:

You were missing the allocation of memory for d_results (you fixed that)

You were trying to pass a host memory address for a device memory address in d_offsets. Of course this results in a CUDA runtime error - but

You did not check for runtime errors.

You only called the CUB function once - although you must run it twice for it to actually do anything: Once with a nullptr as the scratch space, to get the scratch space size, then again with an actual scratch space to do work. It's an annoying API but that's how it works.

It is inappropriate for you to waste the SO community's time in debugging your code when you have not taken time to do so yourself.

Still, there's something you could do to avoid having to check for errors, at least, which is use a library of some kind which does it for you (e.g. by throwing on error). If you did that - for example, using my CUDA Runtime API wrappers (sorry for the self-plug), and properly allocate memory for everything you need to, you'd end up with something like this:

```<code>#include <cub/cub.cuh>
#include <cuda/api_wrappers.h>
#include <vector>
#include <cstdlib>

int main() {

    const int N = 7;
    const int num_segments  = 3;
    auto h_offsets = std::vector<int> {0,3,3,7};

    auto h_data = std::vector<int>(N);
    auto h_results = std::vector<int>(num_segments);

    std::fill(h_data.begin(), h_data.end(), 3);

    auto current_device = cuda::device::current::get();
    auto d_offsets = cuda::memory::device::make_unique<int[]>(
        current_device, h_offsets.size());
    auto d_data = cuda::memory::device::make_unique<int[]>(
        current_device, N);
    cuda::memory::copy(
        d_offsets.get(), &h_offsets[0], h_offsets.size() * sizeof(int));
    cuda::memory::copy(
        d_data.get(),  &h_data[0], h_data.size() * sizeof(int));
    auto d_results = cuda::memory::device::make_unique<int[]>(
        current_device, num_segments);

    auto d_start_offsets = d_offsets.get();
    auto d_end_offsets = d_start_offsets + 1; // aliasing, see CUB documentation

    size_t temp_storage_bytes = 0;

    // This call merely obtains a value for temp_storage_bytes, passed here
    // as a non-const reference; other arguments are unused
    cub::DeviceSegmentedReduce::Sum(
        nullptr, temp_storage_bytes, d_data.get(), d_results.get(),
        num_segments, d_start_offsets, d_end_offsets);

    auto d_temp_storage = cuda::memory::device::make_unique<char[]>(
        current_device, temp_storage_bytes);

    cub::DeviceSegmentedReduce::Sum(
        d_temp_storage.get(), temp_storage_bytes, d_data.get(),
        d_results.get(), num_segments, d_start_offsets, d_end_offsets);

    cuda::memory::copy(
        &h_results[0], d_results.get(), num_segments * sizeof(int));

    std::cout << "Results:\n";

    for (int i=0; i<num_segments; i++) {
        std::cout << "Segment " << i << " data sums up to " << h_results[i] << "\n";
    }

    return EXIT_SUCCESS;
}
</code>```

which works:

```<code>Results:
Segment 0 data sums up to 9
Segment 1 data sums up to 0
Segment 2 data sums up to 12
</code>```

Additional tips:

Always investigate compiler warnings.

Use cuda-memcheck to avoid memory leaks / initializing on the wrong device/host side, etc.

If you're using the CUDA Runtime API directly, you must check every call for errors.

Body:
I'm trying to use CUB's segmented-reduction sum primitive, and I'm stuck on it.

Here is my code:

int main() {

     const int N = 7;
     const int num_segments  = 3;
     int d_offsets[]= {0,3,3,7};

    int *h_data       = (int *)malloc(N * sizeof(int));
    int *h_result = (int *)malloc(num_segments * sizeof(int));

    for (int i=0; i<N; i++) {
        h_data[i] = 3;

    }

    int *d_data;
    cudaMalloc((int**)&d_data, N * sizeof(int));
    cudaMemcpy(d_data, h_data, N * sizeof(int), cudaMemcpyHostToDevice);

    int           *d_result;
    cudaMalloc((int**)&d_result, num_segments * sizeof(int));

    void            *d_temp_storage = NULL;
    size_t          temp_storage_bytes = 0;

    cudaMalloc((void**)&d_temp_storage, temp_storage_bytes);

    cub::DeviceSegmentedReduce::Sum(d_temp_storage, temp_storage_bytes, d_data, d_result,
        num_segments, d_offsets, d_offsets + 1);

    cudaMemcpy(h_result, d_result, num_segments*sizeof(int), cudaMemcpyDeviceToHost);

    printf("Results:\n");

   for (int i=0; i<num_segments; i++) {
        printf("CUB: %d\n", h_result[i]);

    }

}

But as a result I got this :

Results:
CUB: 0
CUB: 0
CUB: 0

I can't figure out what is the problem exactly.
In the real example I have a very large array with segments equal to 400.
s can I optimize the code such that I don't need declare and allocate memory for d_offsets.

Body:
You have really not seriously tried to debug your code:

You were missing the allocation of memory for d_results (you fixed that)

You were trying to pass a host memory address for a device memory address in d_offsets. Of course this results in a CUDA runtime error - but

You did not check for runtime errors.

You only called the CUB function once - although you must run it twice for it to actually do anything: Once with a nullptr as the scratch space, to get the scratch space size, then again with an actual scratch space to do work. It's an annoying API but that's how it works.

It is inappropriate for you to waste the SO community's time in debugging your code when you have not taken time to do so yourself.

Still, there's something you could do to avoid having to check for errors, at least, which is use a library of some kind which does it for you (e.g. by throwing on error). If you did that - for example, using my CUDA Runtime API wrappers (sorry for the self-plug), and properly allocate memory for everything you need to, you'd end up with something like this:

#include <cub/cub.cuh>
#include <cuda/api_wrappers.h>
#include <vector>
#include <cstdlib>

int main() {

    const int N = 7;
    const int num_segments  = 3;
    auto h_offsets = std::vector<int> {0,3,3,7};

    auto h_data = std::vector<int>(N);
    auto h_results = std::vector<int>(num_segments);

    std::fill(h_data.begin(), h_data.end(), 3);

    auto current_device = cuda::device::current::get();
    auto d_offsets = cuda::memory::device::make_unique<int[]>(
        current_device, h_offsets.size());
    auto d_data = cuda::memory::device::make_unique<int[]>(
        current_device, N);
    cuda::memory::copy(
        d_offsets.get(), &h_offsets[0], h_offsets.size() * sizeof(int));
    cuda::memory::copy(
        d_data.get(),  &h_data[0], h_data.size() * sizeof(int));
    auto d_results = cuda::memory::device::make_unique<int[]>(
        current_device, num_segments);

    auto d_start_offsets = d_offsets.get();
    auto d_end_offsets = d_start_offsets + 1; // aliasing, see CUB documentation

    size_t temp_storage_bytes = 0;

    // This call merely obtains a value for temp_storage_bytes, passed here
    // as a non-const reference; other arguments are unused
    cub::DeviceSegmentedReduce::Sum(
        nullptr, temp_storage_bytes, d_data.get(), d_results.get(),
        num_segments, d_start_offsets, d_end_offsets);

    auto d_temp_storage = cuda::memory::device::make_unique<char[]>(
        current_device, temp_storage_bytes);

    cub::DeviceSegmentedReduce::Sum(
        d_temp_storage.get(), temp_storage_bytes, d_data.get(),
        d_results.get(), num_segments, d_start_offsets, d_end_offsets);

    cuda::memory::copy(
        &h_results[0], d_results.get(), num_segments * sizeof(int));

    std::cout << "Results:\n";

    for (int i=0; i<num_segments; i++) {
        std::cout << "Segment " << i << " data sums up to " << h_results[i] << "\n";
    }

    return EXIT_SUCCESS;
}

which works:

Results:
Segment 0 data sums up to 9
Segment 1 data sums up to 0
Segment 2 data sums up to 12

Additional tips:

Always investigate compiler warnings.

Use cuda-memcheck to avoid memory leaks / initializing on the wrong device/host side, etc.

If you're using the CUDA Runtime API directly, you must check every call for errors.


问:
I want to print PHP query with parameters
I have the following code

```<code>$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();
</code>```

I want print the query

```<code>"INSERT INTO `agenz` (`name`, `email`) VALUES ('myname','my@mail.it')"
</code>```

for creating a log.So how to do that?

thanx.

答:
Try fullQuery like below:

```<code>$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();

echo $result->fullQuery;
</code>```

or

```<code>$result->debugQuery();
var_dump($result->debugBindedVariables());
</code>```

if you want to get the error

```<code>var_dump($result->errno);
</code>```

Body:
I have the following code

$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();

I want print the query

"INSERT INTO `agenz` (`name`, `email`) VALUES ('myname','my@mail.it')"

for creating a log.So how to do that?

thanx.

Body:
Try fullQuery like below:

$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();

echo $result->fullQuery;

or

$result->debugQuery();
var_dump($result->debugBindedVariables());

if you want to get the error

var_dump($result->errno);


问:
MySQL - How to parse a string value to DATETIME format inside an Update statement?
I have an application which logs entries with datetime format. Now I want to push that datetime string into db. So i have the query

```<code>db.query "update processing set start_time = STR_TO_DATE('2017053008:04:45', '%Y-%m-%d %H:%i:%s') where dated = '2017-06-07' and zone = 'W13';"
</code>```

I have the datetime format in my log as "2017060708:04:45" and when I run the above query its inputs NULL in the filed start_time.

Any help in this would be much appreciated. Thanks!

答: try STR_TO_DATE('2017053008:04:45', '%Y%m%d%H:%i:%s') ， the next params must match with the first one,hope it works.

Body:
I have an application which logs entries with datetime format. Now I want to push that datetime string into db. So i have the query

db.query "update processing set start_time = STR_TO_DATE('2017053008:04:45', '%Y-%m-%d %H:%i:%s') where dated = '2017-06-07' and zone = 'W13';"

I have the datetime format in my log as "2017060708:04:45" and when I run the above query its inputs NULL in the filed start_time.

Any help in this would be much appreciated. Thanks!


问:
Consuming a web reference in a class library Visual Studio 2008
I have a project that uses a class library for the business layer functionality. A web application sits on top of this. I have a web service that I would like to call in the class library. The web application is hosted in IIS for debugging via Visual Studio 2008. Everything seems to work fine except each time make a call to this web-service (created in Java), I get this error following error “The underlying connection was closed: Could not establish secure channel for SSL/TLS”. I thought this was the cert related error. Hence I installed the cert and loaded the cert at runtime from my local stored and adding the cert to the client proxy (ClientCertificates.Add(certificate)) making sure the ASPNet and other IIS accounts have access to this cert. This didn’t help either. However when I added the web reference to same web-service in the same project to web application the error is gone. I need to call the web service from the class library. I would really appreciate your suggestions.    </p>

答: From what i understand the solution has two projects and the web app is the start project.If so,  what you can do is have a web  reference in the class library and copy the details of the app.config you get when you add the web reference in the class library to web config of the web app.  </p>


问:
Schema Validation error - The attribute {type} is referenced, but has not been declared
The SVG schema in question references the XLink schema which declares the xlink:type attribute, but getting error that the type has not been declared in XLink Schema.

svg.xsd

```<code>    <xs:attribute ref="xlink:type" default="simple"/>
</code>```

xlink.xsd

```<code><xs:attribute name="type">
    <xs:simpleType>
        <xs:restriction base="xs:token">
            <xs:enumeration value="simple"/>
        </xs:restriction>
    </xs:simpleType>
</xs:attribute>
</code>```

答: This is because the oxygen editor uses the default xlink.xsd from oxygen framework location and not from source schema location.</p>

Body:
The SVG schema in question references the XLink schema which declares the xlink:type attribute, but getting error that the type has not been declared in XLink Schema.

svg.xsd

    <xs:attribute ref="xlink:type" default="simple"/>

xlink.xsd

<xs:attribute name="type">
    <xs:simpleType>
        <xs:restriction base="xs:token">
            <xs:enumeration value="simple"/>
        </xs:restriction>
    </xs:simpleType>
</xs:attribute>


问:
Threading vs single thread
Is it always guaranteed that a multi-threaded application would run faster than a single threaded application?

I have two threads that populates data from a data source but different entities (eg: database, from two different tables), seems like single threaded version of the application is running faster than the version with two threads.

Why would the reason be? when i look at the performance monitor, both cpu s are very spikey ? is this due to context switching?

what are the best practices to jack the CPU and fully utilize it?

I hope this is not ambiguous.

答: According to Amdahl's law the maximum speed up is dependent on the proportion of the algorithm that can be parallelized. If the algorithm is highly parallell than increasing the amount of CPUs and threads will have a big increase. If the algorithm is not parallell (there is a lot of code flow control or data contention) than there is no gain or may even happen to exist performance decrease.

Title: Threading vs single thread


问:
Insert table data with column datatype varchar2 to a table with column datatype as number
In oracle DB I have a table TABLE1 with column datatype defined as VARCHAR2(50). I have another table TABLE2 with column datatype defined as a NUMBER. The no of rows present in the TABLE1 is around 23k and they all seems to be number. But when I try the insert command I get the below error.

```<code>    Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 -  "invalid number"
*Cause:
*Action:
</code>```

This clearly means that there are few rows that are not numbers. But I am not able to identify those no numeric cases. How do I identify the non numeric rows.

P.S:
Oracle database version : 9.2.0.8.0

And yes I know its ancient.

答:
Below is the PL SQL block used to identify the discrepancy cases. The special character in my case was double quotes. There were few cases with issue so printing the output was feasible. If there are more number of discrepancy cases then capturing the error msg in a table column will be helpful.</p>

```<code>declare
cursor cur is
select * from TABLE1 ;           ----- cursor to loop through cases individually
begin
for rec in cur
loop
begin
insert into table2 (column1)
select to_number(column1)
from table1
where
column1=rec.column1 ;
exception when others
then
Dbms_Output.Put_Line('error for '||rec.column1||' '||substr(sqlerrm,0,150)); --- error msg with discrepancy case
end;
end loop;
end;
/
</code>```

Body:
In oracle DB I have a table TABLE1 with column datatype defined as VARCHAR2(50). I have another table TABLE2 with column datatype defined as a NUMBER. The no of rows present in the TABLE1 is around 23k and they all seems to be number. But when I try the insert command I get the below error.

    Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 -  "invalid number"
*Cause:
*Action:

This clearly means that there are few rows that are not numbers. But I am not able to identify those no numeric cases. How do I identify the non numeric rows.

P.S:
Oracle database version : 9.2.0.8.0

And yes I know its ancient.

Body:
Below is the PL SQL block used to identify the discrepancy cases. The special character in my case was double quotes. There were few cases with issue so printing the output was feasible. If there are more number of discrepancy cases then capturing the error msg in a table column will be helpful.

declare
cursor cur is
select * from TABLE1 ;           ----- cursor to loop through cases individually
begin
for rec in cur
loop
begin
insert into table2 (column1)
select to_number(column1)
from table1
where
column1=rec.column1 ;
exception when others
then
Dbms_Output.Put_Line('error for '||rec.column1||' '||substr(sqlerrm,0,150)); --- error msg with discrepancy case
end;
end loop;
end;
/


问:
Vue+Semanti-UI: modal element changed,only can run seccuess once
```<code><button class="ui button" @click="beforeAdd">添加</button>

<div class="ui modal">
    <div class="header">Header</div>
    <div class="content">
        <div class="description">
            <p>Description</p>
        </div>
    </div>
    <div class="actions">
        <div class="ui negative right labeled icon button">
            取消
            <i class="remove icon"></i>
        </div>
        <div class="ui positive right labeled icon button">
            提交
            <i class="checkmark icon"></i>
        </div>
    </div>
</div>
</code>```

view methods:

```<code>beforeAdd(){
    const modal = $(this.$el).find('.ui.modal')
    console.log(modal)
    modal.modal('show')
}
</code>```

first click,modal show, second click nothing happened, I found semantic change modal to root for div class='ui dimmer modals page transition hidden',how can solve it

答:
If you also want to use Vue variables in your modal, it is necessary to clone the modal and only show the cloned version.

With this approach Vue will still be able to keep track of the original modal, because Semantic doesn't remove it from the DOM.

```<code>beforeAdd(){
    const modal = $(this.$el).find('.ui.modal').clone()
    console.log(modal)
    modal.modal('show')
}
</code>```

Body:
<button class="ui button" @click="beforeAdd">添加</button>

Header

Description

            取消

            提交

view methods:

beforeAdd(){
    const modal = $(this.$el).find('.ui.modal')
    console.log(modal)
    modal.modal('show')
}

first click,modal show, second click nothing happened, I found semantic change modal to root for div class='ui dimmer modals page transition hidden',how can solve it

Body:
If you also want to use Vue variables in your modal, it is necessary to clone the modal and only show the cloned version.

With this approach Vue will still be able to keep track of the original modal, because Semantic doesn't remove it from the DOM.

beforeAdd(){
    const modal = $(this.$el).find('.ui.modal').clone()
    console.log(modal)
    modal.modal('show')
}


问:
Parse string into JSONArray in velocity template
I am looking for a way to parse a string into json array, so that I can iterate the same and access the objects inside it. I have been looking around for some time but no help.

I found one way which is

```<code>#set ($myjson = $json.fetch('http://www.url.org/feeds/json-packages.dot'))
</code>```

but I want to parse one local string variable into json array. How can we do that?

答:
You could use a library like this, and put in your velocity context a "JSONUtils" object. This object would expose a method "jsonArrayFromString", whose implementation would be as simple as

```<code>public JSONArray jsonArrayFromString(String jsonString) {
    try {
        return new JSONArray(jsonString);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}
</code>```

Here is the documentation of the JSONArray class. Then you can use this object in your template like this:

```<code>#set ($myjson = $JSONUtils.jsonArrayFromString($myString))
#set ($length = $myjson.length())
#foreach( $i in [0..$length-1] )
  ## Use one of the getter methods for the object in this index.
#end
</code>```

Of course you could also put a similar method that creates a JSONObject from a string.

Body:
I am looking for a way to parse a string into json array, so that I can iterate the same and access the objects inside it. I have been looking around for some time but no help.

I found one way which is

#set ($myjson = $json.fetch('http://www.url.org/feeds/json-packages.dot'))

but I want to parse one local string variable into json array. How can we do that?

Body:
You could use a library like this, and put in your velocity context a "JSONUtils" object. This object would expose a method "jsonArrayFromString", whose implementation would be as simple as

public JSONArray jsonArrayFromString(String jsonString) {
    try {
        return new JSONArray(jsonString);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

Here is the documentation of the JSONArray class. Then you can use this object in your template like this:

#set ($myjson = $JSONUtils.jsonArrayFromString($myString))
#set ($length = $myjson.length())
#foreach( $i in [0..$length-1] )
  ## Use one of the getter methods for the object in this index.
#end

Of course you could also put a similar method that creates a JSONObject from a string.


问:
which data structure should I use in java to store duplicate values?
Which is the best data structure to store duplicate values in java? And how easy is to retrieve values from it!?

thanks
EDIT #1 I am reading contents from 1000 files, and I want to put each files content as tokens in some data structure. I used Hashtable but i am not able to view many words when I am doing that. thats why I want a data structure which can store the duplicate values.

答: Any java.util.Collection that does not implement the Set interface.  Probably you'll want something that implements a List.</p>


问:
Input tag is not getteng attach inside the div correctly.
In my javascript function I am getting one div.

my div is

```<code>var divDetails = args.val;
</code>```

where divDetails = "

"

Now I have to add one input tag so Here I am declearing

```<code>var input = '<input class="easyui-combobox" name="language" style="width:100%;" data-options="\
                    url: "JSON/combobox_data1.json",\
                    method: "get",\
                    valueField: "id",\
                    textField: "text",\
                    panelWidth: 350,\
                    multiple:true,\
                    label: "Language:",\
                    labelPosition: "top"\
                    >';
</code>```

My input is comming correctly.

```<code>"<input class="easyui-combobox" name="language" style="width:100%;" data-options="                    url: "JSON/combobox_data1.json",                    method: "get",                    valueField: "id",                    textField: "text",                    panelWidth: 350,                    multiple:true,                    label: "Language:",                    labelPosition: "top"                    >"
</code>```

Now When I am adding this input to the div divDetails.innerHTML = input I am getting this

```<code>"<div id="chart_line" style="width:26%; background-color: lightblue;"><input class="easyui-combobox" name="language" style="width:100%;" data-options="                    url: " json="" combobox_data1.json",="" method:="" "get",="" valuefield:="" "id",="" textfield:="" "text",="" panelwidth:="" 350,="" multiple:true,="" label:="" "language:",="" labelposition:="" "top"=""></div>"
</code>```

Which is wrong. What I suppose to get is

```<code>"<div id="chart_line" style="width:26%; background-color: lightblue;">
       <input class="easyui-combobox" name="language" style="width:100%;" data-options="url: 'JSON/combobox_data1.json',method: 'get',valueField: 'id',textField: 'text',panelWidth: 350,multiple:true,label: 'Language:',labelPosition: 'top'">
    </div>"
</code>```

Can You please suggest me what I am doing wrong here.

答:
First of all, don't do such thing as putting entire Ajax into data attribute. You shouldn't even put that there anyway. But if you actually have to do that, then do it properly. Use multiple data attributes instead of one.

JavaScript

var input = document.createElement('input');

input.setAttribute('data-url', "JSON/combobox_data1.json");
input.setAttribute('data-method', "GET");
input.setAttribute('data-value', "id");
input.setAttribute('data-text', "text");
input.setAttribute('data-panel', "350");
input.setAttribute('data-multiple', "true");
input.setAttribute('data-label', "Language:");
input.setAttribute('data-position', "top");

document.getElementById('div').appendChild(input);

console.log(input.getAttribute('data-url'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div"></div></code>```

jQuery

$('<input/>', {
  data: {
    url: "JSON/combobox_data1.json",
    method: "GET"
    /* ... */
  }
}).appendTo('#div');

console.log($('input').data('url'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div></code>```

Body:
In my javascript function I am getting one div.

my div is

var divDetails = args.val;

where divDetails = "

"

Now I have to add one input tag so Here I am declearing

var input = '<input class="easyui-combobox" name="language" style="width:100%;" data-options="\
                    url: "JSON/combobox_data1.json",\
                    method: "get",\
                    valueField: "id",\
                    textField: "text",\
                    panelWidth: 350,\
                    multiple:true,\
                    label: "Language:",\
                    labelPosition: "top"\
                    >';

My input is comming correctly.

"<input class="easyui-combobox" name="language" style="width:100%;" data-options="                    url: "JSON/combobox_data1.json",                    method: "get",                    valueField: "id",                    textField: "text",                    panelWidth: 350,                    multiple:true,                    label: "Language:",                    labelPosition: "top"                    >"

Now When I am adding this input to the div divDetails.innerHTML = input I am getting this

"
<input class="easyui-combobox" name="language" style="width:100%;" data-options="                    url: " json="" combobox_data1.json",="" method:="" "get",="" valuefield:="" "id",="" textfield:="" "text",="" panelwidth:="" 350,="" multiple:true,="" label:="" "language:",="" labelposition:="" "top"="">
"

Which is wrong. What I suppose to get is

"

       <input class="easyui-combobox" name="language" style="width:100%;" data-options="url: 'JSON/combobox_data1.json',method: 'get',valueField: 'id',textField: 'text',panelWidth: 350,multiple:true,label: 'Language:',labelPosition: 'top'">

"

Can You please suggest me what I am doing wrong here.

Body:
First of all, don't do such thing as putting entire Ajax into data attribute. You shouldn't even put that there anyway. But if you actually have to do that, then do it properly. Use multiple data attributes instead of one.

JavaScript

var input = document.createElement('input');

input.setAttribute('data-url', "JSON/combobox_data1.json");
input.setAttribute('data-method', "GET");
input.setAttribute('data-value', "id");
input.setAttribute('data-text', "text");
input.setAttribute('data-panel', "350");
input.setAttribute('data-multiple', "true");
input.setAttribute('data-label', "Language:");
input.setAttribute('data-position', "top");

document.getElementById('div').appendChild(input);

console.log(input.getAttribute('data-url'));

<div id="div"></div>

jQuery

$('<input/>', {
  data: {
    url: "JSON/combobox_data1.json",
    method: "GET"
    /* ... */
  }
}).appendTo('#div');

console.log($('input').data('url'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>


问:
"Message": "Authorization has been denied for this request." OWIN middleware
I added Token based authentication to my OWIN middleware and can generate the token. But while using, the token for an API call with Authorize attribute I always get "Authorization has been denied for this request." It works fine though without Authorize attribute. Here is my startup.cs and controller method. Any thoughts , what is wrong?

startup.cs

```<code>    public void Configuration(IAppBuilder app)
            {
                var issuer = ConfigurationManager.AppSettings["issuer"];
                var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                    Provider = new SimpleAuthProvider(),
                    AccessTokenFormat = new JwtFormat(issuer)
                });
                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { "*" },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });
                container = BuildDI();
                var config = new HttpConfiguration();
                config.Formatters.XmlFormatter.UseXmlSerializer = true;
                config.MapHttpAttributeRoutes();
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
                app.UseCors(CorsOptions.AllowAll);
                app.UseSerilogRequestContext("RequestId");
                app.UseAutofacMiddleware(container);
                app.UseAutofacWebApi(config);
                app.UseWebApi(config);
                RegisterShutdownCallback(app, container);
            }

 public class SimpleAuthProvider: OAuthAuthorizationServerProvider
        {
            public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {

                if (context.UserName != context.Password)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                    context.Rejected();
                    return Task.FromResult<object>(null);
                }

                var ticket = new AuthenticationTicket(SetClaimsIdentity(context), new AuthenticationProperties());
                context.Validated(ticket);

                return Task.FromResult<object>(null);
            }

            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                context.Validated();
                return Task.FromResult<object>(null);
            }

            private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ExternalBearer);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                return identity;
            }
        }
</code>```

API Controller Method:

```<code> [HttpGet]
        [Route("sampleroute")]
        [Authorize]
        public async Task<HttpResponseMessage> GetSamples(string search)
        {
            try
            {

                HttpResponseMessage response;
                using (HttpClient client = new HttpClient(Common.CreateHttpClientHandler()))
                {
                     response = await client.GetAsync("test url");
                }
                var result = response.Content.ReadAsStringAsync().Result;
                Samples[] sampleArray = JsonConvert.DeserializeObject<Samples[]>(result);
                var filteredSamples = sampleArray .ToList().Where(y => y.NY_SampleName.ToUpper().Contains(search.ToUpper())).Select(n=>n);
                log.Information("<==========Ended==========>");
                return  Request.CreateResponse(HttpStatusCode.OK,filteredSamples);

            }
            catch (Exception ex)
            {
                log.Error($"Error occured while pulling the Samples:  {ex.ToString()}");
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }
</code>```

答:
It's probably a problem with the allowed audiences.
Here

```<code> app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
 {
     ...
     AllowedAudiences = new[] { "*" },
     ...
 }
</code>```

you set the allowed audiences. The tokens audclaim will be checked against the list of AllowedAudiences. But you never add any audience to the token.

In our project I used a CustomJwtFormat based on the code shown in http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

The token will be generated with a call to

```<code>var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
</code>```

the second parameter is responsible for the aud claim in the JWT:

From https://msdn.microsoft.com/en-us/library/dn451037(v=vs.114).aspx :

audience
      Type: System.String

If this value is not null, a { aud, 'audience' } claim will be added.

After setting the aud claim in the token authorization should work fine.

Body:
I added Token based authentication to my OWIN middleware and can generate the token. But while using, the token for an API call with Authorize attribute I always get "Authorization has been denied for this request." It works fine though without Authorize attribute. Here is my startup.cs and controller method. Any thoughts , what is wrong?

startup.cs

    public void Configuration(IAppBuilder app)
            {
                var issuer = ConfigurationManager.AppSettings["issuer"];
                var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                    Provider = new SimpleAuthProvider(),
                    AccessTokenFormat = new JwtFormat(issuer)
                });
                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { "*" },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });
                container = BuildDI();
                var config = new HttpConfiguration();
                config.Formatters.XmlFormatter.UseXmlSerializer = true;
                config.MapHttpAttributeRoutes();
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
                app.UseCors(CorsOptions.AllowAll);
                app.UseSerilogRequestContext("RequestId");
                app.UseAutofacMiddleware(container);
                app.UseAutofacWebApi(config);
                app.UseWebApi(config);
                RegisterShutdownCallback(app, container);
            }

 public class SimpleAuthProvider: OAuthAuthorizationServerProvider
        {
            public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {

                if (context.UserName != context.Password)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                    context.Rejected();
                    return Task.FromResult<object>(null);
                }

                var ticket = new AuthenticationTicket(SetClaimsIdentity(context), new AuthenticationProperties());
                context.Validated(ticket);

                return Task.FromResult<object>(null);
            }

            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                context.Validated();
                return Task.FromResult<object>(null);
            }

            private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ExternalBearer);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                return identity;
            }
        }

API Controller Method:

 [HttpGet]
        [Route("sampleroute")]
        [Authorize]
        public async Task<HttpResponseMessage> GetSamples(string search)
        {
            try
            {

                HttpResponseMessage response;
                using (HttpClient client = new HttpClient(Common.CreateHttpClientHandler()))
                {
                     response = await client.GetAsync("test url");
                }
                var result = response.Content.ReadAsStringAsync().Result;
                Samples[] sampleArray = JsonConvert.DeserializeObject<Samples[]>(result);
                var filteredSamples = sampleArray .ToList().Where(y => y.NY_SampleName.ToUpper().Contains(search.ToUpper())).Select(n=>n);
                log.Information("<==========Ended==========>");
                return  Request.CreateResponse(HttpStatusCode.OK,filteredSamples);

            }
            catch (Exception ex)
            {
                log.Error($"Error occured while pulling the Samples:  {ex.ToString()}");
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }

Body:
It's probably a problem with the allowed audiences.
Here

 app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
 {
     ...
     AllowedAudiences = new[] { "*" },
     ...
 }

you set the allowed audiences. The tokens audclaim will be checked against the list of AllowedAudiences. But you never add any audience to the token.

In our project I used a CustomJwtFormat based on the code shown in http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

The token will be generated with a call to

var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

the second parameter is responsible for the aud claim in the JWT:

From https://msdn.microsoft.com/en-us/library/dn451037(v=vs.114).aspx :

audience
      Type: System.String

If this value is not null, a { aud, 'audience' } claim will be added.

After setting the aud claim in the token authorization should work fine.


问:
Show alert box when closing browser, but not on page reload or refresh using f5 or browser refresh button
Hello i want to show popup to user when my site close by any user. how to detect this event. i have one solution but it will not work on browser refresh click</p>

```<code>var exit = true;
$(window).on("keydown",function(e){
    if(e.which === 116){
      exit = false;
    }
});
    $(window).bind("beforeunload", function() {
        if (exit === true) {
            return "Are you sure you want to leave?";
        } else {
            return;
        }
});
</code>```

答:
It can be done very simply with the following JavaScript...

```<code>window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};
</code>```

EDIT

I don't know of a way to avoid this script firing when a user presses the refresh button in the browser, but there is a way to stop it when they press f5...

jQuery

```<code>//you need to set the variable exit to true first so it fires when f5 is not pressed
var exit = true;

//on keydown event will check if f5 is pressed
$(window).on("keydown",function(e){//begin window on keydown event

    //f5 key code is 116
    if(e.which === 116){//begin if it f5 is pressed

      //set exit to false so the prompt isn't displayed
      exit = false;

    }

});

//bind the beforeunload event to the window
$(window).bind("beforeunload", function() {

    //if exit = true then display the prompt
    if (exit === true) {

        //display the prompt
        return "Are you sure you want to leave?";
    } else {

        //do nothing, no prompt will be created
        return;

    }

});
</code>```

Don't forget to include jQuery in your

Body:
Hello i want to show popup to user when my site close by any user. how to detect this event. i have one solution but it will not work on browser refresh click

var exit = true;
$(window).on("keydown",function(e){
    if(e.which === 116){
      exit = false;
    }
});
    $(window).bind("beforeunload", function() {
        if (exit === true) {
            return "Are you sure you want to leave?";
        } else {
            return;
        }
});

Body:
It can be done very simply with the following JavaScript...

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

EDIT

I don't know of a way to avoid this script firing when a user presses the refresh button in the browser, but there is a way to stop it when they press f5...

jQuery

//you need to set the variable exit to true first so it fires when f5 is not pressed
var exit = true;

//on keydown event will check if f5 is pressed
$(window).on("keydown",function(e){//begin window on keydown event

    //f5 key code is 116
    if(e.which === 116){//begin if it f5 is pressed

      //set exit to false so the prompt isn't displayed
      exit = false;

    }

});

//bind the beforeunload event to the window
$(window).bind("beforeunload", function() {

    //if exit = true then display the prompt
    if (exit === true) {

        //display the prompt
        return "Are you sure you want to leave?";
    } else {

        //do nothing, no prompt will be created
        return;

    }

});

Don't forget to include jQuery in your <head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


问:
Vue: How do I call multiple functions with @click?
How can I call multiple functions in a single @click? (aka v-on:click)?

So far I tried

Splitting the functions with a semicolon:

;

Using several @click:

;

and as a workaround, I can just create a handler:

```<code><div v-on:click="fn3('foo', 'bar')"> </div>

function fn3 (args) {
  fn1(args);
  fn2(args);
}
</code>```

But sometimes this isn't nice. What would be the proper method/syntax?

答:
you can, however, do something like this :

```<code><div onclick="return function()
              {console.log('yaay, another onclick event!')}()"
              @click="defaultFunction"></div>
</code>```

yes, by using native onclick html event.

ContentLicense: CC BY-SA 4.0

Body:
How can I call multiple functions in a single @click? (aka v-on:click)?

So far I tried

Splitting the functions with a semicolon:

;

Using several @click:

;

and as a workaround, I can just create a handler:

function fn3 (args) {
  fn1(args);
  fn2(args);
}

But sometimes this isn't nice. What would be the proper method/syntax?

Body:
you can, however, do something like this :

<div onclick="return function()
              {console.log('yaay, another onclick event!')}()"
              @click="defaultFunction"></div>

yes, by using native onclick html event.


问:
React MaterialUI Card: how to change Card's class on expand? -> Custom React component
There are 20 cards on the page.

MaterialUI Card has onExpandChange property where I can define an action like this:

```<code><Card expandable={true} onExpandChange={this.clickHandle}>
</code>```

In this action I can easily know if the clicked card is expanded or not, because the callback function is defined like this in the MaterialUI: function(newExpandedState: boolean) => void

```<code>clickHandle = (newExpandedState: boolean) => {
    //do something
}
</code>```

Now I would like to change card's class, for example, give it class expanded when newExpandedState is true.

The problem is that I don't know how to tell this function which card has been expanded. Things like onExpandChange={this.clickHandle(newState, 'card1')} don't work. I have 20 cards on the page and I don't know which one should get expanded class. Any ideas how to do this?

答:
You can do this:

1. Maintain an array in state variable that will have the record of all the id's of card (any unique property of card) which are in expanded state.

```<code>constructor(){
   super();
   this.state = {
      cardStatus: []
   }
}
</code>```

2. Pass the unique value to each onExpandChange method:

```<code>onExpandChange={() => this.clickHandle(card.name)}
</code>```

3. Now if newExpandedState is true the push that value inside state array otherwise remove it:

```<code>clickHandle(name, newExpandedState){
    let cardStatus = this.state.cardStatus.slice();
    if(newExpandedState)
        cardStatus.push(name);
    else{
        let index = this.state.cardStatus.indexOf(name);
        cardStatus.splice(index,1);
    }
    this.setState({cardStatus});
}
</code>```

4. Now when generating the card check if that cardStatus array has that unique property of card or not and then apply different classNames.

```<code><Card className={this.state.cardStatus.indexOf(card.name) >= 0 ? 'expanded': 'not'}>
</code>```

Body:
There are 20 cards on the page.

MaterialUI Card has onExpandChange property where I can define an action like this:

<Card expandable={true} onExpandChange={this.clickHandle}>

In this action I can easily know if the clicked card is expanded or not, because the callback function is defined like this in the MaterialUI: function(newExpandedState: boolean) => void

clickHandle = (newExpandedState: boolean) => {
    //do something
}

Now I would like to change card's class, for example, give it class expanded when newExpandedState is true.

The problem is that I don't know how to tell this function which card has been expanded. Things like onExpandChange={this.clickHandle(newState, 'card1')} don't work. I have 20 cards on the page and I don't know which one should get expanded class. Any ideas how to do this?

Body:
You can do this:

1. Maintain an array in state variable that will have the record of all the id's of card (any unique property of card) which are in expanded state.

constructor(){
   super();
   this.state = {
      cardStatus: []
   }
}

2. Pass the unique value to each onExpandChange method:

onExpandChange={() => this.clickHandle(card.name)}

3. Now if newExpandedState is true the push that value inside state array otherwise remove it:

clickHandle(name, newExpandedState){
    let cardStatus = this.state.cardStatus.slice();
    if(newExpandedState)
        cardStatus.push(name);
    else{
        let index = this.state.cardStatus.indexOf(name);
        cardStatus.splice(index,1);
    }
    this.setState({cardStatus});
}

4. Now when generating the card check if that cardStatus array has that unique property of card or not and then apply different classNames.

<Card className={this.state.cardStatus.indexOf(card.name) >= 0 ? 'expanded': 'not'}>


问:
'IServiceCollection' does not contain a definition for 'AddSession'
I am getting an error while adding 'AddSession' in ASP.Net Core 1.1 using VS2017.

'IServiceCollection' does not contain a definition for 'AddSession'
and no extension method 'AddSession' accepting a first argument of
type 'IServiceCollection' could be found (are you missing a using
directive or an assembly reference?)

.csproj

The package is already installed in this solution.

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>

<PropertyGroup>
<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
</PropertyGroup>
 <ItemGroup>
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
 </ItemGroup>
 <ItemGroup>
 <DotNetCliToolReference
 Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
</ItemGroup>

 </Project>
```

Error :

答:
The versions of the dependencies seem to be out of sync.  Use Nuget to update all your packages to be the same version and that should solve the issue.  This applies to most if not all Microsoft.* packages.

Also you need the following using statements:

```<code>using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
</code>```

Body:
I am getting an error while adding 'AddSession' in ASP.Net Core 1.1 using VS2017.

'IServiceCollection' does not contain a definition for 'AddSession'
and no extension method 'AddSession' accepting a first argument of
type 'IServiceCollection' could be found (are you missing a using
directive or an assembly reference?)

.csproj

The package is already installed in this solution.

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>

<PropertyGroup>
<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
</PropertyGroup>
 <ItemGroup>
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
 </ItemGroup>
 <ItemGroup>
 <DotNetCliToolReference
 Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
</ItemGroup>

 </Project>

Error :

Body:
The versions of the dependencies seem to be out of sync.  Use Nuget to update all your packages to be the same version and that should solve the issue.  This applies to most if not all Microsoft.* packages.

Also you need the following using statements:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;


问:
CSV string handling
Typical way of creating a CSV string (pseudocode):

Create a CSV container object (like a StringBuilder in C#).

Loop through the strings you want to add appending a comma after each one.

After the loop, remove that last superfluous comma.

Code sample:

```<code>public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    foreach (Contact c in contactList)
    {
        sb.Append(c.Name + ",");
    }

    sb.Remove(sb.Length - 1, 1);
    //sb.Replace(",", "", sb.Length - 1, 1)

    return sb.ToString();
}
</code>```

I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

答:
You could use LINQ to Objects:

```<code>string [] strings = contactList.Select(c => c.Name).ToArray();
string csv = string.Join(",", strings);
</code>```

Obviously that could all be done in one line, but it's a bit clearer on two.

Title: CSV string handling

Body:
Typical way of creating a CSV string (pseudocode):

Create a CSV container object (like a StringBuilder in C#).

Loop through the strings you want to add appending a comma after each one.

After the loop, remove that last superfluous comma.

Code sample:

public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    foreach (Contact c in contactList)
    {
        sb.Append(c.Name + ",");
    }

    sb.Remove(sb.Length - 1, 1);
    //sb.Replace(",", "", sb.Length - 1, 1)

    return sb.ToString();
}

I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

LastEditorDisplayName: aussieviking

Body:
You could use LINQ to Objects:

string [] strings = contactList.Select(c => c.Name).ToArray();
string csv = string.Join(",", strings);

Obviously that could all be done in one line, but it's a bit clearer on two.


问:
How do I prevent replay attacks?
This is related to another question I asked. In summary, I have a special case of a URL where, when a form is POSTed to it, I can't rely on cookies for authentication or to maintain the user's session, but I somehow need to know who they are, and I need to know they're logged in!

I think I came up with a solution to my problem, but it needs fleshing out. Here's what I'm thinking. I create a hidden form field called "username", and place within it the user's username, encrypted. Then, when the form POSTs, even though I don't receive any cookies from the browser, I know they're logged in because I can decrypt the hidden form  field and get the username.

The major security flaw I can see is replay attacks. How do I prevent someone from getting ahold of that encrypted string, and POSTing as that user? I know I can use SSL to make it harder to steal that string, and maybe I can rotate the encryption key on a regular basis to limit the amount of time that the string is good for, but I'd really like to find a bulletproof solution. Anybody have any ideas? Does the ASP.Net ViewState prevent replay? If so, how do they do it?

Edit: I'm hoping for a solution that doesn't require anything stored in a database. Application state would be okay, except that it won't survive an IIS restart or work at all in a web farm or garden scenario. I'm accepting Chris's answer, for now, because I'm not convinced it's even possible to secure this without a database. But if someone comes up with an answer that does not involve the database, I'll accept it!

答: If you only accept each key once (say, make the key a GUID, and then check when it comes back), that would prevent replays. Of course, if the attacker responds first, then you have a new problem...

OwnerDisplayName: Josh Hinman

Title: How do I prevent replay attacks?

LastEditorDisplayName: Josh Hinman

OwnerDisplayName: Matt Bishop


问:
Extended css sprites not working with :hover?
I just encountered this article of an extention of css sprites that enables the spriting trick with foreground images . I tried to use the technique on :hover but it doesn't appear to work in IE and Opera. See my attempt to use this technique for a  menu here: http://www.kavoir.com/examples/jenny-css-sprites/menu.html

On FF and Safari, it works properly but just doesn't work at all in IE and Opera. Modified the code in a few ways but still doesn't work at all. Maybe it's impossible?

Tried to ask the author but she deleted my comment.

Any idea how to make this work on all browsers?

Update: Thanks for the answers but the :hover IS for , so I believe all IE browsers should work out the effects. Therefore the problem might very probably be about the clip property.

I just want to make sure if :hover works properly with clip on . Appears so far it doesn't.

答:
Here's how I usually make my CSS sprites without the IMG child tag within the A tag:

HTML:

```<code><div class="menu">
    <a href="#">foo</a>
    <a href="#">foo</a>
</div>
</code>```

CSS:

```<code>/* you need to specify its height and width so that they fit with the part of the sprite you want to show */
.menu a{display:block;width: 100px; height: 100px; float:left; margin-right: 10px; text-indent: -9999px;}
/* the background-position is set to top. */
.menu a{background: url(../images/whatever.png) no-repeat top center;}
/* the background-position is set to bottom. */
.menu a:hover{background-position: bottom center;}
</code>```

your whatever.png file would have a height of 200px with both states.

thats it

Body:
Here's how I usually make my CSS sprites without the IMG child tag within the A tag:

HTML:

<div class="menu">
    <a href="#">foo</a>
    <a href="#">foo</a>
</div>

CSS:

/* you need to specify its height and width so that they fit with the part of the sprite you want to show */
.menu a{display:block;width: 100px; height: 100px; float:left; margin-right: 10px; text-indent: -9999px;}
/* the background-position is set to top. */
.menu a{background: url(../images/whatever.png) no-repeat top center;}
/* the background-position is set to bottom. */
.menu a:hover{background-position: bottom center;}

your whatever.png file would have a height of 200px with both states.

thats it

OwnerDisplayName: Bernard Chhun

LastEditorDisplayName: Bernard Chhun